Skip to content

armgit / mso

Public Imported from GitHub
0

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

merge: include latest native connection model before final security review

Rahmanfbbfc61dbe1f
diff --cc docs/PROGRESS.md
index 3bbd522d,4f4d458a..cb0f4488
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@@ -1,21 -1,30 +1,50 @@@
++## 2026-09-05 — Reconcile new connection-model findings before final publication
++
++Published main advanced during the security review and introduced five additional CodeQL alerts. The integration model is preserved while migration backups use a no-follow descriptor for permissions and bounded reads; provider deletion reconstructs maps instead of indexed deletion. New HTML tests use the existing parser helper and CLI tests invoke a committed fixed-argv shell fixture rather than constructing source. The home-relative CLI contract now stubs its service manager and proves the expected teardown request without stopping host services. Source fixes and exact HEAD evidence are required again; no concurrent feature or alert is discarded.
++
+## 2026-09-05 — Close final release review regressions
+
+The documented `~/` store override now expands consistently in the shared server/CLI helper before locking, reading or writing; an end-to-end device test proves both interfaces mutate the same private store. A hosted rollback failure was reproduced deterministically by changing a newly spawned tunnel process title before durable state write. Gateway startup now keeps the original PID/start-ticks handshake until commit, uses it for failed-start rollback, treats zombie processes as stopped, and confirms termination instead of assuming SIGKILL delivery. No assertions were weakened or scanners disabled.
+
+## 2026-09-05 — Scope the final security evidence to the scanned revision
+
+The inventory can now inspect the exact scanned branch after SARIF processing, distinguishes open findings from pre-existing reviewed/closed findings, and rejects a concurrent HEAD change. Reports stream to Actions logs rather than writing remote API content back to files. A newly merged MCP browser fixture now targets the exact widget origin instead of a wildcard; the 17 browser assertions retain their negative-navigation checks. No scanner rule, authentication boundary, or existing disposition is removed by this change.
+
+## 2026-09-05 — Permission-fixture portability under private umask
+
+The deliberately public artifact fixture now sets its final 0644 permissions explicitly: a secure caller umask of 077 otherwise silently creates it as 0600, so the test was asking valid private data to be rejected. The runtime permission check and assertion remain unchanged.
+
+## 2026-09-05 — Resolve actual CodeQL findings and restore the demo
+
+The actual GitHub alert inventory exposed 22 default-branch findings, unlike the previously green scanner-completion jobs. Security-store locks now use an owner-root-validated pinned directory while preserving adjacent CLI lock names; bounded no-follow reads replace file check/reopen pairs. HTML fixture extraction uses parse5; the terminal picker opens its device once. Owner facts and activity logs now have explicit field/byte limits, private no-follow storage, concurrency and rejection tests. Diagnostic logging failures remain isolated from authorized tool execution. Security branches receive real CodeQL, CI and independent scanners; unfiltered SARIF summaries and a separate actual-alert inventory make pending evidence visible. README restores the existing real GIF inline and has a regression test for animation and screenshot presence. No alert is automatically dismissed by these changes.
+
## 2026-09-05 — MCP Page preview lifecycle
+
+ ## 2026-09-05 — Native named-connection identity, not parallel credential forms
+
+ The provider-only Integrations store could not represent multiple deployments or
+ source-aware execution even though its HTML form worked. Replace the foundation
+ with credential users, named connections, direct/Composio/provider-MCP sources,
+ auth methods, folder/default resolution and explicit account selection. Browser,
+ CLI and MCP now call the same domain actions; old infrastructure helpers adapt to
+ that core and pin values for compound provider operations.
+
+ Preserve v1 data through a read-only projection and exact protected backup before
+ the first atomic v2 write. Bind temporary setup capabilities to user/connection
+ UID/revision so stale forms cannot rotate another account. Namespace upstream
+ Composio users by installation/profile UUID; lease both the target and broker for
+ hosted authorization/execution. Duplication is metadata-only unless copying direct
+ credentials is separately approved. Device roles remain distinct from credential
+ profiles, not a new user-login/ACL system.
+
+ Tests exercise two users, five Convex connections, folder resolution, actual
+ Dokploy client routing, source refusal, hosted-account identity, lease protection,
+ MCP/CLI contracts and real shared-core browser saves with synthetic credentials.
+ Page layout follows the host's returned display mode; full-height behavior is
+ measured against the fixture iframe viewport rather than assumed from a button.
+ No real upstream OAuth success is inferred from these tests.
+
- **Reviewed-app Google sign-in leaves the iframe (2026-09-05):** Page v6 adds an explicit host-side Google-login action using a code-owned same-origin path. A nested app may only highlight this action, never trigger navigation, supply a URL or transfer session data. The host opens through `ui/open-link`/`openExternal` after a real button click; sandbox popup restrictions remain unchanged. Play Together finishes sign-in in the browser tab; this does not promise shared login with storage-partitioned embeds. v5 resource requests remain compatible.
diff --cc lib/auth/device-store.test.ts
index a8fba5cd,b14b99ea..fd53211c
--- a/lib/auth/device-store.test.ts
+++ b/lib/auth/device-store.test.ts
@@@ -29,19 -28,6 +29,24 @@@ const DEV = "a".repeat(32)
const OTHER = "b".repeat(32);
describe("device-store — an unreadable file must never look like an empty one", () => {
+ it("keeps documented home-relative overrides identical between server and CLI", async () => {
+ vi.stubEnv("HOME", dir);
+ store = "~/.mso/auth-devices.json";
+ const api = await load();
+ await api.approveDevice(DEV, "home-relative fixture");
++ // Exercise the device file contract without stopping real browser services.
++ const manager = path.join(dir, "systemctl-fixture");
++ await fs.writeFile(manager, "#!/bin/sh\nprintf '%s\n' \"$*\" > \"$HOME/teardown-call\"\n", { mode: 0o700 });
++ vi.stubEnv("MSO_SYSTEMCTL_BIN", manager);
+ const command = path.resolve(__dirname, "../../scripts/approve-device.js");
+ const listing = execFileSync(process.execPath, [command, "--list"], { env: process.env, encoding: "utf8" });
+ expect(listing).toContain(DEV);
+ execFileSync(process.execPath, [command, "--revoke", DEV], { env: process.env, encoding: "utf8" });
+ expect((await api.listDevices()).approved[DEV]).toBeUndefined();
++ expect(await fs.readFile(path.join(dir, "teardown-call"), "utf8")).toContain("--user stop camoufox-vnc.service");
+ expect((await fs.stat(path.join(dir, ".mso/auth-devices.json"))).isFile()).toBe(true);
+ });
+
it("treats a MISSING file as an empty store (legit first run)", async () => {
const { listDevices } = await load();
await expect(listDevices()).resolves.toEqual({ approved: {}, pending: {} });
diff --cc lib/infra/connection-security.test.ts
index 00000000,45672db6..20dabd5e
mode 000000,100644..100644
--- a/lib/infra/connection-security.test.ts
+++ b/lib/infra/connection-security.test.ts
@@@ -1,0 -1,65 +1,83 @@@
+ import {beforeEach,afterEach,it,expect,vi} from "vitest";
+ import {promises as fs} from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ vi.mock("server-only",()=>({}));
+ let root:string;
+ const A="synthetic_secret_alice_project_key",B="synthetic_secret_bob_project_key";
+ beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-identity-security-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+ afterEach(async()=>{vi.unstubAllGlobals();delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+ async function fixture(){
+ const {integrationManage:manage}=await import("./connection-manage"),service=await import("./connection-service"),external=await import("./connection-external");
+ for(const [user,key]of [["alice",A],["bob",B]]){
+ await manage({action:"user.create",user,confirm:true});await manage({action:"connection.create",user,provider:"composio",connection:"broker",source:"direct",authMethod:"project",confirm:true});
+ const snap=await service.credentialSnapshot("composio",{user,connection:"broker"});await service.saveConnectionValues("composio",{user,connection:"broker"},{apiKey:key},snap.connection);
+ await manage({action:"connection.create",user,provider:"github",connection:"work",source:"composio",authMethod:"oauth2",confirm:true});
+ }
+ return{manage,...service,...external};
+ }
+ it("binds Composio authorization to this user's broker and installation-scoped remote identity",async()=>{
+ const f=await fixture(),calls:Array<{url:string;headers:Headers;body:Record<string,unknown>|null}>=[];let remoteUser="";
+ vi.stubGlobal("fetch",vi.fn(async(url:RequestInfo|URL,init?:RequestInit)=>{
+ const req=new Request(url,init),body=req.method==="POST"?await req.json():null;calls.push({url:req.url,headers:req.headers,body});
+ if(req.url.includes("/auth_configs/"))return new Response(JSON.stringify({id:"ac_1",toolkit:{slug:"github"},auth_scheme:"OAUTH2",status:"ENABLED"}));
+ if(req.url.endsWith("/connected_accounts/link")){remoteUser=body.user_id;return new Response(JSON.stringify({connected_account_id:"ca_alice",redirect_url:"https://connect.composio.dev/link/test",link_token:"must-not-persist"}));}
+ if(req.url.endsWith("/connected_accounts/ca_alice"))return new Response(JSON.stringify({id:"ca_alice",toolkit:{slug:"github"},auth_config:{id:"ac_1"},user_id:remoteUser,status:"ACTIVE",state:{access_token:"must-not-persist"}}));
+ if(req.url.includes("/tools/execute/"))return new Response(JSON.stringify({data:{ok:true,access_token:"must-not-persist",echo:A}}));
+ return new Response("{}",{status:404});
+ }));
+ const linked=await f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1",brokerConnection:"broker"});expect(linked.privateUrl).toContain("https://connect.composio.dev/");
+ expect(remoteUser).toMatch(/^mso:[a-f0-9-]+:[a-f0-9-]+$/);expect(remoteUser).not.toContain("alice");
+ const verified=await f.verifyExternalIntegration("github",{user:"alice",connection:"work"});expect(verified.ok).toBe(true);
+ const output=await f.composioConnectionCall("github",{user:"alice",connection:"work"},"GITHUB_GET_THE_AUTHENTICATED_USER",{});expect(JSON.stringify(output)).not.toContain(A);expect(JSON.stringify(output)).not.toContain("must-not-persist");
+ for(const c of calls)expect(c.headers.get("x-api-key")).toBe(A);expect(calls.find(c=>c.url.includes("/tools/execute/"))?.body?.connected_account_id).toBe("ca_alice");
+ const stored=await fs.readFile(process.env.OS_INFRA_STORE!,"utf8");expect(stored).not.toContain("must-not-persist");expect(stored).not.toContain("https://connect.composio.dev/link/test");
+ await expect(f.composioConnectionCall("github",{user:"bob",connection:"work"},"GITHUB_GET_THE_AUTHENTICATED_USER",{})).rejects.toMatchObject({code:"active_connected_account_required"});
+ });
+ it("reserves a connection during hosted auth and refuses concurrent authorization or credential rotation",async()=>{
+ const f=await fixture();let release!:()=>void,entered!:()=>void;const reached=new Promise<void>(r=>entered=r),wait=new Promise<void>(r=>release=r);
+ vi.stubGlobal("fetch",vi.fn(async(url:RequestInfo|URL)=>{
+ if(String(url).includes("/auth_configs/")){entered();await wait;return new Response(JSON.stringify({id:"ac_1",toolkit:{slug:"github"},auth_scheme:"OAUTH2"}));}
+ return new Response(JSON.stringify({connected_account_id:"ca_1",redirect_url:"https://connect.composio.dev/link/test"}));
+ }));
+ const first=f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1"});await reached;
+ await expect(f.authorizeIntegration("github",{user:"alice",connection:"work"},{authConfigId:"ac_1"})).rejects.toMatchObject({code:"connection_busy"});
+ await expect(f.manage({action:"connection.delete",user:"alice",provider:"github",connection:"work",confirm:true})).rejects.toMatchObject({code:"connection_busy"});
+ const snap=await f.credentialSnapshot("composio",{user:"alice",connection:"broker"});await expect(f.saveConnectionValues("composio",{user:"alice",connection:"broker"},{apiKey:B},snap.connection)).rejects.toMatchObject({code:"connection_busy"});
+ release();await first;expect((await f.credentialSnapshot("composio",{user:"alice",connection:"broker"})).connection.lease).toBeUndefined();
+ });
+ it("invalidates an open form after rotation or delete/recreate, without touching another named connection",async()=>{
+ const f=await fixture();const setup=await import("./setup-capability");vi.stubGlobal("fetch",vi.fn(async()=>new Response("{}")));
+ const grant=await setup.openIntegrationSetup("composio","test-principal","project",{user:"alice",connection:"broker"});
+ const snap=await f.credentialSnapshot("composio",{user:"alice",connection:"broker"});await f.saveConnectionValues("composio",{user:"alice",connection:"broker"},{apiKey:B},snap.connection);
+ await expect(setup.consumeIntegrationSetup(grant.token,{apiKey:A})).rejects.toMatchObject({code:"connection_changed_reopen_setup"});
+ const renewed=await setup.openIntegrationSetup("composio","test-principal","project",{user:"alice",connection:"broker"});
+ await f.manage({action:"connection.delete",user:"alice",provider:"composio",connection:"broker",confirm:true});
+ await f.manage({action:"connection.create",user:"alice",provider:"composio",connection:"broker",authMethod:"project",confirm:true});
+ await expect(setup.consumeIntegrationSetup(renewed.token,{apiKey:A})).rejects.toMatchObject({code:"connection_changed_reopen_setup"});
+ expect((await f.credentialSnapshot("composio",{user:"bob",connection:"broker"})).connection.values.apiKey).toBe(B);
+ });
+ it("fails closed for symlink/malformed stores and refuses migration if backup bytes do not match",async()=>{
+ const {readIntegrationState,migrateIntegrationStore}=await import("./connection-storage"),file=process.env.OS_INFRA_STORE!;
+ await fs.writeFile(file,JSON.stringify({providers:{github:{apiKey:A}}}),{mode:0o600});await fs.writeFile(file+".v1-backup.json","different",{mode:0o600});
+ await expect(migrateIntegrationStore()).rejects.toMatchObject({code:"migration_backup_conflict"});expect(JSON.parse(await fs.readFile(file,"utf8")).version).toBeUndefined();
+ await fs.unlink(file);await fs.symlink(file+".v1-backup.json",file);await expect(readIntegrationState()).rejects.toThrow("unsafe");
+ });
++
++it("refuses a symlinked migration backup without touching either file",async()=>{
++ const {migrateIntegrationStore}=await import("./connection-storage"),file=process.env.OS_INFRA_STORE!;
++ const original=JSON.stringify({providers:{github:{apiKey:A}}}),target=path.join(root,"outside.json");
++ await fs.writeFile(file,original,{mode:0o600});await fs.writeFile(target,original,{mode:0o600});await fs.symlink(target,file+".v1-backup.json");
++ await expect(migrateIntegrationStore()).rejects.toThrow();
++ expect(await fs.readFile(file,"utf8")).toBe(original);expect(await fs.readFile(target,"utf8")).toBe(original);
++});
++it("removes only the selected direct connection and does not mutate object prototypes",async()=>{
++ const f=await fixture(),{removeInfraProvider}=await import("./store");
++ await f.manage({action:"connection.create",user:"alice",provider:"github",connection:"direct-work",source:"direct",authMethod:"direct",confirm:true});
++ await f.withIntegrationSelection({user:"alice",connection:"direct-work"},()=>removeInfraProvider("github"));
++ const {readIntegrationState}=await import("./connection-storage");const state=await readIntegrationState();
++ expect(state.users.alice.connections.github["direct-work"]).toBeUndefined();expect(state.users.alice.connections.github.work.source).toBe("composio");
++ expect(state.users.bob.connections.github.work.source).toBe("composio");
++ await expect(f.withIntegrationSelection({user:"constructor",connection:"work"},()=>removeInfraProvider("github"))).rejects.toThrow();
++ expect(Object.prototype).not.toHaveProperty("work");
++});
diff --cc lib/infra/connection-storage.ts
index 00000000,340444f3..e94a6abc
mode 000000,100644..100644
--- a/lib/infra/connection-storage.ts
+++ b/lib/infra/connection-storage.ts
@@@ -1,0 -1,58 +1,60 @@@
++import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+ import { constants, promises as fs } from "node:fs";
+ import { randomUUID } from "node:crypto";
+ import path from "node:path";
+ import os from "node:os";
+ import { withSecurityStoreLock } from "@/lib/security-store-lock";
+ import { connectionMethod, legacyMethod } from "./connection-registry";
+ import { isInfraProviderId } from "./catalog";
+ import { emptyIntegrationState, IntegrationError, identity, type IntegrationState, type IntegrationConnection } from "./identity";
-export const INFRA_STORE_PATH=process.env.OS_INFRA_STORE??path.join(os.homedir(),".mso","private","infra-providers.json");
++export const INFRA_STORE_PATH=expandOwnerStorePath(process.env.OS_INFRA_STORE??path.join(os.homedir(),".mso","private","infra-providers.json"));
+ const MAX=1024*1024;
+ async function readRaw():Promise<{raw:Record<string,unknown>;bytes:string}|null>{
+ let handle;
+ try{handle=await fs.open(INFRA_STORE_PATH,constants.O_RDONLY|constants.O_NOFOLLOW);const s=await handle.stat();
+ if(!s.isFile()||s.size<1||s.size>MAX||(s.mode&0o077)||(typeof process.getuid==="function"&&s.uid!==process.getuid()))throw new IntegrationError("unsafe_integration_store");
+ const bytes=await handle.readFile("utf8"),raw=JSON.parse(bytes);if(!raw||typeof raw!=="object"||Array.isArray(raw))throw new IntegrationError("invalid_integration_store");return{raw,bytes};
+ }catch(e){if((e as NodeJS.ErrnoException).code==="ENOENT")return null;throw new IntegrationError("invalid_or_unsafe_integration_store");}finally{await handle?.close();}
+ }
+ function validate(d:IntegrationState):IntegrationState{
+ if(d.version!==2||!d.instanceId||!d.users||typeof d.users!=="object"||Array.isArray(d.users)||!Array.isArray(d.bindings))throw new IntegrationError("invalid_integration_store");
+ for(const [id,u] of Object.entries(d.users)){identity(id);if(u.id!==id||!u.connections||!u.defaults)throw new IntegrationError("invalid_integration_store");
+ for(const [p,rows]of Object.entries(u.connections)){identity(p);for(const [cid,c]of Object.entries(rows)){identity(cid);if(c.id!==cid||c.provider!==p||!c.uid||!Number.isInteger(c.revision)||!c.values||typeof c.values!=="object"||Array.isArray(c.values)||Object.values(c.values).some(v=>typeof v!=="string"))throw new IntegrationError("invalid_connection_store");connectionMethod(c.provider,c.source,c.authMethod);if(c.source!=="direct"&&Object.keys(c.values).length)throw new IntegrationError("external_secrets_forbidden");}}
+ }
+ return d;
+ }
+ function projected(raw:Record<string,unknown>|undefined):IntegrationState{
+ if(!raw)return emptyIntegrationState();if(raw.version===2)return validate(raw as unknown as IntegrationState);
+ if(raw.version!==undefined)throw new IntegrationError("unsupported_store_version");
+ const d=emptyIntegrationState(),providers=raw.providers;
+ if(providers===undefined)return d;if(!providers||typeof providers!=="object"||Array.isArray(providers))throw new IntegrationError("invalid_legacy_store");
+ const profile={id:"legacy",uid:"legacy",label:"Existing MSO credentials",defaults:{} as Record<string,string>,connections:{} as Record<string,Record<string,IntegrationConnection>>};
+ for(const [provider,v] of Object.entries(providers)){
+ if(!isInfraProviderId(provider)||!v||typeof v!=="object"||Array.isArray(v)||Object.values(v).some(x=>typeof x!=="string"))throw new IntegrationError("legacy_migration_requires_review");
+ const values=v as Record<string,string>;const selected=legacyMethod(provider,values);
+ const methods=provider==="composio"?[...(values.apiKey?["project"]:[]),...(values.orgApiKey?["organization"]:[])]:provider==="convex-cloud"?[...(values.personalToken?["personal"]:[]),...(values.deployKey||values.deploymentName?["deployment"]:[])]:["direct"];
+ if(!methods.length)methods.push(selected);
+ profile.connections[provider]={};
+ for(const method of methods){const def=connectionMethod(provider,"direct",method),id=methods.length===1?"default":method;
+ profile.connections[provider][id]={id,uid:`legacy:${provider}:${method}`,label:methods.length===1?"Existing connection":def.label,provider,source:"direct",authMethod:method,scope:def.scope,revision:1,values:Object.fromEntries(def.fields.filter(f=>values[f.key]!==undefined).map(f=>[f.key,values[f.key]])),createdAt:0,updatedAt:0};
+ if(method===selected)profile.defaults[provider]=id;
+ }
+ }
+ d.users.legacy=profile;d.defaultUser="legacy";return d;
+ }
+ async function write(d:IntegrationState){
+ validate(d);const dir=path.dirname(INFRA_STORE_PATH);await fs.mkdir(dir,{recursive:true,mode:0o700});const st=await fs.lstat(dir);if(st.isSymbolicLink()||!st.isDirectory())throw new IntegrationError("unsafe_integration_directory");await fs.chmod(dir,0o700);
+ const text=JSON.stringify(d,null,2);if(Buffer.byteLength(text)>MAX)throw new IntegrationError("integration_store_capacity",409);
+ const temp=`${INFRA_STORE_PATH}.${randomUUID()}.tmp`;try{await fs.writeFile(temp,text,{mode:0o600,flag:"wx"});await fs.rename(temp,INFRA_STORE_PATH);}finally{await fs.unlink(temp).catch(()=>{});}
+ }
+ export async function readIntegrationState(){return projected((await readRaw())?.raw);}
+ export async function mutateIntegrationState<T>(fn:(d:IntegrationState)=>T|Promise<T>):Promise<T>{
+ return withSecurityStoreLock(INFRA_STORE_PATH,async()=>{const previous=await readRaw(),d=projected(previous?.raw);const out=await fn(d);
+ if(previous&&previous.raw.version!==2){
- const backup=`${INFRA_STORE_PATH}.v1-backup.json`;let h;try{h=await fs.open(backup,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);await h.writeFile(previous.bytes);}catch(e){if((e as NodeJS.ErrnoException).code!=="EEXIST")throw e;const existing=await fs.lstat(backup);if(!existing.isFile()||existing.isSymbolicLink()||(existing.mode&0o077)||(await fs.readFile(backup,"utf8"))!==previous.bytes)throw new IntegrationError("migration_backup_conflict",409);}finally{await h?.close();}d.migratedAt=Date.now();
++ const backup=`${INFRA_STORE_PATH}.v1-backup.json`;let h;try{h=await fs.open(backup,constants.O_WRONLY|constants.O_CREAT|constants.O_EXCL|constants.O_NOFOLLOW,0o600);await h.writeFile(previous.bytes);}catch(e){if((e as NodeJS.ErrnoException).code!=="EEXIST")throw e;const existing=await fs.open(backup,constants.O_RDONLY|constants.O_NOFOLLOW);
++ try{const stat=await existing.stat();if(!stat.isFile()||stat.size>MAX||(stat.mode&0o077)||stat.uid!==process.getuid?.()||(await existing.readFile("utf8"))!==previous.bytes)throw new IntegrationError("migration_backup_conflict",409);}finally{await existing.close();}}finally{await h?.close();}d.migratedAt=Date.now();
+ }
+ await write(d);return out;
+ });
+ }
+ export async function migrateIntegrationStore(){await mutateIntegrationState(()=>null);return{ok:true,version:2,backupPreserved:true};}
diff --cc lib/infra/setup-capability.test.ts
index 03c6a9b5,61d33394..26f4ced8
--- a/lib/infra/setup-capability.test.ts
+++ b/lib/infra/setup-capability.test.ts
@@@ -17,14 -25,11 +25,14 @@@ async function openBound(api:typeof imp
describe("native integration setup capabilities", () => {
it("binds a hashed, owner-only, expiring grant to a provider/method", async () => {
const api = await import("./setup-capability");
- const grant = await api.openIntegrationSetup("composio", "test-owner", "project");
+ const grant = await openBound(api);
expect(grant.token).toMatch(/^[A-Za-z0-9_-]{43}$/);
const file = path.join(root, "integration-setup", createHash("sha256").update(grant.token).digest("hex") + ".json");
- expect((await fs.stat(file)).mode & 0o777).toBe(0o600);
- const stored = await fs.readFile(file, "utf8"); expect(stored).not.toContain(grant.token); expect(stored).toContain("test-owner");
+ const handle = await fs.open(file, "r");
+ try {
+ expect((await handle.stat()).mode & 0o777).toBe(0o600);
+ const stored = await handle.readFile("utf8"); expect(stored).not.toContain(grant.token); expect(stored).toContain("test-owner");
+ } finally { await handle.close(); }
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" });
diff --cc lib/infra/setup-hub.test.ts
index 3f58d102,084a3074..c62d15e6
--- a/lib/infra/setup-hub.test.ts
+++ b/lib/infra/setup-hub.test.ts
@@@ -1,7 -1,6 +1,7 @@@
+import { inlineScripts } from "../../scripts/test-support/inline-scripts";
import { expect, it } from "vitest";
- import { integrationCatalog } from "./setup-catalog";
- import { INTEGRATION_PICKER_SCRIPT } from "./setup-picker";
+ import { connectionCatalog } from "./connection-registry";
+ import { CONNECTION_MANAGER_SCRIPT } from "./connection-ui";
import { INFRA_PROVIDER_IDS } from "./types";
import { integrationSetupPage } from "./setup-page";
it("derives the complete native setup catalog from the same provider registry", () => {
@@@ -11,7 -10,7 +11,7 @@@
});
it("keeps guidance before login and preserves explicit role/expiry recovery", () => {
const page = integrationSetupPage();
- expect(() => new Function(page.html.match(/<script[^>]*>([\s\S]*?)<\/script>/)![1])).not.toThrow();
+ expect(() => new Function(inlineScripts(page.html)[0])).not.toThrow();
- for (const marker of ['"/api/auth/me"', 'session.role!=="owner"', '"visibilitychange"', '"How to get this credential"', 'Open a new setup session']) expect(page.html).toContain(marker);
- expect(INTEGRATION_PICKER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");
+ for (const marker of ['"/api/auth/me"', 'owner=auth.role==="owner"', '"visibilitychange"', 'How to get this credential', 'mountConnectionManager']) expect(page.html).toContain(marker);
+ expect(CONNECTION_MANAGER_SCRIPT).not.toContain('localStorage'); expect(page.csp).toContain("form-action 'none'");
});
diff --cc lib/infra/store.ts
index d891862b,6e3720d2..2f020f3c
--- a/lib/infra/store.ts
+++ b/lib/infra/store.ts
@@@ -1,80 -1,33 +1,36 @@@
- import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
- import { randomUUID } from "node:crypto";
- import { constants as fsConstants, promises as fs } from "node:fs";
- import os from "node:os";
- import path from "node:path";
- import { withSecurityStoreLock } from "@/lib/security-store-lock";
+ import {randomUUID} from "node:crypto";
import { getInfraProviderDefinition, normalizeInfraValues } from "./catalog";
- import type { InfraProviderId, InfraProviderSummary, InfraProviderValues, InfraStore } from "./types";
-
- export const INFRA_STORE_PATH = expandOwnerStorePath(process.env.OS_INFRA_STORE ?? path.join(os.homedir(), ".mso", "private", "infra-providers.json"));
- const MAX_STORE_BYTES = 256 * 1024;
-
- function mask(value: string): string {
- return value ? "configured" : "";
- }
-
- async function readUnlocked(): Promise<InfraStore> {
- let handle: Awaited<ReturnType<typeof fs.open>> | null = null;
- try {
- handle = await fs.open(INFRA_STORE_PATH, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
- const stat = await handle.stat();
- if (!stat.isFile()) throw new Error("infrastructure provider store must be a regular file");
- if (stat.size <= 0 || stat.size > MAX_STORE_BYTES) throw new Error("infrastructure provider store has an invalid size");
- if ((stat.mode & 0o077) !== 0) throw new Error("infrastructure provider store permissions are too broad; expected 0600");
- if (typeof process.getuid === "function" && stat.uid !== process.getuid()) throw new Error("infrastructure provider store is not owned by the MSO user");
- const raw = JSON.parse(await handle.readFile("utf8")) as InfraStore;
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new Error("infrastructure provider store has an invalid shape");
- return raw;
- } catch (error) {
- if ((error as NodeJS.ErrnoException).code === "ENOENT") return {};
- throw error;
- } finally {
- await handle?.close().catch(() => undefined);
- }
- }
-
- async function writeUnlocked(store: InfraStore): Promise<void> {
- const dir = path.dirname(INFRA_STORE_PATH);
- await fs.mkdir(dir, { recursive: true, mode: 0o700 });
- await fs.chmod(dir, 0o700).catch(() => undefined);
- const tmp = `${INFRA_STORE_PATH}.${randomUUID()}.tmp`;
- await fs.writeFile(tmp, JSON.stringify(store, null, 2), { encoding: "utf8", mode: 0o600 });
- await fs.chmod(tmp, 0o600);
- await fs.rename(tmp, INFRA_STORE_PATH);
- await fs.chmod(INFRA_STORE_PATH, 0o600);
- }
-
- export async function readInfraProvider(id: InfraProviderId): Promise<InfraProviderValues> {
- const store = await readUnlocked();
- return { ...(store.providers?.[id] ?? {}) };
- }
-
- export async function setInfraProvider(id: InfraProviderId, raw: Record<string, unknown>): Promise<InfraProviderValues> {
- return withSecurityStoreLock(INFRA_STORE_PATH, async () => {
- const store = await readUnlocked();
- const current = store.providers?.[id] ?? {};
- const normalized = normalizeInfraValues(id, raw);
- const values = { ...current, ...normalized };
- const def = getInfraProviderDefinition(id);
- const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
- if (id === "composio" && !values.apiKey && !values.orgApiKey) missing.push("project or organization API key");
- if (id === "convex-cloud" && !values.personalToken && !(values.deployKey && values.deploymentName)) missing.push("personal token or deployment key and name");
- if (missing.length) throw new Error(`${id} is missing required value(s): ${missing.join(", ")}`);
- await writeUnlocked({ ...store, providers: { ...(store.providers ?? {}), [id]: values } });
- return values;
+ import { mutateIntegrationState } from "./connection-storage";
+ import { currentIntegrationSelection, directConnectionValues, createConnectionIn } from "./connection-service";
+ import { legacyMethod, connectionMethod } from "./connection-registry";
+ import { selectConnection, IntegrationError, assertNotBusy } from "./identity";
+ import type { InfraProviderId, InfraProviderSummary, InfraProviderValues } from "./types";
+ export { INFRA_STORE_PATH } from "./connection-storage";
+ const mask=(value:string)=>value?"configured":"";
+ export const readInfraProvider=(id:InfraProviderId)=>directConnectionValues(id);
+ export async function setInfraProvider(id:InfraProviderId,raw:Record<string,unknown>):Promise<InfraProviderValues>{
+ return mutateIntegrationState(state=>{
+ const selector=currentIntegrationSelection();
+ if(!Object.keys(state.users).length&&!selector.user){state.users.legacy={id:"legacy",uid:randomUUID(),label:"Existing MSO credentials",defaults:{},connections:{}};state.defaultUser="legacy";}
+ let selected;
+ try{selected=selectConnection(state,id,selector);}catch(e){
+ if(!(e instanceof IntegrationError)||e.code!=="connection_not_found"||selector.connection)throw e;
+ const user=selector.user??state.defaultUser;if(!user)throw new IntegrationError("user_required");
+ const c=createConnectionIn(state,{user,provider:id,connection:"default",authMethod:legacyMethod(id,raw as Record<string,string>),makeDefault:true});selected={user,connection:c};
+ }
+ const c=selected.connection;assertNotBusy(c);if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden");
+ const method=connectionMethod(id,c.source,c.authMethod),normalized=normalizeInfraValues(id,raw);
+ if(Object.keys(normalized).some(k=>!method.fields.some(f=>f.key===k)))throw new IntegrationError("connection_auth_mismatch",409);
+ const values={...c.values,...normalized};if(method.fields.some(f=>f.required&&!values[f.key]))throw new IntegrationError("required_fields_missing");
+ c.values=values;c.revision++;c.updatedAt=Date.now();delete c.verifiedAt;return{...values};
});
}
-
- export async function removeInfraProvider(id: InfraProviderId): Promise<void> {
- await withSecurityStoreLock(INFRA_STORE_PATH, async () => {
- const store = await readUnlocked();
- const providers = { ...(store.providers ?? {}) };
- delete providers[id];
- await writeUnlocked({ ...store, providers });
- });
+ export async function removeInfraProvider(id:InfraProviderId){
- await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);delete state.users[r.user].connections[id][r.connection.id];if(state.users[r.user].defaults[id]===r.connection.id)delete state.users[r.user].defaults[id];});
++ await mutateIntegrationState(state=>{const selection=currentIntegrationSelection();const r=selectConnection(state,id,selection);assertNotBusy(r.connection);if(state.bindings.some(b=>b.user===r.user&&b.connections[id]===r.connection.id))throw new IntegrationError("connection_has_folder_binding");if(id==="composio"&&Object.values(state.users[r.user].connections).some(rows=>Object.values(rows).some(c=>c.source==="composio"&&c.external?.brokerConnection===r.connection.id)))throw new IntegrationError("broker_has_linked_connections",409);const profile=state.users[r.user];
++ const remaining=Object.fromEntries(Object.entries(profile.connections[id]).filter(([key])=>key!==r.connection.id));
++ profile.connections=Object.fromEntries(Object.entries(profile.connections).map(([key,rows])=>[key,key===id?remaining:rows]));
++ profile.defaults=Object.fromEntries(Object.entries(profile.defaults).filter(([key,value])=>key!==id||value!==r.connection.id));});
}
-
export function summarizeInfraProvider(id: InfraProviderId, values: InfraProviderValues): InfraProviderSummary {
const def = getInfraProviderDefinition(id);
const missing = def.fields.filter((field) => field.required && !values[field.key]).map((field) => field.key);
diff --cc lib/mcp/integration-model-contract.test.ts
index 00000000,6a803ca8..ae9dae5d
mode 000000,100644..100644
--- a/lib/mcp/integration-model-contract.test.ts
+++ b/lib/mcp/integration-model-contract.test.ts
@@@ -1,0 -1,34 +1,35 @@@
++import { inlineScripts } from "../../scripts/test-support/inline-scripts";
+ import {beforeEach,afterEach,it,expect,vi} from "vitest";
+ import {promises as fs} from "node:fs";
+ import os from "node:os";
+ import path from "node:path";
+ vi.mock("server-only",()=>({}));
+ let root:string;
+ beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-contract-model-"));process.env.OS_INFRA_STORE=path.join(root,"infra.json");vi.resetModules();});
+ afterEach(async()=>{delete process.env.OS_INFRA_STORE;await fs.rm(root,{recursive:true,force:true});vi.resetModules();});
+ it("uses the same native metadata services through actual MCP calls and rejects insufficient scope",async()=>{
+ const {dispatch}=await import("./dispatch");
+ const call=(id:number,name:string,args:Record<string,unknown>,scope:"read"|"write"|"exec"="exec")=>dispatch({id,method:"tools/call",params:{name,arguments:args}},scope,"test",{principal:"mcp-client:integration-contract",sessionId:"integration-contract",toolProfile:"chatgpt"});
+ const denied=await call(1,"integration_manage",{action:"user.create",user:"alice",confirm:true},"read");expect(denied.error??denied.result).toBeTruthy();
+ const {readIntegrationState}=await import("@/lib/infra/connection-storage");expect((await readIntegrationState()).users).toEqual({});
+ const created=await call(2,"integration_manage",{action:"user.create",user:"alice",confirm:true});expect(created.error).toBeUndefined();expect((created.result as any)?.structuredContent?.result?.ok).toBe(true);
+ const added=await call(3,"integration_manage",{action:"connection.create",user:"alice",provider:"convex-cloud",connection:"mimin-production",authMethod:"deployment",source:"direct",confirm:true});expect(added.error).toBeUndefined();
+ const metadata=await call(4,"integration_query",{view:"resolve",user:"alice",provider:"convex-cloud",connection:"mimin-production"});expect((metadata.result as any)?.structuredContent?.result).toMatchObject({user:"alice",id:"mimin-production",source:"direct",authMethod:"deployment"});
+ const inputRejected=await call(5,"integration_manage",{action:"user.create",user:"eve",confirm:true,token:"synthetic"});expect((await readIntegrationState()).users.eve).toBeUndefined();expect(inputRejected.error??(inputRejected.result as any)?.isError).toBeTruthy();
+ });
+ it("returns identity-bound setup only in UI-private metadata on both supported MCP profiles",async()=>{
+ const {integrationManage}=await import("@/lib/infra/connection-manage");await integrationManage({action:"user.create",user:"alice",confirm:true});await integrationManage({action:"connection.create",user:"alice",provider:"github",connection:"work",source:"direct",authMethod:"direct",confirm:true});
+ const {dispatch}=await import("./dispatch");
+ for(const profile of ["full","chatgpt"] as const){
+ const result=await dispatch({id:1,method:"tools/call",params:{name:"integration_setup_open",arguments:{user:"alice",provider:"github",connection:"work"}}},"write","test",{principal:"mcp-client:integration-contract",sessionId:"integration-contract",toolProfile:profile});
+ const wire=result.result as any;expect(result.error).toBeUndefined();expect(wire.structuredContent.setup).toMatchObject({user:"alice",connection:"work",source:"direct"});
+ const token=wire._meta?.integrationSetup?.token;expect(token).toMatch(/^[A-Za-z0-9_-]{43}$/);expect(JSON.stringify(wire.content)).not.toContain(token);expect(JSON.stringify(wire.structuredContent)).not.toContain(token);
+ }
+ });
+ it("keeps current and older Page resources readable and emits no extra UI type",async()=>{
+ const {readUiResource,listUiResources,MSO_PAGE_URI}=await import("./ui-resources");
+ expect(listUiResources()).toHaveLength(2);const html=readUiResource(MSO_PAGE_URI)!.text;
+ for(const version of [1,2,3,4,5,6])expect(readUiResource(`ui://mso/page-v${version}.html`)?.text).toBe(html);
+ expect(html).toContain("mountConnectionManager");expect(html).toContain("data-display-mode");
- const script=html.match(/<script>([\s\S]*)<\/script>/)?.[1];expect(()=>new Function(script!)).not.toThrow();
++ const script=inlineScripts(html)[0];expect(()=>new Function(script!)).not.toThrow();
+ });
diff --cc scripts/mso-cli-integrations.test.ts
index 00000000,a95990fe..49eadc55
mode 000000,100644..100644
--- a/scripts/mso-cli-integrations.test.ts
+++ b/scripts/mso-cli-integrations.test.ts
@@@ -1,0 -1,27 +1,18 @@@
+ import {execFileSync} from "node:child_process";
+ import {expect,it} from "vitest";
+ import path from "node:path";
-const script=path.join(process.cwd(),"scripts/mso-cli-integrations.sh");
-function run(args:string[]){return execFileSync("bash",["-c",`set -e
-source "$1"
-shift
-enc(){ printf '%s' "$1"; }
-jget(){ printf '%s' "$1"; }
-jpost(){ printf '%s' "$2"; }
-die(){ printf '%s' "$*" >&2; exit 2; }
-tty_ok(){ return 1; }
-run_integrations "$@"
-`,"test",script,...args],{encoding:"utf8"});}
++const script=path.join(__dirname,"test-support/integrations-cli-harness.sh");
++function run(args:string[]){return execFileSync("bash",[script,...args],{encoding:"utf8"});}
+ it("routes exact user/provider/connection through the native owner API",()=>{
+ expect(run(["resolve","alice","convex-cloud","mimin-production"])).toContain("view=resolve&user=alice&provider=convex-cloud&connection=mimin-production");
+ expect(JSON.parse(run(["verify","alice","convex-cloud","mimin-staging"]))).toMatchObject({mode:"execute",operation:"verify",user:"alice",provider:"convex-cloud",connection:"mimin-staging"});
+ expect(JSON.parse(run(["create-connection","alice","github","work","composio","oauth2"]))).toMatchObject({mode:"manage",confirm:true,user:"alice",provider:"github",connection:"work",source:"composio",authMethod:"oauth2"});
+ });
+ it("does not print private setup links through a non-interactive caller",()=>{
+ expect(()=>run(["setup","alice","github","work"])).toThrow();
+ });
+ it("requires explicit metadata mutation confirmation and carries folder context",()=>{
+ expect(()=>run(["manage",JSON.stringify({action:"user.delete",user:"alice"})])).toThrow();
+ expect(JSON.parse(run(["manage",JSON.stringify({action:"user.default",user:"alice",confirm:true})]))).toMatchObject({mode:"manage",confirm:true});
+ expect(run(["which","/home/test/project"])).toContain("view=which&cwd=/home/test/project");
+ });
diff --cc scripts/test-support/integrations-cli-harness.sh
index 00000000,00000000..12a7c7e5
new file mode 100644
--- /dev/null
+++ b/scripts/test-support/integrations-cli-harness.sh
@@@ -1,0 -1,0 +1,13 @@@
++#!/usr/bin/env bash
++# Hermetic fixture: run the real CLI handler with local transport replacements.
++# No generated shell program, HTTP request, credential lookup or real service action.
++set -euo pipefail
++ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
++# shellcheck source=scripts/mso-cli-integrations.sh
++source "$ROOT/scripts/mso-cli-integrations.sh"
++enc() { printf '%s' "$1"; }
++jget() { printf '%s' "$1"; }
++jpost() { printf '%s' "$2"; }
++die() { printf '%s' "$*" >&2; exit 2; }
++tty_ok() { return 1; }
++run_integrations "$@"