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.
TypeScript browser-shellcontrol-planefile-managerhomelabmobile-firstnextjsptyreactself-hostedserver-managementshadcn-uisysadmintailwindcssterminaltypescriptvpsweb-desktopweb-terminal
feat(integrations): add native secure credential setup in browser and MCP Page
Rahmanc164dbe2c6a0
diff --git a/README.md b/README.mdindex 839dd411..06abef33 100644--- a/README.md+++ b/README.md@@ -558,3 +558,5 @@ MSO is **Public Alpha / Developer Preview**. The core role-aware auth, filesyste## LicenseMIT — see [LICENSE](./LICENSE).++**Secure connections:** [Native Integrations](docs/INTEGRATIONS.md) provides temporary credential forms in the browser, terminal, and ChatGPT Page.diff --git a/app/api/integrations/setup/route.test.ts b/app/api/integrations/setup/route.test.tsnew file mode 100644index 00000000..f596cd18--- /dev/null+++ b/app/api/integrations/setup/route.test.ts@@ -0,0 +1,38 @@+import { afterEach, beforeEach, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+vi.mock("server-only", () => ({}));+vi.mock("@/lib/host/audit-api", () => ({ audit: vi.fn() }));+let root: string;+beforeEach(async () => { root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-setup-route-")); 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 endpoint = "https://mso.rahmanef.com/api/integrations/setup";+function req(token: string, origin = "https://mso-ui.rahmanef.com", body: unknown = { action: "schema" }) {+ return new NextRequest(endpoint, { method: "POST", headers: { origin, authorization: `Bearer ${token}`, "content-type": "application/json" }, body: JSON.stringify(body) });+}+it("allows only exact trusted Origins and never grants credentialed CORS", async () => {+ const { OPTIONS, POST } = await import("./route");+ const good = OPTIONS(new NextRequest(endpoint, { method: "OPTIONS", headers: { origin: "https://mso-ui.rahmanef.com" } }));+ expect(good.status).toBe(204); expect(good.headers.get("access-control-allow-origin")).toBe("https://mso-ui.rahmanef.com");+ expect(good.headers.has("access-control-allow-credentials")).toBe(false);+ for (const origin of ["https://evil.invalid", "https://mso-ui.rahmanef.com.evil.invalid", "null"]) expect((await POST(req("x".repeat(43), origin))).status).toBe(403);+ expect((await POST(req("x".repeat(43)))).status).toBe(401);+});+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 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);+});+it("rejects oversized and non-JSON body before invoking any provider", async () => {+ const { POST } = await import("./route");+ expect((await POST(req("x".repeat(43), undefined, { action: "save", values: { apiKey: "x".repeat(18000) } }))).status).toBe(413);+ const input = req("x".repeat(43)); input.headers.set("content-type", "text/plain"); expect((await POST(input)).status).toBe(415);+});+it("serves uncached, unframeable HTML without an authenticated key", async () => {+ const { GET } = await import("./route"); const response = GET();+ expect(response.headers.get("cache-control")).toContain("no-store"); expect(response.headers.get("content-security-policy")).toContain("frame-ancestors 'none'");+});diff --git a/app/api/integrations/setup/route.ts b/app/api/integrations/setup/route.tsnew file mode 100644index 00000000..a02e1e87--- /dev/null+++ b/app/api/integrations/setup/route.ts@@ -0,0 +1,42 @@+import { readSetupJson } from "@/lib/infra/setup-http";+import { NextRequest, NextResponse } from "next/server";+import { MSO_ORIGIN, MCP_UI_DOMAIN } from "@/lib/mcp/ui-config";+import { audit } from "@/lib/host/audit-api";+import { consumeIntegrationSetup, describeIntegrationSetup, SetupError } from "@/lib/infra/setup-capability";+import { integrationSetupPage } from "@/lib/infra/setup-page";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const BASE_HEADERS = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer", "X-Content-Type-Options": "nosniff", Vary: "Origin" };+function cors(req: NextRequest): Record<string, string> | null {+ const origin = req.headers.get("origin");+ let local = false;+ try { const url = new URL(req.url); local = ["127.0.0.1", "localhost", "[::1]"].includes(url.hostname) && origin === url.origin; } catch { /* not a local request */ }+ if (!origin || (![MSO_ORIGIN, MCP_UI_DOMAIN].includes(origin) && !local)) return null;+ return { ...BASE_HEADERS, "Access-Control-Allow-Origin": origin, "Access-Control-Allow-Methods": "POST, OPTIONS", "Access-Control-Allow-Headers": "Authorization, Content-Type" };+}+export function GET() {+ const page = integrationSetupPage();+ return new NextResponse(page.html, { headers: { ...BASE_HEADERS, "Content-Type": "text/html; charset=utf-8", "Content-Security-Policy": page.csp, "X-Frame-Options": "DENY" } });+}+export function OPTIONS(req: NextRequest) {+ const headers = cors(req);+ return new NextResponse(null, { status: headers ? 204 : 403, headers: headers ?? BASE_HEADERS });+}+export async function POST(req: NextRequest) {+ const headers = cors(req);+ if (!headers) return NextResponse.json({ error: "origin_not_allowed" }, { status: 403, headers: BASE_HEADERS });+ const match = /^Bearer ([A-Za-z0-9_-]{43})$/.exec(req.headers.get("authorization") ?? "");+ if (!match) return NextResponse.json({ error: "setup_expired_or_invalid" }, { status: 401, headers });+ try {+ const body = await readSetupJson(req);+ if (Object.keys(body).some(k => !["action", "values"].includes(k))) throw new SetupError("invalid_request", 400);+ if (body.action === "schema") return NextResponse.json(await describeIntegrationSetup(match[1]), { headers });+ if (body.action !== "save") throw new SetupError("invalid_request", 400);+ const result = await consumeIntegrationSetup(match[1], body.values);+ 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);+ return NextResponse.json({ error: safe.code }, { status: safe.status, headers });+ }+}diff --git a/app/api/v1/infra/setup/route.ts b/app/api/v1/infra/setup/route.tsnew file mode 100644index 00000000..c61ea7ad--- /dev/null+++ b/app/api/v1/infra/setup/route.ts@@ -0,0 +1,20 @@+import { MSO_ORIGIN } from "@/lib/mcp/ui-config";+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { audit } from "@/lib/host/audit-api";+import { openIntegrationSetup } from "@/lib/infra/setup-capability";+import { readSetupJson } from "@/lib/infra/setup-http";+export const runtime = "nodejs";+export const dynamic = "force-dynamic";+export async function POST(req: NextRequest) {+ const context = await getSessionContext();+ const headers = { "Cache-Control": "no-store, private", "Referrer-Policy": "no-referrer" };+ 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);+ 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}/api/integrations/setup` }, { headers });+ } catch { return NextResponse.json({ error: "setup_unavailable" }, { status: 400, headers }); }+}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex f3b2a4a3..1464848a 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,10 @@ this is the *what*, and it is what Settings → About shows as “What's new”.## 2026-09-05+**Added**++- `integrations` add native secure credential setup in browser and MCP Page+**Fixed**- `mcp` initialize page previews and verify embedded app readinessdiff --git a/docs/INFRASTRUCTURE-PROVIDERS.md b/docs/INFRASTRUCTURE-PROVIDERS.mdindex 2dd07f0c..390a1c40 100644--- a/docs/INFRASTRUCTURE-PROVIDERS.md+++ b/docs/INFRASTRUCTURE-PROVIDERS.md@@ -206,3 +206,12 @@ A provider is not complete merely because MSO can store its token. A new integraPrefer provider-native exact operations over generic `curl`/shell automation. Generic shellremains the escape hatch, not the product API.++## Native Composio setup++Composio project and organization keys are now supported by the native provider+store and doctor, alongside the existing infrastructure providers. Use+`mso provider setup composio project` or `mso provider setup composio organization`+for a temporary form. This verifies platform credentials; it does not authorize+every connected application or copy its OAuth tokens. See [Native Integrations](INTEGRATIONS.md)+for the owner-browser and ChatGPT Page workflows.diff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdnew file mode 100644index 00000000..249c40c8--- /dev/null+++ b/docs/INTEGRATIONS.md@@ -0,0 +1,100 @@+# Native Integrations++Connect Composio, Dokploy, Cloudflare, and Hostinger 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.++## Browser and terminal++Open `/api/integrations/setup` on your MSO origin, sign in as an owner in another+tab when needed, select the provider, then choose **Start secure setup**. 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.++From an interactive terminal with an authenticated MSO session:++```sh+mso provider setup composio project+mso provider setup composio organization+mso provider setup hostinger+```++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.++## ChatGPT Page++`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+```++The grant reaches the UI through hidden MCP `_meta`. A WeakMap keeps it out of+ordinary result serialization and non-ChatGPT model transports. 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.diff --git a/docs/MCP.md b/docs/MCP.mdindex 03dd8cae..da97a73a 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -669,3 +669,10 @@ one on its own the way it does a cookie.### Bounded asynchronous execution`exec_job_start` starts a client/workflow-bound command that may run up to 20 minutes; `exec_job_status` reads its bounded output and final exit state; `exec_job_cancel` stops a still-running job. Use this trio for test/build pipelines instead of wrapping `exec_run` in host-specific background-process plumbing.++## Native credential setup++MSO Integrations uses the existing Page at `/integrations`. The write-scoped+`integration_setup_open` tool opens a secure form without accepting secret values.+See [Native Integrations](INTEGRATIONS.md) for browser/CLI entrypoints, scope,+expiry, direct HTTPS submission, and verification limits.diff --git a/docs/README.md b/docs/README.mdindex 142baa89..30e57eb1 100644--- a/docs/README.md+++ b/docs/README.md@@ -26,10 +26,11 @@ evidence and review freshness. The repository quality gate runs both automatical| [`COMPARISON.md`](./COMPARISON.md) | Generated product comparison methodology, evidence and notes || [`COMPETITIVE-ROADMAP.md`](./COMPETITIVE-ROADMAP.md) | Executed comparison plan, deliberate specialist boundaries and next investments || [`INSTALL.md`](./INSTALL.md) | Owner installation, TLS, updates, backup and uninstall |-| [`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) | Interactive MSO Agent TUI/approval/error contract plus Dokploy/Cloudflare/Hostinger credentials, tools and deployment boundary |+| [`INFRASTRUCTURE-PROVIDERS.md`](./INFRASTRUCTURE-PROVIDERS.md) | Interactive MSO Agent TUI/approval/error contract plus Dokploy/Cloudflare/Hostinger/Composio credentials, tools and deployment boundary || [`DEVELOPMENT.md`](./DEVELOPMENT.md) | Development and release workflow || [`SECURITY-ASSURANCE.md`](./SECURITY-ASSURANCE.md) | Repeatable security verification lanes, public evidence, and claim boundaries || [`CLI.md`](./CLI.md) | Generated `mso` CLI contract |+| [`INTEGRATIONS.md`](./INTEGRATIONS.md) | Native temporary credential forms, direct HTTPS secret submission, CLI and ChatGPT Page || [`MCP.md`](./MCP.md) | MCP/OAuth internals and full external-tool security model || [`A2A.md`](./A2A.md) | A2A v1 peer discovery, delegation/task lifecycle, CLI/MCP surface and trust boundary || [`LOCAL-AGENTS.md`](./LOCAL-AGENTS.md) | Native same-host session presence, identity, mailbox delivery, TUI/tools/API and isolation |diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 9931409e..77c76530 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,17 +4,17 @@## Full MSO catalog-<!-- mcp-toolset: server=1.10.0 version=2026.09.05.1 tools=88 read=44 write=25 exec=19 -->+<!-- mcp-toolset: server=1.10.0 version=2026.09.05.3 tools=89 read=44 write=26 exec=19 -->| Fact | Current source value ||---|---:|| MCP server | `1.10.0` |-| Toolset | `2026.09.05.1` |-| Toolset changed at | `2026-09-04T10:25:00Z` |-| Transport tools | **90** |-| Model/operator tools | **88** |+| Toolset | `2026.09.05.3` |+| Toolset changed at | `2026-09-05T11:45:00Z` |+| Transport tools | **91** |+| Model/operator tools | **89** || Read | **44** |-| Write | **25** |+| Write | **26** || Exec | **19** || App-only bridges | **2** |@@ -65,7 +65,7 @@- `tool_forge_candidates`- `vps_status`-### Write (25)+### Write (26)- `a2a_agent_register`- `a2a_agent_remove`@@ -83,6 +83,7 @@- `fs_upload_file`- `fs_write`- `hostinger_dns_upsert`+- `integration_setup_open`- `local_agent_message_send`- `local_agent_reply`- `project_knowledge_set`@@ -122,16 +123,16 @@## ChatGPT static profile-<!-- mcp-chatgpt-profile: server=1.10.0 version=2026.09.05.1 tools=64 read=35 write=17 exec=12 app-only=2 total=66 -->+<!-- mcp-chatgpt-profile: server=1.10.0 version=2026.09.05.3 tools=65 read=35 write=18 exec=12 app-only=2 total=67 -->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 | **66** |-| ChatGPT model/operator tools | **64** |+| ChatGPT transport tools | **67** |+| ChatGPT model/operator tools | **65** || Read | **35** |-| Write | **17** |+| Write | **18** || Exec | **12** || App-only bridges | **2** |@@ -173,7 +174,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_- `sys_stats`- `vps_status`-### ChatGPT write (17)+### ChatGPT write (18)- `agent_session_rename`- `apps_power`@@ -186,6 +187,7 @@ The ChatGPT profile is a fail-closed static projection defined by `CHATGPT_TOOL_- `fs_upload_file`- `fs_write`- `hostinger_dns_upsert`+- `integration_setup_open`- `local_agent_message_send`- `local_agent_reply`- `project_knowledge_set`diff --git a/lib/capabilities/tool.ts b/lib/capabilities/tool.tsindex 3c2d7ee7..27351ceb 100644--- a/lib/capabilities/tool.ts+++ b/lib/capabilities/tool.ts@@ -17,13 +17,21 @@ export interface CapabilityDirectResult {structuredContent?: Record<string, unknown>;}+// UI-only capability data is deliberately not a property of the result. Generic+// JSON serialization, logs, Alfa, pipelines and model runtimes cannot copy it.+const PRIVATE_RESULT_META = new WeakMap<object, Record<string, unknown>>();+export const capabilityPrivateMeta = (result: object) => PRIVATE_RESULT_META.get(result);+/** Compatibility marker stays __mcpDirect until the public MCP result contract is versioned. */export function capabilityDirect(content: CapabilityContent[],isError = false,structuredContent?: Record<string, unknown>,+ privateMeta?: Record<string, unknown>,): CapabilityDirectResult {- return { __mcpDirect: true, content, ...(isError ? { isError: true } : {}), ...(structuredContent ? { structuredContent } : {}) };+ const result: CapabilityDirectResult = { __mcpDirect: true, content, ...(isError ? { isError: true } : {}), ...(structuredContent ? { structuredContent } : {}) };+ if (privateMeta) PRIVATE_RESULT_META.set(result, privateMeta);+ return result;}export function isCapabilityDirectResult(value: unknown): value is CapabilityDirectResult {diff --git a/lib/infra/catalog.ts b/lib/infra/catalog.tsindex 26f3bf2a..a1d6f2d1 100644--- a/lib/infra/catalog.ts+++ b/lib/infra/catalog.ts@@ -23,6 +23,16 @@ const definitions: Record<InfraProviderId, InfraProviderDefinition> = {{ key: "accountId", label: "Account ID", secret: false, required: false, description: "Optional account identifier for future account-scoped operations." },],},+ composio: {+ id: "composio",+ title: "Composio",+ description: "Connect a Composio project key or organization key for native MSO automation.",+ feature: false,+ fields: [+ { key: "apiKey", label: "Project API key", secret: true, required: false, description: "Project key sent only as x-api-key to /api/v3.1/tools?limit=1." },+ { key: "orgApiKey", label: "Organization API key", secret: true, required: false, description: "Organization key sent only as x-org-api-key to /api/v3.1/org/project/list." },+ ],+ },hostinger: {id: "hostinger",title: "Hostinger",@@ -73,6 +83,9 @@ export function normalizeInfraValues(id: InfraProviderId, raw: Record<string, unif (out.zoneId && !HEX32_RE.test(out.zoneId)) throw new Error("Cloudflare zoneId must be 32 hexadecimal characters");if (out.accountId && out.accountId.length < 16) throw new Error("Cloudflare accountId is too short");}+ if (id === "composio") {+ for (const value of Object.values(out)) if (value.length < 16 || value.length > 4096 || /[\s\x00-\x1f\x7f]/.test(value)) throw new Error("Composio keys must be opaque single-line values (16–4096 characters)");+ }if (id === "hostinger" && out.apiToken && out.apiToken.length < 24) throw new Error("Hostinger API token is too short");return out;}diff --git a/lib/infra/clients.ts b/lib/infra/clients.tsindex 72240285..c48634e9 100644--- a/lib/infra/clients.ts+++ b/lib/infra/clients.ts@@ -1,19 +1,22 @@-import type { InfraDoctorResult, InfraProviderId } from "./types";+import type { InfraDoctorResult, InfraProviderId, InfraProviderValues } from "./types";import { doctorCloudflare } from "./cloudflare";import { doctorDokploy } from "./dokploy";import { doctorHostinger } from "./hostinger";+import { doctorComposio } from "./composio";export { listCloudflareZones, upsertCloudflareDns } from "./cloudflare";export { ensureDokployProject, listDokployProjects } from "./dokploy";export { upsertHostingerDns } from "./hostinger";-export async function doctorInfraProvider(id: InfraProviderId): Promise<InfraDoctorResult> {+export async function doctorInfraProvider(id: InfraProviderId, candidate?: InfraProviderValues): Promise<InfraDoctorResult> {try {const detail = id === "dokploy"- ? await doctorDokploy()+ ? await doctorDokploy(candidate): id === "cloudflare"- ? await doctorCloudflare()- : await doctorHostinger();+ ? await doctorCloudflare(candidate)+ : id === "composio"+ ? await doctorComposio(candidate)+ : await doctorHostinger(candidate);return detail === null ? { id, ok: null, detail: "not configured" } : { id, ok: true, detail };} catch (error) {return { id, ok: false, detail: (error as Error).message.slice(0, 300) };diff --git a/lib/infra/cloudflare.ts b/lib/infra/cloudflare.tsindex 001aa802..a3b8269c 100644--- a/lib/infra/cloudflare.ts+++ b/lib/infra/cloudflare.ts@@ -1,3 +1,4 @@+import type { InfraProviderValues } from "./types";import { readInfraProvider } from "./store";import { HOST_RE, IPV4_RE, obj, request } from "./http";@@ -9,8 +10,8 @@ const parsed = (body: unknown): { success: boolean; result: unknown } => {return { success: value.success === true, result: value.result };};-export async function listCloudflareZones(): Promise<Array<{ id: string; name: string }>> {- const values = await readInfraProvider("cloudflare");+export async function listCloudflareZones(candidate?: InfraProviderValues): Promise<Array<{ id: string; name: string }>> {+ const values = candidate ?? await readInfraProvider("cloudflare");if (!values.apiToken) throw new Error("Cloudflare is not configured; run `mso provider set cloudflare`");const out: Array<{ id: string; name: string }> = [];for (let page = 1; page <= MAX_PAGE; page++) {@@ -28,12 +29,12 @@ export async function listCloudflareZones(): Promise<Array<{ id: string; name: sreturn out;}-export async function doctorCloudflare(): Promise<string | null> {- const values = await readInfraProvider("cloudflare");+export async function doctorCloudflare(candidate?: InfraProviderValues): Promise<string | null> {+ const values = candidate ?? await readInfraProvider("cloudflare");if (!values.apiToken) return null;const verify = await request(`${API}/user/tokens/verify`, { headers: headers(values.apiToken) });if (!verify.ok || obj(verify.body).success !== true) throw new Error(`token verification HTTP ${verify.status}`);- const zones = await listCloudflareZones();+ const zones = await listCloudflareZones(values);return `active token; ${zones.length} accessible zone(s)${zones.length ? `: ${zones.slice(0, 5).map((z) => z.name).join(", ")}` : ""}`;}diff --git a/lib/infra/composio.ts b/lib/infra/composio.tsnew file mode 100644index 00000000..3cfee136--- /dev/null+++ b/lib/infra/composio.ts@@ -0,0 +1,16 @@+import type { InfraProviderValues } from "./types";+import { readInfraProvider } from "./store";+import { request } from "./http";++const API = "https://backend.composio.dev/api/v3.1";+export async function doctorComposio(candidate?: InfraProviderValues): Promise<string | null> {+ const values = candidate ?? await readInfraProvider("composio");+ const key = values.apiKey;+ const orgKey = values.orgApiKey;+ if (!key && !orgKey) return null;+ const target = orgKey ? "/org/project/list" : "/tools?limit=1";+ const header: Record<string, string> = orgKey ? { "x-org-api-key": orgKey } : { "x-api-key": key! };+ const response = await request(`${API}${target}`, { headers: header });+ if (!response.ok) throw new Error(`Composio validation failed (${response.status})`);+ return orgKey ? "Composio organization key accepted" : "Composio project key accepted";+}diff --git a/lib/infra/dokploy.ts b/lib/infra/dokploy.tsindex 1beb3e48..ad3db562 100644--- a/lib/infra/dokploy.ts+++ b/lib/infra/dokploy.ts@@ -1,3 +1,4 @@+import type { InfraProviderValues } from "./types";import { safeProviderFetch } from "@/lib/host/ssrf";import { readInfraProvider } from "./store";import { obj, request, TIMEOUT_MS } from "./http";@@ -33,8 +34,8 @@ async function call(endpoint: string, method = "GET", body?: unknown): Promise<uthrow last ?? new Error("Dokploy request failed");}-export async function doctorDokploy(): Promise<string | null> {- const values = await readInfraProvider("dokploy");+export async function doctorDokploy(candidate?: InfraProviderValues): Promise<string | null> {+ const values = candidate ?? await readInfraProvider("dokploy");if (!values.apiUrl || !values.apiKey) return null;const res = await request(`${values.apiUrl}/project.all`, {headers: { "x-api-key": values.apiKey, accept: "application/json" },diff --git a/lib/infra/hostinger.ts b/lib/infra/hostinger.tsindex ac1c5752..8d982f90 100644--- a/lib/infra/hostinger.ts+++ b/lib/infra/hostinger.ts@@ -1,11 +1,12 @@+import type { InfraProviderValues } from "./types";import { readInfraProvider } from "./store";import { HOST_RE, IPV4_RE, obj, request } from "./http";const API = "https://developers.hostinger.com/api";const headers = (token: string) => ({ authorization: `Bearer ${token}`, accept: "application/json", "content-type": "application/json" });-export async function doctorHostinger(): Promise<string | null> {- const values = await readInfraProvider("hostinger");+export async function doctorHostinger(candidate?: InfraProviderValues): Promise<string | null> {+ const values = candidate ?? await readInfraProvider("hostinger");if (!values.apiToken) return null;const res = await request(`${API}/vps/v1/virtual-machines`, { headers: headers(values.apiToken) });if (!res.ok) throw new Error(`Hostinger HTTP ${res.status}`);diff --git a/lib/infra/setup-capability.test.ts b/lib/infra/setup-capability.test.tsnew file mode 100644index 00000000..22f0d74b--- /dev/null+++ b/lib/infra/setup-capability.test.ts@@ -0,0 +1,74 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { promises as fs } from "node:fs";+import { createHash } from "node:crypto";+import os from "node:os";+import path from "node:path";+vi.mock("server-only", () => ({}));+vi.mock("@/lib/host/audit-api", () => ({ audit: vi.fn() }));+let root: string;+const KEY = "opaque_synthetic_composio_test_key";+beforeEach(async () => {+ root = await fs.mkdtemp(path.join(os.tmpdir(), "mso-setup-test-"));+ process.env.OS_INFRA_STORE = path.join(root, "infra.json");+ vi.resetModules();+ 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(); });+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");+ 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);+ const stored = await fs.readFile(file, "utf8"); expect(stored).not.toContain(grant.token); expect(stored).toContain("test-owner");+ expect(grant.setup.fields.map(f => f.key)).toEqual(["apiKey"]);+ expect(grant.setup.expiresAt - Date.now()).toBeLessThanOrEqual(600000);+ await expect(api.consumeIntegrationSetup(grant.token, { orgApiKey: KEY })).rejects.toMatchObject({ code: "invalid_fields" });+ await expect(api.openIntegrationSetup("composio", "", "project")).rejects.toMatchObject({ status: 403 });+ });+ 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 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);+ expect(JSON.stringify(store.summarizeInfraProvider("composio", await store.readInfraProvider("composio")))).not.toContain(KEY);+ await expect(api.consumeIntegrationSetup(grant.token, { apiKey: KEY })).rejects.toMatchObject({ status: 401 });+ });+ it("failed probes cannot replace existing keys; a session permits bounded retries", async () => {+ 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");+ 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");+ expect(JSON.stringify(grant.setup)).not.toContain("original_synthetic_key_keep_me");+ });+ it("expired grants and concurrent replays fail closed", async () => {+ const api = await import("./setup-capability");+ const expired = await api.openIntegrationSetup("composio", "test-owner");+ 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 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");+ await api.consumeIntegrationSetup(grant.token, { orgApiKey: KEY });+ const [url, options] = vi.mocked(fetch).mock.calls[0];+ expect(String(url)).toContain("/api/v3.1/org/project/list"); expect(options?.headers).toEqual({ "x-org-api-key": KEY });+ expect(store.summarizeInfraProvider("composio", await store.readInfraProvider("composio")).values.orgApiKey).toBe("configured");+ });+ it("standalone page contains no grant and its inline script parses", async () => {+ const { integrationSetupPage } = await import("./setup-page");+ const result = integrationSetupPage(); expect(result.csp).toContain("frame-ancestors 'none'");+ const script = result.html.match(/<script nonce="[^"]+">([\s\S]+)<\/script>/)?.[1];+ expect(script).toBeTruthy(); expect(() => new Function(script!)).not.toThrow();+ expect(result.html).not.toContain(KEY); expect(result.html).not.toContain("si-coder");+ });+});diff --git a/lib/infra/setup-capability.ts b/lib/infra/setup-capability.tsnew file mode 100644index 00000000..f4fafac7--- /dev/null+++ b/lib/infra/setup-capability.ts@@ -0,0 +1,104 @@+import { createHash, randomBytes } from "node:crypto";+import { constants, promises as fs } from "node:fs";+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 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 };+export class SetupError extends Error {+ constructor(public readonly code: string, public readonly status: number) { super(code); }+}+const invalid = () => new SetupError("setup_expired_or_invalid", 401);+const hash = (token: string) => createHash("sha256").update(token).digest("hex");+async function ensureRoot() {+ await fs.mkdir(ROOT, { recursive: true, mode: 0o700 });+ const st = await fs.lstat(ROOT);+ if (!st.isDirectory() || st.isSymbolicLink() || (typeof process.getuid === "function" && st.uid !== process.getuid())) throw invalid();+ await fs.chmod(ROOT, 0o700);+}+function grantPath(token: string) {+ if (!/^[A-Za-z0-9_-]{43}$/.test(token)) throw invalid();+ return path.join(ROOT, `${hash(token)}.json`);+}+async function readGrant(file: string): Promise<Grant> {+ let handle;+ try {+ handle = await fs.open(file, constants.O_RDONLY | constants.O_NOFOLLOW);+ 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();+ 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 schema(g: Grant) {+ const stored = await readInfraProvider(g.provider);+ 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),+ };+}+export async function openIntegrationSetup(provider: string, principal: string, method?: string) {+ 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);+ 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);+ 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 descriptor = await schema(grant);+ await fs.writeFile(grantPath(token), JSON.stringify(grant), { mode: 0o600, flag: "wx" });+ return { token, setup: descriptor };+ });+}+export async function describeIntegrationSetup(token: string) {+ const grant = await readGrant(grantPath(token)); active(grant); return schema(grant);+}+export async function consumeIntegrationSetup(token: string, raw: unknown) {+ const file = grantPath(token);+ 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));+ 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);+ }+ let updates;+ 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 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++;+ await fs.writeFile(file, JSON.stringify(grant), { mode: 0o600 });+ // Probe candidate values before mutating the real store. Only safe enums/status+ // escape this boundary, never provider response text or credential values.+ const result = await doctorInfraProvider(grant.provider, candidate);+ if (result.ok !== true) throw new SetupError(result.ok === null ? "live_validation_unavailable" : "credential_validation_failed", 422);+ 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 };+ });+}diff --git a/lib/infra/setup-guidance.ts b/lib/infra/setup-guidance.tsnew file mode 100644index 00000000..3b0dae99--- /dev/null+++ b/lib/infra/setup-guidance.ts@@ -0,0 +1,45 @@+import { getInfraProviderDefinition } from "./catalog";+import type { InfraProviderId } from "./types";++export type SetupMethod = "direct" | "project" | "organization";+export function setupFields(provider: InfraProviderId, method: SetupMethod) {+ if (provider === "composio") {+ if (!["project", "organization"].includes(method)) throw new Error("Choose a Composio project or organization key");+ return getInfraProviderDefinition(provider).fields.filter(f => f.key === (method === "project" ? "apiKey" : "orgApiKey")).map(f => ({ ...f, required: true }));+ }+ if (method !== "direct") throw new Error("Unsupported authentication method");+ return getInfraProviderDefinition(provider).fields;+}+export function setupMethod(provider: InfraProviderId, method?: string): SetupMethod {+ const value = method ?? (provider === "composio" ? "project" : "direct");+ if (!["direct", "project", "organization"].includes(value)) throw new Error("Unsupported authentication method");+ setupFields(provider, value as SetupMethod);+ return value as SetupMethod;+}+export function setupGuidance(provider: InfraProviderId, method: SetupMethod) {+ const guides = {+ composio: {+ url: "https://platform.composio.dev",+ reference: "https://docs.composio.dev/reference/authenticating-to-composio",+ steps: method === "organization"+ ? ["Open Composio Settings.", "Choose General Settings → Organization Access Tokens.", "Create a token only when cross-project administration is required.", "Copy the organization token into this form. It uses x-org-api-key, not x-api-key."]+ : ["Select the intended Composio project.", "Open Settings → Project Settings → API Keys.", "Create a project API key with the least privileges needed.", "Copy the project key into this form. Connected-account OAuth tokens remain in Composio."],+ },+ cloudflare: {+ url: "https://dash.cloudflare.com/profile/api-tokens",+ reference: "https://developers.cloudflare.com/fundamentals/api/get-started/create-token/",+ steps: ["Open My Profile → API Tokens.", "Choose Create Token, then scope it to the intended zones only.", "Use Zone Read for inventory and DNS Edit only when DNS writes are needed.", "Copy the token. Zone ID and Account ID are optional pins, not secrets."],+ },+ hostinger: {+ url: "https://hpanel.hostinger.com/",+ reference: "https://developers.hostinger.com/",+ steps: ["Sign in to the intended Hostinger account.", "Open Dev Tools → API in the hPanel sidebar.", "Create a named token with a limited expiry. It inherits the owning account permissions.", "Copy it into this form. MSO validates access before saving."],+ },+ dokploy: {+ url: "https://docs.dokploy.com/docs/core/api",+ reference: "https://docs.dokploy.com/docs/core/api",+ steps: ["Open your own Dokploy panel, not a third-party panel.", "Open the account settings and create an API key.", "Enter the panel API URL. Use HTTPS, or loopback for a panel on this VPS.", "Copy the key into this form. MSO checks the project-list endpoint before saving."],+ },+ };+ return guides[provider];+}diff --git a/lib/infra/setup-http.ts b/lib/infra/setup-http.tsnew file mode 100644index 00000000..60160de8--- /dev/null+++ b/lib/infra/setup-http.ts@@ -0,0 +1,24 @@+import { SetupError, SETUP_MAX_BODY } from "./setup-capability";+export async function readSetupJson(req: Request): Promise<Record<string, unknown>> {+ if (req.headers.get("content-type")?.split(";")[0].trim() !== "application/json") throw new SetupError("json_required", 415);+ if (Number(req.headers.get("content-length")) > SETUP_MAX_BODY) throw new SetupError("request_too_large", 413);+ const reader = req.body?.getReader(); if (!reader) throw new SetupError("invalid_request", 400);+ let text = "", bytes = 0;+ const decoder = new TextDecoder();+ try {+ for (;;) {+ let timer: ReturnType<typeof setTimeout> | undefined;+ const part = await Promise.race([reader.read(), new Promise<never>((_, reject) => { timer = setTimeout(() => reject(new SetupError("request_timeout", 408)), 5000); })]).finally(() => clearTimeout(timer));+ if (part.done) break;+ bytes += part.value.byteLength; if (bytes > SETUP_MAX_BODY) throw new SetupError("request_too_large", 413);+ text += decoder.decode(part.value, { stream: true });+ }+ text += decoder.decode();+ const value: unknown = JSON.parse(text);+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new SetupError("invalid_request", 400);+ return value as Record<string, unknown>;+ } catch (error) {+ await reader.cancel().catch(() => undefined);+ throw error instanceof SetupError ? error : new SetupError("invalid_request", 400);+ } finally { reader.releaseLock(); }+}diff --git a/lib/infra/setup-page.ts b/lib/infra/setup-page.tsnew file mode 100644index 00000000..375d53c3--- /dev/null+++ b/lib/infra/setup-page.ts@@ -0,0 +1,19 @@+import { randomBytes } from "node:crypto";+import { MSO_WIDGET_TOKENS } from "@/lib/presentation/widget-tokens";+import { INTEGRATION_FORM_SCRIPT, INTEGRATION_FORM_STYLE } from "./setup-ui";++export function integrationSetupPage() {+ const nonce = randomBytes(18).toString("base64");+ 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>MSO Integrations</title><style nonce="${nonce}">${MSO_WIDGET_TOKENS}${INTEGRATION_FORM_STYLE}*{box-sizing:border-box}body{margin:0;background:var(--surface);padding:clamp(18px,4vw,50px);font-family:var(--font-body);color:var(--text)}header{max-width:850px;margin:0 auto 28px;font-size:13px}button{border:1px solid var(--sep-strong);border-radius:10px;background:var(--field);color:var(--text);padding:9px 15px;cursor:pointer}select{margin:8px 0 16px}a{color:var(--os-accent)}</style></head><body><header>MSO / Integrations · Secure setup</header><main id="setup" class="integration"></main><script nonce="${nonce}">${INTEGRATION_FORM_SCRIPT}+(async()=>{+const root=document.getElementById("setup"),endpoint=location.origin+"/api/integrations/setup";+let token=location.hash.slice(1);history.replaceState(null,"",location.pathname);+if(token){try{const response=await fetch(endpoint,{method:"POST",credentials:"omit",cache:"no-store",headers:{"Content-Type":"application/json",Authorization:"Bearer "+token},body:JSON.stringify({action:"schema"})});if(!response.ok)throw new Error("Setup expired or unavailable. Open a new session.");mountIntegrationForm(root,await response.json(),{endpoint,token});token="";return}catch(error){root.append(integrationNode("p",error.message));return}}+root.append(integrationNode("h2","Connect a service"),integrationNode("p","Sign in to MSO as an owner, then start a temporary credential form. No extra plugin is required."));+const label=integrationNode("label","Provider"),select=integrationNode("select");select.id="provider";label.htmlFor=select.id;for(const name of ["composio","dokploy","cloudflare","hostinger"]){const o=integrationNode("option",name[0].toUpperCase()+name.slice(1));o.value=name;select.append(o)}+const ml=integrationNode("label","Composio key type"),method=integrationNode("select");method.id="method";ml.htmlFor=method.id;for(const name of ["project","organization"]){const o=integrationNode("option",name+" API key");o.value=name;method.append(o)}select.addEventListener("change",()=>{method.hidden=ml.hidden=select.value!=="composio"});+const open=integrationNode("button","Start secure setup"),status=integrationNode("p"),login=integrationNode("a","Open MSO sign-in");login.href="/";login.target="_blank";login.rel="noopener noreferrer";open.type="button";+root.append(label,select,ml,method,open,status,login);open.addEventListener("click",async()=>{open.disabled=true;try{const response=await fetch("/api/v1/infra/setup",{method:"POST",credentials:"same-origin",cache:"no-store",headers:{"Content-Type":"application/json"},body:JSON.stringify({provider:select.value,method:select.value==="composio"?method.value:"direct"})});if(!response.ok)throw new Error("Owner sign-in is required, or setup is temporarily unavailable.");const data=await response.json();mountIntegrationForm(root,data.setup,{endpoint,token:data.token})}catch(error){status.textContent=error.message;open.disabled=false}})+})();</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'` };+}diff --git a/lib/infra/setup-ui.ts b/lib/infra/setup-ui.tsnew file mode 100644index 00000000..7114295f--- /dev/null+++ b/lib/infra/setup-ui.ts@@ -0,0 +1,46 @@+// The same DOM-only form runs in a temporary browser page and in MSO Page.+// No input, capability, or provider response is sent through the MCP bridge.+export const INTEGRATION_FORM_STYLE = String.raw`+.integration{max-width:850px;margin:auto;font:14px/1.55 var(--font-body);color:var(--text)}.integration h2{font:700 24px/1.25 var(--font-display);margin:0 0 8px}.integration p{color:var(--text-dim);margin:6px 0 14px}.integration .setup-grid{display:grid;grid-template-columns:minmax(0,1.2fr) minmax(0,1fr);gap:20px}.integration label{display:block;font-weight:650;margin-bottom:5px}.integration input,.integration select{width:100%;min-width:0;border:1px solid var(--sep-strong);border-radius:9px;background:var(--field);color:var(--text);padding:10px 12px;font:16px var(--font-body)}.integration .input-row{display:flex;gap:6px}.integration .input-row input{flex:1;width:0}.integration button{font-size:13px;min-height:42px;white-space:normal}.integration .field{margin-bottom:18px;min-width:0}.integration small{display:block;margin-top:5px;color:var(--text-dim);overflow-wrap:anywhere}.integration details{border:1px solid var(--sep-strong);border-radius:12px;padding:14px;background:var(--field);margin:12px 0}.integration summary{cursor:pointer;font-weight:650}.integration li{margin:8px 0}.integration a{color:var(--os-accent);text-underline-offset:3px;overflow-wrap:anywhere}.integration .setup-status{min-height:28px;overflow-wrap:anywhere}.integration button:disabled{cursor:not-allowed;opacity:.55}.integration .setup-tag{display:inline-block;border:1px solid var(--sep-strong);border-radius:99px;padding:3px 10px;margin-bottom:12px;font-size:12px}.integration .setup-actions{display:flex;gap:8px;flex-wrap:wrap}.integration .primary{background:var(--text);color:var(--surface);border-color:var(--text)}@media(max-width:620px){.integration .setup-grid{grid-template-columns:1fr;gap:0}.integration h2{font-size:21px}}`;++export const INTEGRATION_FORM_SCRIPT = String.raw`+function integrationNode(tag,value){const n=document.createElement(tag);if(value!==undefined)n.textContent=value;return n}+function mountIntegrationForm(root,setup,access){+ root.replaceChildren();root.classList.add("integration");+ const token=access&&access.token,endpoint=access&&access.endpoint;+ if(!token||!endpoint){root.append(integrationNode("p","Secure setup authorization is missing. Reopen the setup form; never paste a credential into chat."));return}+ 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 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){+ const wrap=integrationNode("div"),label=integrationNode("label",f.label+(f.required&&!f.stored?" *":"")),row=integrationNode("div"),input=integrationNode("input");+ wrap.className="field";row.className="input-row";input.id="setup-"+f.key;label.htmlFor=input.id;input.type=f.secret?"password":"text";input.autocomplete="off";input.spellcheck=false;input.maxLength=4096;input.required=f.required&&!f.stored;input.placeholder=f.stored?"Already stored — leave blank to keep":(f.placeholder||"");+ row.append(input);inputs.push({key:f.key,input});+ if(f.secret){const toggle=integrationNode("button","Show");toggle.type="button";toggle.setAttribute("aria-label","Show or hide "+f.label);toggle.addEventListener("click",()=>{input.type=input.type==="password"?"text":"password";toggle.textContent=input.type==="password"?"Show":"Hide"});row.append(toggle)}+ wrap.append(label,row,integrationNode("small",f.description));form.append(wrap);+ }+ const save=integrationNode("button","Validate & save"),status=integrationNode("p");save.type="button";save.className="primary";status.className="setup-status";status.setAttribute("role","status");status.setAttribute("aria-live","polite");form.append(save,status);+ const guide=integrationNode("details"),summary=integrationNode("summary","How to get this credential"),steps=integrationNode("ol");guide.open=true;guide.append(summary);+ function link(url,label){const a=integrationNode("a",label);try{const u=new URL(url);if(u.protocol!=="https:")return integrationNode("span",label);a.href=u.href}catch{return integrationNode("span",label)}a.target="_blank";a.rel="noopener noreferrer";if(typeof access.openLink==="function")a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(access.openLink(a.href)).catch(()=>{status.textContent="The host could not open this reference. Open the provider dashboard in your browser."})});return a}+ guide.append(link(setup.guidance.url,"Open official provider dashboard"));for(const text of setup.guidance.steps)steps.append(integrationNode("li",text));guide.append(steps,link(setup.guidance.reference,"Official documentation"));+ const storage=integrationNode("details");storage.append(integrationNode("summary","Storage and privacy"),integrationNode("p",setup.store),integrationNode("p","The form expires after 10 minutes and closes after a successful save. Existing keys are never displayed. Blank fields keep existing values. If a key was shared publicly, revoke it at its provider."));+ aside.append(guide,storage);grid.append(form,aside);root.append(grid);+ let used=false;+ const expire=()=>{used=true;save.disabled=true;inputs.forEach(f=>{f.input.value="";f.input.disabled=true});status.textContent="Setup expired. Open a new secure form."};+ const timer=setTimeout(expire,Math.max(0,setup.expiresAt-Date.now()));+ form.addEventListener("submit",e=>e.preventDefault());+ form.addEventListener("keydown",e=>{if(e.key==="Enter"&&e.target instanceof HTMLInputElement){e.preventDefault();save.click()}});+ save.addEventListener("click",async e=>{+ e.preventDefault();if(used||save.disabled||!form.reportValidity())return;save.disabled=true;status.textContent="Checking provider access…";+ const values={};for(const f of inputs)if(f.input.value.trim())values[f.key]=f.input.value.trim();+ 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.timeout(25000)});+ 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.")}+ 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]}+ });+ return()=>{clearTimeout(timer);inputs.forEach(f=>{f.input.value=""});root.replaceChildren()};+}+`;diff --git a/lib/infra/store.test.ts b/lib/infra/store.test.tsindex a1ba1d0f..faa2e0a5 100644--- a/lib/infra/store.test.ts+++ b/lib/infra/store.test.ts@@ -20,6 +20,13 @@ afterEach(async () => {});describe("infra provider store", () => {+ it("never reports an empty Composio configuration as ready", async () => {+ const store = await import("./store");+ expect(store.summarizeInfraProvider("composio", {}).configured).toBe(false);+ await expect(store.setInfraProvider("composio", {})).rejects.toThrow("required");+ expect(store.summarizeInfraProvider("composio", { orgApiKey: "synthetic-organization-key" }).configured).toBe(true);+ });+it("normalizes Dokploy, persists owner-only state, and never returns a raw secret in summaries", async () => {const store = await import("./store");const values = await store.setInfraProvider("dokploy", {diff --git a/lib/infra/store.ts b/lib/infra/store.tsindex 0bd33c13..358ed85e 100644--- a/lib/infra/store.ts+++ b/lib/infra/store.ts@@ -7,7 +7,7 @@ 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 SECRET_KEYS = new Set(["apiKey", "apiToken"]);+const SECRET_KEYS = new Set(["apiKey", "apiToken", "orgApiKey"]);const MAX_STORE_BYTES = 256 * 1024;function mask(value: string): string {@@ -58,6 +58,7 @@ export async function setInfraProvider(id: InfraProviderId, raw: Record<string,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 (missing.length) throw new Error(`${id} is missing required value(s): ${missing.join(", ")}`);await writeUnlocked({ ...store, providers: { ...(store.providers ?? {}), [id]: values } });return values;@@ -76,6 +77,7 @@ export async function removeInfraProvider(id: InfraProviderId): Promise<void> {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);+ if (id === "composio" && !values.apiKey && !values.orgApiKey) missing.push("project or organization API key");const safeValues = Object.fromEntries(def.fields.filter((field) => values[field.key]).map((field) => [field.key, SECRET_KEYS.has(field.key) ? mask(values[field.key]) : values[field.key]]));diff --git a/lib/infra/types.ts b/lib/infra/types.tsindex a58132cb..4476afcc 100644--- a/lib/infra/types.ts+++ b/lib/infra/types.ts@@ -1,4 +1,4 @@-export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger"] as const;+export const INFRA_PROVIDER_IDS = ["dokploy", "cloudflare", "hostinger", "composio"] as const;export type InfraProviderId = (typeof INFRA_PROVIDER_IDS)[number];export type InfraProviderValues = Record<string, string>;diff --git a/lib/mcp/dispatch-tool-support.ts b/lib/mcp/dispatch-tool-support.tsindex 357cc878..b1b44e84 100644--- a/lib/mcp/dispatch-tool-support.ts+++ b/lib/mcp/dispatch-tool-support.ts@@ -1,3 +1,4 @@+import { capabilityPrivateMeta } from "@/lib/capabilities/tool";export { sessionDetail, recordAgentEvent, flowFields, workflowFromResult } from "@/lib/capabilities/execution-support";import { isMcpDirectResult } from "./tool-kit";import { boundedResultText } from "./result-budget";@@ -15,7 +16,8 @@ export function structuredResult(toolName: string, result: unknown, profile: Mcpif (isMcpDirectResult(result)) {return {content: result.content,- ...(profile === "chatgpt" && result.structuredContent ? { structuredContent: result.structuredContent } : {}),+ ...(profile === "chatgpt" && capabilityPrivateMeta(result) ? { _meta: capabilityPrivateMeta(result) } : {}),+ ...((profile === "chatgpt" || tool?.outputSchema) && result.structuredContent ? { structuredContent: result.structuredContent } : {}),...(result.isError ? { isError: true } : {}),};}diff --git a/lib/mcp/integration-setup.test.ts b/lib/mcp/integration-setup.test.tsnew file mode 100644index 00000000..ebf8a65c--- /dev/null+++ b/lib/mcp/integration-setup.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it, vi } from "vitest";+vi.mock("server-only", () => ({}));+import { capabilityDirect, capabilityPrivateMeta } from "@/lib/capabilities/tool";+import { structuredResult } from "./dispatch-tool-support";+import { SURFACE_TOOLS } from "./tools-surface";+import { resolveSurfaceRoute } from "./surface-catalog";+import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";+describe("MCP integration setup privacy", () => {+ it("keeps UI authorization out of serializable/model-visible result fields", () => {+ const secret = "synthetic-ui-only-capability";+ const raw = capabilityDirect([{ type: "text", text: "Form opened" }], false, { route: "/integrations" }, { integrationSetup: { token: secret } });+ expect(JSON.stringify(raw)).not.toContain(secret); expect(capabilityPrivateMeta(raw)).toBeDefined();+ const wire = structuredResult("integration_setup_open", raw, "chatgpt");+ expect(wire).toHaveProperty("_meta.integrationSetup.token", secret);+ expect(JSON.stringify(wire.content)).not.toContain(secret); expect(JSON.stringify(wire.structuredContent)).not.toContain(secret);+ expect(JSON.stringify(structuredResult("integration_setup_open", raw, "full"))).not.toContain(secret);+ });+ 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.meta?.["openai/outputTemplate"]).toMatch(/^ui:\/\/mso\/page/);+ expect(resolveSurfaceRoute("/integrations").kind).toBe("integrations");+ expect(() => new Function(MSO_SURFACE_SCRIPT)).not.toThrow();+ expect(MSO_SURFACE_SCRIPT).toContain('"ui/initialize"');+ expect(MSO_SURFACE_SCRIPT).toContain('credentials:"omit"');+ expect(MSO_SURFACE_SCRIPT).toContain('save.type="button"');+ expect(MSO_SURFACE_SCRIPT).toContain('rpcRequest("ui/open-link"');+ expect(MSO_SURFACE_SCRIPT).toContain("raw.mcp_tool_result");+ });+});diff --git a/lib/mcp/parity.test.ts b/lib/mcp/parity.test.tsindex c67d2563..d41aba71 100644--- a/lib/mcp/parity.test.ts+++ b/lib/mcp/parity.test.ts@@ -33,6 +33,7 @@ const ALFA_ONLY: Record<string, string> = {};const MCP_ONLY: Record<string, string> = {+ "integration.setup.open": "ChatGPT needs a write-scoped UI-only capability; native owner browser and CLI use the same secure setup service without exposing secrets to Alfa tools","screen.capture": "external MCP clients need visual proof of the rendered OS; in-shell Alfa already runs inside that browser UI","projects.list": "an MCP client has no sidebar and no Files window, so it needs an explicit bounded enumeration of every project container; in-shell Alfa reads the same roots through fs.list and the Files app","project.capabilities": "external harnesses need a stable generic discovery seam for project-owned MCP/functions; Alfa can inspect the same project files through its existing fs/skills tools without changing its cached tool array",@@ -184,6 +185,7 @@ describe("MCP rate limits mirror the routes", () => {"projects.mcp.call": 30,"skills.list": 30,"skills.read": 60,+ "integration.setup": 10,"infra.dokploy": 20,"infra.cloudflare": 20,"infra.hostinger": 10,diff --git a/lib/mcp/surface-catalog.ts b/lib/mcp/surface-catalog.tsindex d6bedef0..0752fc3d 100644--- a/lib/mcp/surface-catalog.ts+++ b/lib/mcp/surface-catalog.ts@@ -38,7 +38,7 @@ const BASE = "https://mso-surface.invalid";export type ResolvedSurface = {route: string;- kind: "home" | "monitor" | "project" | "diff" | "browser" | "app";+ kind: "home" | "monitor" | "project" | "diff" | "browser" | "app" | "integrations";title: string;openPath: string;project?: string;@@ -85,6 +85,7 @@ export function resolveSurfaceRoute(rawRoute: string, context?: { project?: striconst route = `${url.pathname}${url.search}`;if (parts.length === 0) return { route, kind: "home", title: "MSO", openPath: "/assistant/mcp" };+ if (parts[0] === "integrations" && parts.length === 1) return { route, kind: "integrations", title: "Integrations", openPath: "/api/integrations/setup" };if (parts[0] === "monitor" && parts.length === 1) return { route, kind: "monitor", title: "System Monitor", openPath: "/monitor" };if (parts[0] === "browser" && parts.length === 1) return { route, kind: "browser", title: "Remote Browser", openPath: "/browser" };if (parts[0] === "project" && parts.length === 1) return { route, kind: "project", title: "Project", openPath: "/files", ...(context?.project ? { project: context.project } : {}) };diff --git a/lib/mcp/tool-context.ts b/lib/mcp/tool-context.tsindex 37fc4073..dd3a75fd 100644--- a/lib/mcp/tool-context.ts+++ b/lib/mcp/tool-context.ts@@ -12,7 +12,7 @@ export const withWorkflowContext = (tool: McpTool): McpTool => WORKFLOW_CONTEXT_...tool.inputSchema.properties,workflow_id: {type: "string",- description: "Exact id returned by workflow_start. Include it on every operational step in that run; omit it for a standalone call.",+ description: "Exact workflow_start id. Omit only for standalone calls.",},},},diff --git a/lib/mcp/tool-contract.ts b/lib/mcp/tool-contract.tsindex f57f712b..4b7dd8e1 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.- "infra_providers_list", "infra_provider_doctor", "dokploy_projects_list", "dokploy_project_ensure",+ "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.diff --git a/lib/mcp/tools-surface.ts b/lib/mcp/tools-surface.tsindex 588c42ca..ae1da47d 100644--- a/lib/mcp/tools-surface.ts+++ b/lib/mcp/tools-surface.ts@@ -1,4 +1,7 @@-import { type McpTool, S, str, opt, READ_ONLY } from "./tool-kit";+import { openIntegrationSetup } from "@/lib/infra/setup-capability";+import { INFRA_PROVIDER_IDS } from "@/lib/infra/types";+import { MSO_ORIGIN } from "./ui-config";+import { type McpTool, S, str, opt, READ_ONLY, mcpDirect } from "./tool-kit";import { MSO_PAGE_URI } from "./ui-surface";import { publicSurfaceApps, resolveSurfaceRoute, type ResolvedSurface } from "./surface-catalog";@@ -17,8 +20,9 @@ const APP_SCHEMA = {const PAGE_OUTPUT = {type: "object",properties: {- route: { type: "string" }, kind: { type: "string", enum: ["home", "monitor", "project", "diff", "browser", "app"] },+ 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" },app: { type: "object" }, catalog: { type: "array", items: APP_SCHEMA },},required: ["route", "kind", "title", "openPath", "catalog"],@@ -44,6 +48,31 @@ const renderPage = async (input: Record<string, unknown>) => ({});export const SURFACE_TOOLS: McpTool[] = [+ {+ name: "integration_setup_open",+ title: "Open MSO Integration Setup",+ description: "Open a native MSO Integrations credential form in ChatGPT. Requires write scope. The user enters a key directly in the form, which sends it only to the MSO HTTPS server for validation and owner-only storage. Never pass credentials in tool arguments or chat. The provider-bound session expires after ten minutes and is consumed after a successful save. MSO needs no external credential plugin. Composio project and organization keys use different methods.",+ chatgptDescription: "Open native MSO Integrations in the Page. User enters keys in the form, never chat/tool arguments. Direct HTTPS validation, owner-only storage, ten-minute single-use setup. Composio project and organization keys are separate.",+ scope: "write",+ 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"], description: "Composio defaults to project; other providers use direct." } }, ["provider"]),+ outputSchema: PAGE_OUTPUT,+ meta: {+ ui: { resourceUri: MSO_PAGE_URI, visibility: ["model", "app"] },+ "openai/outputTemplate": MSO_PAGE_URI,+ "openai/widgetAccessible": true,+ "openai/toolInvocation/invoking": "Opening secure integration setup…",+ "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"));+ const output = { route: "/integrations", kind: "integrations", title: "Integrations", openPath: "/api/integrations/setup", 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` } });+ },+ },{name: "mso_surface_apps_list",title: "List MSO Page Apps",@@ -57,8 +86,8 @@ export const SURFACE_TOOLS: McpTool[] = [{name: "render_mso_page",title: "Render MSO Page",- description: "Render the full MSO Page MCP App for native operator views or reviewed development/production embeds. Use an MSO-style route such as /, /monitor, /project, /diff, /browser, or /apps/<reviewed-app-id>. For project/diff views pass project separately. This tool never accepts raw HTML or arbitrary external URLs; iframe targets come only from the server-owned allowlist.",- chatgptDescription: "Render the full secure MSO Page in ChatGPT. Native routes: /, /monitor, /project, /diff, /browser; reviewed live demo: /apps/play-together. Raw HTML and arbitrary URLs are rejected.",+ description: "Render the full MSO Page MCP App for native operator views or reviewed development/production embeds. Use an MSO-style route such as /, /integrations, /monitor, /project, /diff, /browser, or /apps/<reviewed-app-id>. For project/diff views pass project separately. This tool never accepts raw HTML or arbitrary external URLs; iframe targets come only from the server-owned allowlist.",+ chatgptDescription: "Render the full secure MSO Page in ChatGPT. Native routes: /, /integrations, /monitor, /project, /diff, /browser; reviewed live demo: /apps/play-together. Raw HTML and arbitrary URLs are rejected.",scope: "read", annotations: READ_ONLY,inputSchema: PAGE_INPUT,outputSchema: PAGE_OUTPUT,diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex c2d22e74..e9ba30ac 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.10.0";-export const MCP_TOOLSET_VERSION = "2026.09.05.1";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-04T10:25:00Z";+export const MCP_TOOLSET_VERSION = "2026.09.05.3";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-05T11:45:00Z";export type McpToolsetInfo = {serverVersion: string;diff --git a/lib/mcp/ui-page-bridge.ts b/lib/mcp/ui-page-bridge.tsindex 1a138d34..cb847dcf 100644--- a/lib/mcp/ui-page-bridge.ts+++ b/lib/mcp/ui-page-bridge.ts@@ -21,11 +21,12 @@ function rpcRequest(method,params){});}function acceptPageResult(result){+ captureIntegrationAccess(result);captureIntegrationAccess(window.openai&&window.openai.toolResponseMetadata);const value=unbox(result);- if(!value||typeof value!=="object"||!validRoute(value.route)||!["home","monitor","project","diff","browser","app"].includes(value.kind))return false;+ if(!value||typeof value!=="object"||!validRoute(value.route)||!["home","monitor","project","diff","browser","app","integrations"].includes(value.kind))return false;if(value.kind==="app"&&!safeAppResult(value.app))return false;- const key=JSON.stringify([value.route,value.kind,value.project,value.sha,value.app?.url]);- if(key===lastOutputKey)return true;+ const key=JSON.stringify([value.route,value.kind,value.project,value.sha,value.app?.url,value.setup?.expiresAt]);+ if(key===lastOutputKey){if(value.kind==="integrations"&&value.setup&&integrationAccess&&!body.querySelector("form")){current=value;render()}return true;}lastOutputKey=key;current=value;render();return true;}function acceptPageInput(params){diff --git a/lib/mcp/ui-page-integrations.ts b/lib/mcp/ui-page-integrations.tsnew file mode 100644index 00000000..c49cf937--- /dev/null+++ b/lib/mcp/ui-page-integrations.ts@@ -0,0 +1,39 @@+import { INTEGRATION_FORM_SCRIPT } from "@/lib/infra/setup-ui";+import { INFRA_PROVIDER_IDS } from "@/lib/infra/types";+import { MSO_ORIGIN } from "./ui-config";++/** Native secret form; shares the existing Page lifecycle without sending secrets to it. */+export const MSO_PAGE_INTEGRATIONS_SCRIPT = String.raw`+${INTEGRATION_FORM_SCRIPT}+const INTEGRATION_ENDPOINT=${JSON.stringify(MSO_ORIGIN + "/api/integrations/setup")};+const INTEGRATION_PROVIDERS=${JSON.stringify(INFRA_PROVIDER_IDS)};+let integrationAccess=null;+function captureIntegrationAccess(raw){+ const envelopes=[raw,raw&&raw._meta,raw&&raw.mcp_tool_result&&raw.mcp_tool_result._meta,raw&&raw.call_tool_result&&raw.call_tool_result._meta];+ for(const meta of envelopes){const access=meta&&meta.integrationSetup;if(access&&typeof access.token==="string"&&/^[A-Za-z0-9_-]{43}$/.test(access.token)&&access.endpoint===INTEGRATION_ENDPOINT){integrationAccess=access;return}}+}+async function openIntegrationReference(url){+ if(window.openai&&typeof window.openai.openExternal==="function")return window.openai.openExternal({href:url,redirectUrl:false});+ return rpcRequest("ui/open-link",{url});+}+function renderIntegrations(){+ if(current.setup){+ viewCleanup=mountIntegrationForm(body,current.setup,integrationAccess?{...integrationAccess,openLink:openIntegrationReference}:null)||(()=>{});+ return;+ }+ const root=el("div","integration");root.append(el("h2","","Integrations"),el("p","","Connect a service directly to MSO. Credentials stay outside the chat. Choose a service to open a ten-minute setup form."));+ const list=el("div","grid");+ for(const provider of INTEGRATION_PROVIDERS){+ const card=el("div","card");card.append(el("strong","",provider));+ for(const method of provider==="composio"?["project","organization"]:["direct"]){+ const b=button(provider==="composio"?method+" API key":"Connect",async()=>{+ b.disabled=true;+ try{const result=await rpcCall("integration_setup_open",{provider,method});if(!acceptPageResult(result)||!current.setup)throw new Error("Setup requires write permission and refreshed MSO tools.")}+ catch(error){showError(error)}+ });card.append(b);+ }+ list.append(card);+ }+ root.append(list);body.append(root);+}+`;diff --git a/lib/mcp/ui-page-lifecycle.test.ts b/lib/mcp/ui-page-lifecycle.test.tsindex fd757c3e..d483d07f 100644--- a/lib/mcp/ui-page-lifecycle.test.ts+++ b/lib/mcp/ui-page-lifecycle.test.ts@@ -20,7 +20,7 @@ describe("MCP Page lifecycle and cached resource migration", () => {'event.source!==window.parent','event.source!==frame.contentWindow||event.origin!==safe.origin','data.type!=="play-together:embed-ready"||data.schemaVersion!==1',- 'if(key===lastOutputKey)return true',+ 'if(key===lastOutputKey){','setTimeout(unavailable,12000)',]) expect(script).toContain(marker);});diff --git a/lib/mcp/ui-resources.test.ts b/lib/mcp/ui-resources.test.tsindex a8385067..2749bb99 100644--- a/lib/mcp/ui-resources.test.ts+++ b/lib/mcp/ui-resources.test.ts@@ -68,7 +68,7 @@ describe("MCP Apps Block and Page contract", () => {.filter((tool) => Boolean((tool._meta?.ui as { resourceUri?: string } | undefined)?.resourceUri)).map((tool) => tool.name).sort();- expect(resourceBound).toEqual(["render_mso_block", "render_mso_page"]);+ expect(resourceBound).toEqual(["integration_setup_open", "render_mso_block", "render_mso_page"]);const appOnly = tools.filter((tool) => {const visibility = (tool._meta?.ui as { visibility?: string[] } | undefined)?.visibility;@@ -137,12 +137,14 @@ describe("MCP Apps Block and Page contract", () => {expect(content.text).toContain("https://game.rahmanef.com");expect(content.text).toContain('"environment":"production"');expect(content.text).toContain('app.environment+" · "+app.renderer');- expect(content.text).not.toContain("fetch(");+ expect(content.text).toContain("fetch(endpoint,");+ expect(content.text).toContain('credentials:"omit"');+ expect(content.text).toContain('access.endpoint===INTEGRATION_ENDPOINT');expect(content.text).not.toContain("allow-popups");expect(content.text).not.toContain("allow-top-navigation");expect(content.text).not.toContain("dangerouslySetInnerHTML");expect(content._meta.ui.csp).toMatchObject({- connectDomains: [],+ connectDomains: [MSO_ORIGIN],resourceDomains: [],frameDomains: ["https://game.rahmanef.com"],});diff --git a/lib/mcp/ui-surface-script.ts b/lib/mcp/ui-surface-script.tsindex cb9333eb..4fda07b4 100644--- a/lib/mcp/ui-surface-script.ts+++ b/lib/mcp/ui-surface-script.ts@@ -1,3 +1,4 @@+import { MSO_PAGE_INTEGRATIONS_SCRIPT } from "./ui-page-integrations";import { MSO_PAGE_BRIDGE_SCRIPT } from "./ui-page-bridge";import { MSO_PAGE_FRAME_SCRIPT } from "./ui-page-frame";import { SURFACE_APPS } from "./surface-catalog";@@ -31,6 +32,7 @@ let current={route:"/",kind:"home",title:"MSO",openPath:"/assistant/mcp",catalogconst pending=new Map();let nextRpcId=5000;${MSO_PAGE_BRIDGE_SCRIPT}${MSO_PAGE_FRAME_SCRIPT}+${MSO_PAGE_INTEGRATIONS_SCRIPT}function text(value,fallback="—"){return typeof value==="string"&&value.trim()?value.trim():fallback}function clear(node){while(node.firstChild)node.removeChild(node.firstChild)}@@ -64,6 +66,7 @@ function rpcCall(name,args){return rpcRequest("tools/call",{name,arguments:args}function unbox(result){if(!result||typeof result!=="object")return result;if(result.structuredContent)return result.structuredContent;if(result.result)return unbox(result.result);return result}function nav(route,extra={}){if(!validRoute(route))return;+ if(route!=="/integrations")integrationAccess=null;lastOutputKey="";current={route,kind:route==="/"?"home":"loading",title:"MSO",openPath:"/assistant/mcp",catalog:current.catalog,...extra};render();if(route==="/")return;rpcCall("render_mso_page",{route,...(extra.project?{project:extra.project}:{}),...(extra.sha?{sha:extra.sha}:{})}).then(result=>{if(!acceptPageResult(result))throw new Error("Invalid page result")}).catch(showError)@@ -72,7 +75,7 @@ function showError(error){viewCleanup();viewCleanup=()=>{};clear(body);const boxfunction renderHome(){const root=el("div","home");const hero=el("section","hero");hero.append(el("h2","","MSO Page"),el("p","","ChatGPT is another MSO presentation target. Open a native operator view or a reviewed live demo without leaving the conversation."));root.append(hero);root.append(el("div","section-title","Native pages"));const native=el("div","grid");- for(const item of [{route:"/monitor",title:"System Monitor",desc:"Live bounded host status."},{route:"/project",title:"Project",desc:"Project snapshot and Git state."},{route:"/diff",title:"Diff",desc:"Review project changes."},{route:"/browser",title:"Remote Browser",desc:"Fallback seam for sites that deny framing."}]){const card=button("",()=>nav(item.route),"card");card.append(el("strong","",item.title),el("span","",item.desc));native.append(card)}root.append(native);+ for(const item of [{route:"/integrations",title:"Integrations",desc:"Secure, native credential setup."},{route:"/monitor",title:"System Monitor",desc:"Live bounded host status."},{route:"/project",title:"Project",desc:"Project snapshot and Git state."},{route:"/diff",title:"Diff",desc:"Review project changes."},{route:"/browser",title:"Remote Browser",desc:"Fallback seam for sites that deny framing."}]){const card=button("",()=>nav(item.route),"card");card.append(el("strong","",item.title),el("span","",item.desc));native.append(card)}root.append(native);root.append(el("div","section-title","Reviewed development and production pages"));const apps=el("div","grid");for(const app of SAFE_APPS){const card=button("",()=>nav("/apps/"+encodeURIComponent(app.id)),"card");card.append(el("strong","",app.title),el("span","",app.description),el("span","tag",app.environment+" · "+app.renderer));apps.append(card)}root.append(apps);body.append(root)}@@ -93,7 +96,7 @@ function renderApp(){const box=el("div","notice"),inner=el("div");inner.append(el("h3","",safe.title+" protects itself from framing"),el("p","",safe.reason||"This app is not allowlisted for nested framing. MSO preserves the app's own frame policy instead of stripping it."));const row=el("div","row");row.append(button("Open Remote Browser",()=>openMso(),"primary"));if(window.openai&&typeof window.openai.sendFollowUpMessage==="function")row.append(button("Ask ChatGPT to continue",()=>window.openai.sendFollowUpMessage({prompt:"Continue this demo using the MSO remote-browser fallback for "+safe.title+"."})));inner.append(row);box.append(inner);stage.content.append(box);if(safe.presentation==="pip")pipBtn.hidden=false}function renderBrowser(){const box=el("div","notice"),inner=el("div");inner.append(el("h3","","Remote Browser seam"),el("p","","Sites that deny iframe embedding stay isolated. MSO can continue them through Camoufox without exposing its VNC password or authenticated viewer URL to this widget."));const row=el("div","row");row.append(button("Open MSO Browser",()=>openMso(),"primary"));inner.append(row);box.append(inner);body.append(box);openPath("/browser")}-function render(){viewCleanup();viewCleanup=()=>{};clear(body);titleEl.textContent=text(current.title,"MSO Page");routeEl.textContent=text(current.route,"/");openPath(text(current.openPath,"/assistant/mcp"));persistRoute();if(current.kind==="home")renderHome();else if(current.kind==="monitor")renderMonitor();else if(current.kind==="project")renderProject("project");else if(current.kind==="diff")renderProject("diff");else if(current.kind==="app")renderApp();else if(current.kind==="browser")renderBrowser();else body.append(el("div","loading","Loading MSO Page…"))}+function render(){viewCleanup();viewCleanup=()=>{};clear(body);titleEl.textContent=text(current.title,"MSO Page");routeEl.textContent=text(current.route,"/");openPath(text(current.openPath,"/assistant/mcp"));persistRoute();if(current.kind==="home")renderHome();else if(current.kind==="integrations")renderIntegrations();else if(current.kind==="monitor")renderMonitor();else if(current.kind==="project")renderProject("project");else if(current.kind==="diff")renderProject("diff");else if(current.kind==="app")renderApp();else if(current.kind==="browser")renderBrowser();else body.append(el("div","loading","Loading MSO Page…"))}function readOutput(){return acceptPageResult(window.openai&&window.openai.toolOutput)}window.addEventListener("message",onHostMessage,{passive:true});window.addEventListener("openai:set_globals",()=>{applyHostGlobals();readOutput()},{passive:true});diff --git a/lib/mcp/ui-surface.ts b/lib/mcp/ui-surface.tsindex e50e5a36..6af26084 100644--- a/lib/mcp/ui-surface.ts+++ b/lib/mcp/ui-surface.ts@@ -1,4 +1,5 @@-import { widgetResourceMeta } from "./ui-config";+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";import { surfaceFrameDomains } from "./surface-catalog";import { MSO_SURFACE_SCRIPT } from "./ui-surface-script";@@ -8,7 +9,7 @@ export const MSO_PAGE_URI = "ui://mso/page-v3.html";const MIME = "text/html;profile=mcp-app";const html = String.raw`<main class="surface" aria-label="MSO Page">-<style>${MSO_SURFACE_STYLE}</style>+<style>${MSO_SURFACE_STYLE}${INTEGRATION_FORM_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>@@ -32,6 +33,6 @@ export const MSO_PAGE_RESOURCE = {text: html,_meta: widgetResourceMeta("Interactive MSO Page. It renders native operator views and exact-origin reviewed development or production targets. Nested frames are limited to explicit CSP frame domains and dedicated embed routes; arbitrary HTML and URLs are never accepted from the model.",- { frameDomains: surfaceFrameDomains(), redirectDomains: surfaceFrameDomains() },+ { frameDomains: surfaceFrameDomains(), redirectDomains: surfaceFrameDomains(), connectDomains: [MSO_ORIGIN] },),} as const;diff --git a/lib/mcp/ui-widget-tokens.ts b/lib/mcp/ui-widget-tokens.tsindex 76b2be3e..3082239a 100644--- a/lib/mcp/ui-widget-tokens.ts+++ b/lib/mcp/ui-widget-tokens.ts@@ -1,68 +1 @@-/**- * Shared visual contract for ChatGPT Block and Page resources.- *- * Core values mirror rahmanef.com/app/globals.css. The widget keeps its own- * small presentation aliases, but the public brand palette stays single-source.- */-const DARK_TOKENS = String.raw`---text:#f2f2f5;---text-dim:rgba(242,242,245,.64);---text-faint:rgba(242,242,245,.4);---sep:rgba(255,255,255,.1);---sep-strong:rgba(255,255,255,.18);---grouped:#000;---fill:rgba(120,120,128,.24);---fill2:rgba(120,120,128,.36);---window-bg:rgba(34,34,40,.82);---surface:#1b1b20;---field:rgba(255,255,255,.08);---hover:rgba(255,255,255,.08);---hover-strong:rgba(255,255,255,.14);---inset:rgba(0,0,0,.25);---shadow-pop:0 0 0 .5px rgba(255,255,255,.08),0 16px 40px -8px rgba(0,0,0,.6);---warning:#ff9f0a;---info:#409cff;---destructive-text:#ff5f57;-`;--export const MSO_WIDGET_TOKENS = String.raw`-:root,:root[data-theme="light"]{-color-scheme:light;---text:#1c1c1f;---text-dim:rgba(28,28,31,.66);---text-faint:rgba(28,28,31,.38);---sep:rgba(0,0,0,.1);---sep-strong:rgba(0,0,0,.16);---os-accent:#1f6df0;---accent-text:#fff;---grouped:#f2f2f7;---fill:rgba(118,118,128,.12);---fill2:rgba(118,118,128,.24);---window-bg:rgba(248,248,251,.86);---surface:#f4f4f7;---field:rgba(255,255,255,.7);---hover:rgba(0,0,0,.05);---hover-strong:rgba(0,0,0,.09);---inset:rgba(0,0,0,.04);---shadow-pop:0 0 0 .5px rgba(0,0,0,.12),0 14px 38px -8px rgba(0,0,0,.32);---success:#34c759;---warning:#ff9500;---info:#0060df;---destructive-text:#d70015;---font-display:"Plus Jakarta Sans",Inter,ui-sans-serif,system-ui,sans-serif;---font-body:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;---font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace;---radius:10px;-}-:root[data-theme="dark"]{color-scheme:dark;${DARK_TOKENS}}-@media(prefers-color-scheme:dark){:root:not([data-theme]){color-scheme:dark;${DARK_TOKENS}}}-`;--/** Keep a ChatGPT widget synchronized with the host theme, with media fallback. */-export const MSO_WIDGET_THEME_SCRIPT = String.raw`-function applyHostTheme(){- const theme=window.openai&&window.openai.theme;- if(theme==="light"||theme==="dark")document.documentElement.dataset.theme=theme;- else document.documentElement.removeAttribute("data-theme");-}-`;+export { MSO_WIDGET_TOKENS, MSO_WIDGET_THEME_SCRIPT } from "@/lib/presentation/widget-tokens";diff --git a/lib/presentation/widget-tokens.ts b/lib/presentation/widget-tokens.tsnew file mode 100644index 00000000..76b2be3e--- /dev/null+++ b/lib/presentation/widget-tokens.ts@@ -0,0 +1,68 @@+/**+ * Shared visual contract for ChatGPT Block and Page resources.+ *+ * Core values mirror rahmanef.com/app/globals.css. The widget keeps its own+ * small presentation aliases, but the public brand palette stays single-source.+ */+const DARK_TOKENS = String.raw`+--text:#f2f2f5;+--text-dim:rgba(242,242,245,.64);+--text-faint:rgba(242,242,245,.4);+--sep:rgba(255,255,255,.1);+--sep-strong:rgba(255,255,255,.18);+--grouped:#000;+--fill:rgba(120,120,128,.24);+--fill2:rgba(120,120,128,.36);+--window-bg:rgba(34,34,40,.82);+--surface:#1b1b20;+--field:rgba(255,255,255,.08);+--hover:rgba(255,255,255,.08);+--hover-strong:rgba(255,255,255,.14);+--inset:rgba(0,0,0,.25);+--shadow-pop:0 0 0 .5px rgba(255,255,255,.08),0 16px 40px -8px rgba(0,0,0,.6);+--warning:#ff9f0a;+--info:#409cff;+--destructive-text:#ff5f57;+`;++export const MSO_WIDGET_TOKENS = String.raw`+:root,:root[data-theme="light"]{+color-scheme:light;+--text:#1c1c1f;+--text-dim:rgba(28,28,31,.66);+--text-faint:rgba(28,28,31,.38);+--sep:rgba(0,0,0,.1);+--sep-strong:rgba(0,0,0,.16);+--os-accent:#1f6df0;+--accent-text:#fff;+--grouped:#f2f2f7;+--fill:rgba(118,118,128,.12);+--fill2:rgba(118,118,128,.24);+--window-bg:rgba(248,248,251,.86);+--surface:#f4f4f7;+--field:rgba(255,255,255,.7);+--hover:rgba(0,0,0,.05);+--hover-strong:rgba(0,0,0,.09);+--inset:rgba(0,0,0,.04);+--shadow-pop:0 0 0 .5px rgba(0,0,0,.12),0 14px 38px -8px rgba(0,0,0,.32);+--success:#34c759;+--warning:#ff9500;+--info:#0060df;+--destructive-text:#d70015;+--font-display:"Plus Jakarta Sans",Inter,ui-sans-serif,system-ui,sans-serif;+--font-body:Inter,ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif;+--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono",monospace;+--radius:10px;+}+:root[data-theme="dark"]{color-scheme:dark;${DARK_TOKENS}}+@media(prefers-color-scheme:dark){:root:not([data-theme]){color-scheme:dark;${DARK_TOKENS}}}+`;++/** Keep a ChatGPT widget synchronized with the host theme, with media fallback. */+export const MSO_WIDGET_THEME_SCRIPT = String.raw`+function applyHostTheme(){+ const theme=window.openai&&window.openai.theme;+ if(theme==="light"||theme==="dark")document.documentElement.dataset.theme=theme;+ else document.documentElement.removeAttribute("data-theme");+}+`;diff --git a/proxy.ts b/proxy.tsindex 6dd351ab..0557269c 100644--- a/proxy.ts+++ b/proxy.ts@@ -317,6 +317,7 @@ export async function proxy(request: NextRequest) {MUTATING.has(request.method) &&isApi &&!isMachineProtocol &&+ pathname !== "/api/integrations/setup" &&crossOriginMutation(request))return blocked();diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex 83c17f24..06be51d1 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -24,7 +24,7 @@ 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>|set <dokploy|cloudflare|hostinger>|rm <id>|doctor [id]|projects|zones"+U_provider="provider list|show <id>|setup <id> [method]|set <dokploy|cloudflare|hostinger|composio>|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>"diff --git a/scripts/mso-cli-agent.sh b/scripts/mso-cli-agent.shindex 9b029b7d..c9a8d95a 100755--- a/scripts/mso-cli-agent.sh+++ b/scripts/mso-cli-agent.sh@@ -346,6 +346,13 @@ run_provider() {local sub="${1:-list}" id="${2-}" data row fields key label secret required description existing value bodylocal -a pairs=()case "$sub" in+ setup|web)+ [ -n "$id" ] || die "usage: mso provider setup <id> [direct|project|organization]"+ 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:-$([ "$id" = composio ] && echo project || echo direct)}" '{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+ ;;list)provider_metadata | jq -r '.providers[] | "\(if .configured then "✓" else "·" end) \(.id)\t\(if .configured then "configured" else "missing: " + (.missing|join(", ")) end)\t\(.description)"' ;;show)@@ -372,7 +379,7 @@ run_provider() {tty_ok || die "provider setup needs a terminal because API tokens are entered with hidden input"data=$(provider_metadata)row=$(jq -c --arg id "$id" '.providers[] | select(.id==$id)' <<<"$data")- [ -n "$row" ] || die "unknown provider '$id' (expected dokploy, cloudflare, hostinger)"+ [ -n "$row" ] || die "unknown provider '$id' (expected dokploy, cloudflare, hostinger, composio)"echo "$(jq -r '.title + " — " + .description' <<<"$row")"pairs=()while IFS=$'\t' read -r key label secret required description existing; do