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(integrations): unify native users connections and source-aware execution

Rahman567847e06291
diff --git a/app/api/integrations/setup/route.test.ts b/app/api/integrations/setup/route.test.ts
index f596cd18..19ae0150 100644
--- a/app/api/integrations/setup/route.test.ts
+++ b/app/api/integrations/setup/route.test.ts
@@ -22,7 +22,10 @@ it("allows only exact trusted Origins and never grants credentialed CORS", async
});
it("safe schema is capability protected and secret fields have no prefill", async () => {
const { openIntegrationSetup } = await import("@/lib/infra/setup-capability"), { POST } = await import("./route");
- const grant = await openIntegrationSetup("composio", "test-owner");
+ const {integrationManage}=await import("@/lib/infra/connection-manage");
+ await integrationManage({action:"user.create",confirm:true,user:"test-owner"});
+ await integrationManage({action:"connection.create",confirm:true,user:"test-owner",provider:"composio",connection:"project",authMethod:"project"});
+ const grant = await openIntegrationSetup("composio", "test-owner", "project",{user:"test-owner",connection:"project"});
const response = await POST(req(grant.token)); expect(response.status).toBe(200);
const text = await response.text(); expect(text).not.toContain(grant.token); expect(text).not.toContain('"value":');
expect((await POST(req(grant.token, undefined, { action: "schema", provider: "hostinger" }))).status).toBe(400);
diff --git a/app/api/integrations/setup/route.ts b/app/api/integrations/setup/route.ts
index c1defcea..46a09eda 100644
--- a/app/api/integrations/setup/route.ts
+++ b/app/api/integrations/setup/route.ts
@@ -1,3 +1,4 @@
+import { IntegrationError } from "@/lib/infra/identity";
import { readSetupJson } from "@/lib/infra/setup-http";
import { NextRequest, NextResponse } from "next/server";
import { MSO_ORIGIN, MCP_UI_DOMAIN } from "@/lib/mcp/ui-config";
@@ -33,7 +34,7 @@ export async function POST(req: NextRequest) {
void audit({ action: "infra.write", actor: result.principal, target: result.provider, ok: true, detail: "integration.secure-setup" });
return NextResponse.json({ ok: true, verified: true, provider: result.provider }, { headers });
} catch (error) {
- const safe = error instanceof SetupError ? error : new SetupError("setup_unavailable", 503);
+ const safe = error instanceof SetupError || error instanceof IntegrationError ? error : new SetupError("setup_unavailable", 503);
return NextResponse.json({ error: safe.code }, { status: safe.status, headers });
}
}
diff --git a/app/api/v1/infra/cloudflare/zones/route.ts b/app/api/v1/infra/cloudflare/zones/route.ts
index 79741500..5895fa5a 100644
--- a/app/api/v1/infra/cloudflare/zones/route.ts
+++ b/app/api/v1/infra/cloudflare/zones/route.ts
@@ -1,12 +1,14 @@
-import { NextResponse } from "next/server";
+import {withIntegrationSelection} from "@/lib/infra/connection-service";
+import {selectionFrom} from "@/lib/infra/connection-dispatch";
+import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { listCloudflareZones } from "@/lib/infra";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-export async function GET() {
+export async function GET(req:NextRequest) {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- try { return NextResponse.json({ zones: await listCloudflareZones() }); }
+ try { return NextResponse.json({ zones: await withIntegrationSelection(selectionFrom(Object.fromEntries(req.nextUrl.searchParams)),()=>listCloudflareZones()) }); }
catch (error) { return NextResponse.json({ error: (error as Error).message }, { status: 503 }); }
}
diff --git a/app/api/v1/infra/dokploy/projects/route.ts b/app/api/v1/infra/dokploy/projects/route.ts
index df8939c5..08ad7a7b 100644
--- a/app/api/v1/infra/dokploy/projects/route.ts
+++ b/app/api/v1/infra/dokploy/projects/route.ts
@@ -1,12 +1,14 @@
-import { NextResponse } from "next/server";
+import {withIntegrationSelection} from "@/lib/infra/connection-service";
+import {selectionFrom} from "@/lib/infra/connection-dispatch";
+import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { listDokployProjects } from "@/lib/infra";
export const runtime = "nodejs";
export const dynamic = "force-dynamic";
-export async function GET() {
+export async function GET(req:NextRequest) {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- try { return NextResponse.json({ projects: await listDokployProjects() }); }
+ try { return NextResponse.json({ projects: await withIntegrationSelection(selectionFrom(Object.fromEntries(req.nextUrl.searchParams)),()=>listDokployProjects()) }); }
catch (error) { return NextResponse.json({ error: (error as Error).message }, { status: 503 }); }
}
diff --git a/app/api/v1/infra/providers/doctor/route.ts b/app/api/v1/infra/providers/doctor/route.ts
index 09446f7e..0b0f0169 100644
--- a/app/api/v1/infra/providers/doctor/route.ts
+++ b/app/api/v1/infra/providers/doctor/route.ts
@@ -1,3 +1,5 @@
+import { withIntegrationSelection } from "@/lib/infra/connection-service";
+import { selectionFrom } from "@/lib/infra/connection-dispatch";
import { NextRequest, NextResponse } from "next/server";
import { requireSession } from "@/lib/auth/require-session";
import { INFRA_PROVIDER_IDS, doctorInfraProvider, isInfraProviderId } from "@/lib/infra";
@@ -7,10 +9,10 @@ export const dynamic = "force-dynamic";
export async function POST(req: NextRequest) {
if (!(await requireSession("owner"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- let body: { id?: string } = {};
+ let body: { id?: string; user?: string; connection?:string; cwd?:string } = {};
try { body = await req.json(); } catch { /* empty means all */ }
const ids = body.id ? [body.id] : [...INFRA_PROVIDER_IDS];
if (ids.some((id) => !isInfraProviderId(id))) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
- const results = await Promise.all(ids.map((id) => doctorInfraProvider(id as (typeof INFRA_PROVIDER_IDS)[number])));
+ const results = await withIntegrationSelection(selectionFrom(body),()=>Promise.all(ids.map((id) => doctorInfraProvider(id as (typeof INFRA_PROVIDER_IDS)[number]))));
return NextResponse.json({ results });
}
diff --git a/app/api/v1/infra/providers/route.ts b/app/api/v1/infra/providers/route.ts
index 62c6e978..f96a707e 100644
--- a/app/api/v1/infra/providers/route.ts
+++ b/app/api/v1/infra/providers/route.ts
@@ -1,3 +1,5 @@
+import { withIntegrationSelection } from "@/lib/infra/connection-service";
+import { selectionFrom } from "@/lib/infra/connection-dispatch";
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
import { audit } from "@/lib/host/audit-api";
@@ -11,21 +13,21 @@ async function ownerContext() {
return context?.role === "owner" ? context : null;
}
-export async function GET() {
+export async function GET(req:NextRequest) {
if (!(await ownerContext())) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- const providers = await Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id))));
+ const providers = await withIntegrationSelection(selectionFrom(Object.fromEntries(req.nextUrl.searchParams)),()=>Promise.all(INFRA_PROVIDER_IDS.map(async (id) => summarizeInfraProvider(id, await readInfraProvider(id)))));
return NextResponse.json({ providers });
}
export async function POST(req: NextRequest) {
const context = await ownerContext();
if (!context) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
- let body: { id?: string; values?: Record<string, unknown> };
+ let body: { id?: string; user?:string; connection?:string; cwd?:string; values?: Record<string, unknown> };
try { body = await req.json(); } catch { return NextResponse.json({ error: "Invalid request body" }, { status: 400 }); }
const id = String(body.id ?? "");
if (!isInfraProviderId(id)) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
try {
- const values = await setInfraProvider(id, body.values ?? {});
+ const values = await withIntegrationSelection(selectionFrom(body),()=>setInfraProvider(id, body.values ?? {}));
void audit({ action: "infra.write", actor: context.session.device_id, target: id, detail: "provider.configure" });
return NextResponse.json({ ok: true, provider: summarizeInfraProvider(id, values) });
} catch (error) {
@@ -39,7 +41,7 @@ export async function DELETE(req: NextRequest) {
if (!context) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
const id = new URL(req.url).searchParams.get("id") ?? "";
if (!isInfraProviderId(id)) return NextResponse.json({ error: "unknown infrastructure provider" }, { status: 404 });
- await removeInfraProvider(id);
+ await withIntegrationSelection(selectionFrom(Object.fromEntries(req.nextUrl.searchParams)),()=>removeInfraProvider(id));
void audit({ action: "infra.write", actor: context.session.device_id, target: id, detail: "provider.remove" });
return NextResponse.json({ ok: true });
}
diff --git a/app/api/v1/infra/setup/route.ts b/app/api/v1/infra/setup/route.ts
index 45b8eb02..0b7d0c3d 100644
--- a/app/api/v1/infra/setup/route.ts
+++ b/app/api/v1/infra/setup/route.ts
@@ -1,3 +1,4 @@
+import { selectionFrom } from "@/lib/infra/connection-dispatch";
import { MSO_ORIGIN } from "@/lib/mcp/ui-config";
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
@@ -12,8 +13,8 @@ export async function POST(req: NextRequest) {
if (context?.role !== "owner" || !context.session.device_id) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });
try {
const body = await readSetupJson(req);
- if (Object.keys(body).some(k => !["provider", "method"].includes(k)) || typeof body.provider !== "string" || (body.method !== undefined && typeof body.method !== "string")) throw new Error("invalid");
- const grant = await openIntegrationSetup(body.provider, context.session.device_id, body.method as string | undefined);
+ if (Object.keys(body).some(k => !["provider", "method", "user", "connection"].includes(k)) || typeof body.provider !== "string" || (body.method !== undefined && typeof body.method !== "string")) throw new Error("invalid");
+ const grant = await openIntegrationSetup(body.provider, context.session.device_id, body.method as string | undefined, selectionFrom(body));
void audit({ action: "infra.write", actor: context.session.device_id, target: body.provider, ok: true, detail: "integration.setup-open" });
return NextResponse.json({ ...grant, setupUrl: `${MSO_ORIGIN}/integrations` }, { headers });
} catch { return NextResponse.json({ error: "setup_unavailable" }, { status: 400, headers }); }
diff --git a/app/api/v1/integrations/route.test.ts b/app/api/v1/integrations/route.test.ts
new file mode 100644
index 00000000..7ba25e0b
--- /dev/null
+++ b/app/api/v1/integrations/route.test.ts
@@ -0,0 +1,23 @@
+import {beforeEach,afterEach,it,expect,vi} from "vitest";
+import {NextRequest} from "next/server";
+import {promises as fs} from "node:fs";
+import path from "node:path";
+import os from "node:os";
+const auth=vi.hoisted(()=>({role:"owner" as string|null}));
+vi.mock("server-only",()=>({}));
+vi.mock("@/lib/auth/require-session",()=>({getSessionContext:async()=>auth.role?{role:auth.role,session:{device_id:"synthetic-test-owner"}}:null}));
+vi.mock("@/lib/host/audit-api",()=>({audit:vi.fn()}));
+let root:string;
+beforeEach(async()=>{auth.role="owner";root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-integration-api-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+afterEach(async()=>{delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+const req=(body:unknown)=>new NextRequest("https://mso.rahmanef.com/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});
+it("enforces Owner on profile metadata and mutations regardless of selected credential user",async()=>{
+ const {GET,POST}=await import("./route");for(const role of [null,"viewer","operator"]){auth.role=role;expect((await GET(new NextRequest("https://mso.rahmanef.com/api/v1/integrations"))).status).toBe(403);expect((await POST(req({mode:"manage",action:"user.create",confirm:true,user:"owner"}))).status).toBe(403);}
+});
+it("shares confirmed actions with the CLI/MCP core and rejects secret-shaped metadata",async()=>{
+ const {GET,POST}=await import("./route");
+ expect((await POST(req({mode:"manage",action:"user.create",user:"alice"}))).status).toBe(403);
+ expect((await POST(req({mode:"manage",action:"user.create",confirm:true,user:"alice",token:"synthetic"}))).status).toBe(400);
+ expect((await POST(req({mode:"manage",action:"user.create",confirm:true,user:"alice"}))).status).toBe(200);
+ const response=await GET(new NextRequest("https://mso.rahmanef.com/api/v1/integrations?view=users"));expect(await response.json()).toMatchObject({users:[{id:"alice"}],user:"alice"});
+});
diff --git a/app/api/v1/integrations/route.ts b/app/api/v1/integrations/route.ts
new file mode 100644
index 00000000..26b08027
--- /dev/null
+++ b/app/api/v1/integrations/route.ts
@@ -0,0 +1,22 @@
+import { NextRequest, NextResponse } from "next/server";
+import { getSessionContext } from "@/lib/auth/require-session";
+import { readSetupJson } from "@/lib/infra/setup-http";
+import { queryIntegrationAction, manageIntegrationAction, executeIntegrationAction } from "@/lib/infra/connection-dispatch";
+import { IntegrationError } from "@/lib/infra/identity";
+import { audit } from "@/lib/host/audit-api";
+export const runtime="nodejs";
+export const dynamic="force-dynamic";
+const headers={"Cache-Control":"no-store, private","Referrer-Policy":"no-referrer"};
+export async function GET(req:NextRequest){
+ if((await getSessionContext())?.role!=="owner")return NextResponse.json({error:"owner_required"},{status:403,headers});
+ try{return NextResponse.json(await queryIntegrationAction(Object.fromEntries(req.nextUrl.searchParams)),{headers});}catch(e){return failure(e);}
+}
+function failure(e:unknown){const error=e instanceof IntegrationError?e:new IntegrationError("integration_operation_failed",400);return NextResponse.json({error:error.code},{status:error.status,headers});}
+export async function POST(req:NextRequest){
+ const ctx=await getSessionContext();if(ctx?.role!=="owner")return NextResponse.json({error:"owner_required"},{status:403,headers});
+ try{const {mode,...input}=await readSetupJson(req);if(!["manage","execute"].includes(String(mode)))throw new IntegrationError("invalid_action_mode");
+ const result=mode==="manage"?await manageIntegrationAction(input):await executeIntegrationAction(input);
+ void audit({action:"infra.write",actor:ctx.session.device_id,target:String(input.user??"integrations"),ok:true,detail:`integrations.${String(mode)}`});
+ return NextResponse.json(result,{headers});
+ }catch(e){return failure(e);}
+}
diff --git a/app/integrations/route.test.ts b/app/integrations/route.test.ts
index 133dbcc1..c1a03319 100644
--- a/app/integrations/route.test.ts
+++ b/app/integrations/route.test.ts
@@ -9,7 +9,7 @@ describe("friendly native Integrations page", () => {
expect(response.status).toBe(200); expect(response.headers.get("referrer-policy")).toBe("no-referrer");
expect(response.headers.get("cache-control")).toContain("no-store");
expect(html).toContain("INTEGRATIONS_CATALOG"); expect(html).toContain('"id":"supabase"');
- expect(html).toContain("Step by step: get this credential"); expect(html).not.toContain("si-coder");
+ expect(html).toContain("How to get this credential / authorization"); expect(html).not.toContain("si-coder");
expect(() => new Function(html.match(/<script nonce="[^"]+">([\s\S]*)<\/script>/)![1])).not.toThrow();
});
it("lets the trusted HTML endpoint own its nonce while retaining owner mutation CSRF checks", async () => {
diff --git a/bin/mso b/bin/mso
index c65e9a2d..3cdade62 100755
--- a/bin/mso
+++ b/bin/mso
@@ -47,6 +47,7 @@
# model [ref] Select active model from a connected provider
# onboard [-y] Guided setup: AI, apps, infrastructure, skills
# setup Alias for onboard
+# integrations Named credential users, connections, sources, setup and execution
# provider * Infrastructure credentials: list | set | rm | doctor
# providers * Alias for provider
# gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
diff --git a/bin/mso.test.ts b/bin/mso.test.ts
index ad0308fe..ed39fc29 100644
--- a/bin/mso.test.ts
+++ b/bin/mso.test.ts
@@ -95,6 +95,7 @@ describe("bin/mso", () => {
fs.readFileSync(path.join(repo, "scripts/cli/commands.sh"), "utf8"),
...commandOwnerFiles.map((rel) => fs.readFileSync(path.join(repo, rel), "utf8")),
fs.readFileSync(path.join(repo, "scripts/mso-cli-agent.sh"), "utf8"),
+ fs.readFileSync(path.join(repo, "scripts/mso-cli-integrations.sh"), "utf8"),
].join("\n");
// Not reachable from a shell, each for its own reason:
@@ -105,6 +106,9 @@ describe("bin/mso", () => {
// OAuth is NOT here any more: it is a device-code POST, not a redirect, so
// `mso oauth <provider> start|poll` covers it.
const browserOnly = [
+ // 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",
"GET /api/sw",
"/api/v1/managed-apps/[id]/proxy/[[...path]]",
"/api/auth/devices",
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index fe784674..01ae777e 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Added**
+- `integrations` unify native users connections and source-aware execution
- `artifacts` add private per-session screenshot storage and retention
- `integrations` add native secure credential setup in browser and MCP Page
- add safe local maintenance and visual README
diff --git a/docs/CLI.md b/docs/CLI.md
index c7480886..1ec4581b 100644
--- a/docs/CLI.md
+++ b/docs/CLI.md
@@ -87,6 +87,7 @@ Commands:
model [ref] Select active model from a connected provider
onboard [-y] Guided setup: AI, apps, infrastructure, skills
setup Alias for onboard
+ integrations Named credential users, connections, sources, setup and execution
provider * Infrastructure credentials: list | set | rm | doctor
providers * Alias for provider
gateway * Secure public HTTPS tunnel: start | status | url | stop | doctor | install | domain
diff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.md
index 3c2b4ca5..596b46a9 100644
--- a/docs/INFRASTRUCTURE-PROVIDERS.md
+++ b/docs/INFRASTRUCTURE-PROVIDERS.md
@@ -220,3 +220,11 @@ The native Integrations catalog now also includes GitHub, Vercel, Convex Cloud,
self-hosted Convex, Resend, Stripe, Clerk, and Supabase. This expands secure setup
and bounded read-only credential checking; it does not automatically add every
provider operation to the MCP catalog. Browser entrypoint: `/integrations`.
+
+## Named identity selection
+
+Infrastructure providers now read through the native named-connection resolver.
+MCP operations accept `user`, `connection` and `cwd`; explicit identities override
+folder/default resolution, and external backends never fall back to local keys.
+Provider-only v1 configuration is projected into `legacy` and backed up before
+the first v2 write. See [Integrations](INTEGRATIONS.md) for exact CLI/API contracts.
diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.md
index 83f2604b..d3ce66ae 100644
--- a/docs/INTEGRATIONS.md
+++ b/docs/INTEGRATIONS.md
@@ -1,130 +1,168 @@
# Native Integrations
-Connect Composio, Dokploy, Cloudflare, Hostinger, GitHub, Vercel, Convex Cloud,
-self-hosted Convex, Resend, Stripe, Clerk, and Supabase directly to MSO. No separate
-credential application or plugin is required. Composio accepts either a project
-API key or an organization API key; these are separate setup methods.
+MSO owns a named-connection model, not one global API-key form per provider.
+The browser, CLI and MCP tools call the same native services. No separate credential
+application, package or plugin is required.
-## Browser and terminal
-
-Open `/integrations` on your MSO origin. The searchable catalog and official
-credential instructions are available before signing in. Select the provider and
-authentication method, then choose **Open secure form**. Sign in as an owner in
-another tab only when creating the private form. The old `/api/integrations/setup`
-address remains compatible. The form
-includes official links, expandable instructions, masked inputs with show/hide,
-and **Validate & save**. Existing stored values are never displayed; blank fields
-keep them unchanged. A rejected or unreachable provider does not replace them.
+```text
+Credential user MSO device role
+ └─ Provider └─ Viewer / Operator / Owner
+ └─ Named connection controls permission, not account choice
+ ├─ Source / backend
+ ├─ Authentication method + scope
+ └─ Direct fields OR external routing identifiers
+```
-From an interactive terminal with an authenticated MSO session:
+A credential user is a context for service accounts, **not a login or an access-control
+boundary between MSO operators**. An authorized Owner or suitably scoped MCP client
+can manage the profiles exposed to that MSO instance. Selecting a profile must never
+silently select another user's key.
+
+## Named accounts and deployments
+
+One user can have `convex-cloud/admin`, `convex-cloud/mimin-production`,
+`convex-cloud/mimin-staging`, and other deployments independently. Each connection
+has a stable ID, display label, provider, source, authentication method, scope, and
+revision. Changing a label is not changing the upstream identity.
+
+Resolution is: explicit user → longest matching folder binding → default user.
+Within that user: explicit connection → matching folder's provider binding → provider
+default → sole connection. Several connections without an explicit/default selection
+are ambiguous and refused. An explicit missing user/connection is never replaced by
+a default from somewhere else. Compound direct operations pin resolved values for
+their duration; concurrent work cannot mix two profiles partway through one operation.
+
+## Sources are not authentication methods
+
+**MSO direct** stores owner-only local credential fields. **Composio** keeps the
+provider's OAuth/API credentials upstream; MSO stores its connected-account ID,
+auth-config ID, broker reference, toolkit, and lifecycle status. **Provider MCP**
+returns the provider-owned MCP route and authorization instructions, rather than
+pretending a local API key is an authenticated OAuth session.
+
+A Composio project credential is itself a direct named connection under the same
+credential user. Organization administration keys cannot substitute for that broker.
+Hosted authorization validates the toolkit and auth scheme, requires an explicit
+config when several match, and only creates a managed config with explicit approval.
+The remote user ID uses an installation UUID and immutable profile UUID. External
+account execution includes the exact connected-account ID, rechecks its identity,
+and holds a short operation lease against concurrent deletion/relink/rotation.
+
+Provider-MCP OAuth is completed in the provider's client. Returning that route does
+not prove the external session is authorized, and MSO never falls back to a local key.
+
+## Browser and ChatGPT
+
+Open `/integrations`. Public instructions are readable before sign-in; an Owner
+session is required to read/manage credential profiles or open their private forms.
+Choose the credential user, provider, named connection, source and authentication.
+User creation/rename/duplicate/default/deletion, folder mappings, connection CRUD,
+verification and credential clearing use the same metadata actions as the CLI/MCP.
+User duplication copies metadata by default. Copying direct credential values needs
+the separate explicit `copyCredentials` opt-in; external linked identities are never
+copied into a different profile.
+
+The secure form is bound to an **existing direct connection**, not just a provider.
+It displays official guidance, masked fields, show/hide, and Validate & save. Blank
+fields preserve existing values. Keys go directly to the MSO HTTPS endpoint, never
+through MCP tool arguments, chat messages, widget state or browser storage. Success,
+expiry and navigation clear inputs. A failed provider check never replaces an old key.
+
+`render_mso_page` with `/integrations` opens this same manager. Page v7 retains
+resource aliases for older clients, initializes the standard MCP Apps bridge, and
+uses the actual display mode returned by the host. Fullscreen fills the iframe's
+available viewport instead of retaining an inline height cap. The host still controls
+whether fullscreen is available and how large its viewport is.
+
+A connector that cached old tools must refresh to discover the new actions. A missing
+action or private grant is an explicit recoverable error, not evidence of successful
+setup. Opening an outer widget is not proof that its form or provider authorization works.
+
+## CLI
+
+Inspect methods before creating a connection:
```sh
-mso provider setup composio project
-mso provider setup composio organization
-mso provider setup hostinger
-mso provider setup convex-cloud personal
-mso provider setup convex-cloud deployment
+mso integrations create-user rahman "Rahman"
+mso integrations request rahman convex-cloud
+mso integrations create-connection rahman convex-cloud mimin-production direct deployment
+mso integrations create-connection rahman convex-cloud mimin-staging direct deployment
+mso integrations connections rahman convex-cloud
+mso integrations setup rahman convex-cloud mimin-production
+mso integrations verify rahman convex-cloud mimin-production
+mso integrations resolve rahman convex-cloud mimin-staging
```
-The command prints a private ten-minute URL on the configured public MSO origin.
-The setup token is in the URL fragment, never a query parameter, and is removed
-from browser history after loading. Do not paste the URL into chat or logs.
-Non-interactive invocation is refused rather than exposing a capability in tool
-output. Other credential commands remain available.
+`setup` prints a private ten-minute fragment URL **only in an interactive terminal**.
+Do not paste it into chat or logs. `mso provider setup <provider> <user> <connection>`
+is a compatibility entrypoint to the same flow. Offline CLI help/update does not load
+the connection manager until requested.
-## ChatGPT Page
+Metadata changes require confirmation and contain no secrets:
-`render_mso_page` with route `/integrations` opens the provider picker.
-`integration_setup_open` is write-scoped and opens the selected form directly.
-Neither tool accepts credential values. The tool uses the existing **MSO Page**
-resource; MSO still exposes only the Block and Page presentation types.
-
-```text
-ChatGPT → integration_setup_open(provider, method)
- │
- safe display data + UI-only grant
- ↓
- MSO Page form
- │ direct HTTPS, no owner cookies
- ↓
- provider validation → private MSO store
+```sh
+mso integrations manage '{"action":"folder.map","user":"rahman","path":"/absolute/project","provider":"convex-cloud","connection":"mimin-staging","confirm":true}'
+mso integrations which /absolute/project
+mso integrations execute '{"user":"rahman","provider":"dokploy","connection":"production","operation":"dokploy.projects.list","confirm":true}'
```
-The grant reaches the UI through hidden MCP `_meta`. A WeakMap keeps it out of
-ordinary result serialization and model transports. Both generic MCP Apps and
-the compact ChatGPT transport retain the UI-only result metadata; it is not added
-to text or structured model content. The UI supports
-both standards-based MCP Apps initialization and ChatGPT's canonical metadata
-envelope. Credential values never enter `tools/call`, `ui/message`, widget state,
-local storage, or session storage. Buttons do not require iframe `allow-forms`;
-reference links use the host's approved external-link bridge.
-
-A client that cached the older tool catalog must refresh/reconnect the plugin
-before invoking `integration_setup_open`. A standards-bridge browser fixture is
-not proof that every installed ChatGPT client has refreshed its catalog.
-
-## Security boundary
-
-Each random 32-byte capability is bound to a provider, authentication method, and
-issuing principal. Only its hash is persisted in an owner-only file. It expires
-after ten minutes, permits at most five provider-check attempts, and is consumed
-after one successful validation. Per-grant locks reject concurrent replays.
-The session is a short-lived delegated permission; restarting the UI does not
-extend its expiry.
-
-The cookie-less setup endpoint performs exact-Origin CORS checks, bounded JSON
-parsing, field allowlisting, and bearer authorization. Only that exact API path
-is exempt from the owner's normal same-origin mutation check. Other routes retain
-their existing authorization and CSRF controls. The issuer requires an owner
-session or a write-scoped MCP principal. Public HTML contains no credentials or
-setup capability.
-
-The native store uses owner-only filesystem permissions (0600), atomic writes,
-and cross-process locking. This is filesystem protection, **not encryption at
-rest** or protection from a compromised owner/root account. API keys are sent only
-to their selected provider's verification endpoint; Dokploy URLs retain the
-existing DNS-pinned SSRF checks. Raw provider errors are not returned to the form.
-
-Composio connected-account OAuth tokens remain with Composio. Configuring an API
-key is not the same as completing OAuth for every application connected there.
-A scoped key may authenticate but lack access to the endpoint being checked; the
-form fails closed instead of claiming successful access.
-
-## Official references
-
-- [Composio authentication](https://docs.composio.dev/reference/authenticating-to-composio)
-- [Cloudflare token creation](https://developers.cloudflare.com/fundamentals/api/get-started/create-token/)
-- [Hostinger API](https://developers.hostinger.com/)
-- [Dokploy API](https://docs.dokploy.com/docs/core/api)
-- [OpenAI plugin UI reference](https://developers.openai.com/plugins/reference)
-
-## Verification
-
-Focused tests cover capability expiry, replay, provider/method isolation,
-validation-before-write, secret redaction, strict CORS, bounded request bodies,
-owner-only store permissions, and MCP output separation. Browser fixtures cover
-desktop/mobile Page rendering, standards-bridge initialization, failed validation
-and retry, input clearing, no owner cookies, and no credential in host messages.
-Real provider authentication still requires the user's own valid credential.
-
-The organization-key probe uses Composio's organization-owner endpoint
-`/api/v3.1/org/owner/project/list` with `x-org-api-key`, not the similarly named
-user-key endpoint. Convex personal-token validation uses the explicitly PAT-scoped
-`/v1/list_personal_access_tokens?limit=1`; token inventory is discarded.
-
-The Page resource is v5. Earlier Page resource URIs resolve to the current safe
-renderer, and both standard and compatibility CSP forms advertise the exact MSO
-connection origin. Missing private metadata, an unavailable setup tool, or expired
-authorization shows a recovery message and browser entrypoint instead of a blank
-form. Browser failure/expiry never requests a secret through chat.
-
-Native MSO storage is independent of other applications. Provider registration
-and API-key checks do not imply full provider-operation parity or completion of
-an upstream OAuth flow. MSO does not silently import another tool's credentials.
-
-### Deployment verification
-
-The service release lifecycle waits for the root HTTP endpoint after observing a
-replacement systemd process, then verifies every referenced JS/CSS asset. A new
-process alone is not HTTP readiness. The bounded wait does not waive missing
-chunks, incorrect MIME types, or fallback-runtime restoration requirements.
+## Machine tools and operation coverage
+
+`integration_query` reads catalog/users/connections, resolves an identity, and returns
+source-aware setup instructions. `integration_manage` performs confirmed user,
+connection, folder-binding, credential-deletion or hosted-authorization actions.
+`integration_execute` takes explicit user/provider/connection and returns a route,
+verifies that connection, performs supported bounded direct operations, or executes
+a toolkit-matching Composio tool using its exact connected account.
+`integration_setup_open` requires `user`, `provider` and `connection`; optional `method`
+must match the connection. Its private grant exists only in result `_meta` for the UI.
+
+Existing Dokploy, Cloudflare and Hostinger MCP tools now accept `user`, `connection`
+and `cwd` and use the same resolver. Their owner HTTP routes also accept this selection.
+The compatibility provider APIs operate on a resolved connection, not a parallel store.
+New native provider operations must reuse this resolver rather than read unscoped keys.
+
+The twelve native service definitions provide credential setup and verification.
+This release does **not** add every service's entire API or replace provider-owned
+OAuth clients. Explicit direct execution covers Dokploy project listing/ensure,
+Cloudflare zone listing/DNS upsert, and Hostinger DNS upsert. Composio tool execution
+is generic but restricted to the selected toolkit, active account and exec permission.
+
+## Existing-data migration and concurrency
+
+The protected store remains `OS_INFRA_STORE`, defaulting to
+`~/.mso/private/infra-providers.json`. Reads project a v1 provider-only file into a
+`legacy` profile without rewriting it. On the first successful mutation, MSO saves
+an exact 0600 `<store>.v1-backup.json`, then atomically writes version 2. If both
+Composio key types or both Convex auth methods were configured, they become separate
+connections; the previous effective preference remains the default. Unknown or
+malformed legacy data fails closed for review rather than being discarded.
+
+No other application's store is imported automatically. Restore a backup only after
+reviewing newer v2 changes; restoring old bytes is not a merge and would discard those
+newer records. Stale forms carry connection UID/revision and cannot overwrite a
+concurrently rotated, deleted or recreated identity. Deleting a folder-bound connection
+or a Composio broker with linked dependants is refused until its references are handled.
+
+## Security and verification limits
+
+Credentials use protected filesystem permissions, atomic replacement and cross-process
+locks. **This is not encryption at rest** and cannot protect against a compromised
+owner/root account. Machine metadata schemas reject secret-shaped inputs recursively.
+
+A setup token is a short-lived delegated write capability, not a separate cookie login.
+Its hash is stored with the issuing principal and exact connection, with a ten-minute
+expiry, bounded attempts, strict request sizes/Origins, and single-use successful save.
+The bearer must remain private; requiring the Owner cookie inside a third-party iframe
+would break the deliberate cookie-less secret submission boundary.
+
+Tests cover legacy migration/backup, cross-user multi-deployment selection, actual
+provider-client credential routing, folder/default precedence, external-source refusal,
+confirmation/secret rejection, hosted identity/leases, stale setup grants, replay,
+CLI/API/MCP parity and desktop/mobile/fullscreen browser behavior using synthetic data.
+A real provider OAuth authorization or a user's save inside the actual ChatGPT host
+is a separate user-authorized verification step, not implied by unit tests.
+
+Official contracts: [MCP Apps](https://github.com/modelcontextprotocol/ext-apps),
+[OpenAI plugin UI](https://developers.openai.com/plugins/reference), and
+[Composio connected accounts](https://docs.composio.dev/docs/auth-configuration/connected-accounts).
diff --git a/docs/MCP.md b/docs/MCP.md
index db75ee05..888b3dd4 100644
--- a/docs/MCP.md
+++ b/docs/MCP.md
@@ -712,3 +712,7 @@ entrypoint is `/integrations`; Page v5 retains previous resource aliases.
`session_artifacts` lists or reads this client’s session screenshots/JSON reports. `session_artifact_register` registers bounded browser outputs from the injected `MSO_SCREENSHOT_DIR`; `session_artifacts_cleanup` previews or applies dormant-session retention. `agent_session_current` returns computed temp/manifest locations. See [Session artifacts](./SESSION-ARTIFACTS.md) for the single shared storage policy and trust boundary.
+
+Native named integrations use `integration_query`, `integration_manage`, and
+`integration_execute`. `integration_setup_open` now requires user/provider/connection.
+See [Integrations](INTEGRATIONS.md) for the shared identity, migration and secret boundaries.
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index c68fd4c0..4f4d458a 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,5 +1,30 @@
## 2026-09-05 — MCP Page preview lifecycle
+
+## 2026-09-05 — Native named-connection identity, not parallel credential forms
+
+The provider-only Integrations store could not represent multiple deployments or
+source-aware execution even though its HTML form worked. Replace the foundation
+with credential users, named connections, direct/Composio/provider-MCP sources,
+auth methods, folder/default resolution and explicit account selection. Browser,
+CLI and MCP now call the same domain actions; old infrastructure helpers adapt to
+that core and pin values for compound provider operations.
+
+Preserve v1 data through a read-only projection and exact protected backup before
+the first atomic v2 write. Bind temporary setup capabilities to user/connection
+UID/revision so stale forms cannot rotate another account. Namespace upstream
+Composio users by installation/profile UUID; lease both the target and broker for
+hosted authorization/execution. Duplication is metadata-only unless copying direct
+credentials is separately approved. Device roles remain distinct from credential
+profiles, not a new user-login/ACL system.
+
+Tests exercise two users, five Convex connections, folder resolution, actual
+Dokploy client routing, source refusal, hosted-account identity, lease protection,
+MCP/CLI contracts and real shared-core browser saves with synthetic credentials.
+Page layout follows the host's returned display mode; full-height behavior is
+measured against the fixture iframe viewport rather than assumed from a button.
+No real upstream OAuth success is inferred from these tests.
+
- **Reviewed-app Google sign-in leaves the iframe (2026-09-05):** Page v6 adds an explicit host-side Google-login action using a code-owned same-origin path. A nested app may only highlight this action, never trigger navigation, supply a URL or transfer session data. The host opens through `ui/open-link`/`openExternal` after a real button click; sandbox popup restrictions remain unchanged. Play Together finishes sign-in in the browser tab; this does not promise shared login with storage-partitioned embeds. v5 resource requests remain compatible.
diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.md
index 075789b5..841142a5 100644
--- a/docs/generated/MCP-CATALOG.md
+++ b/docs/generated/MCP-CATALOG.md
@@ -4,21 +4,21 @@
## Full MSO catalog
-<!-- mcp-toolset: server=1.12.0 version=2026.09.05.7 tools=92 read=45 write=28 exec=19 -->
+<!-- mcp-toolset: server=1.12.0 version=2026.09.05.8 tools=95 read=46 write=29 exec=20 -->
| Fact | Current source value |
|---|---:|
| MCP server | `1.12.0` |
-| Toolset | `2026.09.05.7` |
-| Toolset changed at | `2026-09-05T13:00:00Z` |
-| Transport tools | **94** |
-| Model/operator tools | **92** |
-| Read | **45** |
-| Write | **28** |
-| Exec | **19** |
+| Toolset | `2026.09.05.8` |
+| Toolset changed at | `2026-09-05T14:05:00Z` |
+| Transport tools | **97** |
+| Model/operator tools | **95** |
+| Read | **46** |
+| Write | **29** |
+| Exec | **20** |
| App-only bridges | **2** |
-### Read (45)
+### Read (46)
- `a2a_agent_discover`
- `a2a_agents_list`
@@ -41,6 +41,7 @@
- `fs_usage`
- `infra_provider_doctor`
- `infra_providers_list`
+- `integration_query`
- `local_agent_inbox`
- `local_agent_request_wait`
- `local_agents_list`
@@ -66,7 +67,7 @@
- `tool_forge_candidates`
- `vps_status`
-### Write (28)
+### Write (29)
- `a2a_agent_register`
- `a2a_agent_remove`
@@ -84,6 +85,7 @@
- `fs_upload_file`
- `fs_write`
- `hostinger_dns_upsert`
+- `integration_manage`
- `integration_setup_open`
- `local_agent_message_send`
- `local_agent_reply`
@@ -97,7 +99,7 @@
- `workflow_finish`
- `workflow_start`
-### Exec (19)
+### Exec (20)
- `a2a_handoff`
- `a2a_message_send`
@@ -107,6 +109,7 @@
- `exec_job_cancel`
- `exec_job_start`
- `exec_run`
+- `integration_execute`
- `local_agent_request`
- `project_agent_run`
- `project_database_call`
@@ -126,20 +129,20 @@
## ChatGPT static profile
-<!-- mcp-chatgpt-profile: server=1.12.0 version=2026.09.05.7 tools=68 read=36 write=20 exec=12 app-only=2 total=70 -->
+<!-- mcp-chatgpt-profile: server=1.12.0 version=2026.09.05.8 tools=71 read=37 write=21 exec=13 app-only=2 total=73 -->
The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_NAMES`. OAuth scope is still enforced independently; project-owned MCP tool names remain dynamic data behind the generic project bridge.
| Fact | Current source value |
|---|---:|
-| ChatGPT transport tools | **70** |
-| ChatGPT model/operator tools | **68** |
-| Read | **36** |
-| Write | **20** |
-| Exec | **12** |
+| ChatGPT transport tools | **73** |
+| ChatGPT model/operator tools | **71** |
+| Read | **37** |
+| Write | **21** |
+| Exec | **13** |
| App-only bridges | **2** |
-### ChatGPT read (36)
+### ChatGPT read (37)
- `agent_session_current`
- `apps_list`
@@ -155,6 +158,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `fs_usage`
- `infra_provider_doctor`
- `infra_providers_list`
+- `integration_query`
- `local_agent_inbox`
- `local_agent_request_wait`
- `local_agents_list`
@@ -178,7 +182,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `sys_stats`
- `vps_status`
-### ChatGPT write (20)
+### ChatGPT write (21)
- `agent_session_rename`
- `apps_power`
@@ -191,6 +195,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `fs_upload_file`
- `fs_write`
- `hostinger_dns_upsert`
+- `integration_manage`
- `integration_setup_open`
- `local_agent_message_send`
- `local_agent_reply`
@@ -201,12 +206,13 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_
- `workflow_finish`
- `workflow_start`
-### ChatGPT exec (12)
+### ChatGPT exec (13)
- `browser_power`
- `exec_job_cancel`
- `exec_job_start`
- `exec_run`
+- `integration_execute`
- `project_agent_run`
- `project_database_call`
- `project_database_query`
diff --git a/lib/infra/additional-doctor.test.ts b/lib/infra/additional-doctor.test.ts
index dfca0ab0..a8b61ccf 100644
--- a/lib/infra/additional-doctor.test.ts
+++ b/lib/infra/additional-doctor.test.ts
@@ -1,15 +1,15 @@
import { afterEach, describe, expect, it, vi } from "vitest";
vi.mock("server-only", () => ({}));
import { doctorAdditionalProvider } from "./additional-doctor";
-import { integrationCatalog } from "./setup-catalog";
+import { connectionCatalog } from "./connection-registry";
import { setupFields } from "./setup-guidance";
import { summarizeInfraProvider } from "./store";
const KEY = "synthetic_api_credential_for_unit_test";
afterEach(() => vi.unstubAllGlobals());
describe("additional native credential providers", () => {
it("exposes twelve native providers with guided method-specific fields", () => {
- const catalog = integrationCatalog(); expect(catalog).toHaveLength(12);
- for (const p of catalog) for (const m of p.methods) {
+ const catalog = connectionCatalog(); expect(catalog).toHaveLength(12);
+ for (const p of catalog) for (const m of p.sources.find(s=>s.id==="direct")!.methods) {
expect(m.fields.length).toBeGreaterThan(0); expect(m.guidance.steps.length).toBeGreaterThan(1);
expect(m.guidance.url).toMatch(/^https:\/\//); expect(m.guidance.reference).toMatch(/^https:\/\//);
}
diff --git a/lib/infra/clients.ts b/lib/infra/clients.ts
index d2ffb266..175217cf 100644
--- a/lib/infra/clients.ts
+++ b/lib/infra/clients.ts
@@ -1,3 +1,5 @@
+import { currentIntegrationSelection, resolveIntegration } from "./connection-service";
+import { verifyExternalIntegration } from "./connection-external";
import { doctorAdditionalProvider } from "./additional-doctor";
import { readInfraProvider } from "./store";
import type { InfraDoctorResult, InfraProviderId, InfraProviderValues } from "./types";
@@ -12,6 +14,9 @@ export { upsertHostingerDns } from "./hostinger";
export async function doctorInfraProvider(id: InfraProviderId, candidate?: InfraProviderValues): Promise<InfraDoctorResult> {
try {
+ if(!candidate){
+ try{const route=await resolveIntegration(id,currentIntegrationSelection());if(route.source!=="direct")return { ...await verifyExternalIntegration(id,{user:route.user,connection:route.id}), id };}catch(error){if(!["connection_not_found","user_required"].includes((error as Error).message))throw error;}
+ }
const detail = id === "dokploy"
? await doctorDokploy(candidate)
: id === "cloudflare"
diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.ts
new file mode 100644
index 00000000..c831d07a
--- /dev/null
+++ b/lib/infra/connection-dispatch.ts
@@ -0,0 +1,38 @@
+import { integrationManage } from "./connection-manage";
+import { integrationQuery, withIntegrationSelection, resolveIntegration } from "./connection-service";
+import { authorizeIntegration, composioConnectionCall } from "./connection-external";
+import { IntegrationError, identity, metadataOnly, type ConnectionSelector } from "./identity";
+import { doctorInfraProvider, ensureDokployProject, listDokployProjects, listCloudflareZones, upsertCloudflareDns, upsertHostingerDns } from "./clients";
+import { isInfraProviderId } from "./catalog";
+export const safeActionInput=(input:Record<string,unknown>)=>Object.fromEntries(Object.entries(input).filter(([key])=>key!=="workflow_id"));
+export const selectionFrom=(a:Record<string,unknown>):ConnectionSelector=>({user:typeof a.user==="string"?a.user:undefined,connection:typeof a.connection==="string"?a.connection:undefined,cwd:typeof a.cwd==="string"?a.cwd:undefined});
+export async function manageIntegrationAction(raw:Record<string,unknown>){
+ const a=safeActionInput(raw);metadataOnly(a);
+ if(a.action!=="connection.authorize")return integrationManage(a);
+ if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);
+ if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection","authConfigId","brokerConnection","createManaged"].includes(k)))throw new IntegrationError("invalid_management_fields");
+ return authorizeIntegration(identity(a.provider,"provider"),selectionFrom(a),{authConfigId:typeof a.authConfigId==="string"?identity(a.authConfigId):undefined,brokerConnection:typeof a.brokerConnection==="string"?identity(a.brokerConnection):undefined,createManaged:a.createManaged===true});
+}
+export async function executeIntegrationAction(raw:Record<string,unknown>){
+ const a=safeActionInput(raw);metadataOnly(a);
+ if(Object.keys(a).some(k=>!["user","provider","connection","operation","arguments","tool","confirm"].includes(k)))throw new IntegrationError("invalid_execution_fields");
+ const user=identity(a.user,"user"),provider=identity(a.provider,"provider"),connection=identity(a.connection,"connection"),selection={user,connection};
+ const route=await resolveIntegration(provider,selection),operation=String(a.operation);
+ if(operation==="route")return route;
+ if(operation==="verify")return withIntegrationSelection(selection,()=>{if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider");return doctorInfraProvider(provider);});
+ if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);
+ const args=a.arguments??{};if(!args||typeof args!=="object"||Array.isArray(args))throw new IntegrationError("invalid_tool_arguments");
+ if(operation==="composio.tool")return composioConnectionCall(provider,selection,String(a.tool),args as Record<string,unknown>);
+ const verbs:Record<string,{provider:string;fields:string[];run:()=>Promise<unknown>}>= {
+ "dokploy.projects.list":{provider:"dokploy",fields:[],run:()=>listDokployProjects()},
+ "dokploy.project.ensure":{provider:"dokploy",fields:["name"],run:()=>ensureDokployProject(String((args as Record<string,unknown>).name))},
+ "cloudflare.zones.list":{provider:"cloudflare",fields:[],run:()=>listCloudflareZones()},
+ "cloudflare.dns.upsert":{provider:"cloudflare",fields:["name","type","content","ttl","proxied"],run:()=>upsertCloudflareDns(args as Parameters<typeof upsertCloudflareDns>[0])},
+ "hostinger.dns.upsert":{provider:"hostinger",fields:["name","type","content","ttl"],run:()=>upsertHostingerDns(args as Parameters<typeof upsertHostingerDns>[0])},
+ };
+ const verb=verbs[operation];if(!verb||verb.provider!==provider)throw new IntegrationError("provider_operation_mismatch");
+ if(route.source!=="direct")throw new IntegrationError("external_source_requires_own_executor",409);
+ if(Object.keys(args).some(k=>!verb.fields.includes(k)))throw new IntegrationError("invalid_tool_arguments");
+ return withIntegrationSelection(selection,async()=>({identity:route,result:await verb.run()}));
+}
+export const queryIntegrationAction=(input:Record<string,unknown>)=>integrationQuery(safeActionInput(input));
diff --git a/lib/infra/connection-external.ts b/lib/infra/connection-external.ts
new file mode 100644
index 00000000..fa7329ad
--- /dev/null
+++ b/lib/infra/connection-external.ts
@@ -0,0 +1,71 @@
+import {randomUUID} from "node:crypto";
+import { readIntegrationState, mutateIntegrationState } from "./connection-storage";
+import { selectConnection, IntegrationError, assertNotBusy, type ConnectionSelector } from "./identity";
+import { composioDefinition, nativeDefinition } from "./connection-registry";
+import { summaryIn } from "./connection-service";
+import { request, obj } from "./http";
+const BASE="https://backend.composio.dev/api/v3.1";
+async function api(key:string,endpoint:string,body?:unknown){
+ let result;try{result=await request(BASE+endpoint,{method:body===undefined?"GET":"POST",headers:{"x-api-key":key,accept:"application/json","content-type":"application/json"},...(body===undefined?{}:{body:JSON.stringify(body)})});}catch{throw new IntegrationError("composio_unreachable",502);}
+ if(!result.ok)throw new IntegrationError(`composio_http_${result.status}`,502);return obj(result.body);
+}
+async function context(provider:string,selection:ConnectionSelector,brokerId?:string){
+ if(!selection.user||!selection.connection)throw new IntegrationError("choose_user_and_connection",409);
+ const d=await readIntegrationState(),r=selectConnection(d,provider,selection),c=r.connection;
+ if(c.source!=="composio")throw new IntegrationError("composio_source_required");
+ const broker=selectConnection(d,"composio",{user:r.user,connection:brokerId??c.external?.brokerConnection,source:"direct",authMethod:"project"}).connection;
+ if(!broker.values.apiKey)throw new IntegrationError("composio_project_key_required",409);
+ return{d,r,c,broker,definition:composioDefinition(provider)!};
+}
+async function authorizeUnlocked(provider:string,selection:ConnectionSelector,options:{authConfigId?:string;brokerConnection?:string;createManaged?:boolean}={}){
+ const {r,c,broker,definition}=await context(provider,selection,options.brokerConnection);
+ if(c.external?.connectedAccountId)throw new IntegrationError("already_linked_sync_first",409);
+ const scheme=c.authMethod==="oauth2"?"OAUTH2":"API_KEY";let config:Record<string,unknown>;
+ const configId=options.authConfigId??c.external?.authConfigId;
+ if(configId){config=await api(broker.values.apiKey,`/auth_configs/${encodeURIComponent(configId)}`);}
+ else{
+ const result=await api(broker.values.apiKey,`/auth_configs?toolkit_slug=${encodeURIComponent(definition.toolkit)}&show_disabled=false&limit=50`);
+ const rows=(Array.isArray(result.items)?result.items:[]).map(obj).filter(x=>obj(x.toolkit).slug===definition.toolkit&&(x.auth_scheme??obj(x.auth_config).auth_scheme)===scheme&&(!x.status||x.status==="ENABLED"));
+ if(rows.length>1)throw new IntegrationError("choose_auth_config_id",409);
+ if(rows.length)config=rows[0];
+ else if(definition.managed&&options.createManaged){const result=await api(broker.values.apiKey,"/auth_configs",{toolkit:{slug:definition.toolkit}});config={...obj(result.auth_config),toolkit:result.toolkit};}
+ else throw new IntegrationError("matching_auth_config_required",409);
+ }
+ const nested=obj(config.auth_config),actual=String(config.id??nested.id??""),toolkit=String(obj(config.toolkit).slug??"");
+ if(!actual||toolkit!==definition.toolkit||(config.auth_scheme??nested.auth_scheme)!==scheme||(config.status&&config.status!=="ENABLED"))throw new IntegrationError("auth_config_mismatch",409);
+ const namespace=await readIntegrationState();const remoteUserId=`mso:${namespace.instanceId}:${namespace.users[r.user].uid}`,linked=await api(broker.values.apiKey,"/connected_accounts/link",{auth_config_id:actual,user_id:remoteUserId,alias:c.uid});
+ const id=linked.connected_account_id??linked.id;let url:URL;try{url=new URL(String(linked.redirect_url));}catch{throw new IntegrationError("invalid_authorization_link",502);}
+ if(typeof id!=="string"||!id||url.protocol!=="https:"||url.username||url.password||!["connect.composio.dev","backend.composio.dev","platform.composio.dev"].includes(url.hostname))throw new IntegrationError("invalid_authorization_link",502);
+ const safe=await mutateIntegrationState(d=>{const now=selectConnection(d,provider,selection).connection;if(now.uid!==c.uid||now.revision!==c.revision)throw new IntegrationError("connection_changed",409);now.external={connectedAccountId:id,authConfigId:actual,brokerConnection:broker.id,toolkit:definition.toolkit,remoteUserId,status:"INITIALIZING",checkedAt:Date.now()};now.revision++;return summaryIn(d,r.user,now);});
+ // The route/tool adapter must put this link ONLY in a private UI response.
+ return{connection:safe,privateUrl:url.href};
+}
+export async function verifyExternalIntegration(provider:string,selection:ConnectionSelector){
+ const d=await readIntegrationState(),r=selectConnection(d,provider,selection);
+ if(r.connection.source==="native-mcp")return{id:provider,ok:null,detail:"Authorize and verify through the provider-owned MCP client; no local credential fallback",user:r.user,connection:r.connection.id,endpoint:nativeDefinition(provider)?.url};
+ const {c,broker,definition}=await context(provider,selection);const id=c.external?.connectedAccountId;
+ if(!id)return{id:provider,ok:null,detail:"authorization required",user:r.user,connection:c.id};
+ const raw=await api(broker.values.apiKey,`/connected_accounts/${encodeURIComponent(id)}`);
+ if(raw.id!==id||obj(raw.toolkit).slug!==definition.toolkit||(c.external?.remoteUserId&&raw.user_id!==c.external.remoteUserId)||(c.external?.authConfigId&&obj(raw.auth_config).id!==c.external.authConfigId))throw new IntegrationError("connected_account_identity_mismatch",409);
+ const state=typeof raw.status==="string"&&/^[A-Z_]{1,40}$/.test(raw.status)?raw.status:"UNKNOWN";
+ await mutateIntegrationState(d=>{const now=selectConnection(d,provider,selection).connection;if(now.uid!==c.uid||now.revision!==c.revision)throw new IntegrationError("connection_changed",409);now.external={...now.external,status:state,checkedAt:Date.now()};});
+ return{id:provider,ok:state==="ACTIVE",detail:state,user:r.user,connection:c.id};
+}
+async function executeUnlocked(provider:string,selection:ConnectionSelector,tool:string,args:Record<string,unknown>){
+ const {c,broker,definition}=await context(provider,selection);
+ if(c.external?.status!=="ACTIVE"||!c.external.connectedAccountId)throw new IntegrationError("active_connected_account_required",409);
+ if(!/^[A-Z][A-Z0-9_]{2,180}$/.test(tool)||!tool.startsWith(definition.toolkit.toUpperCase()+"_"))throw new IntegrationError("toolkit_tool_mismatch");
+ // Revalidate identity/status immediately before acting; never select another account implicitly.
+ const verified=await verifyExternalIntegration(provider,selection);if(verified.ok!==true)throw new IntegrationError("active_connected_account_required",409);
+ const result=await api(broker.values.apiKey,`/tools/execute/${encodeURIComponent(tool)}`,{connected_account_id:c.external.connectedAccountId,arguments:args});
+ function redact(v:unknown,depth=0):unknown{if(depth>16)return"[depth limited]";if(typeof v==="string")return v.split(broker.values.apiKey).join("[redacted]");if(Array.isArray(v))return v.map(x=>redact(x,depth+1));if(v&&typeof v==="object")return Object.fromEntries(Object.entries(v).map(([k,x])=>[k,/token|password|secret|api.?key|authorization|credential/i.test(k)?"[redacted]":redact(x,depth+1)]));return v;}
+ return{user:selection.user,provider,connection:c.id,source:c.source,result:redact(result)};
+}
+
+async function leased<T>(provider:string,selection:ConnectionSelector,brokerId:string|undefined,fn:(brokerId:string)=>Promise<T>):Promise<T>{
+ const ctx=await context(provider,selection,brokerId),lease={id:randomUUID(),until:Date.now()+120000};
+ await mutateIntegrationState(d=>{for(const [p,id,expected] of [[provider,ctx.c.id,ctx.c],["composio",ctx.broker.id,ctx.broker]] as const){const c=selectConnection(d,p,{user:ctx.r.user,connection:id}).connection;assertNotBusy(c);if(c.uid!==expected.uid||c.revision!==expected.revision)throw new IntegrationError("connection_changed",409);c.lease=lease;}});
+ try{return await fn(ctx.broker.id);}finally{await mutateIntegrationState(d=>{for(const rows of Object.values(d.users[ctx.r.user]?.connections??{}))for(const c of Object.values(rows))if(c.lease?.id===lease.id)delete c.lease;});}
+}
+export const authorizeIntegration=(provider:string,selection:ConnectionSelector,options:Parameters<typeof authorizeUnlocked>[2]={})=>leased(provider,selection,options?.brokerConnection,brokerId=>authorizeUnlocked(provider,selection,{...options,brokerConnection:brokerId}));
+export const composioConnectionCall=(provider:string,selection:ConnectionSelector,tool:string,args:Record<string,unknown>)=>leased(provider,selection,undefined,()=>executeUnlocked(provider,selection,tool,args));
diff --git a/lib/infra/connection-manage.ts b/lib/infra/connection-manage.ts
new file mode 100644
index 00000000..50ac4778
--- /dev/null
+++ b/lib/infra/connection-manage.ts
@@ -0,0 +1,58 @@
+import {connectionMethod} from "./connection-registry";
+import { randomUUID } from "node:crypto";
+import { mutateIntegrationState } from "./connection-storage";
+import { createConnectionIn, summaryIn } from "./connection-service";
+import { IntegrationError, identity, connectionLabel, canonicalFolder, selectConnection, metadataOnly, assertNotBusy, type ConnectionSource } from "./identity";
+export const INTEGRATION_ACTIONS=["user.create","user.rename","user.duplicate","user.delete","user.default","folder.map","folder.unmap","connection.create","connection.rename","connection.default","connection.delete","credential.delete"] as const;
+export async function integrationManage(input:Record<string,unknown>){
+ metadataOnly(input);if(input.confirm!==true)throw new IntegrationError("confirmation_required",403);
+ const shapes:Record<string,string[]>={
+ "user.create":["user","label"],"user.rename":["user","target","label"],"user.duplicate":["user","target","label","copyCredentials"],"user.delete":["user"],"user.default":["user"],
+ "folder.map":["user","path","provider","connection"],"folder.unmap":["path"],"connection.create":["user","provider","connection","label","source","authMethod","makeDefault"],
+ "connection.rename":["user","provider","connection","label"],"connection.default":["user","provider","connection"],"connection.delete":["user","provider","connection"],"credential.delete":["user","provider","connection","key"],
+ };
+ const action=String(input.action);if(!shapes[action]||Object.keys(input).some(k=>!["action","confirm",...shapes[action]].includes(k)))throw new IntegrationError("invalid_management_fields");
+ return mutateIntegrationState(state=>{
+ if(action==="folder.unmap"){const p=canonicalFolder(String(input.path));state.bindings=state.bindings.filter(b=>b.path!==p);return{ok:true,action};}
+ const user=identity(input.user,"user");
+ if(action==="user.create"){
+ if(Object.hasOwn(state.users,user))throw new IntegrationError("user_exists",409);
+ state.users[user]={id:user,uid:randomUUID(),label:connectionLabel(input.label??user),connections:{},defaults:{}};if(!state.defaultUser)state.defaultUser=user;return{ok:true,action,user};
+ }
+ const profile=state.users[user];if(!profile)throw new IntegrationError("user_not_found",404);
+ if(action==="user.default"){state.defaultUser=user;return{ok:true,action,user};}
+ if(action==="user.delete"){
+ Object.values(profile.connections).flatMap(Object.values).forEach(assertNotBusy);
+ delete state.users[user];state.bindings=state.bindings.filter(b=>b.user!==user);if(state.defaultUser===user)state.defaultUser=null;return{ok:true,action,user};
+ }
+ if(action==="user.rename"||action==="user.duplicate"){
+ const target=identity(input.target,"target");if(Object.hasOwn(state.users,target))throw new IntegrationError("user_exists",409);
+ Object.values(profile.connections).flatMap(Object.values).forEach(assertNotBusy);
+ const copy=structuredClone(profile);copy.id=target;if(action==="user.duplicate")copy.uid=randomUUID();copy.label=connectionLabel(input.label??target);
+ for(const rows of Object.values(copy.connections))for(const c of Object.values(rows)){c.uid=randomUUID();c.revision++;c.updatedAt=Date.now();delete c.lease;if(action==="user.duplicate"&&input.copyCredentials!==true){c.values={};delete c.verifiedAt;}if(action==="user.duplicate"&&c.source!=="direct"){c.external=undefined;delete c.verifiedAt;}}
+ state.users[target]=copy;
+ if(action==="user.rename"){delete state.users[user];for(const b of state.bindings)if(b.user===user)b.user=target;if(state.defaultUser===user)state.defaultUser=target;}
+ return{ok:true,action,user:target};
+ }
+ if(action==="folder.map"){
+ const p=canonicalFolder(String(input.path)),old=state.bindings.find(b=>b.path===p),connections=old?.user===user?{...old.connections}:{};
+ if(input.provider||input.connection){const provider=identity(input.provider,"provider"),connection=identity(input.connection,"connection");selectConnection(state,provider,{user,connection});connections[provider]=connection;}
+ state.bindings=state.bindings.filter(b=>b.path!==p);state.bindings.push({path:p,user,connections});return{ok:true,action,user,path:p};
+ }
+ const provider=identity(input.provider,"provider"),connection=identity(input.connection,"connection");
+ if(action==="connection.create"){const c=createConnectionIn(state,{user,provider,connection,label:input.label as string|undefined,source:input.source as ConnectionSource|undefined,authMethod:input.authMethod as string|undefined,makeDefault:input.makeDefault===true});return{ok:true,action,connection:summaryIn(state,user,c)};}
+ const {connection:c}=selectConnection(state,provider,{user,connection});assertNotBusy(c);
+ if(action==="connection.default")profile.defaults[provider]=connection;
+ if(action==="connection.rename"){c.label=connectionLabel(input.label);c.updatedAt=Date.now();}
+ if(action==="connection.delete"){
+ if(state.bindings.some(b=>b.user===user&&b.connections[provider]===connection))throw new IntegrationError("connection_has_folder_binding",409);
+ if(Object.values(profile.connections).some(rows=>Object.values(rows).some(x=>x.source==="composio"&&x.external?.brokerConnection===connection&&provider==="composio")))throw new IntegrationError("broker_has_linked_connections",409);
+ delete profile.connections[provider][connection];if(profile.defaults[provider]===connection)delete profile.defaults[provider];return{ok:true,action,user,provider,connection};
+ }
+ if(action==="credential.delete"){
+ if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden");
+ if(input.key!==undefined){const key=identity(input.key,"key");if(!connectionMethod(provider,c.source,c.authMethod).fields.some(f=>f.key===key))throw new IntegrationError("unknown_credential_field");delete c.values[key];}else c.values={};c.revision++;delete c.verifiedAt;c.updatedAt=Date.now();
+ }
+ return{ok:true,action,connection:summaryIn(state,user,c)};
+ });
+}
diff --git a/lib/infra/connection-model.test.ts b/lib/infra/connection-model.test.ts
new file mode 100644
index 00000000..c73e0f64
--- /dev/null
+++ b/lib/infra/connection-model.test.ts
@@ -0,0 +1,84 @@
+import {beforeEach,afterEach,describe,it,expect,vi} from "vitest";
+import {promises as fs} from "node:fs";
+import os from "node:os";
+import path from "node:path";
+vi.mock("server-only",()=>({}));
+let root:string,file:string;
+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-model-test-"));file=path.join(root,"infra.json");process.env.OS_INFRA_STORE=file;vi.resetModules();});
+afterEach(async()=>{vi.unstubAllGlobals();delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+const KEY_A="synthetic_key_account_alpha_123456",KEY_B="synthetic_key_account_beta_1234567";
+async function fixture(){
+ const {integrationManage:manage}=await import("./connection-manage");
+ const service=await import("./connection-service");
+ await manage({action:"user.create",confirm:true,user:"alice"});await manage({action:"user.create",confirm:true,user:"bob"});
+ async function add(user:string,provider:string,id:string,method:string,values:Record<string,string>,source="direct"){
+ await manage({action:"connection.create",confirm:true,user,provider,connection:id,authMethod:method,source});
+ if(source==="direct"&&Object.keys(values).length){const snap=await service.credentialSnapshot(provider,{user,connection:id});await service.saveConnectionValues(provider,{user,connection:id},values,snap.connection,true);}
+ }
+ return{manage,...service,add};
+}
+describe("native credential identity core",()=>{
+ it("projects legacy state without writes, then atomically migrates with an exact protected backup",async()=>{
+ const original=JSON.stringify({providers:{composio:{apiKey:KEY_A,orgApiKey:KEY_B},"convex-cloud":{personalToken:KEY_A,deployKey:KEY_B,deploymentName:"test-deployment"},github:{apiKey:KEY_A}}},null,2);
+ await fs.writeFile(file,original,{mode:0o600});const {readIntegrationState,migrateIntegrationStore}=await import("./connection-storage");
+ const projected=await readIntegrationState();expect(await fs.readFile(file,"utf8")).toBe(original);
+ expect(Object.keys(projected.users.legacy.connections.composio)).toEqual(["project","organization"]);
+ expect(projected.users.legacy.defaults.composio).toBe("organization");expect(projected.users.legacy.defaults["convex-cloud"]).toBe("deployment");
+ await migrateIntegrationStore();const state=await readIntegrationState();expect(state.version).toBe(2);expect(state.users.legacy.connections.github.default.values.apiKey).toBe(KEY_A);
+ expect(await fs.readFile(file+".v1-backup.json","utf8")).toBe(original);expect((await fs.stat(file+".v1-backup.json")).mode&0o777).toBe(0o600);
+ expect((await readIntegrationState()).instanceId).toBe(state.instanceId);
+ });
+ it("isolates two users and five named Convex account/deployment connections",async()=>{
+ const f=await fixture();await f.add("alice","convex-cloud","admin","personal",{personalToken:KEY_A});
+ for(const id of ["baton","mimin-production","mimin-staging","play-together"]){await f.add("alice","convex-cloud",id,"deployment",{deployKey:KEY_A+id,deploymentName:id});}
+ await f.add("bob","convex-cloud","mimin-production","deployment",{deployKey:KEY_B,deploymentName:"different-deployment"});
+ const state=await f.integrationSnapshot({user:"alice"});expect(state.connections).toHaveLength(5);expect(JSON.stringify(state)).not.toContain(KEY_A);
+ expect((await f.directConnectionValues("convex-cloud",{user:"bob",connection:"mimin-production"})).deployKey).toBe(KEY_B);
+ expect((await f.resolveIntegration("convex-cloud",{user:"alice",connection:"mimin-production"})).scope).toBe("deployment");
+ await expect(f.resolveIntegration("convex-cloud",{user:"missing",connection:"admin"})).rejects.toMatchObject({code:"user_not_found"});
+ await expect(f.resolveIntegration("convex-cloud",{user:"alice",connection:"missing"})).rejects.toMatchObject({code:"connection_not_found"});
+ });
+ it("uses explicit user/connection before folder/default context and refuses ambiguity",async()=>{
+ const f=await fixture();await f.add("alice","github","work","direct",{apiKey:KEY_A});await f.add("alice","github","personal","direct",{apiKey:KEY_B});await f.add("bob","github","work","direct",{apiKey:KEY_B});
+ await f.manage({action:"folder.map",confirm:true,user:"alice",path:root,provider:"github",connection:"personal"});
+ expect((await f.resolveIntegration("github",{cwd:path.join(root,"project")})).id).toBe("personal");
+ expect((await f.resolveIntegration("github",{cwd:root,user:"bob"})).id).toBe("work");
+ expect((await f.resolveIntegration("github",{cwd:root,user:"alice",connection:"work"})).id).toBe("work");
+ await expect(f.manage({action:"connection.delete",confirm:true,user:"alice",provider:"github",connection:"personal"})).rejects.toMatchObject({code:"connection_has_folder_binding"});
+ await f.manage({action:"folder.unmap",confirm:true,path:root});
+ const {mutateIntegrationState}=await import("./connection-storage");await mutateIntegrationState(d=>{delete d.users.alice.defaults.github;});
+ await expect(f.resolveIntegration("github",{user:"alice"})).rejects.toMatchObject({code:"connection_ambiguous"});
+ });
+ it("shares the selected credential with the actual Dokploy client without mixing concurrent calls",async()=>{
+ const f=await fixture();await f.add("alice","dokploy","work","direct",{apiUrl:"http://127.0.0.1:4123",apiKey:KEY_A});await f.add("bob","dokploy","work","direct",{apiUrl:"http://127.0.0.1:4124",apiKey:KEY_B});
+ const calls:Array<{url:string;key:string|null}>=[];vi.stubGlobal("fetch",vi.fn(async(input:RequestInfo|URL,init?:RequestInit)=>{const req=new Request(input,init);calls.push({url:req.url,key:req.headers.get("x-api-key")});await new Promise(r=>setTimeout(r,5));return new Response(JSON.stringify([{projectId:"one",name:"Project"}]),{status:200});}));
+ const {listDokployProjects}=await import("./dokploy");
+ await Promise.all([f.withIntegrationSelection({user:"alice",connection:"work"},()=>listDokployProjects()),f.withIntegrationSelection({user:"bob",connection:"work"},()=>listDokployProjects())]);
+ expect(calls).toContainEqual({url:"http://127.0.0.1:4123/api/project.all",key:KEY_A});expect(calls).toContainEqual({url:"http://127.0.0.1:4124/api/project.all",key:KEY_B});
+ });
+ it("pins credentials for the duration of a compound operation and never changes defaults",async()=>{
+ const f=await fixture();await f.add("alice","github","work","direct",{apiKey:KEY_A});
+ await f.withIntegrationSelection({user:"alice",connection:"work"},async()=>{
+ expect((await f.directConnectionValues("github")).apiKey).toBe(KEY_A);const snap=await f.credentialSnapshot("github",{user:"alice",connection:"work"});await f.saveConnectionValues("github",{user:"alice",connection:"work"},{apiKey:KEY_B},snap.connection);
+ expect((await f.directConnectionValues("github")).apiKey).toBe(KEY_A);
+ });expect((await f.directConnectionValues("github",{user:"alice",connection:"work"})).apiKey).toBe(KEY_B);
+ });
+ it("distinguishes external sources and refuses silent local-key substitution",async()=>{
+ const f=await fixture();await f.add("alice","github","direct","direct",{apiKey:KEY_A});await f.add("alice","github","hosted","oauth2",{},"composio");await f.add("alice","vercel","native","provider-oauth",{},"native-mcp");
+ await expect(f.directConnectionValues("github",{user:"alice",connection:"hosted"})).rejects.toMatchObject({code:"external_source_requires_own_executor"});
+ const native=await f.resolveIntegration("vercel",{user:"alice",connection:"native"});expect(native.execution).toMatchObject({route:"provider-mcp",endpoint:"https://mcp.vercel.com"});
+ await expect(f.resolveIntegration("github",{user:"alice",connection:"hosted",source:"direct"})).rejects.toMatchObject({code:"connection_source_mismatch"});
+ });
+ it("duplicates metadata by default, requires explicit key copying, and migrates folder mappings on rename",async()=>{
+ const f=await fixture();await f.add("alice","github","work","direct",{apiKey:KEY_A});
+ await f.manage({action:"user.duplicate",confirm:true,user:"alice",target:"empty-copy"});expect(await f.directConnectionValues("github",{user:"empty-copy",connection:"work"})).toEqual({});
+ await f.manage({action:"user.duplicate",confirm:true,user:"alice",target:"key-copy",copyCredentials:true});expect((await f.directConnectionValues("github",{user:"key-copy",connection:"work"})).apiKey).toBe(KEY_A);
+ await f.manage({action:"folder.map",confirm:true,user:"alice",path:root});await f.manage({action:"user.rename",confirm:true,user:"alice",target:"renamed"});expect((await f.integrationQuery({view:"which",cwd:root}) as {user:string}).user).toBe("renamed");
+ });
+ it("rejects secret-shaped machine input, unconfirmed writes, and identity pollution",async()=>{
+ const f=await fixture();await expect(f.manage({action:"user.create",user:"eve"})).rejects.toMatchObject({code:"confirmation_required"});
+ await expect(f.integrationQuery({view:"snapshot",nested:{token:"synthetic"}})).rejects.toMatchObject({code:"secret_input_forbidden"});
+ await expect(f.manage({action:"user.create",confirm:true,user:"constructor"})).rejects.toThrow("invalid_user");
+ expect(JSON.stringify(await f.integrationSnapshot())).not.toContain(KEY_A);
+ });
+});
diff --git a/lib/infra/connection-registry.ts b/lib/infra/connection-registry.ts
new file mode 100644
index 00000000..7fb1524c
--- /dev/null
+++ b/lib/infra/connection-registry.ts
@@ -0,0 +1,39 @@
+import { listInfraProviderDefinitions, getInfraProviderDefinition, isInfraProviderId } from "./catalog";
+import { setupFields, setupGuidance, setupMethods, type SetupMethod } from "./setup-guidance";
+import { IntegrationError, type ConnectionSource, type IntegrationConnection } from "./identity";
+const COMPOSIO: Record<string, {toolkit:string; managed:boolean; methods:string[]}> = {
+ github:{toolkit:"github",managed:true,methods:["oauth2"]}, vercel:{toolkit:"vercel",managed:false,methods:["oauth2","api-key"]},
+ cloudflare:{toolkit:"cloudflare",managed:false,methods:["api-key"]}, resend:{toolkit:"resend",managed:false,methods:["api-key"]},
+ stripe:{toolkit:"stripe",managed:false,methods:["api-key"]}, supabase:{toolkit:"supabase",managed:false,methods:["oauth2","api-key"]},
+};
+const NATIVE: Record<string,{url:string;reference:string}> = {
+ vercel:{url:"https://mcp.vercel.com",reference:"https://vercel.com/docs/mcp/vercel-mcp"},
+ github:{url:"https://api.githubcopilot.com/mcp/",reference:"https://docs.github.com/en/copilot/how-tos/provide-context/use-mcp/use-the-github-mcp-server"},
+ supabase:{url:"https://mcp.supabase.com/mcp",reference:"https://supabase.com/docs/guides/getting-started/mcp"},
+};
+export function providerDefinition(provider:string) {
+ if (!isInfraProviderId(provider)) throw new IntegrationError("unknown_provider",404);
+ return getInfraProviderDefinition(provider);
+}
+export function connectionMethods(provider:string, source:ConnectionSource) {
+ const p=providerDefinition(provider);
+ if(source==="direct") return setupMethods(p.id).map(m=>({id:m.id as string,label:m.label,scope:provider==="convex-cloud"?(m.id==="deployment"?"deployment":"account"):provider==="composio"?m.id:provider==="dokploy"?"server":"account",fields:setupFields(p.id,m.id),guidance:setupGuidance(p.id,m.id)}));
+ if(source==="composio" && COMPOSIO[provider]) return COMPOSIO[provider].methods.map(id=>({id,label:id==="oauth2"?"OAuth2":"Hosted API key",scope:"account",fields:[],guidance:{url:"https://platform.composio.dev",reference:`https://docs.composio.dev/toolkits/${COMPOSIO[provider].toolkit}`,steps:["Configure a Composio project key under this same credential user.","Choose a matching authentication configuration for this provider and method.","Open the hosted authorization link. Enter credentials only on the provider/Composio page.","Return and refresh status. MSO stores routing identifiers, not provider OAuth tokens."]}}));
+ if(source==="native-mcp" && NATIVE[provider])return[{id:"provider-oauth",label:"Provider-owned MCP / OAuth",scope:"account",fields:[],guidance:{url:NATIVE[provider].reference,reference:NATIVE[provider].reference,steps:["Connect the provider-owned MCP server in your client.","Complete authorization in that provider's browser flow.","Use this named MSO connection to identify the intended provider route; the authenticated MCP session remains client-owned.","MSO does not copy provider access/refresh tokens or silently fall back to a local key."]}}];
+ throw new IntegrationError("unsupported_connection_source");
+}
+export function connectionMethod(provider:string,source:ConnectionSource,method?:string){
+ const methods=connectionMethods(provider,source), selected=method?methods.find(m=>m.id===method):methods[0];
+ if(!selected)throw new IntegrationError("unsupported_auth_method");return selected;
+}
+export function connectionSources(provider:string){return ["direct",...(COMPOSIO[provider]?["composio"]:[]),...(NATIVE[provider]?["native-mcp"]:[])] as ConnectionSource[];}
+export function connectionCatalog(){return listInfraProviderDefinitions().map(p=>({id:p.id,title:p.title,description:p.description,sources:connectionSources(p.id).map(id=>({id,label:id==="direct"?"MSO direct":id==="composio"?"Composio":"Provider MCP",methods:connectionMethods(p.id,id)}))}));}
+export function connectionSummary(user:string,c:IntegrationConnection,isDefault=false){
+ const method=connectionMethod(c.provider,c.source,c.authMethod),missing=method.fields.filter(f=>f.required&&!c.values[f.key]).map(f=>f.key);
+ return {user,id:c.id,label:c.label,provider:c.provider,source:c.source,authMethod:c.authMethod,scope:c.scope,revision:c.revision,isDefault,missing,fields:method.fields.map(f=>({...f,stored:Boolean(c.values[f.key])})),state:c.source==="direct"?(missing.length?"incomplete":c.verifiedAt?"verified":"configured"):c.external?.status??"authorization-required",verifiedAt:c.verifiedAt??null,external:c.external??null};
+}
+export const composioDefinition=(provider:string)=>COMPOSIO[provider];
+export const nativeDefinition=(provider:string)=>NATIVE[provider];
+export function legacyMethod(provider:string,values:Record<string,string>):SetupMethod {
+ return provider==="composio"?(values.orgApiKey?"organization":"project"):provider==="convex-cloud"?(values.deployKey?"deployment":"personal"):"direct";
+}
diff --git a/lib/infra/connection-security.test.ts b/lib/infra/connection-security.test.ts
new file mode 100644
index 00000000..45672db6
--- /dev/null
+++ b/lib/infra/connection-security.test.ts
@@ -0,0 +1,65 @@
+import {beforeEach,afterEach,it,expect,vi} from "vitest";
+import {promises as fs} from "node:fs";
+import os from "node:os";
+import path from "node:path";
+vi.mock("server-only",()=>({}));
+let root:string;
+const A="synthetic_secret_alice_project_key",B="synthetic_secret_bob_project_key";
+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-identity-security-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+afterEach(async()=>{vi.unstubAllGlobals();delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+async function fixture(){
+ const {integrationManage:manage}=await import("./connection-manage"),service=await import("./connection-service"),external=await import("./connection-external");
+ for(const [user,key]of [["alice",A],["bob",B]]){
+ await manage({action:"user.create",user,confirm:true});await manage({action:"connection.create",user,provider:"composio",connection:"broker",source:"direct",authMethod:"project",confirm:true});
+ const snap=await service.credentialSnapshot("composio",{user,connection:"broker"});await service.saveConnectionValues("composio",{user,connection:"broker"},{apiKey:key},snap.connection);
+ await manage({action:"connection.create",user,provider:"github",connection:"work",source:"composio",authMethod:"oauth2",confirm:true});
+ }
+ return{manage,...service,...external};
+}
+it("binds Composio authorization to this user's broker and installation-scoped remote identity",async()=>{
+ const f=await fixture(),calls:Array<{url:string;headers:Headers;body:Record<string,unknown>|null}>=[];let remoteUser="";
+ vi.stubGlobal("fetch",vi.fn(async(url:RequestInfo|URL,init?:RequestInit)=>{
+ const req=new Request(url,init),body=req.method==="POST"?await req.json():null;calls.push({url:req.url,headers:req.headers,body});
+ if(req.url.includes("/auth_configs/"))return new Response(JSON.stringify({id:"ac_1",toolkit:{slug:"github"},auth_scheme:"OAUTH2",status:"ENABLED"}));
+ if(req.url.endsWith("/connected_accounts/link")){remoteUser=body.user_id;return new Response(JSON.stringify({connected_account_id:"ca_alice",redirect_url:"https://connect.composio.dev/link/test",link_token:"must-not-persist"}));}
+ if(req.url.endsWith("/connected_accounts/ca_alice"))return new Response(JSON.stringify({id:"ca_alice",toolkit:{slug:"github"},auth_config:{id:"ac_1"},user_id:remoteUser,status:"ACTIVE",state:{access_token:"must-not-persist"}}));
+ if(req.url.includes("/tools/execute/"))return new Response(JSON.stringify({data:{ok:true,access_token:"must-not-persist",echo:A}}));
+ return new Response("{}",{status:404});
+ }));
+ const linked=await f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1",brokerConnection:"broker"});expect(linked.privateUrl).toContain("https://connect.composio.dev/");
+ expect(remoteUser).toMatch(/^mso:[a-f0-9-]+:[a-f0-9-]+$/);expect(remoteUser).not.toContain("alice");
+ const verified=await f.verifyExternalIntegration("github",{user:"alice",connection:"work"});expect(verified.ok).toBe(true);
+ const output=await f.composioConnectionCall("github",{user:"alice",connection:"work"},"GITHUB_GET_THE_AUTHENTICATED_USER",{});expect(JSON.stringify(output)).not.toContain(A);expect(JSON.stringify(output)).not.toContain("must-not-persist");
+ for(const c of calls)expect(c.headers.get("x-api-key")).toBe(A);expect(calls.find(c=>c.url.includes("/tools/execute/"))?.body?.connected_account_id).toBe("ca_alice");
+ const stored=await fs.readFile(process.env.OS_INFRA_STORE!,"utf8");expect(stored).not.toContain("must-not-persist");expect(stored).not.toContain("https://connect.composio.dev/link/test");
+ await expect(f.composioConnectionCall("github",{user:"bob",connection:"work"},"GITHUB_GET_THE_AUTHENTICATED_USER",{})).rejects.toMatchObject({code:"active_connected_account_required"});
+});
+it("reserves a connection during hosted auth and refuses concurrent authorization or credential rotation",async()=>{
+ const f=await fixture();let release!:()=>void,entered!:()=>void;const reached=new Promise<void>(r=>entered=r),wait=new Promise<void>(r=>release=r);
+ vi.stubGlobal("fetch",vi.fn(async(url:RequestInfo|URL)=>{
+ if(String(url).includes("/auth_configs/")){entered();await wait;return new Response(JSON.stringify({id:"ac_1",toolkit:{slug:"github"},auth_scheme:"OAUTH2"}));}
+ return new Response(JSON.stringify({connected_account_id:"ca_1",redirect_url:"https://connect.composio.dev/link/test"}));
+ }));
+ const first=f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1"});await reached;
+ await expect(f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1"})).rejects.toMatchObject({code:"connection_busy"});
+ await expect(f.manage({action:"connection.delete",user:"alice",provider:"github",connection:"work",confirm:true})).rejects.toMatchObject({code:"connection_busy"});
+ const snap=await f.credentialSnapshot("composio",{user:"alice",connection:"broker"});await expect(f.saveConnectionValues("composio",{user:"alice",connection:"broker"},{apiKey:B},snap.connection)).rejects.toMatchObject({code:"connection_busy"});
+ release();await first;expect((await f.credentialSnapshot("composio",{user:"alice",connection:"broker"})).connection.lease).toBeUndefined();
+});
+it("invalidates an open form after rotation or delete/recreate, without touching another named connection",async()=>{
+ const f=await fixture();const setup=await import("./setup-capability");vi.stubGlobal("fetch",vi.fn(async()=>new Response("{}")));
+ const grant=await setup.openIntegrationSetup("composio","test-principal","project",{user:"alice",connection:"broker"});
+ const snap=await f.credentialSnapshot("composio",{user:"alice",connection:"broker"});await f.saveConnectionValues("composio",{user:"alice",connection:"broker"},{apiKey:B},snap.connection);
+ await expect(setup.consumeIntegrationSetup(grant.token,{apiKey:A})).rejects.toMatchObject({code:"connection_changed_reopen_setup"});
+ const renewed=await setup.openIntegrationSetup("composio","test-principal","project",{user:"alice",connection:"broker"});
+ await f.manage({action:"connection.delete",user:"alice",provider:"composio",connection:"broker",confirm:true});
+ await f.manage({action:"connection.create",user:"alice",provider:"composio",connection:"broker",authMethod:"project",confirm:true});
+ await expect(setup.consumeIntegrationSetup(renewed.token,{apiKey:A})).rejects.toMatchObject({code:"connection_changed_reopen_setup"});
+ expect((await f.credentialSnapshot("composio",{user:"bob",connection:"broker"})).connection.values.apiKey).toBe(B);
+});
+it("fails closed for symlink/malformed stores and refuses migration if backup bytes do not match",async()=>{
+ const {readIntegrationState,migrateIntegrationStore}=await import("./connection-storage"),file=process.env.OS_INFRA_STORE!;
+ await fs.writeFile(file,JSON.stringify({providers:{github:{apiKey:A}}}),{mode:0o600});await fs.writeFile(file+".v1-backup.json","different",{mode:0o600});
+ await expect(migrateIntegrationStore()).rejects.toMatchObject({code:"migration_backup_conflict"});expect(JSON.parse(await fs.readFile(file,"utf8")).version).toBeUndefined();
+ await fs.unlink(file);await fs.symlink(file+".v1-backup.json",file);await expect(readIntegrationState()).rejects.toThrow("unsafe");
+});
diff --git a/lib/infra/connection-service.ts b/lib/infra/connection-service.ts
new file mode 100644
index 00000000..9546ac73
--- /dev/null
+++ b/lib/infra/connection-service.ts
@@ -0,0 +1,66 @@
+import { randomUUID } from "node:crypto";
+import { AsyncLocalStorage } from "node:async_hooks";
+import { connectionCatalog, connectionMethod, connectionSummary, nativeDefinition } from "./connection-registry";
+import { readIntegrationState, mutateIntegrationState } from "./connection-storage";
+import { IntegrationError, identity, connectionLabel, selectConnection, resolveUser, folderBinding, metadataOnly, assertNotBusy, type ConnectionSelector, type IntegrationState, type IntegrationConnection, type ConnectionSource } from "./identity";
+import { normalizeInfraValues, isInfraProviderId } from "./catalog";
+const CONTEXT=new AsyncLocalStorage<{selector:ConnectionSelector; pinned:Map<string,Record<string,string>>}>();
+export function withIntegrationSelection<T>(selector:ConnectionSelector,fn:()=>T){return CONTEXT.run({selector,pinned:new Map()},fn);}
+export function currentIntegrationSelection():ConnectionSelector{return CONTEXT.getStore()?.selector??{};}
+export async function directConnectionValues(provider:string,selector:ConnectionSelector=currentIntegrationSelection()):Promise<Record<string,string>>{
+ const context=CONTEXT.getStore(),cached=context?.selector===selector?context.pinned.get(provider):undefined;if(cached)return{...cached};
+ const state=await readIntegrationState();if(!Object.keys(state.users).length&&!selector.user&&!selector.connection)return{};
+ let result;try{result=selectConnection(state,provider,selector);}catch(e){if(e instanceof IntegrationError&&e.code==="connection_not_found"&&!selector.connection&&!folderBinding(state,selector.cwd)?.connections[provider]&&!state.users[resolveUser(state,selector)]?.defaults[provider])return{};throw e;}
+ if(result.connection.source!=="direct")throw new IntegrationError("external_source_requires_own_executor",409);
+ const copy={...result.connection.values};if(context&&context.selector===selector)context.pinned.set(provider,copy);return copy;
+}
+export function summaryIn(state:IntegrationState,user:string,c:IntegrationConnection){return connectionSummary(user,c,state.users[user].defaults[c.provider]===c.id);}
+export async function resolveIntegration(provider:string,selector:ConnectionSelector={}){
+ const state=await readIntegrationState(),resolved=selectConnection(state,provider,selector),c=resolved.connection;
+ return{...summaryIn(state,resolved.user,c),resolution:resolved.reason,execution:c.source==="direct"?{route:"native-direct"}:c.source==="composio"?{route:"composio",connectedAccountId:c.external?.connectedAccountId??null,toolkit:c.external?.toolkit??null}:{route:"provider-mcp",endpoint:nativeDefinition(provider)?.url??null,authorization:"provider-client-owned"}};
+}
+export async function integrationSnapshot(selector:ConnectionSelector={}){
+ const state=await readIntegrationState();let user:string|null=null;try{user=resolveUser(state,selector);}catch(e){if(selector.user)throw e;}
+ const profiles=Object.values(state.users).map(u=>({id:u.id,label:u.label,isDefault:state.defaultUser===u.id,connectionCount:Object.values(u.connections).reduce((n,rows)=>n+Object.keys(rows).length,0)}));
+ const connections=user?Object.values(state.users[user].connections).flatMap(rows=>Object.values(rows).map(c=>summaryIn(state,user!,c))):[];
+ return{version:2,catalog:connectionCatalog(),users:profiles,user,bindings:state.bindings,connections,resolution:user?(selector.user?"explicit":folderBinding(state,selector.cwd)?"folder":"default"):"choose-user"};
+}
+export function createConnectionIn(state:IntegrationState,input:{user:string;provider:string;connection:string;label?:string;source?:ConnectionSource;authMethod?:string;makeDefault?:boolean}){
+ const user=identity(input.user,"user"),provider=identity(input.provider,"provider"),id=identity(input.connection,"connection"),profile=state.users[user];if(!profile)throw new IntegrationError("user_not_found",404);
+ const source=input.source??"direct",method=connectionMethod(provider,source,input.authMethod),rows=profile.connections[provider]??{};
+ if(Object.hasOwn(rows,id))throw new IntegrationError("connection_exists",409);
+ const c:IntegrationConnection={id,uid:randomUUID(),label:connectionLabel(input.label??id),provider,source,authMethod:method.id,scope:method.scope,revision:1,values:{},createdAt:Date.now(),updatedAt:Date.now()};
+ profile.connections[provider]={...rows,[id]:c};if(input.makeDefault||!Object.keys(rows).length)profile.defaults[provider]=id;return c;
+}
+export async function credentialSnapshot(provider:string,selector:ConnectionSelector){
+ const state=await readIntegrationState(),r=selectConnection(state,provider,selector);
+ if(r.connection.source!=="direct")throw new IntegrationError("external_secrets_forbidden",409);
+ return{user:r.user,connection:structuredClone(r.connection)};
+}
+export async function saveConnectionValues(provider:string,selector:ConnectionSelector,values:Record<string,unknown>,expected:{uid:string;revision:number},verified=true){
+ return mutateIntegrationState(state=>{
+ const r=selectConnection(state,provider,selector),c=r.connection;assertNotBusy(c);if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden",409);
+ if(c.uid!==expected.uid||c.revision!==expected.revision)throw new IntegrationError("connection_changed_reopen_setup",409);
+ if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider",404);
+ const method=connectionMethod(provider,c.source,c.authMethod),allowed=new Set(method.fields.map(f=>f.key));
+ if(Object.keys(values).some(k=>!allowed.has(k)))throw new IntegrationError("invalid_credential_fields");
+ const normalized=normalizeInfraValues(provider,values),candidate={...c.values,...normalized};
+ if(method.fields.some(f=>f.required&&!candidate[f.key]))throw new IntegrationError("required_fields_missing");
+ c.values=candidate;c.revision++;c.updatedAt=Date.now();if(verified)c.verifiedAt=Date.now();else delete c.verifiedAt;
+ return summaryIn(state,r.user,c);
+ });
+}
+export async function integrationQuery(input:Record<string,unknown>){
+ metadataOnly(input);const allowed=["view","user","provider","connection","cwd","source","authMethod"];
+ if(Object.keys(input).some(k=>!allowed.includes(k)))throw new IntegrationError("invalid_query_fields");
+ const selection=input as ConnectionSelector,view=input.view??"snapshot";
+ if(view==="catalog")return{catalog:connectionCatalog()};
+ if(view==="resolve")return resolveIntegration(identity(input.provider,"provider"),selection);
+ if(view==="request"){
+ const provider=identity(input.provider,"provider");const catalog=connectionCatalog().find(p=>p.id===provider);if(!catalog)throw new IntegrationError("unknown_provider",404);
+ if(!input.connection)return{provider,user:input.user??null,sources:catalog.sources,next:"choose named connection, source and auth; never pass keys through tool JSON"};
+ const route=await resolveIntegration(provider,selection);return{...route,guidance:connectionMethod(provider,route.source,route.authMethod).guidance,next:route.source==="direct"?"integration_setup_open with this user and connection":route.source==="composio"?"authorize, then sync until ACTIVE":"authorize the provider-owned MCP in your client"};
+ }
+ if(!["snapshot","users","connections","which"].includes(String(view)))throw new IntegrationError("unknown_query_view");
+ const out=await integrationSnapshot(selection);if(view==="users")return{users:out.users,user:out.user};if(view==="which")return{user:out.user,resolution:out.resolution,bindings:out.bindings};if(view==="connections")return{user:out.user,connections:out.connections.filter(c=>!input.provider||c.provider===input.provider)};return out;
+}
diff --git a/lib/infra/connection-storage.ts b/lib/infra/connection-storage.ts
new file mode 100644
index 00000000..340444f3
--- /dev/null
+++ b/lib/infra/connection-storage.ts
@@ -0,0 +1,58 @@
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import os from "node:os";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { connectionMethod, legacyMethod } from "./connection-registry";
+import { isInfraProviderId } from "./catalog";
+import { emptyIntegrationState, IntegrationError, identity, type IntegrationState, type IntegrationConnection } from "./identity";
+export const INFRA_STORE_PATH=process.env.OS_INFRA_STORE??path.join(os.homedir(),".mso","private","infra-providers.json");
+const MAX=1024*1024;
+async function readRaw():Promise<{raw:Record<string,unknown>;bytes:string}|null>{
+ let handle;
+ try{handle=await fs.open(INFRA_STORE_PATH,constants.O_RDONLY|constants.O_NOFOLLOW);const s=await handle.stat();
+ if(!s.isFile()||s.size<1||s.size>MAX||(s.mode&0o077)||(typeof process.getuid==="function"&&s.uid!==process.getuid()))throw new IntegrationError("unsafe_integration_store");
+ const bytes=await handle.readFile("utf8"),raw=JSON.parse(bytes);if(!raw||typeof raw!=="object"||Array.isArray(raw))throw new IntegrationError("invalid_integration_store");return{raw,bytes};
+ }catch(e){if((e as NodeJS.ErrnoException).code==="ENOENT")return null;throw new IntegrationError("invalid_or_unsafe_integration_store");}finally{await handle?.close();}
+}
+function validate(d:IntegrationState):IntegrationState{
+ if(d.version!==2||!d.instanceId||!d.users||typeof d.users!=="object"||Array.isArray(d.users)||!Array.isArray(d.bindings))throw new IntegrationError("invalid_integration_store");
+ for(const [id,u] of Object.entries(d.users)){identity(id);if(u.id!==id||!u.connections||!u.defaults)throw new IntegrationError("invalid_integration_store");
+ for(const [p,rows]of Object.entries(u.connections)){identity(p);for(const [cid,c]of Object.entries(rows)){identity(cid);if(c.id!==cid||c.provider!==p||!c.uid||!Number.isInteger(c.revision)||!c.values||typeof c.values!=="object"||Array.isArray(c.values)||Object.values(c.values).some(v=>typeof v!=="string"))throw new IntegrationError("invalid_connection_store");connectionMethod(c.provider,c.source,c.authMethod);if(c.source!=="direct"&&Object.keys(c.values).length)throw new IntegrationError("external_secrets_forbidden");}}
+ }
+ return d;
+}
+function projected(raw:Record<string,unknown>|undefined):IntegrationState{
+ if(!raw)return emptyIntegrationState();if(raw.version===2)return validate(raw as unknown as IntegrationState);
+ if(raw.version!==undefined)throw new IntegrationError("unsupported_store_version");
+ const d=emptyIntegrationState(),providers=raw.providers;
+ if(providers===undefined)return d;if(!providers||typeof providers!=="object"||Array.isArray(providers))throw new IntegrationError("invalid_legacy_store");
+ const profile={id:"legacy",uid:"legacy",label:"Existing MSO credentials",defaults:{} as Record<string,string>,connections:{} as Record<string,Record<string,IntegrationConnection>>};
+ for(const [provider,v] of Object.entries(providers)){
+ if(!isInfraProviderId(provider)||!v||typeof v!=="object"||Array.isArray(v)||Object.values(v).some(x=>typeof x!=="string"))throw new IntegrationError("legacy_migration_requires_review");
+ const values=v as Record<string,string>;const selected=legacyMethod(provider,values);
+ const methods=provider==="composio"?[...(values.apiKey?["project"]:[]),...(values.orgApiKey?["organization"]:[])]:provider==="convex-cloud"?[...(values.personalToken?["personal"]:[]),...(values.deployKey||values.deploymentName?["deployment"]:[])]:["direct"];
+ if(!methods.length)methods.push(selected);
+ profile.connections[provider]={};
+ for(const method of methods){const def=connectionMethod(provider,"direct",method),id=methods.length===1?"default":method;
+ profile.connections[provider][id]={id,uid:`legacy:${provider}:${method}`,label:methods.length===1?"Existing connection":def.label,provider,source:"direct",authMethod:method,scope:def.scope,revision:1,values:Object.fromEntries(def.fields.filter(f=>values[f.key]!==undefined).map(f=>[f.key,values[f.key]])),createdAt:0,updatedAt:0};
+ if(method===selected)profile.defaults[provider]=id;
+ }
+ }
+ d.users.legacy=profile;d.defaultUser="legacy";return d;
+}
+async function write(d:IntegrationState){
+ validate(d);const dir=path.dirname(INFRA_STORE_PATH);await fs.mkdir(dir,{recursive:true,mode:0o700});const st=await fs.lstat(dir);if(st.isSymbolicLink()||!st.isDirectory())throw new IntegrationError("unsafe_integration_directory");await fs.chmod(dir,0o700);
+ const text=JSON.stringify(d,null,2);if(Buffer.byteLength(text)>MAX)throw new IntegrationError("integration_store_capacity",409);
+ const temp=`${INFRA_STORE_PATH}.${randomUUID()}.tmp`;try{await fs.writeFile(temp,text,{mode:0o600,flag:"wx"});await fs.rename(temp,INFRA_STORE_PATH);}finally{await fs.unlink(temp).catch(()=>{});}
+}
+export async function readIntegrationState(){return projected((await readRaw())?.raw);}
+export async function mutateIntegrationState<T>(fn:(d:IntegrationState)=>T|Promise<T>):Promise<T>{
+ return withSecurityStoreLock(INFRA_STORE_PATH,async()=>{const previous=await readRaw(),d=projected(previous?.raw);const out=await fn(d);
+ if(previous&&previous.raw.version!==2){
+ const backup=`${INFRA_STORE_PATH}.v1-backup.json`;let h;try{h=await fs.open(backup,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);await h.writeFile(previous.bytes);}catch(e){if((e as NodeJS.ErrnoException).code!=="EEXIST")throw e;const existing=await fs.lstat(backup);if(!existing.isFile()||existing.isSymbolicLink()||(existing.mode&0o077)||(await fs.readFile(backup,"utf8"))!==previous.bytes)throw new IntegrationError("migration_backup_conflict",409);}finally{await h?.close();}d.migratedAt=Date.now();
+ }
+ await write(d);return out;
+ });
+}
+export async function migrateIntegrationStore(){await mutateIntegrationState(()=>null);return{ok:true,version:2,backupPreserved:true};}
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
new file mode 100644
index 00000000..b49e5d10
--- /dev/null
+++ b/lib/infra/connection-ui.ts
@@ -0,0 +1,73 @@
+// One metadata-only manager for browser, CLI-opened browser and MCP Page.
+// Only mountIntegrationForm handles secrets, using its direct HTTPS capability.
+export const CONNECTION_MANAGER_STYLE=String.raw`
+.integration .identity-bar{display:flex;gap:10px;align-items:end;flex-wrap:wrap;margin:14px 0 20px}.integration .identity-bar>label{flex:1;min-width:170px;margin:0}.integration .identity-bar select{margin-top:6px}.integration .identity-layout{display:grid;grid-template-columns:220px minmax(0,1fr);gap:20px}.integration .identity-providers{display:grid;gap:7px;align-content:start;max-height:560px;overflow:auto}.integration .identity-providers button{display:block;text-align:left;padding:10px 12px;min-height:42px}.integration [aria-pressed=true]{border-color:var(--os-accent);background:color-mix(in srgb,var(--os-accent) 10%,var(--surface))}.integration .connection-card{border:1px solid var(--sep-strong);border-radius:12px;padding:16px;margin:12px 0;background:var(--field)}.integration .connection-card h3{margin:0 0 6px;font-size:18px}.integration .identity-tags{display:flex;flex-wrap:wrap;gap:5px;margin:8px 0}.integration .identity-tags span{padding:3px 7px;border:1px solid var(--sep-strong);border-radius:99px;font-size:11px;color:var(--text-dim)}.integration .identity-actions{display:flex;gap:7px;flex-wrap:wrap;margin-top:12px}.integration .identity-fields{display:grid;grid-template-columns:1fr 1fr;gap:14px;margin:14px 0}.integration .identity-fields label{min-width:0}.integration .identity-fields input,.integration .identity-fields select{margin-top:6px}.integration .identity-feedback{min-height:24px;margin:8px 0;color:var(--text-dim);overflow-wrap:anywhere}.integration .identity-path{font:12px var(--font-mono);overflow-wrap:anywhere;margin:8px 0 15px}.integration .identity-check{display:flex;align-items:center;gap:8px}.integration .identity-check input{width:18px;height:18px;flex:none}.integration .identity-empty{border:1px dashed var(--sep-strong);border-radius:12px;padding:22px}.integration .identity-detail{min-width:0}.integration .identity-detail h2{font-size:22px}.integration .danger{color:var(--destructive-text)}.integration .identity-guide a{display:inline-block;margin:8px 12px 5px 0}.integration .identity-guide li{font-size:13px}.integration .identity-muted{font-size:12px;color:var(--text-dim)}.integration .identity-form{border:1px solid var(--sep-strong);border-radius:12px;padding:16px}.integration .identity-readonly{padding:10px 14px;border-left:3px solid var(--os-accent);background:var(--field);font-size:13px}@media(max-width:640px){.integration .identity-layout{grid-template-columns:1fr;gap:12px}.integration .identity-providers{grid-template-columns:1fr 1fr;max-height:180px}.integration .identity-providers input{grid-column:1/-1}.integration .identity-fields{grid-template-columns:1fr}.integration .identity-bar{gap:7px}.integration .connection-card{padding:13px}}
+`;
+export const CONNECTION_MANAGER_SCRIPT=String.raw`
+function mountConnectionManager(root,catalog,bridge,initial={}){
+ let disposed=false,sequence=0,snapshot=initial.snapshot||{users:[],connections:[],bindings:[]},user=initial.user||snapshot.user||null,provider=catalog.find(p=>p.id===initial.provider)||catalog.find(p=>p.id==="github")||catalog[0];
+ let detail,status,container;
+ const n=(tag,text,cls)=>{const v=integrationNode(tag,text);if(cls)v.className=cls;return v};
+ const b=(text,fn,cls)=>{const v=n("button",text,cls);v.type="button";v.addEventListener("click",fn);return v};
+ const input=(label,value="",type="text")=>{const l=n("label",label),i=n("input");i.type=type;i.value=value;i.autocomplete="off";i.maxLength=120;l.append(i);return{label:l,input:i}};
+ const textError=e=>({user_required:"Select a credential owner first.",connection_ambiguous:"Choose a named connection; more than one account exists.",connection_has_folder_binding:"Remove or change this connection's folder binding before deleting it.",connection_busy:"This connection is being used. Retry after that operation finishes.",choose_auth_config_id:"Several Composio auth configs match. Enter the intended auth config ID.",matching_auth_config_required:"Select a matching Composio auth config, or explicitly permit managed OAuth setup.",composio_project_key_required:"Configure a Composio project key under this same credential owner first.",external_source_requires_own_executor:"This connection uses an external backend; a local API key will not be substituted.",owner_required:"Sign in as an Owner before changing connections."}[e.code||e.message]||e.message||"Operation failed.");
+ function remember(){if(bridge.remember)bridge.remember({user,provider:provider.id})}
+ async function reload(){const version=++sequence;if(!bridge.query){draw();return}try{const next=await bridge.query({view:"snapshot",...(user?{user}:{})});if(disposed||version!==sequence)return;snapshot=next;user=next.user||user;draw();remember()}catch(e){if(!disposed){draw();status.textContent=textError(e)}}}
+ async function change(args,after=reload){if(!bridge.manage)return;try{status.textContent="Saving connection metadata…";await bridge.manage({...args,confirm:true});await after()}catch(e){status.textContent=textError(e)}}
+ function guide(method,parent=detail){const d=n("details",undefined,"identity-guide");d.open=true;d.append(n("summary","How to get this credential / authorization"));const g=method.guidance,ol=n("ol");for(const step of g.steps)ol.append(n("li",step));d.append(ol);for(const[url,label]of [[g.url,"Official setup page"],[g.reference,"Documentation"]]){const a=n("a",label);a.href=url;a.rel="noopener noreferrer";a.target="_blank";if(bridge.openLink)a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(bridge.openLink(url)).catch(error=>status.textContent=textError(error))});d.append(a)}parent.append(d)}
+ function draw(){
+ root.replaceChildren();root.classList.add("integration");root.append(n("h2","Integrations"),n("p","Credential owners, named accounts and deployments — shared by MSO CLI, tools and this form."));
+ const toolbar=n("div",undefined,"identity-bar"),label=n("label","Credential owner"),select=n("select");select.setAttribute("aria-label","Credential owner");const placeholder=n("option","Choose a user");placeholder.value="";select.append(placeholder);
+ for(const row of snapshot.users){const o=n("option",row.label+" ("+row.id+")"+(row.isDefault?" · default":""));o.value=row.id;select.append(o)}select.value=user||"";select.addEventListener("change",()=>{user=select.value||null;remember();void reload()});label.append(select);toolbar.append(label,b("Manage users",profiles),b("Folder bindings",bindings),b("Refresh",reload));root.append(toolbar);
+ if(!bridge.manage)root.append(n("p","Sign in as an MSO Owner to manage credentials. Device roles and credential users are different; the public guides remain available.","identity-readonly"));
+ container=n("div",undefined,"identity-layout");const sidebar=n("nav",undefined,"identity-providers"),search=n("input");search.type="search";search.placeholder="Search services";search.setAttribute("aria-label","Search services");sidebar.append(search);
+ const buttons=[];for(const p of catalog){const item=b(p.title,()=>{provider=p;remember();drawProvider();for(const[row,button]of buttons)button.setAttribute("aria-pressed",String(row.id===provider.id))});item.setAttribute("aria-pressed",String(p.id===provider.id));buttons.push([p,item]);sidebar.append(item)}search.addEventListener("input",()=>{for(const[p,item]of buttons)item.hidden=!(p.title+" "+p.id).toLowerCase().includes(search.value.toLowerCase())});
+ detail=n("section",undefined,"identity-detail");status=n("p",undefined,"identity-feedback");status.setAttribute("role","status");status.setAttribute("aria-live","polite");container.append(sidebar,detail);root.append(container,status);drawProvider();
+ }
+ function confirmation(title,id,fn){detail.replaceChildren(n("h2",title),n("p","This changes only the selected identity. Type “"+id+"” to confirm."));const value=input("Confirmation");detail.append(value.label,b("Confirm",()=>{if(value.input.value!==id){status.textContent="Confirmation does not match.";return}void fn()},"danger"),b("Cancel",drawProvider));}
+ function profiles(){
+ detail.replaceChildren(n("h2","Credential owners"),n("p","These profiles isolate service accounts. They do not grant MSO device roles."));
+ const id=input("New user ID"),name=input("Display label");detail.append(id.label,name.label);const create=b("Create user",()=>change({action:"user.create",user:id.input.value,label:name.input.value||id.input.value},async()=>{user=id.input.value;await reload()}),"primary");create.disabled=!bridge.manage;detail.append(create);
+ if(!user)return;const current=snapshot.users.find(u=>u.id===user);detail.append(n("h3",current?.label||user));
+ const target=input("Target user ID"),label=input("New display label",current?.label||user),copy=input("", "","checkbox");copy.input.checked=false;copy.label.className="identity-check";copy.label.append(document.createTextNode("Copy saved direct credentials when duplicating (otherwise metadata only)"));
+ detail.append(target.label,label.label,copy.label);const row=n("div",undefined,"identity-actions");
+ for(const[text,action]of [["Rename user","user.rename"],["Duplicate user","user.duplicate"]]){const button=b(text,()=>change({action,user,target:target.input.value,label:label.input.value,...(action==="user.duplicate"?{copyCredentials:copy.input.checked}:{})},async()=>{user=target.input.value;await reload()}));button.disabled=!bridge.manage;row.append(button)}
+ const def=b("Set default user",()=>change({action:"user.default",user}));def.disabled=!bridge.manage;row.append(def);const del=b("Delete user",()=>confirmation("Delete credential owner",user,()=>change({action:"user.delete",user},async()=>{user=null;await reload()})),"danger");del.disabled=!bridge.manage;row.append(del);detail.append(row);
+ }
+ function bindings(){
+ detail.replaceChildren(n("h2","Folder → credential context"),n("p","The longest matching folder selects its credential user and optional provider connection. It never changes another user's defaults."));
+ const folder=input("Absolute project folder"),connection=input("Connection ID (optional)");detail.append(folder.label,connection.label);const save=b("Bind this folder",()=>change({action:"folder.map",path:folder.input.value,user,...(connection.input.value?{provider:provider.id,connection:connection.input.value}:{})}));save.disabled=!user||!bridge.manage;detail.append(save);
+ for(const binding of snapshot.bindings){const card=n("div",undefined,"connection-card");card.append(n("strong",binding.path),n("p",binding.user+" · "+Object.entries(binding.connections).map(([p,id])=>p+"="+id).join(", ")));const remove=b("Remove binding",()=>change({action:"folder.unmap",path:binding.path}));remove.disabled=!bridge.manage;card.append(remove);detail.append(card)}
+ }
+ function drawProvider(){
+ detail.replaceChildren(n("h2",provider.title),n("p",provider.description),n("div",(user||"Choose user")+" → "+provider.id+" → Connection → Source → Auth","identity-path"));
+ const create=b("New connection",newConnection,"primary");create.disabled=!user||!bridge.manage;detail.append(create);
+ const rows=snapshot.connections.filter(c=>c.provider===provider.id);
+ if(!rows.length){detail.append(n("p","No named connection for this user. Create one before entering credentials.","identity-empty"));for(const s of provider.sources)for(const m of s.methods){const info=n("details");info.append(n("summary",s.label+" · "+m.label));guide(m,info);detail.append(info)}}
+ for(const c of rows){const card=n("article",undefined,"connection-card");card.append(n("h3",c.label),n("small",c.id));const tags=n("div",undefined,"identity-tags");for(const value of [c.source,c.authMethod,c.scope,c.state,c.isDefault?"default":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions");
+ const open=b(c.source==="direct"?"Set / rotate credentials":"Authorization",()=>{if(c.source==="direct")void bridge.openSetup({user,provider:provider.id,connection:c.id}).catch(e=>status.textContent=textError(e));else external(c)});open.disabled=!bridge.manage;actions.append(open);
+ const verify=b("Verify",async()=>{try{status.textContent="Checking selected connection…";const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});status.textContent=(result.ok===true?"Verified: ":"Status: ")+result.detail}catch(e){status.textContent=textError(e)}});verify.disabled=!bridge.execute;actions.append(verify);
+ const rename=b("Rename",()=>{detail.replaceChildren(n("h2","Rename connection"));const name=input("Label",c.label);detail.append(name.label,b("Save label",()=>change({action:"connection.rename",user,provider:provider.id,connection:c.id,label:name.input.value})),b("Cancel",drawProvider))});rename.disabled=!bridge.manage;actions.append(rename);
+ if(c.source==="direct"&&c.fields.some(f=>f.stored)){const clear=b("Clear credentials",()=>confirmation("Clear this connection's credential fields",c.id,()=>change({action:"credential.delete",user,provider:provider.id,connection:c.id})),"danger");clear.disabled=!bridge.manage;actions.append(clear)}
+ if(!c.isDefault){const def=b("Make default",()=>change({action:"connection.default",user,provider:provider.id,connection:c.id}));def.disabled=!bridge.manage;actions.append(def)}
+ const del=b("Delete",()=>confirmation("Delete named connection",c.id,()=>change({action:"connection.delete",user,provider:provider.id,connection:c.id})),"danger");del.disabled=!bridge.manage;actions.append(del);card.append(actions);detail.append(card);
+ }
+ }
+ function newConnection(){
+ detail.replaceChildren(n("h2","New "+provider.title+" connection"));const label=input("Connection label"),id=input("Connection ID"),source=n("select"),auth=n("select"),sourceLabel=n("label","Source / backend"),authLabel=n("label","Authentication method"),preview=n("div");source.setAttribute("aria-label","Source / backend");auth.setAttribute("aria-label","Authentication method");sourceLabel.append(source);authLabel.append(auth);
+ label.input.addEventListener("input",()=>{if(!id.input.dataset.edited)id.input.value=label.input.value.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")});id.input.addEventListener("input",()=>id.input.dataset.edited="true");
+ for(const s of provider.sources){const o=n("option",s.label);o.value=s.id;source.append(o)}
+ function changeAuth(){auth.replaceChildren();for(const m of provider.sources.find(s=>s.id===source.value).methods){const o=n("option",m.label+" · "+m.scope);o.value=m.id;auth.append(o)}previewGuide()}
+ function previewGuide(){preview.replaceChildren();const method=provider.sources.find(s=>s.id===source.value).methods.find(m=>m.id===auth.value);if(method.fields.length)preview.append(n("p","Fields: "+method.fields.map(f=>f.label+(f.required?" *":"")).join(", ")));else preview.append(n("p","No provider tokens are stored locally for this source."));guide(method,preview)}source.addEventListener("change",changeAuth);auth.addEventListener("change",previewGuide);changeAuth();
+ const fields=n("div",undefined,"identity-fields");fields.append(label.label,id.label,sourceLabel,authLabel);detail.append(fields,preview,b("Create connection",()=>change({action:"connection.create",user,provider:provider.id,connection:id.input.value,label:label.input.value,source:source.value,authMethod:auth.value}),"primary"),b("Cancel",drawProvider));
+ }
+ function external(c){
+ detail.replaceChildren(n("h2",c.label),n("p",user+" / "+provider.id+" / "+c.source+" / "+c.authMethod));const method=provider.sources.find(s=>s.id===c.source).methods.find(m=>m.id===c.authMethod);guide(method);
+ if(c.source==="native-mcp"){detail.append(n("p","Authorize in the provider's own MCP client. MSO will return this route, never substitute a stored API key."),b("Back",drawProvider));return}
+ const broker=input("Composio project connection ID",c.external?.brokerConnection||""),config=input("Auth config ID (when several exist)",c.external?.authConfigId||""),managed=input("","","checkbox");managed.label.className="identity-check";managed.label.append(document.createTextNode("Allow creation of a managed OAuth config if none exists"));detail.append(broker.label,config.label,managed.label);
+ const authorize=b("Open hosted authorization",async()=>{try{authorize.disabled=true;const result=await bridge.manage({action:"connection.authorize",confirm:true,user,provider:provider.id,connection:c.id,...(broker.input.value?{brokerConnection:broker.input.value}:{}),...(config.input.value?{authConfigId:config.input.value}:{}),createManaged:managed.input.checked});if(result.privateUrl){const a=n("a","Continue on Composio");a.href=result.privateUrl;a.rel="noopener noreferrer";a.target="_blank";a.addEventListener("click",e=>{if(bridge.openLink){e.preventDefault();bridge.openLink(result.privateUrl)}});detail.append(a)}status.textContent="Authorization pending. Complete the provider flow, then refresh status."}catch(e){status.textContent=textError(e);authorize.disabled=false}});authorize.disabled=Boolean(c.external?.connectedAccountId);detail.append(authorize,b("Refresh authorization status",async()=>{try{const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});status.textContent=result.detail}catch(e){status.textContent=textError(e)}}),b("Back",drawProvider));
+ }
+ draw();if(bridge.query)void reload();
+ return()=>{disposed=true;sequence++;root.replaceChildren();root.classList.remove("integration")};
+}
+`;
diff --git a/lib/infra/dokploy.ts b/lib/infra/dokploy.ts
index ad3db562..8f8a3632 100644
--- a/lib/infra/dokploy.ts
+++ b/lib/infra/dokploy.ts
@@ -24,10 +24,10 @@ async function call(endpoint: string, method = "GET", body?: unknown): Promise<u
...(body === undefined ? {} : { body: JSON.stringify(body) }),
}, TIMEOUT_MS, dokployFetch);
if (res.ok) return res.body;
- if (res.status !== 429 && res.status < 500) throw new Error(`Dokploy HTTP ${res.status}: ${res.text.slice(0, 300)}`);
+ if (res.status !== 429 && res.status < 500) throw new Error(`Dokploy HTTP ${res.status}`);
last = new Error(`Dokploy HTTP ${res.status}`);
} catch (error) {
- last = error as Error;
+ last = new Error(/^Dokploy HTTP \d{3}$/.test((error as Error).message)?(error as Error).message:"Dokploy request failed");
}
if (attempt < 2) await new Promise((resolve) => setTimeout(resolve, 500 * 2 ** attempt));
}
diff --git a/lib/infra/identity.ts b/lib/infra/identity.ts
new file mode 100644
index 00000000..3e200b67
--- /dev/null
+++ b/lib/infra/identity.ts
@@ -0,0 +1,65 @@
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import { realpathSync } from "node:fs";
+export const SOURCES = ["direct", "composio", "native-mcp"] as const;
+export type ConnectionSource = typeof SOURCES[number];
+export type ConnectionSelector = { user?: string; connection?: string; cwd?: string; source?: ConnectionSource; authMethod?: string };
+export type ExternalIdentity = { toolkit?: string; connectedAccountId?: string; authConfigId?: string; brokerConnection?: string; remoteUserId?: string; status?: string; checkedAt?: number };
+export type IntegrationConnection = {
+ id: string; uid: string; label: string; provider: string; source: ConnectionSource; authMethod: string;
+ scope: string; revision: number; values: Record<string,string>; external?: ExternalIdentity;
+ createdAt: number; updatedAt: number; verifiedAt?: number; lease?: {id:string;until:number};
+};
+export type IntegrationUser = { id: string; uid:string; label: string; connections: Record<string, Record<string, IntegrationConnection>>; defaults: Record<string, string> };
+export type IntegrationBinding = { path: string; user: string; connections: Record<string, string> };
+export type IntegrationState = { version: 2; instanceId:string; defaultUser: string | null; users: Record<string, IntegrationUser>; bindings: IntegrationBinding[]; migratedAt?: number };
+export class IntegrationError extends Error { constructor(public readonly code: string, public readonly status = 400) { super(code); } }
+export const emptyIntegrationState = (): IntegrationState => ({ version: 2, instanceId:randomUUID(), defaultUser: null, users: {}, bindings: [] });
+export function identity(value: unknown, name = "identity"): string {
+ if (typeof value !== "string" || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(value) || ["__proto__", "constructor", "prototype"].includes(value)) throw new IntegrationError(`invalid_${name}`);
+ return value;
+}
+export function connectionLabel(value: unknown): string {
+ if (typeof value !== "string" || !value.trim() || value.length > 120 || /[\x00-\x1f\x7f]/.test(value)) throw new IntegrationError("invalid_label");
+ return value.trim();
+}
+export function canonicalFolder(value: string): string {
+ if (!path.isAbsolute(value) || value.length > 4096 || /[\x00-\x1f]/.test(value)) throw new IntegrationError("invalid_folder");
+ try { return realpathSync(value); } catch { return path.resolve(value); }
+}
+export function folderBinding(state: IntegrationState, cwd?: string) {
+ if (!cwd) return undefined;
+ const p = canonicalFolder(cwd);
+ return state.bindings.filter(b => p === b.path || p.startsWith(b.path.endsWith(path.sep) ? b.path : b.path + path.sep)).sort((a,b) => b.path.length-a.path.length)[0];
+}
+export function resolveUser(state: IntegrationState, selection: ConnectionSelector = {}): string {
+ const name = selection.user ?? folderBinding(state, selection.cwd)?.user ?? state.defaultUser;
+ if (!name) throw new IntegrationError("user_required", 409);
+ identity(name, "user"); if (!Object.hasOwn(state.users, name)) throw new IntegrationError("user_not_found", 404);
+ return name;
+}
+export function selectConnection(state: IntegrationState, provider: string, selection: ConnectionSelector = {}) {
+ identity(provider, "provider"); const user = resolveUser(state, selection), profile = state.users[user];
+ const bound = folderBinding(state, selection.cwd);
+ const mapped = bound?.user === user ? bound.connections[provider] : undefined;
+ const rows = profile.connections[provider] ?? {};
+ const requested = selection.connection ?? mapped ?? profile.defaults[provider];
+ const id = requested ?? (Object.keys(rows).length === 1 ? Object.keys(rows)[0] : undefined);
+ if (!id) throw new IntegrationError(Object.keys(rows).length ? "connection_ambiguous" : "connection_not_found", Object.keys(rows).length ? 409 : 404);
+ const connection = Object.hasOwn(rows, identity(id,"connection")) ? rows[id] : undefined;
+ if (!connection) throw new IntegrationError("connection_not_found", 404);
+ if (selection.source && selection.source !== connection.source) throw new IntegrationError("connection_source_mismatch",409);
+ if (selection.authMethod && selection.authMethod !== connection.authMethod) throw new IntegrationError("connection_auth_mismatch",409);
+ return { user, connection, reason: selection.connection ? "explicit" : mapped ? "folder" : profile.defaults[provider] ? "default" : "only-connection" };
+}
+// Safe machine operations accept metadata only. Secret form endpoints use a separate schema.
+export function metadataOnly(value: unknown, depth = 0): void {
+ if (depth > 12) throw new IntegrationError("metadata_too_deep");
+ if (!value || typeof value !== "object") return;
+ for (const [k,v] of Object.entries(value)) {
+ if (/^(values?|secrets?|secretValue|password|token|apiKey|apiToken|accessToken|refreshToken|authorization|headers|__proto__|constructor|prototype)$/i.test(k)) throw new IntegrationError("secret_input_forbidden");
+ metadataOnly(v,depth+1);
+ }
+}
+
+export function assertNotBusy(c:IntegrationConnection){if(c.lease&&c.lease.until>Date.now())throw new IntegrationError("connection_busy",409);}
diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.ts
index 68aa4e67..84bce593 100644
--- a/lib/infra/setup-browser.ts
+++ b/lib/infra/setup-browser.ts
@@ -1,46 +1,25 @@
-export const INTEGRATION_BROWSER_SCRIPT = String.raw`
+export const INTEGRATION_BROWSER_SCRIPT=String.raw`
(async()=>{
- const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup";
- let teardown=()=>{};
- window.addEventListener("pagehide",()=>teardown(),{once:true});
- const preset=new URLSearchParams(location.search);
- function form(setup,token){teardown();teardown=mountIntegrationForm(root,setup,{endpoint,token,onBack:picker})||(()=>{})}
- function picker(){
- teardown();
- const session={loading:true,authenticated:false,role:null};let disposed=false;const abort=new AbortController();
- async function refreshAuth(){
- if(disposed)return;
- try{
- const response=await fetch("/api/auth/me",{credentials:"same-origin",cache:"no-store",signal:AbortSignal.any([abort.signal,AbortSignal.timeout(8000)])});
- if(!response.ok)throw new Error("unavailable");
- const data=await response.json();session.authenticated=data.authenticated===true;session.role=data.role;
- }catch{session.authenticated=false;session.role=null}
- if(disposed)return;session.loading=false;
- const label=root.querySelector("#integration-auth-status");
- if(label)label.textContent=session.role==="owner"?"Owner session ready. Credentials are never displayed.":session.authenticated?"This device is not an Owner. Use an approved Owner session to change credentials.":"Sign in to MSO as an owner to open a private form. The catalog and guidance remain available.";
- for(const b of root.querySelectorAll("[data-integration-start]"))b.disabled=session.role!=="owner";
+ const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup";let cleanup=()=>{},state={},authController;
+ const error=data=>{const e=new Error(data.error||"integration_operation_failed");e.code=data.error;return e};
+ async function json(url,init){const r=await fetch(url,{credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",...init});const data=await r.json();if(!r.ok)throw error(data);return data}
+ const post=(mode,input)=>json("/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode,...input})});
+ function showForm(setup,token){cleanup();authController?.abort();cleanup=mountIntegrationForm(root,setup,{endpoint,token,onBack:loadManager})||(()=>{})}
+ async function loadManager(){
+ cleanup();authController?.abort();authController=new AbortController();
+ let owner=false;try{const auth=await json("/api/auth/me",{signal:authController.signal});owner=auth.role==="owner"}catch{}
+ const bridge={remember:s=>state=s,openLink:url=>window.open(url,"_blank","noopener,noreferrer")};
+ if(owner){
+ bridge.query=args=>json("/api/v1/integrations?"+new URLSearchParams(args));
+ bridge.manage=args=>post("manage",args);bridge.execute=args=>post("execute",args);
+ bridge.openSetup=async args=>{const data=await json("/api/v1/infra/setup",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(args)});showForm(data.setup,data.token)};
}
- const visible=()=>{if(document.visibilityState!=="hidden")void refreshAuth()};
- const disposePicker=mountIntegrationPicker(root,INTEGRATIONS_CATALOG,{
- provider:preset.get("provider"),method:preset.get("method"),session,
- browserLabel:"MSO sign-in",
- openBrowser:()=>{window.open(location.origin+"/","_blank","noopener,noreferrer")},
- openSetup:async(provider,method)=>{
- const response=await fetch("/api/v1/infra/setup",{method:"POST",credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider,method}),signal:AbortSignal.timeout(15000)});
- if(response.status===401||response.status===403){await refreshAuth();throw new Error("Your Owner session is no longer available. Sign in using MSO sign-in, then return here.")}
- if(!response.ok)throw new Error("Setup is temporarily unavailable. Check the selected method and retry.");
- const data=await response.json();if(!data.setup||!data.token)throw new Error("Incomplete setup response. Reload this page.");form(data.setup,data.token);
- }
- });
- document.addEventListener("visibilitychange",visible);window.addEventListener("focus",visible);
- teardown=()=>{disposed=true;abort.abort();document.removeEventListener("visibilitychange",visible);window.removeEventListener("focus",visible);disposePicker()};
- void refreshAuth();
+ cleanup=mountConnectionManager(root,INTEGRATIONS_CATALOG,bridge,state);
+ if(!owner){const link=integrationNode("a","Sign in to MSO as Owner");link.href="/";link.target="_blank";link.rel="noopener noreferrer";root.prepend(link);const refresh=()=>{if(document.visibilityState!=="hidden")void loadManager()};document.addEventListener("visibilitychange",refresh,{signal:authController.signal});window.addEventListener("focus",refresh,{signal:authController.signal});}
}
- let token=location.hash.slice(1);history.replaceState(null,"",location.pathname+location.search);
- if(token){
- try{const response=await fetch(endpoint,{method:"POST",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},body:JSON.stringify({action:"schema"}),signal:AbortSignal.timeout(12000)});if(!response.ok)throw new Error("This private form has expired or was already used. Open a new setup session below.");form(await response.json(),token);token="";return}
- catch(error){picker();const note=integrationNode("p",error.message);note.className="picker-note";root.prepend(note);token="";return}
- }
- picker();
+ window.addEventListener("pagehide",()=>{cleanup();authController?.abort()},{once:true});
+ let token=location.hash.slice(1);history.replaceState(null,"",location.pathname);
+ if(token){try{const data=await json(endpoint,{method:"POST",credentials:"omit",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},body:JSON.stringify({action:"schema"})});showForm(data,token);token="";return}catch{token=""}}
+ await loadManager();
})();
`;
diff --git a/lib/infra/setup-capability.test.ts b/lib/infra/setup-capability.test.ts
index 0ceedf37..61d33394 100644
--- a/lib/infra/setup-capability.test.ts
+++ b/lib/infra/setup-capability.test.ts
@@ -14,10 +14,18 @@ beforeEach(async () => {
vi.stubGlobal("fetch", vi.fn(async () => new Response("{}", { status: 200 })));
});
afterEach(async () => { vi.unstubAllGlobals(); delete process.env.OS_INFRA_STORE; await fs.rm(root, { recursive: true, force: true }); vi.resetModules(); });
+async function openBound(api:typeof import("./setup-capability"), method="project", principal="test-owner") {
+ const {integrationManage}=await import("./connection-manage");const {readIntegrationState}=await import("./connection-storage");
+ let state=await readIntegrationState();const user=state.defaultUser??"test-user";
+ if(!state.users[user])await integrationManage({action:"user.create",confirm:true,user});
+ state=await readIntegrationState();const id=Object.values(state.users[user].connections.composio??{}).find(c=>c.authMethod===method)?.id??method;
+ if(!state.users[user].connections.composio?.[id])await integrationManage({action:"connection.create",confirm:true,user,provider:"composio",connection:id,authMethod:method});
+ return api.openIntegrationSetup("composio",principal,method,{user,connection:id});
+}
describe("native integration setup capabilities", () => {
it("binds a hashed, owner-only, expiring grant to a provider/method", async () => {
const api = await import("./setup-capability");
- const grant = await api.openIntegrationSetup("composio", "test-owner", "project");
+ const grant = await openBound(api);
expect(grant.token).toMatch(/^[A-Za-z0-9_-]{43}$/);
const file = path.join(root, "integration-setup", createHash("sha256").update(grant.token).digest("hex") + ".json");
expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
@@ -29,7 +37,7 @@ describe("native integration setup capabilities", () => {
});
it("verifies candidates before saving and returns no secrets", async () => {
const api = await import("./setup-capability"), store = await import("./store");
- const grant = await api.openIntegrationSetup("composio", "test-owner");
+ const grant = await openBound(api);
const output = await api.consumeIntegrationSetup(grant.token, { apiKey: ` ${KEY} ` });
expect(output.verified).toBe(true); expect(JSON.stringify(output)).not.toContain(KEY);
expect((await store.readInfraProvider("composio")).apiKey).toBe(KEY);
@@ -40,7 +48,7 @@ describe("native integration setup capabilities", () => {
const api = await import("./setup-capability"), store = await import("./store");
await store.setInfraProvider("composio", { apiKey: "original_synthetic_key_keep_me" });
vi.stubGlobal("fetch", vi.fn(async () => new Response(KEY, { status: 403 })));
- const grant = await api.openIntegrationSetup("composio", "test-owner");
+ const grant = await openBound(api);
for (let i = 0; i < 5; i++) await expect(api.consumeIntegrationSetup(grant.token, { apiKey: KEY })).rejects.toMatchObject({ code: "credential_validation_failed" });
await expect(api.consumeIntegrationSetup(grant.token, { apiKey: KEY })).rejects.toMatchObject({ status: 401 });
expect((await store.readInfraProvider("composio")).apiKey).toBe("original_synthetic_key_keep_me");
@@ -48,17 +56,17 @@ describe("native integration setup capabilities", () => {
});
it("expired grants and concurrent replays fail closed", async () => {
const api = await import("./setup-capability");
- const expired = await api.openIntegrationSetup("composio", "test-owner");
+ const expired = await openBound(api);
const file = path.join(root, "integration-setup", createHash("sha256").update(expired.token).digest("hex") + ".json");
const row = JSON.parse(await fs.readFile(file, "utf8")); row.expiresAt = Date.now() - 1; await fs.writeFile(file, JSON.stringify(row));
await expect(api.describeIntegrationSetup(expired.token)).rejects.toMatchObject({ status: 401 });
- const grant = await api.openIntegrationSetup("composio", "test-owner");
+ const grant = await openBound(api);
const results = await Promise.allSettled([api.consumeIntegrationSetup(grant.token, { apiKey: KEY }), api.consumeIntegrationSetup(grant.token, { apiKey: KEY })]);
expect(results.filter(r => r.status === "fulfilled")).toHaveLength(1);
});
it("organization keys use the correct header and are masked in summaries", async () => {
const api = await import("./setup-capability"), store = await import("./store");
- const grant = await api.openIntegrationSetup("composio", "test-owner", "organization");
+ const grant = await openBound(api,"organization");
await api.consumeIntegrationSetup(grant.token, { orgApiKey: KEY });
const [url, options] = vi.mocked(fetch).mock.calls[0];
expect(String(url)).toContain("/api/v3.1/org/owner/project/list"); expect(options?.headers).toEqual({ "x-org-api-key": KEY });
diff --git a/lib/infra/setup-capability.ts b/lib/infra/setup-capability.ts
index f4fafac7..0bfc837f 100644
--- a/lib/infra/setup-capability.ts
+++ b/lib/infra/setup-capability.ts
@@ -4,14 +4,17 @@ import path from "node:path";
import { withSecurityStoreLock } from "@/lib/security-store-lock";
import { getInfraProviderDefinition, isInfraProviderId, normalizeInfraValues } from "./catalog";
import { doctorInfraProvider } from "./clients";
-import { INFRA_STORE_PATH, readInfraProvider, setInfraProvider } from "./store";
-import { setupFields, setupGuidance, setupMethod, type SetupMethod } from "./setup-guidance";
+import { INFRA_STORE_PATH } from "./connection-storage";
+import { credentialSnapshot, saveConnectionValues } from "./connection-service";
+import { connectionMethod } from "./connection-registry";
+import { type ConnectionSelector } from "./identity";
+import { setupMethod, type SetupMethod } from "./setup-guidance";
import type { InfraProviderId } from "./types";
export const SETUP_TTL_MS = 10 * 60_000;
export const SETUP_MAX_BODY = 16 * 1024;
const ROOT = path.join(path.dirname(INFRA_STORE_PATH), "integration-setup");
-type Grant = { provider: InfraProviderId; method: SetupMethod; principal: string; expiresAt: number; attempts: number; used: boolean };
+type Grant = { user: string; connection: string; uid: string; revision: number; provider: InfraProviderId; method: SetupMethod; principal: string; expiresAt: number; attempts: number; used: boolean };
export class SetupError extends Error {
constructor(public readonly code: string, public readonly status: number) { super(code); }
}
@@ -34,37 +37,47 @@ async function readGrant(file: string): Promise<Grant> {
const st = await handle.stat();
if (!st.isFile() || st.size > 2048 || (st.mode & 0o077) || (typeof process.getuid === "function" && st.uid !== process.getuid())) throw invalid();
const g = JSON.parse(await handle.readFile("utf8")) as Grant;
- if (!isInfraProviderId(g.provider) || !g.principal || !Number.isFinite(g.expiresAt)) throw invalid();
+ if (!g.user || !g.connection || !g.uid || !Number.isInteger(g.revision) || !isInfraProviderId(g.provider) || !g.principal || !Number.isFinite(g.expiresAt)) throw invalid();
setupMethod(g.provider, g.method);
return g;
} catch { throw invalid(); } finally { await handle?.close(); }
}
function active(g: Grant) { if (g.used || g.attempts >= 5 || g.expiresAt <= Date.now()) throw invalid(); }
+async function target(g: Grant) {
+ const snapshot=await credentialSnapshot(g.provider,{user:g.user,connection:g.connection,source:"direct",authMethod:g.method});
+ if(snapshot.connection.uid!==g.uid||snapshot.connection.revision!==g.revision)throw new SetupError("connection_changed_reopen_setup",409);
+ return snapshot.connection;
+}
async function schema(g: Grant) {
- const stored = await readInfraProvider(g.provider);
+ const c=await target(g),method=connectionMethod(g.provider,"direct",g.method);
return {
- provider: g.provider, title: getInfraProviderDefinition(g.provider).title, method: g.method,
- expiresAt: g.expiresAt, store: "MSO private credentials · owner-only permissions (0600)",
- fields: setupFields(g.provider, g.method).map(f => ({ ...f, stored: Boolean(stored[f.key]) })),
- guidance: setupGuidance(g.provider, g.method),
+ user:g.user,connection:c.id,label:c.label,source:c.source,authMethod:c.authMethod,scope:c.scope,
+ provider:g.provider,title:getInfraProviderDefinition(g.provider).title,method:g.method,
+ expiresAt:g.expiresAt,store:"MSO named connection · owner-only permissions (0600)",
+ fields:method.fields.map(f=>({...f,stored:Boolean(c.values[f.key])})),guidance:method.guidance,
};
}
-export async function openIntegrationSetup(provider: string, principal: string, method?: string) {
+export async function openIntegrationSetup(provider: string, principal: string, method?: string, selection:ConnectionSelector={}) {
if (!isInfraProviderId(provider)) throw new SetupError("unknown_provider", 400);
if (!principal || principal.length > 256) throw new SetupError("authenticated_principal_required", 403);
- const selectedMethod = setupMethod(provider, method);
+ // A UI must never guess which user's deployment to rotate.
+ if(!selection.user||!selection.connection)throw new SetupError("choose_user_and_connection",409);
+ const snapshot=await credentialSnapshot(provider,selection),c=snapshot.connection;
+ const selectedMethod=setupMethod(provider,method??c.authMethod);
+ if(selectedMethod!==c.authMethod)throw new SetupError("connection_auth_mismatch",409);
await ensureRoot();
return withSecurityStoreLock(path.join(ROOT, "issuance"), async () => {
let activeCount = 0;
for (const name of await fs.readdir(ROOT)) {
if (!/^[a-f0-9]{64}\.json$/.test(name)) continue;
- const file = path.join(ROOT, name), previous = await readGrant(file);
+ const file = path.join(ROOT, name);let previous:Grant;
+ try{previous=await readGrant(file);}catch{await fs.unlink(file);continue;}
if (previous.used || previous.expiresAt <= Date.now()) await fs.unlink(file);
else activeCount++;
}
if (activeCount >= 256) throw new SetupError("too_many_setup_sessions", 429);
const token = randomBytes(32).toString("base64url");
- const grant: Grant = { provider, principal, method: selectedMethod, expiresAt: Date.now() + SETUP_TTL_MS, attempts: 0, used: false };
+ const grant: Grant = { user:snapshot.user,connection:c.id,uid:c.uid,revision:c.revision,provider, principal, method: selectedMethod, expiresAt: Date.now() + SETUP_TTL_MS, attempts: 0, used: false };
const descriptor = await schema(grant);
await fs.writeFile(grantPath(token), JSON.stringify(grant), { mode: 0o600, flag: "wx" });
return { token, setup: descriptor };
@@ -78,7 +91,7 @@ export async function consumeIntegrationSetup(token: string, raw: unknown) {
return withSecurityStoreLock(file, async () => {
const grant = await readGrant(file); active(grant);
if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new SetupError("invalid_fields", 400);
- const fields = setupFields(grant.provider, grant.method), allowed = new Set(fields.map(f => f.key));
+ const fields = connectionMethod(grant.provider, "direct", grant.method).fields, allowed = new Set(fields.map(f => f.key));
for (const [key, value] of Object.entries(raw)) {
if (!allowed.has(key) || typeof value !== "string" || value.length > 4096 || /[\x00-\x1f\x7f]/.test(value)) throw new SetupError("invalid_fields", 400);
}
@@ -86,7 +99,7 @@ export async function consumeIntegrationSetup(token: string, raw: unknown) {
try { updates = normalizeInfraValues(grant.provider, raw as Record<string, unknown>); }
catch { throw new SetupError("invalid_credential_format", 400); }
if (!Object.keys(updates).length) throw new SetupError("enter_at_least_one_value", 400);
- const stored = await readInfraProvider(grant.provider);
+ const stored = (await target(grant)).values;
const candidate = Object.fromEntries(fields.filter(f => updates[f.key] || stored[f.key]).map(f => [f.key, updates[f.key] ?? stored[f.key]]));
if (fields.some(f => f.required && !candidate[f.key])) throw new SetupError("required_fields_missing", 400);
grant.attempts++;
@@ -98,7 +111,7 @@ export async function consumeIntegrationSetup(token: string, raw: unknown) {
if (grant.expiresAt <= Date.now()) throw invalid();
grant.used = true;
await fs.writeFile(file, JSON.stringify(grant), { mode: 0o600 });
- await setInfraProvider(grant.provider, updates);
- return { ok: true, verified: true, provider: grant.provider, principal: grant.principal };
+ await saveConnectionValues(grant.provider,{user:grant.user,connection:grant.connection},updates,{uid:grant.uid,revision:grant.revision},true);
+ return { ok: true, verified: true, provider: grant.provider,user:grant.user,connection:grant.connection,principal: grant.principal };
});
}
diff --git a/lib/infra/setup-catalog.ts b/lib/infra/setup-catalog.ts
deleted file mode 100644
index 304b89ed..00000000
--- a/lib/infra/setup-catalog.ts
+++ /dev/null
@@ -1,9 +0,0 @@
-import { listInfraProviderDefinitions } from "./catalog";
-import { setupFields, setupGuidance, setupMethods } from "./setup-guidance";
-// Pure display metadata only. No imports from credential storage.
-export function integrationCatalog() {
- return listInfraProviderDefinitions().map(p => ({
- id: p.id, title: p.title, description: p.description,
- methods: setupMethods(p.id).map(method => ({ ...method, fields: setupFields(p.id, method.id), guidance: setupGuidance(p.id, method.id) })),
- }));
-}
diff --git a/lib/infra/setup-hub.test.ts b/lib/infra/setup-hub.test.ts
index c1c9a367..084a3074 100644
--- a/lib/infra/setup-hub.test.ts
+++ b/lib/infra/setup-hub.test.ts
@@ -1,16 +1,16 @@
import { expect, it } from "vitest";
-import { integrationCatalog } from "./setup-catalog";
-import { INTEGRATION_PICKER_SCRIPT } from "./setup-picker";
+import { connectionCatalog } from "./connection-registry";
+import { CONNECTION_MANAGER_SCRIPT } from "./connection-ui";
import { INFRA_PROVIDER_IDS } from "./types";
import { integrationSetupPage } from "./setup-page";
it("derives the complete native setup catalog from the same provider registry", () => {
- const rows = integrationCatalog(); expect(rows.map(p => p.id)).toEqual([...INFRA_PROVIDER_IDS]);
- for (const p of rows) for (const method of p.methods) { expect(method.guidance.url).toMatch(/^https:/); expect(method.guidance.steps.length).toBeGreaterThan(1); }
- expect(rows.find(p => p.id === "composio")?.methods.map(m => m.id)).toEqual(["project", "organization"]);
+ const rows = connectionCatalog(); expect(rows.map(p => p.id)).toEqual([...INFRA_PROVIDER_IDS]);
+ for (const p of rows) for (const source of p.sources) for (const method of source.methods) { expect(method.guidance.url).toMatch(/^https:/); expect(method.guidance.steps.length).toBeGreaterThan(1); }
+ expect(rows.find(p => p.id === "composio")?.sources.find(s=>s.id==="direct")?.methods.map(m => m.id)).toEqual(["project", "organization"]);
});
it("keeps guidance before login and preserves explicit role/expiry recovery", () => {
const page = integrationSetupPage();
expect(() => new Function(page.html.match(/<script[^>]*>([\s\S]*?)<\/script>/)![1])).not.toThrow();
- for (const marker of ['"/api/auth/me"', 'session.role!=="owner"', '"visibilitychange"', '"How to get this credential"', 'Open a new setup session']) expect(page.html).toContain(marker);
- expect(INTEGRATION_PICKER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");
+ for (const marker of ['"/api/auth/me"', 'owner=auth.role==="owner"', '"visibilitychange"', 'How to get this credential', 'mountConnectionManager']) expect(page.html).toContain(marker);
+ expect(CONNECTION_MANAGER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");
});
diff --git a/lib/infra/setup-page.ts b/lib/infra/setup-page.ts
index 962b1490..d6ee3d9f 100644
--- a/lib/infra/setup-page.ts
+++ b/lib/infra/setup-page.ts
@@ -1,13 +1,13 @@
import { randomBytes } from "node:crypto";
import { MSO_WIDGET_TOKENS } from "@/lib/presentation/widget-tokens";
import { INTEGRATION_FORM_SCRIPT, INTEGRATION_FORM_STYLE } from "./setup-ui";
-import { INTEGRATION_PICKER_SCRIPT, INTEGRATION_PICKER_STYLE } from "./setup-picker";
+import { CONNECTION_MANAGER_SCRIPT, CONNECTION_MANAGER_STYLE } from "./connection-ui";
import { INTEGRATION_BROWSER_SCRIPT } from "./setup-browser";
-import { integrationCatalog } from "./setup-catalog";
+import { connectionCatalog } from "./connection-registry";
export function integrationSetupPage() {
const nonce = randomBytes(18).toString("base64");
- const catalog = JSON.stringify(integrationCatalog()).replace(/</g,"\\u003c");
- const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Integrations · MSO</title><style nonce="${nonce}">${MSO_WIDGET_TOKENS}${INTEGRATION_FORM_STYLE}${INTEGRATION_PICKER_STYLE}*{box-sizing:border-box}body{margin:0;background:var(--surface);padding:clamp(16px,3vw,40px);font-family:var(--font-body);color:var(--text)}.site-bar{max-width:1100px;margin:0 auto 26px;font-size:13px;display:flex;justify-content:space-between;gap:12px}.site-bar strong{font-weight:750}.site-bar span{color:var(--text-dim)}button{border:1px solid var(--sep-strong);border-radius:9px;background:var(--field);color:var(--text);padding:9px 13px;cursor:pointer}a{color:var(--os-accent)}</style></head><body><header class="site-bar"><strong>MSO / Integrations</strong><span>Native · Private credential setup</span></header><main id="setup" class="integration"><h1>Integrations</h1><p>Preparing the native provider catalog…</p><noscript>Enable JavaScript to open the secure credential form. Credentials can also be entered through the MSO terminal.</noscript></main><script nonce="${nonce}">const INTEGRATIONS_CATALOG=${catalog};${INTEGRATION_FORM_SCRIPT}${INTEGRATION_PICKER_SCRIPT}${INTEGRATION_BROWSER_SCRIPT}</script></body></html>`;
+ const catalog = JSON.stringify(connectionCatalog()).replace(/</g,"\\u003c");
+ const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><meta name="referrer" content="no-referrer"><title>Integrations · MSO</title><style nonce="${nonce}">${MSO_WIDGET_TOKENS}${INTEGRATION_FORM_STYLE}${CONNECTION_MANAGER_STYLE}*{box-sizing:border-box}body{margin:0;background:var(--surface);padding:clamp(16px,3vw,40px);font-family:var(--font-body);color:var(--text)}.site-bar{max-width:1100px;margin:0 auto 26px;font-size:13px;display:flex;justify-content:space-between;gap:12px}.site-bar strong{font-weight:750}.site-bar span{color:var(--text-dim)}button{border:1px solid var(--sep-strong);border-radius:9px;background:var(--field);color:var(--text);padding:9px 13px;cursor:pointer}a{color:var(--os-accent)}</style></head><body><header class="site-bar"><strong>MSO / Integrations</strong><span>Native · Private credential setup</span></header><main id="setup" class="integration"><h1>Integrations</h1><p>Preparing the native provider catalog…</p><noscript>Enable JavaScript to open the secure credential form. Credentials can also be entered through the MSO terminal.</noscript></main><script nonce="${nonce}">const INTEGRATIONS_CATALOG=${catalog};${INTEGRATION_FORM_SCRIPT}${CONNECTION_MANAGER_SCRIPT}${INTEGRATION_BROWSER_SCRIPT}</script></body></html>`;
return { html, csp: `default-src 'none'; script-src 'nonce-${nonce}'; style-src 'nonce-${nonce}'; connect-src 'self'; form-action 'none'; base-uri 'none'; frame-ancestors 'none'` };
}
export function integrationPageResponse() {
diff --git a/lib/infra/setup-picker.ts b/lib/infra/setup-picker.ts
deleted file mode 100644
index 9d2036b7..00000000
--- a/lib/infra/setup-picker.ts
+++ /dev/null
@@ -1,35 +0,0 @@
-export const INTEGRATION_PICKER_STYLE = String.raw`
-.integration{max-width:1100px;width:100%;margin:0 auto}.integration .picker-header{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;margin-bottom:22px}.integration .picker-header h2{margin:0;font-size:26px}.integration .picker-header p{max-width:630px;margin:7px 0}.integration .picker-layout{display:grid;grid-template-columns:minmax(210px,280px) minmax(0,1fr);gap:22px}.integration .provider-list{display:grid;gap:7px;margin-top:12px;max-height:490px;overflow:auto;padding-right:4px}.integration .provider-option{display:block;text-align:left;width:100%;border:1px solid var(--sep-strong);background:var(--field);color:var(--text);padding:11px 12px;border-radius:10px;font:600 14px var(--font-body);cursor:pointer}.integration .provider-option[aria-pressed=true]{border-color:var(--os-accent);background:color-mix(in srgb,var(--os-accent) 12%,var(--surface))}.integration .provider-option small{margin-top:2px;font-size:11px;font-weight:400}.integration .provider-detail{border:1px solid var(--sep-strong);border-radius:14px;padding:20px;background:var(--field);min-width:0}.integration .provider-detail h3{font:700 22px var(--font-display);margin:0 0 8px}.integration .provider-detail label{font-size:13px}.integration .provider-fields{display:flex;flex-wrap:wrap;gap:6px;margin:10px 0 18px}.integration .field-tag{font:12px var(--font-body);padding:5px 9px;border:1px solid var(--sep-strong);border-radius:7px;color:var(--text-dim)}.integration .picker-actions{display:flex;gap:8px;flex-wrap:wrap;margin-top:18px}.integration .picker-note{padding:12px 14px;border-left:3px solid var(--os-accent);background:color-mix(in srgb,var(--os-accent) 7%,var(--surface));border-radius:7px;font-size:12px}.integration .picker-feedback{min-height:22px;margin:10px 0 0;font-size:13px;overflow-wrap:anywhere}.integration .back-link{margin-bottom:14px}.integration [type=search]{font-size:15px}.integration .setup-grid{margin-top:18px}@media(max-width:640px){.integration .picker-layout{grid-template-columns:1fr;gap:14px}.integration .provider-list{grid-template-columns:repeat(2,minmax(0,1fr));max-height:220px;padding:0}.integration .provider-detail{padding:15px}.integration .picker-header{display:block}.integration .provider-option{min-height:55px}}@media(max-width:360px){.integration .provider-list{grid-template-columns:1fr}}
-`;
-export const INTEGRATION_PICKER_SCRIPT = String.raw`
-function mountIntegrationPicker(root,catalog,options={}){
- root.replaceChildren();root.classList.add("integration");
- const node=(tag,text,className)=>{const n=integrationNode(tag,text);if(className)n.className=className;return n};
- const button=(label,handler,className)=>{const b=node("button",label,className);b.type="button";b.addEventListener("click",handler);return b};
- const header=node("header",undefined,"picker-header"),head=node("div");head.append(node("h2","Integrations"),node("p","Connect services directly to MSO. Review the official steps first, then enter your credential in a private form."));header.append(head);if(options.session){const status=node("p","Checking MSO session…","picker-note");status.id="integration-auth-status";status.setAttribute("role","status");header.append(status)}root.append(header);
- const layout=node("div",undefined,"picker-layout"),directory=node("section"),detail=node("section",undefined,"provider-detail"),list=node("div",undefined,"provider-list"),search=node("input");
- search.type="search";search.placeholder="Search "+catalog.length+" services";search.setAttribute("aria-label","Search integrations");directory.append(search,list);layout.append(directory,detail);root.append(layout);
- let selected=catalog.find(p=>p.id===options.provider)||catalog.find(p=>p.id==="composio")||catalog[0];
- function trustedLink(url,text,feedback){const a=node("a",text);try{const u=new URL(url);if(u.protocol!=="https:")return node("span",text);a.href=u.href}catch{return node("span",text)}a.target="_blank";a.rel="noopener noreferrer";if(options.openLink)a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(options.openLink(a.href)).catch(()=>{feedback.textContent="The chat host could not open this link. Open the provider dashboard in your browser."})});return a}
- function drawList(){list.replaceChildren();for(const p of catalog.filter(p=>(p.title+" "+p.description).toLowerCase().includes(search.value.toLowerCase()))){const b=button("",()=>{selected=p;drawList();drawDetail()},"provider-option");b.setAttribute("aria-pressed",String(p.id===selected.id));b.append(node("span",p.title),node("small",p.methods.length>1?p.methods.length+" authentication methods":"Direct credential"));list.append(b)}if(!list.children.length)list.append(node("p","No services matched."))}
- function drawDetail(){
- detail.replaceChildren(node("h3",selected.title),node("p",selected.description));
- const methodLabel=node("label","Authentication method"),select=node("select"),preview=node("div"),feedback=node("p",undefined,"picker-feedback");select.id="integration-auth-method";methodLabel.htmlFor=select.id;feedback.setAttribute("role","status");feedback.setAttribute("aria-live","polite");
- for(const method of selected.methods){const o=node("option",method.label);o.value=method.id;select.append(o)}if(options.method&&selected.methods.some(m=>m.id===options.method)){select.value=options.method;options.method=null}
- const actions=node("div",undefined,"picker-actions"),open=button("Open secure form",async()=>{
- open.disabled=true;feedback.textContent="Opening private setup…";
- try{await options.openSetup(selected.id,select.value)}catch(error){feedback.textContent=error.message||"Setup could not be opened. Sign in as an owner or refresh the connector.";open.disabled=false}
- },"primary");open.dataset.integrationStart="true";if(options.session)open.disabled=options.session.loading||options.session.role!=="owner";actions.append(open);
- if(options.openBrowser)actions.append(button(options.browserLabel||"Open in browser",()=>Promise.resolve(options.openBrowser()).catch(()=>{feedback.textContent="Open the MSO Integrations address in your browser."})));
- function drawGuide(){
- preview.replaceChildren();const method=selected.methods.find(m=>m.id===select.value),guide=method.guidance;
- preview.append(node("label","What you will need"));const fields=node("div",undefined,"provider-fields");for(const f of method.fields)fields.append(node("span",f.label+(f.required?" *":""),"field-tag"));preview.append(fields);
- const d=node("details"),summary=node("summary","Step by step: get this credential"),ol=node("ol");d.open=true;d.append(summary,trustedLink(guide.url,"Open official provider dashboard",feedback));for(const step of guide.steps)ol.append(node("li",step));d.append(ol,trustedLink(guide.reference,"Official documentation",feedback));preview.append(d);
- preview.append(node("p","Ten-minute form · direct HTTPS submission · values never enter the chat. An API check proves access to that endpoint, not every future operation.","picker-note"));
- }
- select.addEventListener("change",drawGuide);detail.append(methodLabel,select,preview,actions,feedback);drawGuide();
- }
- search.addEventListener("input",drawList);drawList();drawDetail();
- return()=>{root.replaceChildren();root.classList.remove("integration")};
-}
-`;
diff --git a/lib/infra/setup-ui.ts b/lib/infra/setup-ui.ts
index 15c688ec..fddf4059 100644
--- a/lib/infra/setup-ui.ts
+++ b/lib/infra/setup-ui.ts
@@ -11,8 +11,8 @@ function mountIntegrationForm(root,setup,access){
const token=access&&access.token,endpoint=access&&access.endpoint;
const back=()=>{if(typeof access?.onBack==="function"){const b=integrationNode("button","← All integrations");b.type="button";b.className="back-link";b.addEventListener("click",access.onBack);root.append(b)}};back();
if(!token||!endpoint){root.append(integrationNode("h2","Secure form unavailable"),integrationNode("p","The chat host did not deliver private setup authorization. Reopen the form or use the browser entrypoint; never paste a credential into chat."));if(access?.openBrowser){const b=integrationNode("button","Open Integrations in browser");b.type="button";b.addEventListener("click",()=>access.openBrowser());root.append(b)}return()=>{root.replaceChildren();root.classList.remove("integration")}}
- const heading=integrationNode("h2",setup.title+" connection"),tag=integrationNode("span",setup.method+" · single-use session");tag.className="setup-tag";
- root.append(tag,heading,integrationNode("p","API keys go directly to your MSO server. They are not sent to ChatGPT or saved in browser storage."));
+ const heading=integrationNode("h2",setup.title+" · "+(setup.label||setup.connection||"connection")),tag=integrationNode("span",setup.method+" · single-use session");tag.className="setup-tag";
+ root.append(tag,heading,integrationNode("p",[setup.user,setup.connection,setup.source,setup.scope].filter(Boolean).join(" → ")),integrationNode("p","API keys go directly to your MSO server. They are not sent to ChatGPT or saved in browser storage."));
const grid=integrationNode("div"),form=integrationNode("form"),aside=integrationNode("aside");grid.className="setup-grid";form.autocomplete="off";form.setAttribute("action","#");
const inputs=[];
for(const f of setup.fields){
@@ -39,7 +39,7 @@ function mountIntegrationForm(root,setup,access){
try{
const response=await fetch(endpoint,{method:"POST",credentials:"omit",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},body:JSON.stringify({action:"save",values}),signal:AbortSignal.any([abort.signal,AbortSignal.timeout(45000)])});
const data=await response.json();
- if(!response.ok){const messages={credential_validation_failed:"The provider rejected this key or could not be reached. Check key type, permissions, and expiry; nothing was saved.",invalid_credential_format:"Check the credential format and remove pasted line breaks.",required_fields_missing:"Complete all required fields.",enter_at_least_one_value:"Enter a value to update.",setup_expired_or_invalid:"Setup expired or already used. Open a new form."};throw new Error(messages[data.error]||"Unable to save. Reopen setup or check the provider; nothing was displayed.")}
+ if(!response.ok){const messages={credential_validation_failed:"The provider rejected this key or could not be reached. Check key type, permissions, and expiry; nothing was saved.",invalid_credential_format:"Check the credential format and remove pasted line breaks.",connection_changed_reopen_setup:"This connection changed after the form opened. Reopen it before updating credentials.",required_fields_missing:"Complete all required fields.",enter_at_least_one_value:"Enter a value to update.",setup_expired_or_invalid:"Setup expired or already used. Open a new form."};throw new Error(messages[data.error]||"Unable to save. Reopen setup or check the provider; nothing was displayed.")}
used=true;clearTimeout(timer);inputs.forEach(f=>{f.input.value="";f.input.disabled=true});save.textContent="Saved";status.textContent="Verified and saved in MSO. This setup session is now closed.";
}catch(error){status.textContent=error.message||"Connection failed. Check MSO connectivity."}finally{if(!used)save.disabled=false;for(const key of Object.keys(values))delete values[key]}
});
diff --git a/lib/infra/store.ts b/lib/infra/store.ts
index ff90da53..6e3720d2 100644
--- a/lib/infra/store.ts
+++ b/lib/infra/store.ts
@@ -1,79 +1,33 @@
-import { randomUUID } from "node:crypto";
-import { constants as fsConstants, promises as fs } from "node:fs";
-import os from "node:os";
-import path from "node:path";
-import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import {randomUUID} from "node:crypto";
import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
-import type { InfraProviderId, InfraProviderSummary, InfraProviderValues, InfraStore } from "./types";
-
-export const INFRA_STORE_PATH = process.env.OS_INFRA_STORE ?? path.join(os.homedir(), ".mso", "private", "infra-providers.json");
-const MAX_STORE_BYTES = 256 * 1024;
-
-function mask(value: string): string {
- return value ? "configured" : "";
-}
-
-async function readUnlocked(): Promise<InfraStore> {
- let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
- try {
- handle = await fs.open(INFRA_STORE_PATH, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
- const stat = await handle.stat();
- if (!stat.isFile()) throw new Error("infrastructure provider store must be a regular file");
- if (stat.size <= 0 || stat.size > MAX_STORE_BYTES) throw new Error("infrastructure provider store has an invalid size");
- if ((stat.mode & 0o077) !== 0) throw new Error("infrastructure provider store permissions are too broad; expected 0600");
- if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("infrastructure provider store is not owned by the MSO user");
- const raw = JSON.parse(await handle.readFile("utf8")) as InfraStore;
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("infrastructure provider store has an invalid shape");
- return raw;
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
- throw error;
- } finally {
- await handle?.close().catch(() => undefined);
- }
-}
-
-async function writeUnlocked(store: InfraStore): Promise<void> {
- const dir = path.dirname(INFRA_STORE_PATH);
- await fs.mkdir(dir, { recursive: true, mode: 0o700 });
- await fs.chmod(dir, 0o700).catch(() => undefined);
- const tmp = `${INFRA_STORE_PATH}.${randomUUID()}.tmp`;
- await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
- await fs.chmod(tmp, 0o600);
- await fs.rename(tmp, INFRA_STORE_PATH);
- await fs.chmod(INFRA_STORE_PATH, 0o600);
-}
-
-export async function readInfraProvider(id: InfraProviderId): Promise<InfraProviderValues> {
- const store = await readUnlocked();
- return { ...(store.providers?.[id] ?? {}) };
-}
-
-export async function setInfraProvider(id: InfraProviderId, raw: Record<string, unknown>): Promise<InfraProviderValues> {
- return withSecurityStoreLock(INFRA_STORE_PATH, async () => {
- const store = await readUnlocked();
- const current = store.providers?.[id] ?? {};
- const normalized = normalizeInfraValues(id, raw);
- const values = { ...current, ...normalized };
- const def = getInfraProviderDefinition(id);
- const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
- if (id === "composio" && !values.apiKey && !values.orgApiKey) missing.push("project or organization API key");
- if (id === "convex-cloud" && !values.personalToken && !(values.deployKey && values.deploymentName)) missing.push("personal token or deployment key and name");
- if (missing.length) throw new Error(`${id} is missing required value(s): ${missing.join(", ")}`);
- await writeUnlocked({ ...store, providers: { ...(store.providers ?? {}), [id]: values } });
- return values;
+import { mutateIntegrationState } from "./connection-storage";
+import { currentIntegrationSelection, directConnectionValues, createConnectionIn } from "./connection-service";
+import { legacyMethod, connectionMethod } from "./connection-registry";
+import { selectConnection, IntegrationError, assertNotBusy } from "./identity";
+import type { InfraProviderId, InfraProviderSummary, InfraProviderValues } from "./types";
+export { INFRA_STORE_PATH } from "./connection-storage";
+const mask=(value:string)=>value?"configured":"";
+export const readInfraProvider=(id:InfraProviderId)=>directConnectionValues(id);
+export async function setInfraProvider(id:InfraProviderId,raw:Record<string,unknown>):Promise<InfraProviderValues>{
+ return mutateIntegrationState(state=>{
+ const selector=currentIntegrationSelection();
+ if(!Object.keys(state.users).length&&!selector.user){state.users.legacy={id:"legacy",uid:randomUUID(),label:"Existing MSO credentials",defaults:{},connections:{}};state.defaultUser="legacy";}
+ let selected;
+ try{selected=selectConnection(state,id,selector);}catch(e){
+ if(!(e instanceof IntegrationError)||e.code!=="connection_not_found"||selector.connection)throw e;
+ const user=selector.user??state.defaultUser;if(!user)throw new IntegrationError("user_required");
+ const c=createConnectionIn(state,{user,provider:id,connection:"default",authMethod:legacyMethod(id,raw as Record<string,string>),makeDefault:true});selected={user,connection:c};
+ }
+ const c=selected.connection;assertNotBusy(c);if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden");
+ const method=connectionMethod(id,c.source,c.authMethod),normalized=normalizeInfraValues(id,raw);
+ if(Object.keys(normalized).some(k=>!method.fields.some(f=>f.key===k)))throw new IntegrationError("connection_auth_mismatch",409);
+ const values={...c.values,...normalized};if(method.fields.some(f=>f.required&&!values[f.key]))throw new IntegrationError("required_fields_missing");
+ c.values=values;c.revision++;c.updatedAt=Date.now();delete c.verifiedAt;return{...values};
});
}
-
-export async function removeInfraProvider(id: InfraProviderId): Promise<void> {
- await withSecurityStoreLock(INFRA_STORE_PATH, async () => {
- const store = await readUnlocked();
- const providers = { ...(store.providers ?? {}) };
- delete providers[id];
- await writeUnlocked({ ...store, providers });
- });
+export async function removeInfraProvider(id:InfraProviderId){
+ await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);delete state.users[r.user].connections[id][r.connection.id];if(state.users[r.user].defaults[id]===r.connection.id)delete state.users[r.user].defaults[id];});
}
-
export function summarizeInfraProvider(id: InfraProviderId, values: InfraProviderValues): InfraProviderSummary {
const def = getInfraProviderDefinition(id);
const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
diff --git a/lib/infra/types.ts b/lib/infra/types.ts
index d0bcba5d..61f33b10 100644
--- a/lib/infra/types.ts
+++ b/lib/infra/types.ts
@@ -2,7 +2,7 @@ export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "compos
export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];
export type InfraProviderValues = Record<string, string>;
-export type InfraStore = {
+export type LegacyInfraStore = {
providers?: Partial<Record<InfraProviderId, InfraProviderValues>>;
};
@@ -39,3 +39,5 @@ export type InfraDoctorResult = {
ok: boolean | null;
detail: string;
};
+
+export type { IntegrationState as InfraStore, ConnectionSelector, IntegrationConnection, IntegrationUser } from "./identity";
diff --git a/lib/mcp/integration-model-contract.test.ts b/lib/mcp/integration-model-contract.test.ts
new file mode 100644
index 00000000..6a803ca8
--- /dev/null
+++ b/lib/mcp/integration-model-contract.test.ts
@@ -0,0 +1,34 @@
+import {beforeEach,afterEach,it,expect,vi} from "vitest";
+import {promises as fs} from "node:fs";
+import os from "node:os";
+import path from "node:path";
+vi.mock("server-only",()=>({}));
+let root:string;
+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-contract-model-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+afterEach(async()=>{delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+it("uses the same native metadata services through actual MCP calls and rejects insufficient scope",async()=>{
+ const {dispatch}=await import("./dispatch");
+ const call=(id:number,name:string,args:Record<string,unknown>,scope:"read"|"write"|"exec"="exec")=>dispatch({id,method:"tools/call",params:{name,arguments:args}},scope,"test",{principal:"mcp-client:integration-contract",sessionId:"integration-contract",toolProfile:"chatgpt"});
+ const denied=await call(1,"integration_manage",{action:"user.create",user:"alice",confirm:true},"read");expect(denied.error??denied.result).toBeTruthy();
+ const {readIntegrationState}=await import("@/lib/infra/connection-storage");expect((await readIntegrationState()).users).toEqual({});
+ const created=await call(2,"integration_manage",{action:"user.create",user:"alice",confirm:true});expect(created.error).toBeUndefined();expect((created.result as any)?.structuredContent?.result?.ok).toBe(true);
+ const added=await call(3,"integration_manage",{action:"connection.create",user:"alice",provider:"convex-cloud",connection:"mimin-production",authMethod:"deployment",source:"direct",confirm:true});expect(added.error).toBeUndefined();
+ const metadata=await call(4,"integration_query",{view:"resolve",user:"alice",provider:"convex-cloud",connection:"mimin-production"});expect((metadata.result as any)?.structuredContent?.result).toMatchObject({user:"alice",id:"mimin-production",source:"direct",authMethod:"deployment"});
+ const inputRejected=await call(5,"integration_manage",{action:"user.create",user:"eve",confirm:true,token:"synthetic"});expect((await readIntegrationState()).users.eve).toBeUndefined();expect(inputRejected.error??(inputRejected.result as any)?.isError).toBeTruthy();
+});
+it("returns identity-bound setup only in UI-private metadata on both supported MCP profiles",async()=>{
+ const {integrationManage}=await import("@/lib/infra/connection-manage");await integrationManage({action:"user.create",user:"alice",confirm:true});await integrationManage({action:"connection.create",user:"alice",provider:"github",connection:"work",source:"direct",authMethod:"direct",confirm:true});
+ const {dispatch}=await import("./dispatch");
+ for(const profile of ["full","chatgpt"] as const){
+ const result=await dispatch({id:1,method:"tools/call",params:{name:"integration_setup_open",arguments:{user:"alice",provider:"github",connection:"work"}}},"write","test",{principal:"mcp-client:integration-contract",sessionId:"integration-contract",toolProfile:profile});
+ const wire=result.result as any;expect(result.error).toBeUndefined();expect(wire.structuredContent.setup).toMatchObject({user:"alice",connection:"work",source:"direct"});
+ const token=wire._meta?.integrationSetup?.token;expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);expect(JSON.stringify(wire.content)).not.toContain(token);expect(JSON.stringify(wire.structuredContent)).not.toContain(token);
+ }
+});
+it("keeps current and older Page resources readable and emits no extra UI type",async()=>{
+ const {readUiResource,listUiResources,MSO_PAGE_URI}=await import("./ui-resources");
+ expect(listUiResources()).toHaveLength(2);const html=readUiResource(MSO_PAGE_URI)!.text;
+ for(const version of [1,2,3,4,5,6])expect(readUiResource(`ui://mso/page-v${version}.html`)?.text).toBe(html);
+ expect(html).toContain("mountConnectionManager");expect(html).toContain("data-display-mode");
+ const script=html.match(/<script>([\s\S]*)<\/script>/)?.[1];expect(()=>new Function(script!)).not.toThrow();
+});
diff --git a/lib/mcp/integration-setup.test.ts b/lib/mcp/integration-setup.test.ts
index beca79a9..7fd7eeed 100644
--- a/lib/mcp/integration-setup.test.ts
+++ b/lib/mcp/integration-setup.test.ts
@@ -19,7 +19,7 @@ describe("MCP integration setup privacy", () => {
});
it("requires write scope, accepts no credential parameters, and uses the existing Page", () => {
const tool = SURFACE_TOOLS.find(t => t.name === "integration_setup_open")!;
- expect(tool.scope).toBe("write"); expect(Object.keys(tool.inputSchema.properties)).toEqual(["provider", "method"]);
+ expect(tool.scope).toBe("write"); expect(Object.keys(tool.inputSchema.properties)).toEqual(["user", "connection", "provider", "method"]);
expect(tool.meta?.["openai/outputTemplate"]).toMatch(/^ui:\/\/mso\/page/);
expect(resolveSurfaceRoute("/integrations").kind).toBe("integrations");
expect(() => new Function(MSO_SURFACE_SCRIPT)).not.toThrow();
diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.ts
index 12e43a42..c072c352 100644
--- a/lib/mcp/parity.test.ts
+++ b/lib/mcp/parity.test.ts
@@ -4,21 +4,9 @@ vi.mock("server-only", () => ({}));
const { TOOLS } = await import("./tools");
const { HOST_TOOLS } = await import("@/frontend/slices/assistant/host-tools/catalog");
-// THE GATE. Alfa and MCP are two catalogs on purpose — different transport,
-// different guard (an approval card vs a scope tier), different handlers — and
-// unifying them was considered and rejected: they share zero names, zero
-// descriptions and zero handlers, so a shared registry would be an abstraction
-// with two divergent consumers.
-//
-// What they must NOT do is drift by ACCIDENT, which is exactly what happened:
-// MCP shipped apps_logs / apps_power / browser_status / browser_power and Alfa
-// silently had less reach over the box than a remote ChatGPT connector, while
-// Alfa's apps.list had been answering "no apps installed" for months. Nobody
-// decided either one.
-//
-// So: every capability must appear in BOTH catalogs, or be listed below with a
-// reason. Adding a tool to one surface alone fails this test until someone writes
-// down why.
+// Every capability must be available through both MCP and Alfa, or explicitly
+// justify the deliberate identity/transport boundary below. Different adapters
+// are not permission to let their executable capabilities drift accidentally.
/** MCP is snake_case, Alfa is dot.case. Same capability, different convention. */
const capability = (name: string) => name.replace(/[._]/g, ".");
@@ -33,6 +21,10 @@ const ALFA_ONLY: Record<string, string> = {
};
const MCP_ONLY: Record<string, string> = {
+ "integration.query":"Native credential profiles are managed by owner browser/CLI and external agents; Alfa has no independent credential-owner identity and must not invent one",
+ "integration.manage":"Same credential-owner boundary; browser and CLI use the shared native action service with confirmation rather than duplicating it in Alfa",
+ "integration.execute":"External deployment agents require explicit account selection; the native owner UI/CLI share the executor without exposing keys to Alfa",
+
"session.artifacts": "CLI/MCP durable-session artifact records use the authenticated client principal; Alfa browser threads have a separate identity and must not inherit another session's files",
"session.artifact.register": "same durable-session boundary; external browser producers stage files under session context rather than accepting arbitrary paths",
"session.artifacts.cleanup": "same session store; bounded retention is controlled by the authenticated external/CLI principal, not unrelated Alfa thread state",
@@ -189,7 +181,7 @@ describe("MCP rate limits mirror the routes", () => {
"projects.mcp.call": 30,
"skills.list": 30,
"skills.read": 60,
- "integration.setup": 10,
+ "integration.setup": 10, "integration.manage":30, "integration.execute":30,
"infra.dokploy": 20,
"infra.cloudflare": 20,
"infra.hostinger": 10,
diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.ts
index e8d1dd1c..a5967c32 100644
--- a/lib/mcp/tool-contract.ts
+++ b/lib/mcp/tool-contract.ts
@@ -53,7 +53,7 @@ export const CHATGPT_TOOL_NAMES = new Set([
"sys_stats", "sys_processes", "apps_list", "apps_logs", "apps_power", "browser_status", "browser_power",
// Infrastructure operations remain explicit and bounded; secrets stay server-side.
- "integration_setup_open", "infra_providers_list", "infra_provider_doctor", "dokploy_projects_list", "dokploy_project_ensure",
+ "integration_query", "integration_manage", "integration_execute", "integration_setup_open", "infra_providers_list", "infra_provider_doctor", "dokploy_projects_list", "dokploy_project_ensure",
"cloudflare_zones_list", "cloudflare_dns_upsert", "hostinger_dns_upsert",
// Arbitrary shell is still a last-resort escape hatch and long builds remain job-bound.
@@ -115,7 +115,7 @@ export function toolAllowedForProfile(name: string, profile: McpToolProfile = "f
return profile === "full" || CHATGPT_TOOL_NAMES.has(name as never);
}
-function compactText(value: string, max = 190): string {
+function compactText(value: string, max = 125): string {
const clean = value.replace(/\s+/g, " ").trim();
if (clean.length <= max) return clean;
const cut = clean.slice(0, max - 1);
@@ -128,8 +128,8 @@ function compactSchema(value: unknown): unknown {
if (!value || typeof value !== "object") return value;
const out: Record<string, unknown> = {};
for (const [key, item] of Object.entries(value as Record<string, unknown>)) {
- if (key === "workflow_id" && item && typeof item === "object") out[key] = { ...compactSchema(item) as Record<string, unknown>, description: "workflow_start id." };
- else if (key === "description" && typeof item === "string") out[key] = compactText(item, 105);
+ if (key === "workflow_id" && item && typeof item === "object") out[key] = { type:"string" };
+ else if (key === "description" && typeof item === "string") out[key] = compactText(item, 72);
else out[key] = compactSchema(item);
}
return out;
diff --git a/lib/mcp/tools-infra.ts b/lib/mcp/tools-infra.ts
index a5a29315..e66a31f7 100644
--- a/lib/mcp/tools-infra.ts
+++ b/lib/mcp/tools-infra.ts
@@ -1,3 +1,6 @@
+import { withIntegrationSelection } from "@/lib/infra/connection-service";
+import { selectionFrom } from "@/lib/infra/connection-dispatch";
+import { INTEGRATION_SELECTOR_SCHEMA } from "./tools-integrations";
import { doctorInfraProvider, ensureDokployProject, INFRA_PROVIDER_IDS, isInfraProviderId, listCloudflareZones, listDokployProjects, readInfraProvider, summarizeInfraProvider, upsertCloudflareDns, upsertHostingerDns } from "@/lib/infra";
import { type McpTool, S, str } from "./tool-kit";
@@ -8,7 +11,7 @@ const dnsSchema = {
ttl: { type: "number", description: "Optional TTL seconds. Cloudflare defaults to automatic." },
};
-export const INFRA_TOOLS: McpTool[] = [
+const BASE_INFRA_TOOLS: McpTool[] = [
{
name: "infra_providers_list",
description: "List native MSO integrations and infrastructure providers, showing masked configuration state and missing required fields. Raw credentials are never returned.",
@@ -76,3 +79,8 @@ export const INFRA_TOOLS: McpTool[] = [
run: async (a) => upsertHostingerDns({ name: str(a, "name"), type: str(a, "type"), content: str(a, "content"), ttl: typeof a.ttl === "number" ? a.ttl : undefined }),
},
];
+
+export const INFRA_TOOLS:McpTool[]=BASE_INFRA_TOOLS.map(tool=>({...tool,
+ inputSchema:{...tool.inputSchema,properties:{...tool.inputSchema.properties,...INTEGRATION_SELECTOR_SCHEMA}},
+ run:async(a,context)=>withIntegrationSelection(selectionFrom(a),()=>tool.run(a,context)),
+}));
diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.ts
new file mode 100644
index 00000000..b6e93db4
--- /dev/null
+++ b/lib/mcp/tools-integrations.ts
@@ -0,0 +1,25 @@
+import { queryIntegrationAction, manageIntegrationAction, executeIntegrationAction } from "@/lib/infra/connection-dispatch";
+import { INTEGRATION_ACTIONS } from "@/lib/infra/connection-manage";
+import { SOURCES } from "@/lib/infra/identity";
+import { type McpTool, S, mcpDirect } from "./tool-kit";
+export const INTEGRATION_SELECTOR_SCHEMA={user:{type:"string",maxLength:64},connection:{type:"string",maxLength:64},cwd:{type:"string",maxLength:4096}};
+const BASE={...INTEGRATION_SELECTOR_SCHEMA,provider:{type:"string",maxLength:64}};
+const OUTPUT={type:"object",properties:{result:{type:"object"}},required:["result"],additionalProperties:false};
+export const INTEGRATION_TOOLS:McpTool[]=[
+ {name:"integration_query",title:"Inspect Integration Connections",scope:"read",annotations:{readOnlyHint:true,idempotentHint:true,openWorldHint:false},
+ description:"Read native MSO credential users, providers, named connections, source/auth guidance and directory resolution. Never returns keys. User profiles are credential owners, not device roles. Resolve before acting when multiple accounts or deployments exist.",
+ inputSchema:S({...BASE,view:{type:"string",enum:["snapshot","catalog","users","connections","which","resolve","request"]},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64}}),outputSchema:OUTPUT,
+ meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await queryIntegrationAction(a)}),
+ },
+ {name:"integration_manage",title:"Manage Named Integrations",scope:"write",annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},audit:{action:"infra.write",targetArg:"user"},limit:{key:"integration.manage",max:30,windowMs:60000},
+ description:"Manage native credential users, directory bindings and named provider connections. Actions require confirm=true. Direct credential values are forbidden: use integration_setup_open with user/provider/connection. Composio authorization keeps only external IDs/status and returns its transient URL privately to the UI. Native MCP authorization stays provider-owned.",
+ inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Explicit opt-in when duplicating a user; default copies metadata only."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,
+ meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},
+ run:async a=>{const out=await manageIntegrationAction(a);if("privateUrl" in out){const{privateUrl,...safe}=out;return mcpDirect([{type:"text",text:"Authorization link available in the private integration UI."}],false,{result:safe},{integrationAuthorization:{url:privateUrl}});}return{result:out};},
+ },
+ {name:"integration_execute",title:"Use an Exact Integration Connection",scope:"exec",annotations:{readOnlyHint:false,destructiveHint:true,openWorldHint:true},audit:{action:"infra.write",targetArg:"connection"},limit:{key:"integration.execute",max:30,windowMs:60000},
+ description:"Execute using an explicit user/provider/named connection. Verify or inspect its route; bounded direct operations reject external backends. Composio tool execution requires an ACTIVE matching connected account and a toolkit-prefixed tool. Native-MCP returns the provider route without copying OAuth tokens. Non-verification operations require confirm=true. No credentials in arguments.",
+ inputSchema:S({...BASE,operation:{type:"string",enum:["route","verify","dokploy.projects.list","dokploy.project.ensure","cloudflare.zones.list","cloudflare.dns.upsert","hostinger.dns.upsert","composio.tool"]},confirm:{type:"boolean"},tool:{type:"string",maxLength:180},arguments:{type:"object",additionalProperties:true}},["user","provider","connection","operation"]),outputSchema:OUTPUT,
+ meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await executeIntegrationAction(a)}),
+ },
+];
diff --git a/lib/mcp/tools-surface.ts b/lib/mcp/tools-surface.ts
index eafec815..7d4fca63 100644
--- a/lib/mcp/tools-surface.ts
+++ b/lib/mcp/tools-surface.ts
@@ -1,3 +1,6 @@
+import {metadataOnly} from "@/lib/infra/identity";
+import { selectionFrom, safeActionInput } from "@/lib/infra/connection-dispatch";
+import { integrationSnapshot } from "@/lib/infra/connection-service";
import { openIntegrationSetup } from "@/lib/infra/setup-capability";
import { INFRA_PROVIDER_IDS } from "@/lib/infra/types";
import { MSO_ORIGIN } from "./ui-config";
@@ -22,7 +25,7 @@ const PAGE_OUTPUT = {
properties: {
route: { type: "string" }, kind: { type: "string", enum: ["home", "monitor", "project", "diff", "browser", "app", "integrations"] },
title: { type: "string" }, openPath: { type: "string" }, project: { type: "string" }, sha: { type: "string" },
- setup: { type: "object" },
+ setup: { type: "object" }, integrations: {type:"object"},
app: { type: "object" }, catalog: { type: "array", items: APP_SCHEMA },
},
required: ["route", "kind", "title", "openPath", "catalog"],
@@ -42,10 +45,10 @@ function publicResolved(resolved: ResolvedSurface): Record<string, unknown> {
return { ...rest, app: safeApp };
}
-const renderPage = async (input: Record<string, unknown>) => ({
- ...publicResolved(resolveSurfaceRoute(str(input, "route"), { project: opt(input, "project"), sha: opt(input, "sha") })),
- catalog: publicSurfaceApps(),
-});
+const renderPage = async (input:Record<string,unknown>) => {
+ const resolved=publicResolved(resolveSurfaceRoute(str(input,"route"),{project:opt(input,"project"),sha:opt(input,"sha")}));
+ return {...resolved,catalog:publicSurfaceApps(),...(resolved.kind==="integrations"?{integrations:await integrationSnapshot()}: {})};
+};
export const SURFACE_TOOLS: McpTool[] = [
{
@@ -57,7 +60,7 @@ export const SURFACE_TOOLS: McpTool[] = [
annotations: { readOnlyHint: false, destructiveHint: true, openWorldHint: false, idempotentHint: false },
audit: { action: "infra.write", targetArg: "provider" },
limit: { key: "integration.setup", max: 10, windowMs: 60_000 },
- inputSchema: S({ provider: { type: "string", enum: [...INFRA_PROVIDER_IDS] }, method: { type: "string", enum: ["direct", "project", "organization", "personal", "deployment"], description: "Composio defaults to project; other providers use direct." } }, ["provider"]),
+ inputSchema: S({ user:{type:"string",maxLength:64},connection:{type:"string",maxLength:64}, provider: { type: "string", enum: [...INFRA_PROVIDER_IDS] }, method: { type: "string", enum: ["direct", "project", "organization", "personal", "deployment"], description: "Must match this connection; omitted uses its stored auth method." } }, ["user","provider","connection"]),
outputSchema: PAGE_OUTPUT,
meta: {
ui: { resourceUri: MSO_PAGE_URI, visibility: ["model", "app"] },
@@ -67,7 +70,8 @@ export const SURFACE_TOOLS: McpTool[] = [
"openai/toolInvocation/invoked": "Secure setup form opened",
},
run: async (input, context) => {
- const grant = await openIntegrationSetup(str(input, "provider"), context.principal ?? context.actor ?? "", opt(input, "method"));
+ metadataOnly(safeActionInput(input));
+ const grant = await openIntegrationSetup(str(input, "provider"), context.principal ?? context.actor ?? "", opt(input, "method"), selectionFrom(input));
const output = { route: "/integrations", kind: "integrations", title: "Integrations", openPath: "/integrations", catalog: publicSurfaceApps(), setup: grant.setup };
return mcpDirect([{ type: "text", text: `Secure ${grant.setup.title} setup opened. Enter the credential in the form, never in chat.` }], false, output,
{ integrationSetup: { token: grant.token, endpoint: `${MSO_ORIGIN}/api/integrations/setup` } });
diff --git a/lib/mcp/tools.ts b/lib/mcp/tools.ts
index 41eac288..aa65b2a6 100644
--- a/lib/mcp/tools.ts
+++ b/lib/mcp/tools.ts
@@ -1,3 +1,4 @@
+import { INTEGRATION_TOOLS } from "./tools-integrations";
import { SESSION_ARTIFACT_TOOLS } from "./tools-session-artifacts";
import { sessionArtifactEnvironment } from "@/lib/agent/artifact-session";
import { writeFileGuarded, makeDir, remove, move, copy } from "@/lib/host/fs-api";
@@ -230,4 +231,4 @@ const MUTATE_TOOLS: McpTool[] = [
},
];
-export const TOOLS: McpTool[] = [...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
+export const TOOLS: McpTool[] = [...SESSION_ARTIFACT_TOOLS, ...READ_TOOLS, ...DISCOVERY_TOOLS, ...LEARNING_TOOLS, ...AGENT_TOOLS, ...LOCAL_AGENT_TOOLS, ...SUBAGENT_TOOLS, ...A2A_TOOLS, ...FORGE_TOOLS, ...READ_PIPELINE_TOOLS, ...PROJECT_MCP_TOOLS, ...PROJECT_EXPERIENCE_TOOLS, ...OPERATOR_DASHBOARD_TOOLS, ...BLOCK_TOOLS, ...SURFACE_TOOLS, ...INFRA_TOOLS, ...INTEGRATION_TOOLS, ...MUTATE_TOOLS, ...POWER_TOOLS].map(withWorkflowContext); export const TOOLS_BY_NAME = new Map(TOOLS.map((t) => [t.name, t]));
diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.ts
index 25f053ee..b2676427 100644
--- a/lib/mcp/toolset.ts
+++ b/lib/mcp/toolset.ts
@@ -4,8 +4,8 @@ import type { McpTool } from "./tool-kit";
import { toolDescriptor, type McpToolProfile } from "./tool-contract";
export const MCP_SERVER_VERSION = "1.12.0";
-export const MCP_TOOLSET_VERSION = "2026.09.05.7";
-export const MCP_TOOLSET_CHANGED_AT = "2026-09-05T13:00:00Z";
+export const MCP_TOOLSET_VERSION = "2026.09.05.8";
+export const MCP_TOOLSET_CHANGED_AT = "2026-09-05T14:05:00Z";
export type McpToolsetInfo = {
serverVersion: string;
diff --git a/lib/mcp/ui-page-bridge.ts b/lib/mcp/ui-page-bridge.ts
index cb847dcf..498ae6e5 100644
--- a/lib/mcp/ui-page-bridge.ts
+++ b/lib/mcp/ui-page-bridge.ts
@@ -3,7 +3,7 @@ export const MSO_PAGE_BRIDGE_SCRIPT = String.raw`
let hostConnected=false, hostContext={}, lastOutputKey="", viewCleanup=()=>{};
let lastPageSize="";
function reportPageSize(){
- if(!hostConnected)return;const root=document.querySelector(".surface");if(!root)return;
+ if(!hostConnected||document.documentElement.dataset.displayMode==="fullscreen")return;const root=document.querySelector(".surface");if(!root)return;
const rect=root.getBoundingClientRect(),style=getComputedStyle(document.body);
const height=Math.ceil(rect.height+(parseFloat(style.paddingTop)||0)+(parseFloat(style.paddingBottom)||0));
const width=Math.ceil(document.documentElement.clientWidth),key=width+","+height;
diff --git a/lib/mcp/ui-page-integrations.ts b/lib/mcp/ui-page-integrations.ts
index 842fe07d..324eed89 100644
--- a/lib/mcp/ui-page-integrations.ts
+++ b/lib/mcp/ui-page-integrations.ts
@@ -1,39 +1,30 @@
import { INTEGRATION_FORM_SCRIPT } from "@/lib/infra/setup-ui";
-import { INTEGRATION_PICKER_SCRIPT } from "@/lib/infra/setup-picker";
-import { integrationCatalog } from "@/lib/infra/setup-catalog";
+import { CONNECTION_MANAGER_SCRIPT } from "@/lib/infra/connection-ui";
+import { connectionCatalog } from "@/lib/infra/connection-registry";
import { MSO_ORIGIN } from "./ui-config";
-export const MSO_PAGE_INTEGRATIONS_SCRIPT = String.raw`
+export const MSO_PAGE_INTEGRATIONS_SCRIPT=String.raw`
${INTEGRATION_FORM_SCRIPT}
-${INTEGRATION_PICKER_SCRIPT}
-const INTEGRATION_ENDPOINT=${JSON.stringify(MSO_ORIGIN + "/api/integrations/setup")};
-const INTEGRATION_BROWSER=${JSON.stringify(MSO_ORIGIN + "/integrations")};
-const INTEGRATION_CATALOG=${JSON.stringify(integrationCatalog()).replace(/</g,"\\u003c")};
-let integrationAccess=null;
-function captureIntegrationAccess(raw,depth=0){
- if(!raw||typeof raw!=="object"||depth>4)return;
- const access=raw.integrationSetup;
- if(access&&typeof access.token==="string"&&/^[A-Za-z0-9_-]{43}$/.test(access.token)&&access.endpoint===INTEGRATION_ENDPOINT){integrationAccess=access;return}
- for(const key of ["_meta","mcp_tool_result","call_tool_result","result"])if(raw[key])captureIntegrationAccess(raw[key],depth+1);
-}
-async function openIntegrationReference(url){
- if(hostConnected)return rpcRequest("ui/open-link",{url});
- if(window.openai&&typeof window.openai.openExternal==="function")return window.openai.openExternal({href:url,redirectUrl:false});
- return rpcRequest("ui/open-link",{url});
+${CONNECTION_MANAGER_SCRIPT}
+const INTEGRATION_ENDPOINT=${JSON.stringify(MSO_ORIGIN+"/api/integrations/setup")};
+const INTEGRATION_BROWSER=${JSON.stringify(MSO_ORIGIN+"/integrations")};
+const INTEGRATION_CATALOG=${JSON.stringify(connectionCatalog()).replace(/</g,"\\u003c")};
+let integrationAccess=null,integrationSelection={};
+function privateIntegrationMeta(raw,key,depth=0){if(!raw||typeof raw!=="object"||depth>5)return null;if(raw[key])return raw[key];for(const k of ["_meta","result","mcp_tool_result","call_tool_result"]){const found=privateIntegrationMeta(raw[k],key,depth+1);if(found)return found}return null}
+function captureIntegrationAccess(raw){const access=privateIntegrationMeta(raw,"integrationSetup");if(access&&/^[A-Za-z0-9_-]{43}$/.test(access.token)&&access.endpoint===INTEGRATION_ENDPOINT)integrationAccess=access}
+function openIntegrationReference(url){if(hostConnected)return rpcRequest("ui/open-link",{url});if(window.openai?.openExternal)return window.openai.openExternal({href:url,redirectUrl:false});return rpcRequest("ui/open-link",{url})}
+async function integrationTool(name,args){
+ const response=await rpcCall(name,args);if(response?.isError||response?.error){const e=new Error("Integration action unavailable or rejected. Check permissions, or refresh the MSO connector's tools.");throw e}
+ const out=unbox(response);return{response,data:out?.result??out};
}
function renderIntegrations(){
- const onBack=()=>{integrationAccess=null;lastOutputKey="";current={route:"/integrations",kind:"integrations",title:"Integrations",openPath:"/integrations",catalog:[]};render()};
- const openBrowser=()=>openIntegrationReference(INTEGRATION_BROWSER);
- if(current.setup){
- captureIntegrationAccess(window.openai&&window.openai.toolResponseMetadata);
- viewCleanup=mountIntegrationForm(body,current.setup,{...(integrationAccess||{}),openLink:openIntegrationReference,onBack,openBrowser})||(()=>{});return;
- }
- viewCleanup=mountIntegrationPicker(body,INTEGRATION_CATALOG,{
- openBrowser,openLink:openIntegrationReference,
- openSetup:async(provider,method)=>{
- const result=await rpcCall("integration_setup_open",{provider,method});
- captureIntegrationAccess(result);captureIntegrationAccess(window.openai&&window.openai.toolResponseMetadata);
- if(!acceptPageResult(result)||!current.setup)throw new Error("The connector could not open the secure form. Use Open in browser, or refresh the MSO connector to load the new setup action.");
- }
- });
+ const back=()=>{integrationAccess=null;lastOutputKey="";current={route:"/integrations",kind:"integrations",title:"Integrations",openPath:"/integrations",catalog:[]};render()};
+ if(current.setup){captureIntegrationAccess(window.openai?.toolResponseMetadata);viewCleanup=mountIntegrationForm(body,current.setup,{...(integrationAccess||{}),onBack:back,openLink:openIntegrationReference,openBrowser:()=>openIntegrationReference(INTEGRATION_BROWSER)})||(()=>{});return}
+ const bridge={remember:s=>integrationSelection=s,openLink:openIntegrationReference,
+ query:async args=>(await integrationTool("integration_query",args)).data,
+ manage:async args=>{const{response,data}=await integrationTool("integration_manage",args);const meta=privateIntegrationMeta(response,"integrationAuthorization")||privateIntegrationMeta(window.openai?.toolResponseMetadata,"integrationAuthorization");return{...data,...(meta?.url?{privateUrl:meta.url}:{})}},
+ execute:async args=>(await integrationTool("integration_execute",args)).data,
+ openSetup:async args=>{const{response}=await integrationTool("integration_setup_open",args);captureIntegrationAccess(response);captureIntegrationAccess(window.openai?.toolResponseMetadata);if(!acceptPageResult(response))throw new Error("The host did not return a valid setup Page. Use Open in MSO or refresh this connector.")},
+ };
+ viewCleanup=mountConnectionManager(body,INTEGRATION_CATALOG,bridge,{...integrationSelection,snapshot:current.integrations});
}
`;
diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.ts
index ead05f68..b1a1c65b 100644
--- a/lib/mcp/ui-resources.test.ts
+++ b/lib/mcp/ui-resources.test.ts
@@ -149,7 +149,7 @@ describe("MCP Apps Block and Page contract", () => {
frameDomains: ["https://game.rahmanef.com"],
});
expect(content._meta["openai/widgetCSP"]).toEqual({ connect_domains: [MSO_ORIGIN], frame_domains: ["https://game.rahmanef.com"], redirect_domains: [MSO_ORIGIN, "https://game.rahmanef.com"] });
- expect(MSO_PAGE_URI).toContain("page-v6.html");
+ expect(MSO_PAGE_URI).toContain("page-v7.html");
});
it("returns only redacted structured workflow state and keeps status polling out of workflow memory", async () => {
diff --git a/lib/mcp/ui-resources.ts b/lib/mcp/ui-resources.ts
index 6cc5d8f4..16d75f9a 100644
--- a/lib/mcp/ui-resources.ts
+++ b/lib/mcp/ui-resources.ts
@@ -8,6 +8,7 @@ export const MCP_APP_MIME_TYPE = "text/html;profile=mcp-app";
// across the UI-contract migration. They are intentionally not advertised by
// resources/list: the public product contract has exactly Block and Page.
export const LEGACY_BLOCK_V1_URI = "ui://mso/block-v1.html";
+export const LEGACY_PAGE_V6_URI = "ui://mso/page-v6.html";
export const LEGACY_PAGE_V5_URI = "ui://mso/page-v5.html";
export const LEGACY_PAGE_V4_URI = "ui://mso/page-v4.html";
export const LEGACY_PAGE_V3_URI = "ui://mso/page-v3.html";
@@ -27,6 +28,7 @@ export type McpUiResource = {
const RESOURCES: readonly McpUiResource[] = [MSO_BLOCK_RESOURCE, MSO_PAGE_RESOURCE];
const LEGACY_ALIASES = new Map<string, McpUiResource>([
+ [LEGACY_PAGE_V6_URI, MSO_PAGE_RESOURCE],
[LEGACY_PAGE_V5_URI, MSO_PAGE_RESOURCE],
[LEGACY_PAGE_V4_URI, MSO_PAGE_RESOURCE],
[LEGACY_PAGE_V3_URI, MSO_PAGE_RESOURCE],
diff --git a/lib/mcp/ui-surface-script.ts b/lib/mcp/ui-surface-script.ts
index 25ed40f7..186b79b0 100644
--- a/lib/mcp/ui-surface-script.ts
+++ b/lib/mcp/ui-surface-script.ts
@@ -53,14 +53,20 @@ function safeAppResult(raw){
}
function openPath(path){setMsoTarget(validRoute(path)?path:"/assistant/mcp")}
function applyHostGlobals(){
- const api={...hostContext,...(window.openai||{})};
+ const api=hostConnected?{...(window.openai||{}),...hostContext}:{...hostContext,...(window.openai||{})};
applyHostTheme();
const max=Number(api.maxHeight);document.documentElement.style.setProperty("--host-max-h",Number.isFinite(max)&&max>180?Math.floor(max)+"px":"680px");
const safe=api.safeArea||{};for(const [key,value] of [["top",safe.top],["right",safe.right],["bottom",safe.bottom],["left",safe.left]]){const n=Number(value);document.documentElement.style.setProperty("--safe-"+key,Number.isFinite(n)?Math.max(0,n)+"px":"0px")}
- modeEl.textContent=text(api.displayMode,"inline");
+ const mode=["inline","fullscreen","pip"].includes(api.displayMode)?api.displayMode:"inline";
+ document.documentElement.dataset.displayMode=mode;
+ modeEl.textContent=mode;fsBtn.textContent=mode==="fullscreen"?"Exit fullscreen":"Fullscreen";
+ fsBtn.setAttribute("aria-label",mode==="fullscreen"?"Exit fullscreen":"Fullscreen");
}
async function displayMode(mode){
- try{if(hostConnected){await rpcRequest("ui/request-display-mode",{mode})}else{if(!window.openai||typeof window.openai.requestDisplayMode!=="function")throw new Error("unsupported");await window.openai.requestDisplayMode({mode})}}catch(_){modeEl.textContent=mode+" unavailable"}
+ try{const target=mode==="fullscreen"&&document.documentElement.dataset.displayMode==="fullscreen"?"inline":mode;let result;
+ if(hostConnected){result=await rpcRequest("ui/request-display-mode",{mode:target});if(result&&["inline","fullscreen","pip"].includes(result.mode||result.displayMode))hostContext={...hostContext,displayMode:result.mode||result.displayMode};}
+ else{if(!window.openai||typeof window.openai.requestDisplayMode!=="function")throw new Error("unsupported");result=await window.openai.requestDisplayMode({mode:target});}
+ applyHostGlobals();}catch(_){modeEl.textContent=mode+" unavailable"}
}
function persistRoute(){
try{if(window.openai&&typeof window.openai.setWidgetState==="function")window.openai.setWidgetState({modelContent:"MSO Page: "+current.route,privateContent:{route:current.route},imageIds:[]})}catch(_){}
diff --git a/lib/mcp/ui-surface-style.ts b/lib/mcp/ui-surface-style.ts
index b9b35d5e..248c597f 100644
--- a/lib/mcp/ui-surface-style.ts
+++ b/lib/mcp/ui-surface-style.ts
@@ -6,4 +6,11 @@ ${MSO_WIDGET_TOKENS}
.frame-status{display:flex;gap:8px;align-items:center;flex-wrap:wrap;padding:6px 2px 10px;font-size:10px;color:var(--text-dim)}.frame-status span{flex:1;min-width:120px}.frame-status button{min-height:34px}.stage>div:last-child{min-height:0;display:flex;flex-direction:column;flex:1}.frame-wrap[data-state="unavailable"]{border-color:var(--destructive-text)}
@media(max-width:660px){body{padding:5px}.surface{max-height:var(--host-max-h);border-radius:14px}.bar{align-items:flex-start;min-height:46px}.tools{max-width:50%}.tools button,.tools .button{padding:5px 7px}.grid{grid-template-columns:1fr 1fr}.frame-wrap iframe{min-height:430px}.metrics{grid-template-columns:1fr 1fr}.body{padding:9px}}
@media(max-width:420px){.grid{grid-template-columns:1fr}.heading span{max-width:150px}.tools .optional{display:none}.metrics{grid-template-columns:1fr}.frame-wrap iframe{min-height:480px}}
+html[data-display-mode="fullscreen"],html[data-display-mode="fullscreen"] body{height:100%;width:100%;overflow:hidden}
+html[data-display-mode="fullscreen"] body{padding:0}
+html[data-display-mode="fullscreen"] .surface{height:100vh;height:100dvh;min-height:0;max-height:none;border:0;border-radius:0;box-shadow:none}
+html[data-display-mode="fullscreen"] .surface>.bar{flex:0 0 auto;padding-top:max(8px,var(--safe-top))}
+html[data-display-mode="fullscreen"] .surface>.body{flex:1;min-height:0;overscroll-behavior:contain}
+html[data-display-mode="fullscreen"] .stage{min-height:0}
+html[data-display-mode="fullscreen"] .frame-wrap iframe{min-height:0;height:100%}
`;
diff --git a/lib/mcp/ui-surface.ts b/lib/mcp/ui-surface.ts
index 4f0f751c..e7c47b54 100644
--- a/lib/mcp/ui-surface.ts
+++ b/lib/mcp/ui-surface.ts
@@ -1,4 +1,4 @@
-import { INTEGRATION_PICKER_STYLE } from "@/lib/infra/setup-picker";
+import { CONNECTION_MANAGER_STYLE } from "@/lib/infra/connection-ui";
import { INTEGRATION_FORM_STYLE } from "@/lib/infra/setup-ui";
import { widgetResourceMeta, MSO_ORIGIN } from "./ui-config";
import { OPEN_IN_MSO_SCRIPT, openInMsoControls } from "./ui-navigation";
@@ -6,11 +6,11 @@ import { surfaceFrameDomains } from "./surface-catalog";
import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";
import { MSO_SURFACE_STYLE } from "./ui-surface-style";
-export const MSO_PAGE_URI = "ui://mso/page-v6.html";
+export const MSO_PAGE_URI = "ui://mso/page-v7.html";
const MIME = "text/html;profile=mcp-app";
const html = String.raw`<main class="surface" aria-label="MSO Page">
-<style>${MSO_SURFACE_STYLE}${INTEGRATION_FORM_STYLE}${INTEGRATION_PICKER_STYLE}</style>
+<style>${MSO_SURFACE_STYLE}${INTEGRATION_FORM_STYLE}${CONNECTION_MANAGER_STYLE}</style>
<header class="bar">
<div class="brand" aria-hidden="true">M</div>
<div class="heading"><strong id="surface-title">MSO Page</strong><span id="surface-route">/</span></div>
diff --git a/scripts/cli/commands-runtime.sh b/scripts/cli/commands-runtime.sh
index a4fd439d..43c7a583 100755
--- a/scripts/cli/commands-runtime.sh
+++ b/scripts/cli/commands-runtime.sh
@@ -9,6 +9,7 @@ case "$cmd" in
model) run_model_setup "$@" ;;
setup) run_onboard "${1-}" ;;
onboard) run_onboard "${1-}" ;;
+ integrations) run_integrations "$@" ;;
provider|providers) run_provider "$@" ;;
# ── local/public gateway + browser launcher ───────────────────────────────
diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.sh
index 8c2689a6..c68b8c31 100755
--- a/scripts/cli/commands.sh
+++ b/scripts/cli/commands.sh
@@ -24,7 +24,8 @@ verbs() {
U_camoufox="camoufox status|start|stop|session"
U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"
U_doctor="doctor [--fix]"
-U_provider="provider list|show <id>|setup <id> [method]|set <id>|rm <id>|doctor [id]|projects|zones"
+U_integrations="integrations status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|execute <JSON>"
+U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"
U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"
U_agent="agent [--continue|-c|--resume|-r <latest|index|id|title>|--yolo|-yolo] | agent --oneshot <prompt> [--json] [--approve-scope read|write|exec]"
U_mapp="mapp list|show|logs|backups|jobs|job <id> <jobId>|pending <id>|install|update|power <id> <act>|cancel <id> <jobId>"
@@ -87,7 +88,7 @@ mso_cli_main() {
case "$cmd" in
version|--version|-V|-v|ls|cat|raw|share|usage|search|write|mkdir|rm|mv|cp|zip|upload|exec|stats|ps|units|unit|packages|cleanup|status|health|doctor)
mso_cmd_host "$cmd" "$@" ;;
- agent|chat|model|setup|onboard|provider|providers|gateway|web|camoufox|apps|mapp|term)
+ agent|chat|model|setup|onboard|provider|providers|integrations|gateway|web|camoufox|apps|mapp|term)
mso_cmd_runtime "$cmd" "$@" ;;
ai|cockpit|threads|agent-sessions|agents|a2a|memory|config|prefs|models|skills|changelog|stock)
mso_cmd_state "$cmd" "$@" ;;
diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.sh
index a558a74a..16eadcbd 100755
--- a/scripts/mso-cli-agent.sh
+++ b/scripts/mso-cli-agent.sh
@@ -347,11 +347,8 @@ run_provider() {
local -a pairs=()
case "$sub" in
setup|web)
- [ -n "$id" ] || die "usage: mso provider setup <id> [direct|project|organization|personal|deployment]"
- tty_ok || die "secure setup links are terminal-only; MCP callers must use integration_setup_open (never exec)"
- data=$(jpost "/api/v1/infra/setup" "$(jq -nc --arg provider "$id" --arg method "${3:-$(case "$id" in composio) echo project ;; convex-cloud) echo personal ;; *) echo direct ;; esac)}" '{provider:$provider,method:$method}')")
- printf 'Open this private link in your browser (expires after 10 minutes):\n%s#%s\n' "$(jq -r '.setupUrl' <<<"$data")" "$(jq -r '.token' <<<"$data")"
- unset data
+ [ $# -eq 4 ] || die "usage: mso provider setup <provider> <user> <connection>; or mso integrations setup <user> <provider> <connection>"
+ run_integrations setup "$3" "$2" "$4"
;;
list)
provider_metadata | jq -r '.providers[] | "\(if .configured then "✓" else "·" end) \(.id)\t\(if .configured then "configured" else "missing: " + (.missing|join(", ")) end)\t\(.description)"' ;;
@@ -446,3 +443,10 @@ run_agent() {
MSO_AGENT_CLI="$ROOT/bin/mso" MSO_AGENT_VERSION="$VERSION" \
node "$ROOT/scripts/mso-agent.mjs" "$@"
}
+
+# Lazy loading keeps offline update/recovery independent of optional command slices.
+run_integrations() {
+ # shellcheck source=mso-cli-integrations.sh
+ source "$ROOT/scripts/mso-cli-integrations.sh"
+ run_integrations "$@"
+}
diff --git a/scripts/mso-cli-integrations.sh b/scripts/mso-cli-integrations.sh
new file mode 100644
index 00000000..ba76163a
--- /dev/null
+++ b/scripts/mso-cli-integrations.sh
@@ -0,0 +1,51 @@
+#!/usr/bin/env bash
+# Native connection management. All actions use the same owner API as the browser.
+run_integrations() {
+ local sub="${1:-status}" data user provider connection query body
+ shift || true
+ case "$sub" in
+ status|users|catalog)
+ query="snapshot"; [ "$sub" = users ] && query=users; [ "$sub" = catalog ] && query=catalog
+ jget "/api/v1/integrations?view=$query" ;;
+ connections)
+ query="view=connections"; [ -n "${1-}" ] && query="$query&user=$(enc "$1")"; [ -n "${2-}" ] && query="$query&provider=$(enc "$2")"
+ jget "/api/v1/integrations?$query" ;;
+ which) jget "/api/v1/integrations?view=which&cwd=$(enc "${1:-$PWD}")" ;;
+ request|resolve)
+ [ $# -ge 2 ] || die "usage: mso integrations $sub <user> <provider> [connection]"
+ query="view=$sub&user=$(enc "$1")&provider=$(enc "$2")"; [ -n "${3-}" ] && query="$query&connection=$(enc "$3")"
+ jget "/api/v1/integrations?$query" ;;
+ setup)
+ [ $# -eq 3 ] || die "usage: mso integrations setup <user> <provider> <connection>"
+ tty_ok || die "private setup links are terminal-only; use integration_setup_open from MCP"
+ user="$1"; provider="$2"; connection="$3"
+ data=$(jpost "/api/v1/infra/setup" "$(jq -nc --arg user "$user" --arg provider "$provider" --arg connection "$connection" '{user:$user,provider:$provider,connection:$connection}')")
+ printf 'Private setup for %s / %s / %s (10 minutes; do not share):\n%s#%s\n' "$user" "$provider" "$connection" "$(jq -r '.setupUrl' <<<"$data")" "$(jq -r '.token' <<<"$data")"
+ unset data ;;
+ create-user)
+ [ $# -ge 1 ] || die "usage: mso integrations create-user <id> [label]"
+ body=$(jq -nc --arg user "$1" --arg label "${2:-$1}" '{mode:"manage",action:"user.create",confirm:true,user:$user,label:$label}')
+ jpost "/api/v1/integrations" "$body" ;;
+ create-connection)
+ [ $# -ge 5 ] || die "usage: mso integrations create-connection <user> <provider> <id> <direct|composio|native-mcp> <auth-method> [label]"
+ body=$(jq -nc --arg user "$1" --arg provider "$2" --arg connection "$3" --arg source "$4" --arg authMethod "$5" --arg label "${6:-$3}" '{mode:"manage",action:"connection.create",confirm:true,user:$user,provider:$provider,connection:$connection,source:$source,authMethod:$authMethod,label:$label}')
+ jpost "/api/v1/integrations" "$body" ;;
+ manage)
+ [ $# -eq 1 ] || die 'usage: mso integrations manage <metadata-JSON with action and confirm:true>'
+ body=$(jq -ce 'if type=="object" and .confirm==true then .+{mode:"manage"} else error("explicit confirmation required") end' <<<"$1")
+ data=$(jpost "/api/v1/integrations" "$body")
+ # Hosted authorization links must not be emitted by non-interactive agent calls.
+ if jq -e '.privateUrl' >/dev/null <<<"$data"; then
+ if tty_ok; then jq . <<<"$data"; else jq 'del(.privateUrl)+{notice:"Authorization link available only in the private UI or interactive terminal"}' <<<"$data"; fi
+ else printf '%s\n' "$data"; fi ;;
+ verify|route)
+ [ $# -eq 3 ] || die "usage: mso integrations $sub <user> <provider> <connection>"
+ body=$(jq -nc --arg op "$sub" --arg user "$1" --arg provider "$2" --arg connection "$3" '{mode:"execute",operation:$op,user:$user,provider:$provider,connection:$connection}')
+ jpost "/api/v1/integrations" "$body" ;;
+ execute)
+ [ $# -eq 1 ] || die 'usage: mso integrations execute <metadata-JSON with user, provider, connection, operation and confirm:true>'
+ body=$(jq -ce 'if type=="object" then .+{mode:"execute"} else error("object required") end' <<<"$1")
+ jpost "/api/v1/integrations" "$body" ;;
+ *) die 'usage: mso integrations status|users|catalog|connections|which|request|resolve|create-user|create-connection|manage|setup|verify|route|execute' ;;
+ esac
+}
diff --git a/scripts/mso-cli-integrations.test.ts b/scripts/mso-cli-integrations.test.ts
new file mode 100644
index 00000000..a95990fe
--- /dev/null
+++ b/scripts/mso-cli-integrations.test.ts
@@ -0,0 +1,27 @@
+import {execFileSync} from "node:child_process";
+import {expect,it} from "vitest";
+import path from "node:path";
+const script=path.join(process.cwd(),"scripts/mso-cli-integrations.sh");
+function run(args:string[]){return execFileSync("bash",["-c",`set -e
+source "$1"
+shift
+enc(){ printf '%s' "$1"; }
+jget(){ printf '%s' "$1"; }
+jpost(){ printf '%s' "$2"; }
+die(){ printf '%s' "$*" >&2; exit 2; }
+tty_ok(){ return 1; }
+run_integrations "$@"
+`,"test",script,...args],{encoding:"utf8"});}
+it("routes exact user/provider/connection through the native owner API",()=>{
+ expect(run(["resolve","alice","convex-cloud","mimin-production"])).toContain("view=resolve&user=alice&provider=convex-cloud&connection=mimin-production");
+ expect(JSON.parse(run(["verify","alice","convex-cloud","mimin-staging"]))).toMatchObject({mode:"execute",operation:"verify",user:"alice",provider:"convex-cloud",connection:"mimin-staging"});
+ expect(JSON.parse(run(["create-connection","alice","github","work","composio","oauth2"]))).toMatchObject({mode:"manage",confirm:true,user:"alice",provider:"github",connection:"work",source:"composio",authMethod:"oauth2"});
+});
+it("does not print private setup links through a non-interactive caller",()=>{
+ expect(()=>run(["setup","alice","github","work"])).toThrow();
+});
+it("requires explicit metadata mutation confirmation and carries folder context",()=>{
+ expect(()=>run(["manage",JSON.stringify({action:"user.delete",user:"alice"})])).toThrow();
+ expect(JSON.parse(run(["manage",JSON.stringify({action:"user.default",user:"alice",confirm:true})]))).toMatchObject({mode:"manage",confirm:true});
+ expect(run(["which","/home/test/project"])).toContain("view=which&cwd=/home/test/project");
+});