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): simplify UI and secure credential exports
Rahmanf54e61d9d70d
diff --git a/app/api/v1/integrations/transfer/route.test.ts b/app/api/v1/integrations/transfer/route.test.tsindex 8fdd957f..245a4de8 100644--- a/app/api/v1/integrations/transfer/route.test.ts+++ b/app/api/v1/integrations/transfer/route.test.ts@@ -1,14 +1,24 @@import {beforeEach,afterEach,it,expect,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';import sample from '@/schemas/integration-bundle-example.json';-vi.mock('server-only',()=>({}));vi.mock('@/lib/host/audit-api',()=>({audit:vi.fn()}));+vi.mock('server-only',()=>({}));const audit=vi.hoisted(()=>({write:vi.fn()}));vi.mock('@/lib/host/audit-api',()=>({audit:audit.write}));const auth=vi.hoisted(()=>({role:'owner' as string}));vi.mock('@/lib/auth/require-session',()=>({getSessionContext:async()=>({role:auth.role,session:{device_id:'test-device'}})}));let root:string;-beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),'mso-transfer-route-'));process.env.OS_INFRA_STORE=path.join(root,'infra.json');process.env.OS_PUBLIC_ORIGIN='https://mso.example.test';auth.role='owner';vi.resetModules()});-afterEach(async()=>{delete process.env.OS_INFRA_STORE;delete process.env.OS_PUBLIC_ORIGIN;await fs.rm(root,{recursive:true,force:true});vi.resetModules()});+beforeEach(async()=>{root=await fs.mkdtemp(path.join(os.tmpdir(),'mso-transfer-route-'));process.env.OS_INFRA_STORE=path.join(root,'infra.json');process.env.OS_PUBLIC_ORIGIN='https://mso.example.test';process.env.OS_LOGIN_PASSWORD='fixture-owner-password';auth.role='owner';audit.write.mockReset();vi.resetModules()});+afterEach(async()=>{delete process.env.OS_INFRA_STORE;delete process.env.OS_PUBLIC_ORIGIN;delete process.env.OS_LOGIN_PASSWORD;await fs.rm(root,{recursive:true,force:true});vi.resetModules()});const req=(body:unknown)=>new NextRequest('https://mso.example.test/api/v1/integrations/transfer',{method:'POST',headers:{'content-type':'application/json',origin:'https://mso.example.test'},body:JSON.stringify(body)});it('refuses non-owner export and import',async()=>{const {POST}=await import('./route');auth.role='viewer';expect((await POST(req({action:'export'}))).status).toBe(403);expect((await POST(req({action:'import',document:sample}))).status).toBe(403)});it('supports preview then confirmed application and returns only safe summaries',async()=>{const {POST}=await import('./route');const r=await POST(req({action:'import',document:sample}));expect(r.status).toBe(200);const p=await r.json();expect(p.applied).toBeUndefined();const applied=await POST(req({action:'import',document:sample,apply:true,confirm:p.planId}));expect(applied.status).toBe(200);const exportResult=await POST(req({action:'export'}));expect((await exportResult.json()).bundle.mode).toBe('metadata');expect(exportResult.headers.get('cache-control')).toContain('no-store')});it('rejects giant, malformed, or non-JSON bodies',async()=>{const {POST}=await import('./route');expect((await POST(req({action:'import',document:'x'.repeat(3*1024*1024)}))).status).toBe(413);const request=req({action:'export'});request.headers.set('content-type','text/plain');expect((await POST(request)).status).toBe(415);expect((await POST(req({action:'export',includeSecrets:'true'}))).status).toBe(400)});it("returns the configured public entrypoint instead of a VPS loopback URL",async()=>{const {GET}=await import("./route");const r=await GET();expect(r.status).toBe(200);expect((await r.json()).url).toBe("https://mso.example.test/integrations?transfer=1");auth.role="viewer";expect((await GET()).status).toBe(403)});++it('requires fresh owner password for a one-time raw download and keeps secrets out of metadata/audit',async()=>{+ const codec=await import('@/lib/infra/portable/codec.js'),{POST}=await import('./route');const secret='synthetic-raw-export-secret-123456';+ const payload=codec.validate({...structuredClone(sample),mode:'secrets'},true);payload.users[0].connections[0].values={GITHUB_TOKEN:secret,GH_OWNER:'sample-org'};const envelope=await codec.seal(payload,'bundle-passphrase');+ const preview=await (await POST(req({action:'import',document:envelope,passphrase:'bundle-passphrase'}))).json();expect((await POST(req({action:'import',document:envelope,passphrase:'bundle-passphrase',apply:true,confirm:preview.planId}))).status).toBe(200);+ const tree=await (await POST(req({action:'tree'}))).json();expect(JSON.stringify(tree)).not.toContain(secret);const selection=[{user:'sample-user',provider:'github',connection:'work'}];+ expect((await POST(req({action:'authorize-raw-export',password:'wrong-password',selection}))).status).toBe(401);const authorized=await POST(req({action:'authorize-raw-export',password:'fixture-owner-password',selection}));expect(authorized.status).toBe(200);const grant=(await authorized.json()).grant;expect(grant).toMatch(/^[A-Za-z0-9_-]{43}$/);+ const raw=await POST(req({action:'export-raw',grant,format:'env',selection}));expect(raw.status).toBe(200);expect(raw.headers.get('content-disposition')).toContain('.env');expect(raw.headers.get('cache-control')).toContain('no-store');expect(raw.headers.get('x-mso-credential-export')).toBe('plaintext');expect(await raw.text()).toContain(secret);+ expect((await POST(req({action:'export-raw',grant,format:'env',selection}))).status).toBe(401);expect(JSON.stringify(audit.write.mock.calls)).not.toContain(secret);expect(JSON.stringify(audit.write.mock.calls)).not.toContain('fixture-owner-password');+});diff --git a/app/api/v1/integrations/transfer/route.ts b/app/api/v1/integrations/transfer/route.tsindex db62c194..390883ef 100644--- a/app/api/v1/integrations/transfer/route.ts+++ b/app/api/v1/integrations/transfer/route.ts@@ -3,11 +3,13 @@ import {NextRequest,NextResponse} from 'next/server';import {getSessionContext} from '@/lib/auth/require-session';import {audit} from '@/lib/host/audit-api';import {exportIntegrationData,importIntegrationData,type TransferOptions} from '@/lib/infra/portable/data';+import {authorizeRawCredentialExport,consumeRawCredentialExportGrant} from '@/lib/infra/portable/export-grant';+import {exportRawCredentials,exportSelectionTree,type RawCredentialFormat} from '@/lib/infra/portable/raw-export';import {transferBody} from '@/lib/infra/portable/http';import {BundleError} from '@/lib/infra/portable/codec.js';import {IntegrationError} from '@/lib/infra/identity';export const runtime='nodejs';export const dynamic='force-dynamic';-const headers={'Cache-Control':'no-store, private','Referrer-Policy':'no-referrer','X-Content-Type-Options':'nosniff'};+const headers={'Cache-Control':'no-store, private','Pragma':'no-cache','Expires':'0','Referrer-Policy':'no-referrer','X-Content-Type-Options':'nosniff'};let active=0,windowAt=0,requests=0;export async function GET(){if((await getSessionContext())?.role!=="owner")return NextResponse.json({error:"owner_required"},{status:403,headers});@@ -16,16 +18,32 @@ export async function GET(){export async function POST(req:NextRequest){const ctx=await getSessionContext();if(ctx?.role!=='owner')return NextResponse.json({error:'owner_required'},{status:403,headers});if(Date.now()-windowAt>60000){windowAt=Date.now();requests=0}- if(active>=2||++requests>20)return NextResponse.json({error:'transfer_rate_limited'},{status:429,headers});- active++;+ if(active>=2||++requests>30)return NextResponse.json({error:'transfer_rate_limited'},{status:429,headers});+ active++;let action='unknown';try{- const body=await transferBody(req);const options=body as TransferOptions;+ const body=await transferBody(req);action=String(body.action??'');const options=body as TransferOptions;+ if(action==='tree')return NextResponse.json(await exportSelectionTree(),{headers});+ if(action==='authorize-raw-export'){+ const result=authorizeRawCredentialExport(ctx.session.device_id??'unknown',body.password,body.selection);+ void audit({action:'infra.write',actor:ctx.session.device_id,target:'integrations',ok:true,detail:'transfer.raw.reauth'});+ return NextResponse.json(result,{headers});+ }+ if(action==='export-raw'){+ const format=body.format;if(format!=='json'&&format!=='env')throw new IntegrationError('invalid_raw_export_format');+ consumeRawCredentialExportGrant(ctx.session.device_id??'unknown',body.grant,body.selection);+ const file=await exportRawCredentials(body.selection,format as RawCredentialFormat);+ void audit({action:'infra.write',actor:ctx.session.device_id,target:'integrations',ok:true,detail:`transfer.raw.${format}.${file.connectionCount}`});+ return new NextResponse(file.content,{headers:{...headers,'Content-Type':file.contentType,'Content-Disposition':`attachment; filename="${file.filename}"`,'X-MSO-Credential-Export':'plaintext'}});+ }let result;- if(body.action==='export')result={bundle:await exportIntegrationData(options)};- else if(body.action==='import')result=await importIntegrationData(body.document,options);+ if(action==='export')result={bundle:await exportIntegrationData(options)};+ else if(action==='import')result=await importIntegrationData(body.document,options);else throw new IntegrationError('invalid_transfer_action');- void audit({action:'infra.write',actor:ctx.session.device_id,target:'integrations',ok:true,detail:`transfer.${body.action}.${body.apply?'apply':'prepare'}`});+ void audit({action:'infra.write',actor:ctx.session.device_id,target:'integrations',ok:true,detail:`transfer.${action}.${body.apply?'apply':'prepare'}`});return NextResponse.json(result,{headers});- }catch(e){const status=e instanceof IntegrationError?e.status:400;const error=e instanceof IntegrationError||e instanceof BundleError?e.message:'transfer_failed';return NextResponse.json({error},{status,headers});}- finally{active--;}+ }catch(e){+ const status=e instanceof IntegrationError?e.status:400,error=e instanceof IntegrationError||e instanceof BundleError?e.message:'transfer_failed';+ if(action==='authorize-raw-export')void audit({action:'infra.write',actor:ctx.session.device_id,target:'integrations',ok:false,detail:`transfer.raw.reauth.${error}`});+ return NextResponse.json({error},{status,headers});+ }finally{active--;}}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 575f9ccd..b16263a7 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Added**+- `integrations` simplify UI and secure credential exports- `mcp` add original-byte file transfer**Fixed**diff --git a/docs/INTEGRATION-PORTABILITY.md b/docs/INTEGRATION-PORTABILITY.mdindex 976ab396..08bc8526 100644--- a/docs/INTEGRATION-PORTABILITY.md+++ b/docs/INTEGRATION-PORTABILITY.md@@ -7,10 +7,12 @@ explicit, reviewed JSON transfer instead. This is a snapshot, not live sync.## Supported workflowsSI-Coder provides `sc data export`, `sc data import`, and **Import / export JSON**-in its temporary browser manager. MSO provides the same browser workflow at+in its temporary browser manager. MSO exposes **More → Transfer & backup** at`/integrations?transfer=1`, opened from the native manager or-`mso integrations transfer`. Both use their own independent bundled codec and-native store adapter. Neither imports application code from the other product.+`mso integrations transfer`. Portable metadata/encrypted backups use the same+Integration Bundle v1 contract. MSO also offers deliberate raw JSON/.env downloads+for private/manual use; those files are not Integration Bundles and are not the+recommended restore format. Neither product imports application code from the other.**Metadata is the default.** It carries user IDs/labels, named connections,provider/source/auth identity, scope, and field names/presence. It carries **no@@ -21,8 +23,15 @@ users/connections appear but credentials still need to be configured.AES-256-GCM with a random 12-byte IV and 16-byte authentication tag, and a 32-bytekey derived by scrypt (N=32768, r=8, p=1; random 16-byte salt). Passphrases must beat least 12 UTF-8 bytes; the UI requires 12 characters. No passphrase CLI argument,-MCP field, browser storage, or unencrypted full export is provided. Share the-passphrase separately from the file. A forgotten passphrase cannot be recovered.+MCP field, or browser storage is used. Share the passphrase separately from the+file. A forgotten passphrase cannot be recovered.++**Raw JSON / `.env` export is a separate Owner-only escape hatch**, not a portable+bundle. It requires the current MSO owner password, an explicit plaintext warning,+and a 90-second one-time export grant bound to the selected owner/provider/connection+tree. The grant is consumed by one no-store download. Password and credential values+are excluded from audit details. External OAuth/provider sessions are never converted+into local plaintext secrets. Use encrypted export for backup/restore whenever possible.The encrypted bundle protects the transferred file; it does not add encryptionat rest to either application's existing private credential store. Metadata namesdiff --git a/docs/INTEGRATIONS.md b/docs/INTEGRATIONS.mdindex 1e2a48f0..6fe7dd2c 100644--- a/docs/INTEGRATIONS.md+++ b/docs/INTEGRATIONS.md@@ -101,12 +101,16 @@ The managed dispatch boundary prevents accidental use of SC's parallel credentiaOpen `/integrations`. Public instructions are readable before sign-in; an Ownersession is required to read/manage credential profiles or open their private forms.Choose the credential user, provider, named connection, source and authentication.-The browser workbench keeps **Users**, **Routing**, and **Transfer** visible instead of-hiding identity management in a generic settings menu. The credential-owner picker is-a semantic-token listbox rather than a native OS select, so dark/light rendering stays-consistent across desktop and mobile. User creation/rename/duplicate/default/deletion,-folder mappings, connection CRUD/defaults, verification, per-field credential removal,-and full credential clearing use the same metadata actions as the CLI/MCP.+The browser workbench is intentionally progressive: the main surface shows the current+connections, **Add connection**, and **More**. Credential owners, project routing,+**Transfer & backup**, project MCP setup, and refresh live under More so users who only+need one service account do not have to understand the whole credential model. Mobile+uses the same hierarchy with the service picker collapsed to a native control.++When an agent needs external access, it must inspect Integrations before asking for a new+credential. Resolve the exact project/context → credential owner → provider → named+connection first. Only open setup when no suitable connection exists. Credential values+belong in the private setup/export surfaces, never chat or MCP tool arguments.A direct named connection can also be **shared** to another credential user as aread-only alias. The alias resolves the owner's current backing credential at use time,@@ -275,11 +279,24 @@ Official contracts: [MCP Apps](https://github.com/modelcontextprotocol/ext-apps)## Move identities between standalone projects-Use **Import / export JSON** or `/integrations?transfer=1`. Plain JSON carries-metadata only; optional encrypted JSON can carry direct credential values. Imports-are previewed, create-only, unverified, and never change defaults or folder bindings.-See [Integration Bundle v1](INTEGRATION-PORTABILITY.md) for CLI syntax, mappings and-receiver support. There is no mandatory SC dependency or automatic data sharing.+Open **More → Transfer & backup** or `/integrations?transfer=1`.++- **Encrypted JSON** is the default/recommended backup and may carry selected direct+ credential values behind a separate backup passphrase.+- **Metadata JSON** never contains credential values.+- **Raw JSON** and **.env** are deliberate plaintext exports. They are Owner-only and+ require the current MSO owner password. The server issues a 90-second, one-time grant+ bound to the selected connection tree; the grant is consumed by one download and the+ password is not stored in the export state or audit log.+- **All connections / Custom selection…** uses a checkbox tree of credential owner →+ provider → named connection. Raw formats include direct stored values only; external+ OAuth/provider sessions are never converted into local secrets.++Imports remain preview-first, create-only, unverified, and never overwrite existing+connections or silently change defaults/folder bindings. **Share linked access** keeps+one owner/backing secret; **Copy to another owner** creates an independent connection+and copies direct values only when explicitly selected. See [Integration Bundle v1]+(INTEGRATION-PORTABILITY.md) for portable bundle details.## Hostinger Mail APIdiff --git a/docs/MCP.md b/docs/MCP.mdindex 9f74cf52..9a4b0f70 100644--- a/docs/MCP.md+++ b/docs/MCP.md@@ -26,6 +26,8 @@ demo mode also forces MCP off. Existing installs keep their current `.env.local`Settings → MCP separates **Access MSO** (external clients → MSO), **MSO Access** (host connections plus exact-project plugin installation), and **Sessions** (activity and handover). Under MSO Access, **Project plugins** lists SI-Coder and Batonly as available catalog entries. They are not installed into a fresh project, are never inherited from a parent/sibling project, and require an explicit project-scoped install. Registry declarations alone do not install code or configure credentials.+Credential-dependent work follows one rule: **inspect MSO Integrations first**. Resolve the exact project/context → credential owner → provider → named connection before asking for setup. Reuse an existing explicit connection when it matches; refuse ambiguity instead of guessing. Secret values enter only private Integrations setup/export surfaces, never ordinary chat or MCP tool arguments.+Access MSO opens a task index: **Connect an app**, **Connected apps**, **Recent activity**, **Tools & updates**, and **Connection details**. Setup first asks for the client and shows only that client's steps. Use **MCP overview** to return; technical OAuth/tunnel fields live under Connection details. Connected apps separates active access from expired/revoked history and confirms disconnection. Tools & updates stores only a browser-local refresh reminder, never a verified client-health claim.Anonymous visitors see an Owner sign-in entry, not private API requests or an endless loading state. Failed settings/activity loads expose a retry action; activity failures never become an empty-success state. The public `/settings?section=mcp` deep link returns sign-in users to MCP.diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex a5aea63f..df17568f 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,9 @@+## 2026-09-15 — Integrations progressive UI + password-gated credential export++Integrations now defaults to a simple connection-management surface: current account, **Add connection**, and **More**. Credential-owner administration, project routing, transfer/backup and project MCP setup are progressive-disclosure actions rather than peer-level toolbar controls. Connection cards distinguish linked **Share** from independent **Copy to another owner**.++Transfer & backup adds All/Custom selection with an owner → provider → connection checkbox tree. Encrypted JSON remains the recommended secret-bearing backup; metadata JSON is value-free. Deliberate raw JSON/.env downloads require Owner role, the current MSO password, an explicit plaintext acknowledgement, a 90-second one-time grant bound to the selection, no-store response headers and audit metadata that never contains the password or exported values. Bulk imports remain preview-first/create-only. Agent guidance now requires checking Integrations before asking for a new credential.+## 2026-09-15 — Original-byte MCP transfer final hardening- `fs_upload_file` is content-idempotent and fail-closed on filename conflicts by default; deterministic rename and SHA-guarded replacement are explicit.diff --git a/docs/generated/MCP-CATALOG.md b/docs/generated/MCP-CATALOG.mdindex 6b06e130..66c86444 100644--- a/docs/generated/MCP-CATALOG.md+++ b/docs/generated/MCP-CATALOG.md@@ -4,13 +4,13 @@## Full MSO catalog-<!-- mcp-toolset: server=1.14.2 version=2026.09.15.1 tools=105 read=50 write=34 exec=21 -->+<!-- mcp-toolset: server=1.14.3 version=2026.09.15.2 tools=105 read=50 write=34 exec=21 -->| Fact | Current source value ||---|---:|-| MCP server | `1.14.2` |-| Toolset | `2026.09.15.1` |-| Toolset changed at | `2026-09-15T00:30:00+07:00` |+| MCP server | `1.14.3` |+| Toolset | `2026.09.15.2` |+| Toolset changed at | `2026-09-15T02:00:00+07:00` || Transport tools | **107** || Model/operator tools | **105** || Read | **50** |@@ -139,7 +139,7 @@## ChatGPT model profile-<!-- mcp-chatgpt-profile: server=1.14.2 version=2026.09.15.1 tools=105 read=50 write=34 exec=21 app-only=2 total=107 -->+<!-- mcp-chatgpt-profile: server=1.14.3 version=2026.09.15.2 tools=105 read=50 write=34 exec=21 app-only=2 total=107 -->The ChatGPT profile automatically projects the complete MSO-owned generic model/operator catalog. OAuth scope is still enforced independently; app-only compatibility bridges stay app-only, and project-owned MCP tool names remain dynamic data behind the generic project bridge.diff --git a/lib/infra/connection-manage.ts b/lib/infra/connection-manage.tsindex e3b517e9..b9cff3d3 100644--- a/lib/infra/connection-manage.ts+++ b/lib/infra/connection-manage.ts@@ -3,13 +3,13 @@ import { randomUUID } from "node:crypto";import { mutateIntegrationState } from "./connection-storage";import { createConnectionIn, summaryIn } from "./connection-service";import { IntegrationError, identity, connectionLabel, canonicalFolder, selectConnection, metadataOnly, assertNotBusy, type ConnectionSource } from "./identity";-export const INTEGRATION_ACTIONS=["user.create","user.rename","user.duplicate","user.delete","user.default","folder.map","folder.unmap","connection.create","connection.rename","connection.default","connection.delete","connection.share","connection.unshare","credential.delete"] as const;+export const INTEGRATION_ACTIONS=["user.create","user.rename","user.duplicate","user.delete","user.default","folder.map","folder.unmap","connection.create","connection.rename","connection.default","connection.delete","connection.share","connection.duplicate","connection.unshare","credential.delete"] as const;export async function integrationManage(input:Record<string,unknown>){metadataOnly(input);if(input.confirm!==true)throw new IntegrationError("confirmation_required",403);const shapes:Record<string,string[]>={"user.create":["user","label"],"user.rename":["user","target","label"],"user.duplicate":["user","target","label","copyCredentials"],"user.delete":["user"],"user.default":["user"],"folder.map":["user","path","provider","connection"],"folder.unmap":["path"],"connection.create":["user","provider","connection","label","source","authMethod","makeDefault"],- "connection.rename":["user","provider","connection","label"],"connection.default":["user","provider","connection"],"connection.delete":["user","provider","connection"],"connection.share":["user","provider","connection","target","label","makeDefault"],"connection.unshare":["user","provider","connection"],"credential.delete":["user","provider","connection","key"],+ "connection.rename":["user","provider","connection","label"],"connection.default":["user","provider","connection"],"connection.delete":["user","provider","connection"],"connection.share":["user","provider","connection","target","label","makeDefault"],"connection.duplicate":["user","provider","connection","target","targetConnection","label","copyCredentials","makeDefault"],"connection.unshare":["user","provider","connection"],"credential.delete":["user","provider","connection","key"],};const action=String(input.action);if(!shapes[action]||Object.keys(input).some(k=>!["action","confirm",...shapes[action]].includes(k)))throw new IntegrationError("invalid_management_fields");return mutateIntegrationState(state=>{@@ -45,6 +45,13 @@ export async function integrationManage(input:Record<string,unknown>){const provider=identity(input.provider,"provider"),connection=identity(input.connection,"connection");if(action==="connection.create"){const c=createConnectionIn(state,{user,provider,connection,label:input.label as string|undefined,source:input.source as ConnectionSource|undefined,authMethod:input.authMethod as string|undefined,makeDefault:input.makeDefault===true});return{ok:true,action,connection:summaryIn(state,user,c)};}const {connection:c}=selectConnection(state,provider,{user,connection});assertNotBusy(c);+ if(action==="connection.duplicate"){+ if(c.sharedFrom)throw new IntegrationError("shared_alias_copy_from_owner",409);+ const target=identity(input.target,"target"),targetUser=state.users[target];if(!targetUser)throw new IntegrationError("user_not_found",404);+ const targetConnection=identity(input.targetConnection??connection,"target_connection"),rows=targetUser.connections[provider]??{};if(Object.hasOwn(rows,targetConnection))throw new IntegrationError("connection_exists",409);+ const clone=structuredClone(c);clone.id=targetConnection;clone.uid=randomUUID();clone.label=connectionLabel(input.label??c.label);clone.values=c.source==="direct"&&input.copyCredentials===true?{...c.values}:{};delete clone.sharedFrom;delete clone.external;delete clone.verifiedAt;delete clone.lastCheck;delete clone.lease;clone.revision=1;clone.createdAt=clone.updatedAt=Date.now();+ targetUser.connections[provider]={...rows,[targetConnection]:clone};if(input.makeDefault===true||!targetUser.defaults[provider])targetUser.defaults[provider]=targetConnection;return{ok:true,action,connection:summaryIn(state,target,clone)};+ }if(action==="connection.share"){if(c.source!=="direct")throw new IntegrationError("external_connections_cannot_share",409);if(c.sharedFrom)throw new IntegrationError("shared_alias_cannot_share",409);const target=identity(input.target,"target"), targetUser=state.users[target];if(!targetUser)throw new IntegrationError("user_not_found",404);if(target===user)throw new IntegrationError("shared_alias_same_user",409);diff --git a/lib/infra/connection-model.test.ts b/lib/infra/connection-model.test.tsindex 9c101b3b..6033eca7 100644--- a/lib/infra/connection-model.test.ts+++ b/lib/infra/connection-model.test.ts@@ -90,6 +90,12 @@ describe("native credential identity core",()=>{await f.manage({action:"user.duplicate",confirm:true,user:"alice",target:"key-copy",copyCredentials:true});expect((await f.directConnectionValues("github",{user:"key-copy",connection:"work"})).apiKey).toBe(KEY_A);await f.manage({action:"folder.map",confirm:true,user:"alice",path:root});await f.manage({action:"user.rename",confirm:true,user:"alice",target:"renamed"});expect((await f.integrationQuery({view:"which",cwd:root}) as {user:string}).user).toBe("renamed");});+ it("copies one connection independently to another owner without overwriting an existing id",async()=>{+ const f=await fixture();await f.add("alice","github","work","direct",{apiKey:KEY_A});await f.manage({action:"connection.duplicate",confirm:true,user:"alice",provider:"github",connection:"work",target:"bob",targetConnection:"copied",label:"Copied GitHub",copyCredentials:true});+ expect((await f.directConnectionValues("github",{user:"bob",connection:"copied"})).apiKey).toBe(KEY_A);const owner=await f.credentialSnapshot("github",{user:"alice",connection:"work"});await f.saveConnectionValues("github",{user:"alice",connection:"work"},{apiKey:KEY_B},owner.connection);expect((await f.directConnectionValues("github",{user:"bob",connection:"copied"})).apiKey).toBe(KEY_A);+ await expect(f.manage({action:"connection.duplicate",confirm:true,user:"alice",provider:"github",connection:"work",target:"bob",targetConnection:"copied",label:"No overwrite",copyCredentials:true})).rejects.toMatchObject({code:"connection_exists"});+ await f.manage({action:"connection.duplicate",confirm:true,user:"alice",provider:"github",connection:"work",target:"bob",targetConnection:"metadata-only",label:"Metadata only"});expect(await f.directConnectionValues("github",{user:"bob",connection:"metadata-only"})).toEqual({});+ });it("shares direct credentials as read-only aliases with live backing, safe ids, rename/default, duplication, and unshare invariants",async()=>{const f=await fixture();await f.add("alice","github","work","direct",{apiKey:KEY_A});const shared=await f.manage({action:"connection.share",confirm:true,user:"alice",provider:"github",connection:"work",target:"bob",label:"Shared Work GitHub"}) as {connection:{id:string}};diff --git a/lib/infra/connection-ui-style.ts b/lib/infra/connection-ui-style.tsindex d9b2ad35..14126b36 100644--- a/lib/infra/connection-ui-style.ts+++ b/lib/infra/connection-ui-style.ts@@ -47,7 +47,7 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .identity-guide li{font-size:var(--type-small)}.integration .identity-muted{font-size:var(--type-caption);color:var(--text-dim)}.integration .identity-form{border:var(--stroke) solid var(--sep-strong);border-radius:var(--radius-panel);padding:var(--space-4)}.integration .identity-readonly{padding:var(--space-3) var(--space-4);border-left:3px solid var(--os-accent);background:var(--field);font-size:var(--type-small)}-.integration .identity-summary{display:flex;align-items:center;gap:var(--space-4);padding:0 0 var(--space-4);margin-bottom:var(--space-6);border:0;border-bottom:var(--stroke) solid var(--sep);border-radius:0;background:transparent}+.integration .identity-summary-line{margin:0 0 var(--space-4);padding:0 0 var(--space-3);border-bottom:var(--stroke) solid var(--sep);font-size:var(--type-small);color:var(--text-dim)}.integration .identity-summary{display:flex;align-items:center;gap:var(--space-4);padding:0 0 var(--space-4);margin-bottom:var(--space-6);border:0;border-bottom:var(--stroke) solid var(--sep);border-radius:0;background:transparent}.integration .identity-ring{width:64px;height:64px;flex:none;border-radius:50%;display:grid;place-items:center;background:conic-gradient(var(--os-accent) var(--ready-angle),var(--sep) 0)}.integration .identity-ring strong{display:grid;place-items:center;width:50px;height:50px;border-radius:50%;background:var(--surface);font:700 var(--type-section) var(--font-body)}.integration .identity-summary dl{display:flex;gap:var(--space-6);flex-wrap:wrap;margin:0}.integration .identity-summary dt{font-size:var(--type-caption);color:var(--text-dim)}.integration .identity-summary dd{font-weight:700;font-size:var(--type-section);margin:2px 0 0}@@ -60,17 +60,17 @@ export const CONNECTION_MANAGER_STYLE = String.raw`.integration .owner-picker-popup{position:absolute;z-index:3;top:calc(100% + 6px);left:0;right:0;max-height:240px;overflow:auto;padding:var(--space-2);background:var(--surface);border:var(--stroke) solid var(--sep-strong);border-radius:var(--radius);box-shadow:var(--shadow-pop)}.integration .owner-picker-option{display:flex;width:100%;text-align:left;background:transparent;border-color:transparent}.integration .owner-picker-option:hover,.integration .owner-picker-option:focus-visible,.integration .owner-picker-option[aria-selected=true]{background:var(--hover);border-color:var(--sep-strong)}.integration .owner-picker-option[aria-selected=true]{font-weight:700}.integration .service-picker{display:none}-.integration .identity-context{flex:1;min-width:0;margin:0;padding:0;background:transparent;border:0}+.integration .identity-current-owner{margin-right:auto;align-self:center;font-size:var(--type-small);font-weight:650;color:var(--text-dim);max-width:260px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.integration .identity-context{flex:0 0 auto;min-width:0;margin:0;padding:0;background:transparent;border:0}.integration .identity-context>summary{display:flex;align-items:center;min-height:var(--control-size);padding:var(--space-2) var(--space-3);border:var(--stroke) solid var(--sep-strong);border-radius:var(--radius-control);font-size:var(--type-small);font-weight:var(--weight-medium);overflow-wrap:anywhere}.integration .identity-context>summary::before{content:"+";margin-right:var(--space-2)}.integration .identity-context[open]>summary::before{content:"−"}.integration .identity-context-controls{display:flex;align-items:end;gap:var(--space-2);flex-wrap:wrap;padding-top:var(--space-3)}.integration .identity-context .owner-picker{min-width:0;flex-basis:100%;max-width:none}-.integration .identity-bar{align-items:start}+.integration .identity-bar{align-items:center}.integration .identity-context .identity-workbench{width:auto}.integration .identity-summary{padding-block:var(--space-3);margin-bottom:var(--space-4)}.integration .identity-ring{display:none}.integration .identity-providers{overflow:visible}-@container integration (max-width:35rem){.integration .service-picker{display:block;margin-bottom:var(--space-4)}.integration .connection-card{padding-inline:0}.integration .identity-summary dl{gap:var(--space-4)}.integration .identity-tools[open] .identity-actions{position:static;box-shadow:none;min-width:0}.integration .identity-credential-status>div{grid-template-columns:minmax(0,1fr) auto}.integration .identity-credential-status>div>button{grid-column:1/-1;justify-self:start}}+@container integration (max-width:35rem){.integration .identity-current-owner{width:100%;max-width:none;margin-right:0}.integration .identity-bar>.primary{flex:1}.integration .service-picker{display:block;margin-bottom:var(--space-4)}.integration .connection-card{padding-inline:0}.integration .identity-summary dl{gap:var(--space-4)}.integration .identity-tools[open] .identity-actions{position:static;box-shadow:none;min-width:0}.integration .identity-credential-status>div{grid-template-columns:minmax(0,1fr) auto}.integration .identity-credential-status>div>button{grid-column:1/-1;justify-self:start}}@container mso (max-height:20rem){.integration .service-picker{margin-bottom:var(--space-2);font-size:0}.integration .service-picker select{font-size:var(--type-small);margin:0}.integration .identity-heading,.integration .identity-summary{display:none}.integration .identity-bar{margin-block:var(--space-2)}.integration .identity-picker-label{display:none}}`;\ No newline at end of filediff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.tsindex 98e54b01..bfcecf1f 100644--- a/lib/infra/connection-ui.ts+++ b/lib/infra/connection-ui.ts@@ -30,14 +30,12 @@ function mountConnectionManager(root,catalog,bridge,initial={}){function guide(method,parent=detail){const d=n("details",undefined,"identity-guide");d.open=parent!==detail;d.append(n("summary","How to get this credential / authorization"));const g=method.guidance,ol=n("ol");for(const step of g.steps)ol.append(n("li",step));d.append(ol);for(const[url,label]of [[g.url,"Official setup page"],[g.reference,"Documentation"]]){const a=n("a",label);a.href=url;a.rel="noopener noreferrer";a.target="_blank";if(bridge.openLink)a.addEventListener("click",e=>{e.preventDefault();Promise.resolve(bridge.openLink(url)).catch(error=>status.textContent=textError(error))});d.append(a)}parent.append(d)}function draw(){root.replaceChildren();root.classList.add("integration","manager");- const heading=n("header",undefined,"identity-heading"),title=n("div");title.append(n(bridge.headingLevel===1?"h1":"h2","Integrations"),n("p","Connect your services. Choose the account each project uses."));heading.append(title,n("span",catalog.length+" services","identity-count"));root.append(heading);- const toolbar=n("div",undefined,"identity-bar"),owner=choicePicker("Credential owner",snapshot.users.map(row=>({id:row.id,text:row.label+" · "+row.id+(row.isDefault?" · default":"")})),user,row=>{user=row.id;remember();void reload()});toolbar.append(owner.wrap,b("Refresh",reload));const workbench=n("div",undefined,"identity-actions identity-workbench");const usersAction=b("Users",profiles),routingAction=b("Routing",bindings);usersAction.disabled=routingAction.disabled=!bridge.manage;workbench.append(usersAction,routingAction);const transfer=b("Transfer",()=>bridge.openTransfer?bridge.openTransfer():bridge.openTransferBrowser?.());transfer.disabled=!bridge.openTransfer&&!bridge.openTransferBrowser;workbench.append(transfer);const addMcp=b("Add MCP",()=>mountProjectMcpForm(detail,bridge,snapshot,user,status,drawProvider,{n,b,input}),"primary");addMcp.disabled=!bridge.projectMcp;workbench.append(addMcp);const context=n("details",undefined,"identity-context"),contextSummary=n("summary",(snapshot.users.find(row=>row.id===user)?.label||"Account")+" · Account & tools"),contextControls=n("div",undefined,"identity-context-controls");context.open=contextOpen;context.addEventListener("toggle",()=>{contextOpen=context.open});contextSummary.setAttribute("aria-label","Account and tools");contextControls.append(owner.wrap,...Array.from(toolbar.children),workbench);context.append(contextSummary,contextControls);toolbar.replaceChildren(context,addMcp);root.append(toolbar);+ const heading=n("header",undefined,"identity-heading"),title=n("div");title.append(n(bridge.headingLevel===1?"h1":"h2","Integrations"),n("p","Service connections for this VPS. Advanced routing and transfer tools stay under More."));heading.append(title,n("span",catalog.length+" services","identity-count"));root.append(heading);+ const toolbar=n("div",undefined,"identity-bar"),owner=choicePicker("Credential owner",snapshot.users.map(row=>({id:row.id,text:row.label+" · "+row.id+(row.isDefault?" · default":"")})),user,row=>{user=row.id;remember();void reload()}),currentOwner=n("span",snapshot.users.find(row=>row.id===user)?.label||"No credential owner","identity-current-owner");+ const addConnection=b("Add connection",()=>user?newConnection():profiles(),"primary");addConnection.disabled=!bridge.manage;const context=n("details",undefined,"identity-tools identity-context"),contextSummary=n("summary","More"),contextControls=n("div",undefined,"identity-actions");context.open=contextOpen;context.addEventListener("toggle",()=>{contextOpen=context.open});contextSummary.setAttribute("aria-label","More integration actions");+ const usersAction=b("Credential owners",profiles),routingAction=b("Project routing",bindings),transfer=b("Transfer & backup",()=>bridge.openTransfer?bridge.openTransfer():bridge.openTransferBrowser?.()),addMcp=b("Add project MCP",()=>mountProjectMcpForm(detail,bridge,snapshot,user,status,drawProvider,{n,b,input})),refresh=b("Refresh",reload);usersAction.disabled=routingAction.disabled=!bridge.manage;transfer.disabled=!bridge.openTransfer&&!bridge.openTransferBrowser;addMcp.disabled=!bridge.projectMcp;contextControls.append(owner.wrap,usersAction,routingAction,transfer,addMcp,refresh);context.append(contextSummary,contextControls);toolbar.append(currentOwner,addConnection,context);root.append(toolbar);if(!bridge.manage)root.append(n("p","Sign in as an MSO Owner to manage credentials. Device roles and credential users are different; the public guides remain available.","identity-readonly"));- if(snapshot.connections.length){- const summary=n("section",undefined,"identity-summary"),count=snapshot.connections.filter(ready).length,ring=n("div",undefined,"identity-ring");- ring.style.setProperty("--ready-angle",(count/snapshot.connections.length*360)+"deg");ring.setAttribute("role","img");ring.setAttribute("aria-label",count+" of "+snapshot.connections.length+" connections verified");ring.append(n("strong",count));- const stats=n("dl");for(const[label,value]of [["Verified",count],["Needs attention",snapshot.connections.length-count],["Project folders",snapshot.bindings.filter(row=>row.user===user).length]]){const item=n("div");item.append(n("dt",label),n("dd",value));stats.append(item)}summary.append(ring,stats);root.append(summary)- }+ if(snapshot.connections.length){const count=snapshot.connections.filter(ready).length;root.append(n("p",snapshot.connections.length+" connection"+(snapshot.connections.length===1?"":"s")+" · "+count+" verified","identity-summary-line"))}container=n("div",undefined,"identity-layout");const sidebar=n("nav",undefined,"identity-providers"),search=n("input");search.type="search";search.placeholder="Search services";search.setAttribute("aria-label","Search services");sidebar.setAttribute("aria-label","Services");sidebar.append(search);const buttons=[];for(const p of catalog){const item=b(undefined,()=>{provider=p;serviceSelect.value=p.id;remember();drawProvider();for(const[row,button]of buttons)button.setAttribute("aria-pressed",String(row.id===provider.id))});item.append(mark(p),n("span",p.title));const count=snapshot.connections.filter(c=>c.provider===p.id).length;if(count)item.append(n("span",count,"provider-count"));item.setAttribute("aria-pressed",String(p.id===provider.id));buttons.push([p,item]);sidebar.append(item)}search.addEventListener("input",()=>{for(const[p,item]of buttons)item.hidden=!(p.title+" "+p.id).toLowerCase().includes(search.value.toLowerCase())});const serviceLabel=n("label","Service","service-picker"),serviceSelect=n("select");serviceSelect.setAttribute("aria-label","Service");@@ -63,7 +61,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){}function drawProvider(){detail.replaceChildren();const heading=n("header",undefined,"provider-heading"),title=n("div",undefined,"provider-title"),copy=n("div");copy.append(n("h2",provider.title),n("p",provider.description));title.append(mark(provider),copy);heading.append(title);detail.append(heading);- const create=b("New connection",newConnection,"primary");create.disabled=!user||!bridge.manage;if(bridge.manage&&snapshot.connections.some(c=>c.provider===provider.id))heading.append(create);+const rows=snapshot.connections.filter(c=>c.provider===provider.id);if(!rows.length){const empty=n("div",undefined,"identity-empty");empty.append(n("h3","Connect "+provider.title),n("p",user?"Add an account to start using "+provider.title+" in your projects.":bridge.manage?"Select a credential owner to add an account.":"Read the setup guide below, then sign in to connect your account."));const start=b("Add "+provider.title+" account",newConnection,"primary");start.disabled=!user||!bridge.manage;if(bridge.manage)empty.append(start);detail.append(empty);const help=n("details");help.append(n("summary","Connection methods & setup guides"));for(const s of provider.sources)for(const m of s.methods){const info=n("section");info.append(n("h3",s.label+" · "+m.label));guide(m,info);help.append(info)}detail.append(help)}for(const c of rows){const card=n("article",undefined,"connection-card");const top=n("header",undefined,"connection-heading"),name=n("div");name.append(n("h3",c.label),n("small",c.id));const state=n("span",stateLabel(c),"connection-state");state.dataset.ready=String(ready(c));top.append(name,state);card.append(top);const tags=n("div",undefined,"identity-tags");for(const value of [human(c.source),human(c.authMethod),c.sharedFrom?"Shared from "+c.sharedFrom.user:"",c.isDefault?"Default account":""])if(value)tags.append(n("span",value));card.append(tags);const actions=n("div",undefined,"identity-actions"),more=n("details",undefined,"identity-tools"),secondary=n("div",undefined,"identity-actions");more.append(n("summary","More"));more.append(secondary);@@ -72,7 +70,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){const rename=b("Rename",()=>{detail.replaceChildren(n("h2","Rename connection"));const name=input("Label",c.label);detail.append(name.label,b("Save label",()=>change({action:"connection.rename",user,provider:provider.id,connection:c.id,label:name.input.value})),b("Cancel",drawProvider))});rename.disabled=!bridge.manage;secondary.append(rename);if(c.sharedFrom){card.append(n("p","Read-only shared backing: "+c.sharedFrom.user+" / "+c.sharedFrom.connection,"identity-muted"));}else if(c.source==="direct"){const fields=n("div",undefined,"identity-credential-status");for(const f of c.fields){const line=n("div");line.append(n("span",f.label));const fieldState=n("span",f.stored?"Stored":"Missing","credential-field-state");fieldState.dataset.stored=String(f.stored);line.append(fieldState);if(f.stored){const remove=b("Remove",()=>confirmation("Remove credential field",f.key,()=>change({action:"credential.delete",user,provider:provider.id,connection:c.id,key:f.key})),"danger");remove.disabled=!bridge.manage;line.append(remove)}fields.append(line)}card.append(fields);if(c.fields.some(f=>f.stored)){const clear=b("Clear credentials",()=>confirmation("Clear this connection's credential fields",c.id,()=>change({action:"credential.delete",user,provider:provider.id,connection:c.id})),"danger");clear.disabled=!bridge.manage;secondary.append(clear)}}if(!c.isDefault){const def=b("Make default",()=>change({action:"connection.default",user,provider:provider.id,connection:c.id}));def.disabled=!bridge.manage;secondary.append(def)}- if(c.sharedFrom){const unshare=b("Unshare",()=>confirmation("Remove shared alias",c.id,()=>change({action:"connection.unshare",user,provider:provider.id,connection:c.id})),"danger");unshare.disabled=!bridge.manage;secondary.append(unshare)}else if(c.source==="direct"){const share=b("Share",()=>shareConnection(c));share.disabled=!bridge.manage;secondary.append(share)}+ if(c.sharedFrom){const unshare=b("Unshare",()=>confirmation("Remove shared alias",c.id,()=>change({action:"connection.unshare",user,provider:provider.id,connection:c.id})),"danger");unshare.disabled=!bridge.manage;secondary.append(unshare)}else{if(c.source==="direct"){const share=b("Share linked access",()=>shareConnection(c));share.disabled=!bridge.manage;secondary.append(share)}const duplicate=b("Copy to another owner",()=>copyConnection(c));duplicate.disabled=!bridge.manage;secondary.append(duplicate)}if(!c.sharedFrom){const del=b("Delete",()=>confirmation("Delete named connection",c.id,()=>change({action:"connection.delete",user,provider:provider.id,connection:c.id})),"danger");del.disabled=!bridge.manage;secondary.append(del);}actions.append(more);card.append(actions);if(c.lastCheck)card.append(n("small","Last checked "+new Date(c.lastCheck.checkedAt).toLocaleString()+" · "+stateLabel(c)));else if(c.verifiedAt)card.append(n("small","Last verified "+new Date(c.verifiedAt).toLocaleString()));detail.append(card);}}@@ -84,7 +82,8 @@ function mountConnectionManager(root,catalog,bridge,initial={}){function previewGuide(){preview.replaceChildren();const method=provider.sources.find(s=>s.id===source.value).methods.find(m=>m.id===auth.value);if(method.fields.length)preview.append(n("p","Fields: "+method.fields.map(f=>f.label+(f.required?" *":"")).join(", ")));else preview.append(n("p","No provider tokens are stored locally for this source."));guide(method,preview)}source.addEventListener("change",changeAuth);auth.addEventListener("change",previewGuide);changeAuth();const fields=n("div",undefined,"identity-fields");fields.append(label.label,sourceLabel,authLabel);const advanced=n("details");advanced.append(n("summary","Connection identifier"),id.label);detail.append(fields,advanced,preview,b("Create & connect",()=>change({action:"connection.create",user,provider:provider.id,connection:id.input.value,label:label.input.value,source:source.value,authMethod:auth.value},async()=>{await reload();if(source.value==="direct")await bridge.openSetup({user,provider:provider.id,connection:id.input.value});else{const created=snapshot.connections.find(c=>c.provider===provider.id&&c.id===id.input.value);if(created)external(created)}}),"primary"),b("Cancel",drawProvider));label.input.focus();}- function shareConnection(c){detail.replaceChildren(n("h2","Share "+c.label),n("p","Creates a read-only direct alias. The owner keeps control of credential rotation."));const targets=snapshot.users.filter(row=>row.id!==user).map(row=>({id:row.id,text:row.label+" · "+row.id})),target=choicePicker("Target credential owner",targets,targets[0]?.id||"",()=>sync()),label=input("New alias label",c.label),make=input("", "","checkbox");make.label.className="identity-check";make.label.append(document.createTextNode("Make this owner’s default for this service"));const submit=b("Create shared alias",()=>change({action:"connection.share",user,provider:provider.id,connection:c.id,target:target.value,label:label.input.value,makeDefault:make.input.checked}),"primary"),sync=()=>{submit.disabled=!bridge.manage||!target.value||target.value===user||!label.input.value.trim()};label.input.addEventListener("input",sync);sync();detail.append(target.wrap,label.label,make.label,submit,b("Cancel",drawProvider));}+ function copyConnection(c){detail.replaceChildren(n("h2","Copy "+c.label),n("p","Creates an independent connection for another credential owner. Existing connections are never overwritten."));const targets=snapshot.users.filter(row=>row.id!==user).map(row=>({id:row.id,text:row.label+" · "+row.id})),target=choicePicker("Target credential owner",targets,targets[0]?.id||"",()=>sync()),id=input("New connection ID",c.id),label=input("New connection label",c.label),copy=input("","","checkbox"),make=input("","","checkbox");copy.label.className=make.label.className="identity-check";copy.label.append(document.createTextNode("Copy saved direct credentials"));copy.input.checked=c.source==="direct";copy.label.hidden=c.source!=="direct";make.label.append(document.createTextNode("Make the copied connection default for this service"));const submit=b("Copy connection",()=>change({action:"connection.duplicate",user,provider:provider.id,connection:c.id,target:target.value,targetConnection:id.input.value,label:label.input.value,copyCredentials:copy.input.checked,makeDefault:make.input.checked}),"primary"),sync=()=>{submit.disabled=!bridge.manage||!target.value||target.value===user||!id.input.value.trim()||!label.input.value.trim()};for(const control of[id.input,label.input])control.addEventListener("input",sync);sync();detail.append(target.wrap,id.label,label.label,copy.label,make.label,submit,b("Cancel",drawProvider));}+ function shareConnection(c){detail.replaceChildren(n("h2","Share "+c.label),n("p","Creates a read-only linked alias. Credential rotation stays with the current owner."));const targets=snapshot.users.filter(row=>row.id!==user).map(row=>({id:row.id,text:row.label+" · "+row.id})),target=choicePicker("Target credential owner",targets,targets[0]?.id||"",()=>sync()),label=input("New alias label",c.label),make=input("", "","checkbox");make.label.className="identity-check";make.label.append(document.createTextNode("Make this owner’s default for this service"));const submit=b("Create shared alias",()=>change({action:"connection.share",user,provider:provider.id,connection:c.id,target:target.value,label:label.input.value,makeDefault:make.input.checked}),"primary"),sync=()=>{submit.disabled=!bridge.manage||!target.value||target.value===user||!label.input.value.trim()};label.input.addEventListener("input",sync);sync();detail.append(target.wrap,label.label,make.label,submit,b("Cancel",drawProvider));}function external(c){detail.replaceChildren(n("h2",c.label),n("p",user+" / "+provider.id+" / "+c.source+" / "+c.authMethod));const method=provider.sources.find(s=>s.id===c.source).methods.find(m=>m.id===c.authMethod);guide(method);if(c.source==="native-mcp"){detail.append(n("p","Authorize in the provider's own MCP client. MSO will return this route, never substitute a stored API key."),b("Back",drawProvider));return}diff --git a/lib/infra/portable/data.test.ts b/lib/infra/portable/data.test.tsindex cf62cb61..7ce2e80f 100644--- a/lib/infra/portable/data.test.ts+++ b/lib/infra/portable/data.test.ts@@ -54,3 +54,9 @@ it('rejects truncated GCM authentication tags before importing any credentials',await expect(codec.open(envelope,PASS)).rejects.toThrow('invalid_envelope');await expect(fs.stat(process.env.OS_INFRA_STORE!)).rejects.toMatchObject({code:'ENOENT'});});++it('exports only the exact custom selection while preserving the all-scope default',async()=>{+ const api=await import('./data'),apply=async(prefix='')=>{const p=await api.importIntegrationData(sample,{prefix});await api.importIntegrationData(sample,{prefix,apply:true,confirm:p.planId})};+ await apply();await apply('copy-');const all=await api.exportIntegrationData() as {users:Array<{id:string;connections:unknown[]}>};expect(all.users.map(u=>u.id).sort()).toEqual(['copy-sample-user','sample-user']);+ const one=await api.exportIntegrationData({selection:[{user:'sample-user',provider:'github',connection:'work'}]}) as {users:Array<{id:string;connections:unknown[]}>};expect(one.users.map(u=>u.id)).toEqual(['sample-user']);expect(one.users[0].connections).toHaveLength(1);+});diff --git a/lib/infra/portable/data.ts b/lib/infra/portable/data.tsindex c4dae27e..5e00609c 100644--- a/lib/infra/portable/data.ts+++ b/lib/infra/portable/data.ts@@ -5,7 +5,8 @@ import {readIntegrationState,mutateIntegrationState} from '../connection-storageimport {connectionMethod} from '../connection-registry';import {IntegrationError,identity,type IntegrationState} from '../identity';import {isInfraProviderId,normalizeInfraValues} from '../catalog';-export type TransferOptions={users?:string[];includeSecrets?:boolean;passphrase?:string;prefix?:string;policy?:'skip'|'error';apply?:boolean;confirm?:string;acceptWarnings?:boolean};+import {assertTransferSelectionExists,normalizeTransferSelection,transferSelectionMatches,type TransferSelection} from './selection';+export type TransferOptions={users?:string[];selection?:TransferSelection[];includeSecrets?:boolean;passphrase?:string;prefix?:string;policy?:'skip'|'error';apply?:boolean;confirm?:string;acceptWarnings?:boolean};// Import previews use opaque, process-local one-time tokens. The snapshot contains// the original document (encrypted when credentials are present), options and// destination metadata — never a password/credential digest exposed to the caller.@@ -15,9 +16,9 @@ function snapshot(document:unknown,options:TransferOptions,state:IntegrationStatfunction issuePlan(value:string){const now=Date.now();for(const [id,p]of plans)if(p.expires<=now)plans.delete(id);while(plans.size>=MAX_PLANS)plans.delete(plans.keys().next().value!);const id=randomBytes(32).toString('hex');plans.set(id,{snapshot:value,expires:now+PLAN_TTL_MS});return id;}function requirePlan(id:string|undefined,value:string){if(!id)throw new IntegrationError('preview_required_or_destination_changed',409);const p=plans.get(id);if(!p||p.expires<=Date.now()||p.snapshot!==value){plans.delete(id);throw new IntegrationError('preview_required_or_destination_changed',409)}return id;}export async function exportIntegrationData(options:TransferOptions={}){- const state=await readIntegrationState(),ids=options.users??Object.keys(state.users);- if(!Array.isArray(ids)||ids.some(id=>!Object.hasOwn(state.users,identity(id))))throw new IntegrationError('unknown_export_user');- const users=[...new Set(ids)].map(id=>({id,label:state.users[id].label,connections:Object.values(state.users[id].connections).flatMap(rows=>Object.values(rows)).map(c=>{+ const state=await readIntegrationState(),selection=normalizeTransferSelection(options.selection),ids=options.users??(selection?[...new Set(selection.map(row=>row.user))]:Object.keys(state.users));+ if(!Array.isArray(ids)||ids.some(id=>!Object.hasOwn(state.users,identity(id))))throw new IntegrationError('unknown_export_user');assertTransferSelectionExists(state,selection);+ const users=[...new Set(ids)].map(id=>({id,label:state.users[id].label,connections:Object.values(state.users[id].connections).flatMap(rows=>Object.values(rows)).filter(c=>transferSelectionMatches(selection,id,c.provider,c.id)).map(c=>{const m=connectionMethod(c.provider,c.source,c.authMethod),map=FIELD_MAP[c.provider]??{},reverse=Object.fromEntries(Object.entries(map).map(([a,b])=>[b,a]));const fields=m.fields.map(f=>({key:reverse[f.key],secret:f.secret,configured:Boolean(c.values[f.key])}));if(fields.some(f=>!f.key))throw new IntegrationError('unmapped_export_field');diff --git a/lib/infra/portable/export-grant.ts b/lib/infra/portable/export-grant.tsnew file mode 100644index 00000000..eaa78800--- /dev/null+++ b/lib/infra/portable/export-grant.ts@@ -0,0 +1,21 @@+import { createHash, randomBytes } from "node:crypto";+import { constantTimeEq, MAX_COMPARE_BYTES } from "@/lib/auth/session";+import { rateLimited } from "@/lib/host/rate-limit";+import { IntegrationError } from "../identity";+import { normalizeTransferSelection } from "./selection";++const TTL_MS=90_000,MAX_GRANTS=128;+const grants=new Map<string,{actor:string;selectionHash:string;expires:number}>();+function selectionHash(value:unknown){return createHash("sha256").update(JSON.stringify(normalizeTransferSelection(value)??null)).digest("hex");}+function prune(){const now=Date.now();for(const[token,row]of grants)if(row.expires<=now)grants.delete(token);while(grants.size>=MAX_GRANTS)grants.delete(grants.keys().next().value!);}+export function authorizeRawCredentialExport(actor:string,password:unknown,selection:unknown){+ const configured=process.env.OS_LOGIN_PASSWORD??"",candidate=typeof password==="string"&&password&&Buffer.byteLength(password,"utf8")<=MAX_COMPARE_BYTES?password:null;+ const valid=Boolean(candidate)&&configured.length>=6&&Buffer.byteLength(configured,"utf8")<=MAX_COMPARE_BYTES&&constantTimeEq(configured,candidate!);+ if(!valid){if(rateLimited(`integration.raw-export.reauth:${actor}`,5,60_000))throw new IntegrationError("reauth_rate_limited",429);throw new IntegrationError("bad_password",401);}+ prune();const grant=randomBytes(32).toString("base64url");grants.set(grant,{actor,selectionHash:selectionHash(selection),expires:Date.now()+TTL_MS});return{grant,expiresInSeconds:TTL_MS/1000};+}+export function consumeRawCredentialExportGrant(actor:string,grant:unknown,selection:unknown){+ if(typeof grant!=="string"||!/^[A-Za-z0-9_-]{43}$/.test(grant))throw new IntegrationError("raw_export_reauth_required",401);+ const row=grants.get(grant);grants.delete(grant);+ if(!row||row.expires<=Date.now()||row.actor!==actor||row.selectionHash!==selectionHash(selection))throw new IntegrationError("raw_export_reauth_required",401);+}diff --git a/lib/infra/portable/http.ts b/lib/infra/portable/http.tsindex fe820f03..bb9f0263 100644--- a/lib/infra/portable/http.ts+++ b/lib/infra/portable/http.ts@@ -6,10 +6,11 @@ export async function transferBody(req:Request):Promise<Record<string,unknown>>{const reader=req.body?.getReader();if(!reader)throw new IntegrationError('invalid_transfer_request');let bytes=0;const chunks:Uint8Array[]=[];try{for(;;){let timer:ReturnType<typeof setTimeout>|undefined;const r=await Promise.race([reader.read(),new Promise<never>((_,reject)=>{timer=setTimeout(()=>reject(new IntegrationError('request_timeout',408)),5000)})]).finally(()=>clearTimeout(timer));if(r.done)break;bytes+=r.value.byteLength;if(bytes>MAX_BYTES+16384)throw new IntegrationError('bundle_too_large',413);chunks.push(r.value);}let b;try{b=JSON.parse(Buffer.concat(chunks).toString('utf8'))}catch{throw new IntegrationError('invalid_json')}- const allowed=['action','document','users','includeSecrets','passphrase','prefix','policy','apply','confirm','acceptWarnings'];+ const allowed=['action','document','users','selection','includeSecrets','passphrase','password','grant','format','prefix','policy','apply','confirm','acceptWarnings'];if(!b||typeof b!=='object'||Array.isArray(b)||Object.keys(b).some(k=>!allowed.includes(k)))throw new IntegrationError('invalid_transfer_request');for(const k of ['apply','includeSecrets','acceptWarnings'])if(b[k]!==undefined&&typeof b[k]!=='boolean')throw new IntegrationError('invalid_transfer_request');- for(const k of ['passphrase','confirm','prefix','policy'])if(b[k]!==undefined&&typeof b[k]!=='string')throw new IntegrationError('invalid_transfer_request');+ for(const k of ['passphrase','password','grant','format','confirm','prefix','policy'])if(b[k]!==undefined&&typeof b[k]!=='string')throw new IntegrationError('invalid_transfer_request');+ if(b.selection!==undefined&&(!Array.isArray(b.selection)||b.selection.length<1||b.selection.length>512))throw new IntegrationError('invalid_transfer_request');return b;}finally{await reader.cancel().catch(()=>{});reader.releaseLock()}}diff --git a/lib/infra/portable/raw-export.ts b/lib/infra/portable/raw-export.tsnew file mode 100644index 00000000..db3677ac--- /dev/null+++ b/lib/infra/portable/raw-export.ts@@ -0,0 +1,39 @@+import { FIELD_MAP } from "./mapping";+import { readIntegrationState } from "../connection-storage";+import { connectionCatalog } from "../connection-registry";+import { IntegrationError, resolveSharedConnection } from "../identity";+import { assertTransferSelectionExists, normalizeTransferSelection, transferSelectionMatches } from "./selection";++export type RawCredentialFormat = "json" | "env";+type RawRow = { user:string; provider:string; connection:string; label:string; values:Record<string,string> };++function envKey(value:string){ return value.toUpperCase().replace(/[^A-Z0-9]+/g,"_").replace(/^_+|_+$/g,"") || "VALUE"; }+function dotenvQuote(value:string){return JSON.stringify(value).replace(/\u2028/g,'\\u2028').replace(/\u2029/g,'\\u2029');}++async function rawRows(selectionInput: unknown):Promise<RawRow[]> {+ const state=await readIntegrationState(),selection=normalizeTransferSelection(selectionInput);assertTransferSelectionExists(state,selection);+ const rows:RawRow[]=[];+ for(const [user,profile] of Object.entries(state.users))for(const [provider,connections] of Object.entries(profile.connections))for(const [connection,c] of Object.entries(connections)){+ if(!transferSelectionMatches(selection,user,provider,connection)||c.source!=="direct")continue;+ const backing=resolveSharedConnection(state,user,c).connection,map=FIELD_MAP[provider]??{},reverse=Object.fromEntries(Object.entries(map).map(([wire,native])=>[native,wire]));+ if(Object.keys(backing.values).some(key=>!reverse[key]))throw new IntegrationError("unmapped_export_field");const values=Object.fromEntries(Object.entries(backing.values).map(([key,value])=>[reverse[key],value]));+ if(Object.keys(values).length)rows.push({user,provider,connection,label:c.label,values});+ }+ return rows;+}++export async function exportRawCredentials(selectionInput:unknown,format:RawCredentialFormat){+ const rows=await rawRows(selectionInput),stamp=new Date().toISOString();if(!rows.length)throw new IntegrationError("no_plaintext_credentials_selected",409);+ if(format==="json"){+ const users=[...new Set(rows.map(row=>row.user))].map(user=>({id:user,connections:rows.filter(row=>row.user===user).map(({provider,connection,label,values})=>({provider,id:connection,label,values}))}));+ return{content:JSON.stringify({format:"mso-raw-credentials",version:1,exportedAt:stamp,users},null,2)+"\n",contentType:"application/json; charset=utf-8",filename:`mso-credentials-${stamp.slice(0,10)}.json`,connectionCount:rows.length};+ }+ const single=rows.length===1;const lines=["# MSO RAW CREDENTIAL EXPORT — KEEP PRIVATE",`# Exported ${stamp}`,"# Values below are plaintext. Rotate credentials if this file is exposed.",""];+ for(const row of rows){lines.push(`# ${row.user} / ${row.provider} / ${row.connection} / ${row.label}`);for(const[key,value]of Object.entries(row.values)){const name=single?key:`${envKey(row.user)}__${envKey(row.provider)}__${envKey(row.connection)}__${key}`;lines.push(`${name}=${dotenvQuote(value)}`)}lines.push("")}+ return{content:lines.join("\n"),contentType:"text/plain; charset=utf-8",filename:`mso-credentials-${stamp.slice(0,10)}.env`,connectionCount:rows.length};+}++export async function exportSelectionTree(){+ const state=await readIntegrationState(),titles=Object.fromEntries(connectionCatalog().map(row=>[row.id,row.title]));+ return{users:Object.values(state.users).map(profile=>({id:profile.id,label:profile.label,providers:Object.entries(profile.connections).filter(([,rows])=>Object.keys(rows).length).map(([provider,rows])=>({id:provider,title:titles[provider]??provider,connections:Object.values(rows).map(c=>({id:c.id,label:c.label,source:c.source,storedFields:c.source==="direct"?Object.keys(resolveSharedConnection(state,profile.id,c).connection.values).length:0}))}))}))};+}diff --git a/lib/infra/portable/selection.ts b/lib/infra/portable/selection.tsnew file mode 100644index 00000000..fcfbee5b--- /dev/null+++ b/lib/infra/portable/selection.ts@@ -0,0 +1,38 @@+import { IntegrationError, identity, type IntegrationState } from "../identity";++export type TransferSelection = { user: string; provider?: string; connection?: string };+const MAX_SELECTIONS = 512;++export function normalizeTransferSelection(value: unknown): TransferSelection[] | undefined {+ if (value === undefined) return undefined;+ if (!Array.isArray(value) || value.length < 1 || value.length > MAX_SELECTIONS) throw new IntegrationError("invalid_transfer_selection");+ const seen = new Set<string>();+ const out: TransferSelection[] = [];+ for (const raw of value) {+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) throw new IntegrationError("invalid_transfer_selection");+ const row = raw as Record<string, unknown>;+ if (Object.keys(row).some(key => !["user", "provider", "connection"].includes(key))) throw new IntegrationError("invalid_transfer_selection");+ const user = identity(row.user, "user");+ const provider = row.provider === undefined ? undefined : identity(row.provider, "provider");+ const connection = row.connection === undefined ? undefined : identity(row.connection, "connection");+ if (connection && !provider) throw new IntegrationError("invalid_transfer_selection");+ const key = [user, provider ?? "*", connection ?? "*"].join("/");+ if (!seen.has(key)) { seen.add(key); out.push({ user, ...(provider ? { provider } : {}), ...(connection ? { connection } : {}) }); }+ }+ return out.sort((a,b) => `${a.user}/${a.provider ?? ""}/${a.connection ?? ""}`.localeCompare(`${b.user}/${b.provider ?? ""}/${b.connection ?? ""}`));+}++export function transferSelectionMatches(selection: TransferSelection[] | undefined, user: string, provider: string, connection: string) {+ if (!selection) return true;+ return selection.some(row => row.user === user && (!row.provider || row.provider === provider) && (!row.connection || row.connection === connection));+}++export function assertTransferSelectionExists(state: IntegrationState, selection: TransferSelection[] | undefined) {+ if (!selection) return;+ for (const row of selection) {+ const profile = state.users[row.user];+ if (!profile) throw new IntegrationError("unknown_export_user",404);+ if (row.provider && !profile.connections[row.provider]) throw new IntegrationError("unknown_export_provider",404);+ if (row.connection && !profile.connections[row.provider!]?.[row.connection]) throw new IntegrationError("unknown_export_connection",404);+ }+}diff --git a/lib/infra/portable/ui.ts b/lib/infra/portable/ui.tsindex 6ad5eb5d..b84dba77 100644--- a/lib/infra/portable/ui.ts+++ b/lib/infra/portable/ui.ts@@ -1,51 +1,67 @@-// Bundled independent implementation of the versioned transfer UI.+// Owner-only transfer workbench. The default Integrations screen stays simple;+// this surface is opened explicitly from More → Transfer & backup.export const PORTABILITY_SCRIPT=String.raw`function mountPortability(root,bridge){- let disposed=false,documentData=null,preview=null;root.replaceChildren();root.classList.add('integration','portable-transfer');- const el=(tag,text)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;return n};- const button=(text,fn)=>{const b=el('button',text);b.type='button';b.addEventListener('click',fn);return b};+ let disposed=false,documentData=null,preview=null,tree=null,active='export';const selected=new Set();root.replaceChildren();root.classList.add('integration','portable-transfer');+ const el=(tag,text,cls)=>{const n=document.createElement(tag);if(text!==undefined)n.textContent=text;if(cls)n.className=cls;return n};+ const button=(text,fn,cls)=>{const b=el('button',text,cls);b.type='button';b.addEventListener('click',fn);return b};const field=(name,type='text')=>{const l=el('label',name),i=el('input');i.type=type;i.autocomplete='off';if(type==='checkbox')l.className='check identity-check';l.append(i);return{l,i}};- const back=button('← Connections',()=>{cleanup();bridge.back()});root.append(back,el('h2','Import / export JSON'),el('p','Move credential users and named connections between independent applications. This is a one-time copy, not live synchronization. No existing connection is overwritten.'));- const exp=el('section'),imp=el('section');exp.className=imp.className='connection-card';exp.append(el('h3','Export'));- const owner=field('User ID (blank exports all users)'),secrets=field('Include direct credentials — encrypted JSON','checkbox'),password=field('Export passphrase (12+ characters)','password'),repeat=field('Confirm export passphrase','password');- password.i.maxLength=1024;- repeat.i.maxLength=1024;- password.l.hidden=true;- repeat.l.hidden=true;- secrets.i.addEventListener('change',()=>{password.l.hidden=repeat.l.hidden=!secrets.i.checked;if(!secrets.i.checked)password.i.value=repeat.i.value=''});- const note=el('p','Metadata export includes names, source/auth methods and field status only. All field values, active OAuth sessions, defaults and folder mappings are excluded.');- const exportStatus=el('p');exportStatus.setAttribute('role','status');- const download=button('Export JSON',async()=>{- download.disabled=true;exportStatus.textContent='Preparing export…';- try{if(secrets.i.checked&&(password.i.value.length<12||password.i.value!==repeat.i.value))throw Error('Use a matching passphrase of at least 12 characters.');- const response=await bridge.request({action:'export',...(owner.i.value.trim()?{users:[owner.i.value.trim()]}:{}),includeSecrets:secrets.i.checked,...(secrets.i.checked?{passphrase:password.i.value}:{})});- if(disposed)return;const encrypted=response.bundle.format.endsWith('.encrypted');- const blob=new Blob([JSON.stringify(response.bundle,null,2)+'\n'],{type:'application/json'}),url=URL.createObjectURL(blob),a=el('a','Save JSON file');- a.href=url;a.download='connections-'+new Date().toISOString().slice(0,10)+(encrypted?'.integration-bundle.enc.json':'.integration-bundle.json');a.click();setTimeout(()=>URL.revokeObjectURL(url),1000);- exportStatus.textContent=encrypted?'Encrypted export created. Share the passphrase through a separate channel.':'Metadata export created. It contains no credential values.';- }catch(e){exportStatus.textContent=e.message}finally{password.i.value=repeat.i.value='';download.disabled=false}- });exp.append(owner.l,secrets.l,password.l,repeat.l,note,download,exportStatus);- imp.append(el('h3','Import'));const file=field('JSON bundle file','file');file.i.accept='.json,application/json';- const decrypt=field('Import passphrase (encrypted files only)','password'),prefix=field('User ID prefix (optional, for a separate copy)'),policy=el('select'),policyLabel=el('label','Conflicts');- decrypt.i.maxLength=1024;prefix.i.placeholder='imported-';prefix.i.maxLength=32;decrypt.l.hidden=true;- for(const [value,text]of [['skip','Preserve existing connections; skip conflicts'],['error','Stop when a conflict exists']]){const o=el('option',text);o.value=value;policy.append(o)}policyLabel.append(policy);- const previewBox=el('pre');const importStatus=el('p');importStatus.setAttribute('role','status');- const reviewed=field('I reviewed the preview and accept listed skips / omitted fields','checkbox');reviewed.i.checked=false;- function reset(){preview=null;previewBox.textContent='';apply.disabled=true;reviewed.i.checked=false;}- file.i.addEventListener('change',async()=>{reset();documentData=null;decrypt.i.value='';const selected=file.i.files?.[0];if(!selected)return;try{if(selected.size>2*1024*1024)throw Error('JSON file exceeds 2 MiB.');documentData=JSON.parse(await selected.text());decrypt.l.hidden=documentData.format!=='integration-bundle.encrypted';importStatus.textContent='File loaded locally. Choose Preview import.'}catch(e){importStatus.textContent=e.message}});- prefix.i.addEventListener('input',reset);policy.addEventListener('change',reset);- const input=()=>({action:'import',document:documentData,prefix:prefix.i.value.trim(),policy:policy.value,...(!decrypt.l.hidden?{passphrase:decrypt.i.value}:{})});- const check=button('Preview import',async()=>{if(!documentData){importStatus.textContent='Choose a JSON file first.';return}check.disabled=true;try{preview=await bridge.request(input());if(disposed)return;previewBox.textContent=JSON.stringify(preview,null,2);apply.disabled=!preview.canApply;importStatus.textContent='Preview only: nothing has been imported.'}catch(e){reset();importStatus.textContent=e.message}finally{check.disabled=false}});- const apply=button('Apply import',async()=>{- if(!preview||!reviewed.i.checked){importStatus.textContent='Review the preview and check the confirmation box.';return}apply.disabled=check.disabled=true;- try{const result=await bridge.request({...input(),apply:true,confirm:preview.planId,acceptWarnings:reviewed.i.checked});if(disposed)return;previewBox.textContent=JSON.stringify(result,null,2);importStatus.textContent='Imported. Connections are not marked verified; external sources must be authorized again. Select the imported user when you return.';documentData=null;file.i.value='';decrypt.i.value='';preview=null;}- catch(e){importStatus.textContent=e.message;apply.disabled=false}finally{check.disabled=false}- });apply.disabled=true;- imp.append(file.l,decrypt.l,prefix.l,policyLabel,check,previewBox,reviewed.l,apply,importStatus);const grid=el('div');grid.className='transfer-grid';grid.append(exp,imp);root.append(grid);- function cleanup(){disposed=true;password.i.value=repeat.i.value=decrypt.i.value='';documentData=null;preview=null;root.replaceChildren();root.classList.remove('portable-transfer','integration')}+ const save=(blob,name)=>{const url=URL.createObjectURL(blob),a=el('a');a.href=url;a.download=name;a.click();setTimeout(()=>URL.revokeObjectURL(url),1000)};+ const selection=()=>scope.value==='all'?undefined:[...selected].map(key=>{const[user,provider,connection]=key.split('|');return{user,provider,connection}});+ const ensureSelection=()=>{const value=selection();if(value&&value.length===0)throw Error('Choose at least one connection.');return value};+ const back=button('← Connections',()=>{cleanup();bridge.back()});const title=el('div',undefined,'transfer-heading');title.append(el('h2','Transfer & backup'),el('p','Backup, move, or restore connections. Advanced tools stay out of the normal connection screen.'));root.append(back,title);+ const tabs=el('div',undefined,'transfer-tabs'),body=el('div');const exportTab=button('Export',()=>{active='export';render()}),importTab=button('Import',()=>{active='import';render()});tabs.setAttribute('role','tablist');for(const b of[exportTab,importTab])b.setAttribute('role','tab');tabs.append(exportTab,importTab);root.append(tabs,body);+ const scope=el('select');for(const[value,text]of[['all','All connections'],['custom','Custom selection…']]){const o=el('option',text);o.value=value;scope.append(o)}+ function scopeTree(){+ const wrap=el('div',undefined,'transfer-tree');if(!tree){wrap.append(el('p','Loading connection list…'));return wrap}+ for(const owner of tree.users){const group=el('section',undefined,'transfer-tree-user'),head=field(owner.label+' · '+owner.id,'checkbox'),keys=[];{const ownerKeys=owner.providers.flatMap(p=>p.connections.map(c=>owner.id+'|'+p.id+'|'+c.id));head.i.checked=ownerKeys.length>0&&ownerKeys.every(key=>selected.has(key));head.i.indeterminate=!head.i.checked&&ownerKeys.some(key=>selected.has(key))}group.append(head.l);+ for(const provider of owner.providers){const pgroup=el('div',undefined,'transfer-tree-provider'),ph=field(provider.title||provider.id,'checkbox'),providerKeys=provider.connections.map(c=>owner.id+'|'+provider.id+'|'+c.id);keys.push(...providerKeys);ph.i.checked=providerKeys.length>0&&providerKeys.every(key=>selected.has(key));ph.i.indeterminate=!ph.i.checked&&providerKeys.some(key=>selected.has(key));pgroup.append(ph.l);+ for(const c of provider.connections){const key=owner.id+'|'+provider.id+'|'+c.id,cf=field(c.label+' · '+c.id+(c.source==='direct'?' · '+c.storedFields+' stored fields':' · authorization metadata only'),'checkbox');cf.i.checked=selected.has(key);cf.i.addEventListener('change',()=>{cf.i.checked?selected.add(key):selected.delete(key);render()});pgroup.append(cf.l)}+ ph.i.addEventListener('change',()=>{for(const key of providerKeys)ph.i.checked?selected.add(key):selected.delete(key);render()});group.append(pgroup)}+ head.i.addEventListener('change',()=>{for(const key of keys)head.i.checked?selected.add(key):selected.delete(key);render()});wrap.append(group)}return wrap;+ }+ function exportView(){+ const card=el('section',undefined,'connection-card transfer-card'),head=el('div');head.append(el('h3','Download backup'),el('p','Encrypted backup is recommended. Plaintext downloads require your MSO password and expire after one use.'));card.append(head);+ const scopeLabel=el('label','Download');scope.setAttribute('aria-label','Export scope');scopeLabel.append(scope);scope.onchange=render;card.append(scopeLabel);if(scope.value==='custom')card.append(scopeTree());+ const format=el('select');for(const[value,text]of[['encrypted','Encrypted JSON · recommended'],['metadata','Metadata JSON · no credential values'],['raw-json','Raw JSON · plaintext credentials'],['env','.env · plaintext credentials']]){const o=el('option',text);o.value=value;format.append(o)}format.value=exportView.format||'encrypted';format.setAttribute('aria-label','Export format');const formatLabel=el('label','Format');formatLabel.append(format);card.append(formatLabel);+ const security=el('div',undefined,'transfer-security'),status=el('p');status.setAttribute('role','status');let pass,repeat,ownerPassword,ack;+ const paint=()=>{exportView.format=format.value;render()};format.addEventListener('change',paint);+ if(format.value==='encrypted'){+ pass=field('Backup passphrase (12+ characters)','password');repeat=field('Confirm backup passphrase','password');pass.i.maxLength=repeat.i.maxLength=1024;security.append(el('p','The file contains selected direct credentials encrypted with your passphrase.'),pass.l,repeat.l);+ }else if(format.value==='raw-json'||format.value==='env'){+ ownerPassword=field('MSO owner password','password');ownerPassword.i.autocomplete='current-password';ownerPassword.i.maxLength=1024;ack=field('I understand this download contains plaintext credentials','checkbox');security.classList.add('danger-zone');security.append(el('strong','Sensitive download'),el('p','MSO will re-authenticate you, issue a 90-second one-time grant, create the file, then invalidate the grant. The password is not stored. Use encrypted JSON when you need a restorable backup.'),ownerPassword.l,ack.l);+ }else security.append(el('p','Metadata only: connection names, methods and configured-field status. No credential values.'));+ card.append(security);+ const download=button(format.value==='metadata'?'Download metadata':format.value==='encrypted'?'Download encrypted backup':'Re-authenticate & download',async()=>{+ download.disabled=true;status.textContent='Preparing download…';+ try{const chosen=ensureSelection();+ if(format.value==='metadata'||format.value==='encrypted'){+ if(format.value==='encrypted'&&(pass.i.value.length<12||pass.i.value!==repeat.i.value))throw Error('Use a matching backup passphrase of at least 12 characters.');+ const response=await bridge.request({action:'export',...(chosen?{selection:chosen}:{}),includeSecrets:format.value==='encrypted',...(format.value==='encrypted'?{passphrase:pass.i.value}:{})});const encrypted=response.bundle.format.endsWith('.encrypted');+ save(new Blob([JSON.stringify(response.bundle,null,2)+'\n'],{type:'application/json'}),'connections-'+new Date().toISOString().slice(0,10)+(encrypted?'.integration-bundle.enc.json':'.integration-bundle.json'));status.textContent=encrypted?'Encrypted backup downloaded.':'Metadata downloaded; it contains no credential values.';+ }else{+ if(!ownerPassword.i.value||!ack.i.checked)throw Error('Enter your MSO password and confirm the plaintext warning.');+ const authorized=await bridge.request({action:'authorize-raw-export',password:ownerPassword.i.value,...(chosen?{selection:chosen}:{})});ownerPassword.i.value='';+ const file=await bridge.download({action:'export-raw',grant:authorized.grant,format:format.value==='env'?'env':'json',...(chosen?{selection:chosen}:{})});save(file.blob,file.filename);ack.i.checked=false;status.textContent='Sensitive file downloaded. The one-time export grant is now invalid.';+ }+ }catch(e){status.textContent=e.message}finally{if(pass)pass.i.value=repeat.i.value='';if(ownerPassword)ownerPassword.i.value='';download.disabled=false}+ },format.value==='raw-json'||format.value==='env'?'danger':'primary');card.append(download,status);body.append(card);+ const hint=el('p','Need to move one credential between owners? Go back to Connections → More on that connection and choose Copy to another owner. Share keeps one owner; Copy creates an independent connection.','transfer-hint');body.append(hint);+ }+ function importView(){+ const card=el('section',undefined,'connection-card transfer-card');card.append(el('h3','Bulk import'),el('p','Upload a metadata or encrypted Integration Bundle. MSO always previews changes first and never overwrites an existing connection.'));+ const file=field('JSON bundle file','file');file.i.accept='.json,application/json';const decrypt=field('Import passphrase (encrypted files only)','password'),prefix=field('User ID prefix (optional)'),policy=el('select'),policyLabel=el('label','Conflicts');decrypt.i.maxLength=1024;prefix.i.placeholder='imported-';prefix.i.maxLength=32;decrypt.l.hidden=true;+ for(const[value,text]of[['skip','Preserve existing connections; skip conflicts'],['error','Stop when a conflict exists']]){const o=el('option',text);o.value=value;policy.append(o)}policyLabel.append(policy);const previewBox=el('pre'),status=el('p');status.setAttribute('role','status');const reviewed=field('I reviewed the preview and accept listed skips / omitted fields','checkbox');+ const reset=()=>{preview=null;previewBox.textContent='';apply.disabled=true;reviewed.i.checked=false};file.i.addEventListener('change',async()=>{reset();documentData=null;decrypt.i.value='';const selectedFile=file.i.files?.[0];if(!selectedFile)return;try{if(selectedFile.size>2*1024*1024)throw Error('JSON file exceeds 2 MiB.');documentData=JSON.parse(await selectedFile.text());decrypt.l.hidden=documentData.format!=='integration-bundle.encrypted';status.textContent='File loaded locally. Preview before applying.'}catch(e){status.textContent=e.message}});prefix.i.addEventListener('input',reset);policy.addEventListener('change',reset);+ const input=()=>({action:'import',document:documentData,prefix:prefix.i.value.trim(),policy:policy.value,...(!decrypt.l.hidden?{passphrase:decrypt.i.value}:{})});const check=button('Preview import',async()=>{if(!documentData){status.textContent='Choose a JSON file first.';return}check.disabled=true;try{preview=await bridge.request(input());previewBox.textContent=JSON.stringify(preview,null,2);apply.disabled=!preview.canApply;status.textContent='Preview only — nothing has changed yet.'}catch(e){reset();status.textContent=e.message}finally{check.disabled=false}});+ const apply=button('Apply import',async()=>{if(!preview||!reviewed.i.checked){status.textContent='Review the preview and confirm first.';return}apply.disabled=check.disabled=true;try{const result=await bridge.request({...input(),apply:true,confirm:preview.planId,acceptWarnings:reviewed.i.checked});previewBox.textContent=JSON.stringify(result,null,2);status.textContent='Import complete. Imported connections are not marked verified; external authorization must be completed again.';documentData=null;file.i.value='';decrypt.i.value='';preview=null}catch(e){status.textContent=e.message;apply.disabled=false}finally{check.disabled=false}},'primary');apply.disabled=true;card.append(file.l,decrypt.l,prefix.l,policyLabel,check,previewBox,reviewed.l,apply,status);body.append(card);+ }+ function render(){if(disposed)return;body.replaceChildren();exportTab.setAttribute('aria-selected',String(active==='export'));importTab.setAttribute('aria-selected',String(active==='import'));active==='export'?exportView():importView()}+ render();bridge.request({action:'tree'}).then(data=>{if(disposed)return;tree=data;for(const owner of tree.users)for(const p of owner.providers)for(const c of p.connections)selected.add(owner.id+'|'+p.id+'|'+c.id);if(active==='export')render()}).catch(e=>{if(!disposed){tree={users:[]};body.prepend(el('p',e.message,'transfer-error'))}});+ function cleanup(){disposed=true;documentData=null;preview=null;selected.clear();root.replaceChildren();root.classList.remove('portable-transfer','integration')}return cleanup;}`;export const PORTABILITY_STYLE=String.raw`-.portable-transfer{max-width:1100px!important;margin:auto}.portable-transfer .transfer-grid{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:20px}.portable-transfer section{min-width:0;border:1px solid var(--sep-strong);border-radius:12px;padding:20px;background:var(--field)}.portable-transfer h3{margin-top:0}.portable-transfer label{display:block;margin:14px 0 6px;font-weight:600;font-size:13px}.portable-transfer input,.portable-transfer select{margin-top:6px;min-width:0;max-width:100%}.portable-transfer .identity-check{display:flex;gap:9px;align-items:center;font-weight:400}.portable-transfer .identity-check input{width:18px;height:18px;margin:0;order:-1;flex:none}.portable-transfer button{min-height:40px;margin:8px 7px 8px 0}.portable-transfer pre{max-height:330px;overflow:auto;font-size:12px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}.portable-transfer [role=status]{font-size:13px;overflow-wrap:anywhere}@media(max-width:700px){.portable-transfer .transfer-grid{grid-template-columns:1fr}.portable-transfer section{padding:15px}}+.portable-transfer{max-width:880px!important;margin:auto}.portable-transfer .transfer-heading h2{margin-bottom:4px}.portable-transfer .transfer-heading p{margin-top:0}.portable-transfer .transfer-tabs{display:flex;gap:4px;margin:20px 0;border-bottom:1px solid var(--sep)}.portable-transfer .transfer-tabs button{border:0;border-radius:0;background:transparent;margin:0;padding:10px 14px}.portable-transfer .transfer-tabs button[aria-selected=true]{border-bottom:2px solid var(--os-accent);font-weight:700}.portable-transfer .transfer-card{border:1px solid var(--sep-strong);border-radius:12px;padding:20px;background:var(--field);margin-top:0}.portable-transfer .transfer-card>label{display:block;margin:14px 0 6px;font-weight:600;font-size:13px}.portable-transfer select,.portable-transfer input{margin-top:6px;max-width:100%}.portable-transfer .transfer-security{margin:16px 0;padding:14px;border-radius:10px;background:var(--inset)}.portable-transfer .danger-zone{border:1px solid color-mix(in srgb,var(--destructive-text) 40%,var(--sep));background:color-mix(in srgb,var(--destructive-text) 5%,var(--surface))}.portable-transfer .identity-check{display:flex;gap:9px;align-items:center;font-weight:400}.portable-transfer .identity-check input{width:18px;height:18px;margin:0;order:-1;flex:none}.portable-transfer .transfer-tree{max-height:360px;overflow:auto;margin:10px 0;padding:10px;border:1px solid var(--sep);border-radius:10px;background:var(--surface)}.portable-transfer .transfer-tree-user{padding:8px 0;border-bottom:1px solid var(--sep)}.portable-transfer .transfer-tree-provider{padding-left:22px}.portable-transfer .transfer-tree-provider>.identity-check~.identity-check{padding-left:22px;color:var(--text-dim)}.portable-transfer pre{max-height:330px;overflow:auto;font-size:12px;line-height:1.6;white-space:pre-wrap;overflow-wrap:anywhere}.portable-transfer [role=status]{font-size:13px;overflow-wrap:anywhere}.portable-transfer .transfer-hint{font-size:12px;color:var(--text-dim);margin-top:12px}.portable-transfer button{min-height:40px;margin:8px 7px 8px 0}@media(max-width:700px){.portable-transfer .transfer-card{padding:14px}.portable-transfer .transfer-tabs button{flex:1}.portable-transfer .transfer-tree-provider{padding-left:12px}.portable-transfer .transfer-tree-provider>.identity-check~.identity-check{padding-left:12px}}`;diff --git a/lib/infra/setup-browser.ts b/lib/infra/setup-browser.tsindex f4f0202c..582f8629 100644--- a/lib/infra/setup-browser.ts+++ b/lib/infra/setup-browser.ts@@ -7,7 +7,7 @@ export const INTEGRATION_BROWSER_SCRIPT=String.raw`function showForm(setup,token){cleanup();authController?.abort();cleanup=mountIntegrationForm(root,setup,{endpoint,token,onBack:loadManager})||(()=>{})}function openTransfer(){cleanup();authController?.abort();wantsTransfer=true;- cleanup=mountPortability(root,{back:()=>{wantsTransfer=false;void loadManager()},request:body=>json("/api/v1/integrations/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)})});+ cleanup=mountPortability(root,{back:()=>{wantsTransfer=false;void loadManager()},request:body=>json("/api/v1/integrations/transfer",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)}),download:async body=>{const r=await fetch("/api/v1/integrations/transfer",{method:"POST",credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json"},body:JSON.stringify(body)});if(!r.ok)throw error(await r.json());const disposition=r.headers.get("content-disposition")||"",match=/filename="([^"]+)"/.exec(disposition);return{blob:await r.blob(),filename:match?.[1]||"mso-credentials.txt"}}});}async function loadManager(){cleanup();authController?.abort();authController=new AbortController();diff --git a/lib/mcp/integration-model-contract.test.ts b/lib/mcp/integration-model-contract.test.tsindex 35bcceb5..bf5f1435 100644--- a/lib/mcp/integration-model-contract.test.ts+++ b/lib/mcp/integration-model-contract.test.ts@@ -18,7 +18,7 @@ it("uses the same native metadata services through actual MCP calls and rejectsconst 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("keeps share/unshare in the same integration management contract without accepting secret values",async()=>{- const {INTEGRATION_TOOLS}=await import("./tools-integrations");const tool=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_manage")!;const schema=tool.inputSchema as {properties?:Record<string,{enum?:string[]}>};const actions=schema.properties?.action?.enum??[];expect(actions).toContain("connection.share");expect(actions).toContain("connection.unshare");expect(schema.properties).toHaveProperty("target");expect(schema.properties).toHaveProperty("label");expect(schema.properties).toHaveProperty("key");expect(schema.properties).not.toHaveProperty("token");expect(schema.properties).not.toHaveProperty("apiKey");+ const {INTEGRATION_TOOLS}=await import("./tools-integrations");const tool=INTEGRATION_TOOLS.find(entry=>entry.name==="integration_manage")!;const schema=tool.inputSchema as {properties?:Record<string,{enum?:string[]}>};const actions=schema.properties?.action?.enum??[];expect(actions).toContain("connection.share");expect(actions).toContain("connection.duplicate");expect(actions).toContain("connection.unshare");expect(schema.properties).toHaveProperty("target");expect(schema.properties).toHaveProperty("targetConnection");expect(schema.properties).toHaveProperty("label");expect(schema.properties).toHaveProperty("key");expect(schema.properties).not.toHaveProperty("token");expect(schema.properties).not.toHaveProperty("apiKey");});it("exposes the bounded Dokploy application operations through integration_execute without adding a generic request escape hatch",async()=>{const {INTEGRATION_TOOLS}=await import("./tools-integrations");diff --git a/lib/mcp/tools-integrations.ts b/lib/mcp/tools-integrations.tsindex d2d44da4..ec024b38 100644--- a/lib/mcp/tools-integrations.ts+++ b/lib/mcp/tools-integrations.ts@@ -7,15 +7,15 @@ const BASE={...INTEGRATION_SELECTOR_SCHEMA,provider:{type:"string",maxLength:64}const OUTPUT={type:"object",properties:{result:{type:"object"}},required:["result"],additionalProperties:false};export const INTEGRATION_TOOLS:McpTool[]=[{name:"integration_query",title:"Inspect Integration Connections",scope:"read",annotations:{readOnlyHint:true,idempotentHint:true,openWorldHint:false},- description:"Read native MSO credential users, providers, named connections, source/auth guidance and directory resolution. Never returns keys. User profiles are credential owners, not device roles. Resolve before acting when multiple accounts or deployments exist.",- chatgptDescription:"Inspect users, providers and connections. Use view=request for setup or view=resolve before an exact operation.",+ description:"Read native MSO credential users, providers, named connections, source/auth guidance and directory resolution. Never returns keys. Before asking the user for a credential or creating new setup, inspect Integrations for the exact project/context and resolve the intended user/provider/connection. User profiles are credential owners, not device roles. Resolve before acting when multiple accounts or deployments exist.",+ chatgptDescription:"When work needs a service credential, check Integrations first. Inspect users/providers/connections and resolve the exact existing connection; use view=request only when setup is actually missing.",inputSchema:S({...BASE,view:{type:"string",enum:["snapshot","catalog","users","connections","which","resolve","request"]},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64}}),outputSchema:OUTPUT,meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>({result:await queryIntegrationAction(a)}),},{name:"integration_manage",title:"Manage Integrations",scope:"write",annotations:{readOnlyHint:false,destructiveHint:true,idempotentHint:false,openWorldHint:true},audit:{action:"infra.write",targetArg:"user"},limit:{key:"integration.manage",max:30,windowMs:60000},description:"Manage native credential users, directory bindings and named provider connections. Actions require confirm=true. Direct credential values are forbidden: use integration_setup_open with user/provider/connection. Composio authorization keeps only external IDs/status and returns its transient URL privately to the UI. Native MCP authorization stays provider-owned.",chatgptDescription:"Create or update connection metadata with action and confirm=true. Credentials use integration_setup_open.",- inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize","connection.import-convex-cli"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Duplicate with credentials."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,+ inputSchema:S({...BASE,action:{type:"string",enum:[...INTEGRATION_ACTIONS,"connection.authorize","connection.import-convex-cli"]},confirm:{type:"boolean",const:true},target:{type:"string",maxLength:64},targetConnection:{type:"string",maxLength:64},label:{type:"string",maxLength:120},path:{type:"string",maxLength:4096},source:{type:"string",enum:[...SOURCES]},authMethod:{type:"string",maxLength:64},copyCredentials:{type:"boolean",description:"Duplicate with credentials."},makeDefault:{type:"boolean"},key:{type:"string",maxLength:64},authConfigId:{type:"string",maxLength:64},brokerConnection:{type:"string",maxLength:64},createManaged:{type:"boolean"}},["action","confirm"]),outputSchema:OUTPUT,meta:{ui:{visibility:["model","app"]},"openai/widgetAccessible":true},run:async a=>{const out=await manageIntegrationAction(a);if("privateUrl" in out){const{privateUrl,...safe}=out;return mcpDirect([{type:"text",text:"Authorization link available in the private integration UI."}],false,{result:safe},{integrationAuthorization:{url:privateUrl}});}return{result:out};},},diff --git a/lib/mcp/toolset.ts b/lib/mcp/toolset.tsindex dbd82249..782ab0c1 100644--- a/lib/mcp/toolset.ts+++ b/lib/mcp/toolset.ts@@ -3,9 +3,9 @@ import type { Scope } from "./scope";import type { McpTool } from "./tool-kit";import { toolDescriptor, type McpToolProfile } from "./tool-contract";-export const MCP_SERVER_VERSION = "1.14.2";-export const MCP_TOOLSET_VERSION = "2026.09.15.1";-export const MCP_TOOLSET_CHANGED_AT = "2026-09-15T00:30:00+07:00";+export const MCP_SERVER_VERSION = "1.14.3";+export const MCP_TOOLSET_VERSION = "2026.09.15.2";+export const MCP_TOOLSET_CHANGED_AT = "2026-09-15T02:00:00+07:00";export type McpToolsetInfo = {serverVersion: string;diff --git a/package.json b/package.jsonindex db89bc86..64a15615 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "mso",- "version": "0.2.11",+ "version": "0.2.12","private": true,"engines": {"node": ">=20.9",diff --git a/scripts/e2e/automation.mjs b/scripts/e2e/automation.mjsindex d55321cd..2e75792d 100644--- a/scripts/e2e/automation.mjs+++ b/scripts/e2e/automation.mjs@@ -34,7 +34,8 @@ export async function automationJourney(page, fixture) {return {status:response.status,body:await response.json()};}, [route,body]);await page.goto(fixture.base + "/integrations");- await page.getByRole("button", {name:"Add MCP",exact:true}).click();+ await page.getByLabel("More integration actions", {exact:true}).click();+ await page.getByRole("button", {name:"Add project MCP",exact:true}).click();await page.getByLabel("Project id or path").fill(project);await page.getByLabel("Server alias", {exact:true}).fill("public-fixture");await page.getByLabel("HTTPS MCP endpoint").fill("https://example.com/mcp");@@ -69,5 +70,5 @@ export async function automationJourney(page, fixture) {expect((await call("/api/v1/flows",{action:"delete",project,flow:definition.id,revision:current.body.revision})).status).toBe(200);const binding = await call("/api/v1/project-mcp",{action:"inspect",project});expect((await call("/api/v1/project-mcp",{action:"delete",project,server:"public-fixture",revision:binding.body.revision})).status).toBe(200);- console.log("PASS Add MCP, preserved binding, project flow CRUD, execution, Unicode result and idempotent replay");+ console.log("PASS progressive Add MCP, preserved binding, project flow CRUD, execution, Unicode result and idempotent replay");}diff --git a/scripts/e2e/integrations.mjs b/scripts/e2e/integrations.mjsindex 41149bcf..e49d95f3 100644--- a/scripts/e2e/integrations.mjs+++ b/scripts/e2e/integrations.mjs@@ -33,7 +33,7 @@ try{});await page.goto("https://mso.example.com/integrations");await waitDelivery("initial");- const accountTools=page.getByLabel("Account and tools",{exact:true});+ const accountTools=page.getByLabel("More integration actions",{exact:true});const expandTools=async()=>{if(!await accountTools.evaluate(el=>el.parentElement.open))await accountTools.click()};await expandTools();assert.equal(await page.getByRole("combobox",{name:"Credential owner"}).count(),0,"credential owner must not use a native select popup");checks++;@@ -43,22 +43,22 @@ try{await page.evaluate(theme=>document.documentElement.dataset.theme=theme,theme);assert(await page.evaluate(()=>document.documentElement.scrollWidth<=innerWidth+1),"no document overflow at "+width+" "+theme);checks++;assert(await page.getByRole("button",{name:"Update credentials",exact:true}).isVisible());checks++;- for(const action of ["Users","Routing","Transfer"])assert(await page.getByRole("button",{name:action,exact:true}).isVisible(),action+" must stay discoverable");checks++;+ for(const action of ["Credential owners","Project routing","Transfer & backup"])assert(await page.getByRole("button",{name:action,exact:true}).isVisible(),action+" must stay discoverable");checks++;}}await page.setViewportSize({width:1440,height:900});await page.getByRole("button",{name:"Verify",exact:true}).click();await page.getByRole("status").filter({hasText:"Verified: Connected to GitHub"}).waitFor();checks++;assert(await page.getByRole("button",{name:"Remove",exact:true}).isVisible(),"stored credential fields expose per-field removal");checks++;- await page.getByText("More",{exact:true}).click();await page.getByRole("button",{name:"Share",exact:true}).click();await page.getByRole("heading",{name:"Share Delivery GitHub"}).waitFor();assert(await page.getByRole("group",{name:"Target credential owner"}).getByRole("button").isVisible());assert(await page.getByRole("textbox",{name:"New alias label",exact:true}).isVisible());checks++;await page.getByRole("button",{name:"Cancel",exact:true}).click();+ const connectionCard=page.getByRole("article").filter({hasText:"Delivery GitHub"});await connectionCard.getByText("More",{exact:true}).click();assert(await connectionCard.getByRole("button",{name:"Copy to another owner",exact:true}).isVisible());await connectionCard.getByRole("button",{name:"Share linked access",exact:true}).click();await page.getByRole("heading",{name:"Share Delivery GitHub"}).waitFor();assert(await page.getByRole("group",{name:"Target credential owner"}).getByRole("button").isVisible());assert(await page.getByRole("textbox",{name:"New alias label",exact:true}).isVisible());checks++;await page.getByRole("button",{name:"Cancel",exact:true}).click();await expandTools();const owner=page.getByRole("group",{name:"Credential owner"}).getByRole("button");await owner.focus();await owner.press("ArrowDown");await page.getByRole("option",{name:/Studio/}).waitFor();await page.getByRole("option",{name:/Studio/}).press("ArrowDown");await page.getByRole("option",{name:/Personal/}).press("Enter");await page.getByRole("button",{name:"Add GitHub account",exact:true}).waitFor();assert.equal(await page.getByRole("heading",{name:"Delivery GitHub"}).count(),0);checks++;await expandTools();await owner.click();await page.getByRole("option",{name:/Studio/}).click();await waitDelivery("after owner switch back to Studio");checks++;- await expandTools();await page.getByRole("button",{name:"Users",exact:true}).click();await page.getByRole("textbox",{name:"New user ID",exact:true}).fill("client-a");await page.getByRole("textbox",{name:"Display label",exact:true}).fill("Client A");await page.getByRole("button",{name:"Create user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client A/}).waitFor();checks++;- await expandTools();await page.getByRole("button",{name:"Users",exact:true}).click();await page.getByRole("textbox",{name:"Target user ID",exact:true}).fill("client-main");await page.getByRole("textbox",{name:"New display label",exact:true}).fill("Client Main");await page.getByRole("button",{name:"Rename user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client Main/}).waitFor();checks++;- await expandTools();await page.getByRole("button",{name:"Users",exact:true}).click();await page.getByRole("textbox",{name:"Target user ID",exact:true}).fill("client-copy");await page.getByRole("textbox",{name:"New display label",exact:true}).fill("Client Copy");await page.getByRole("button",{name:"Duplicate user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client Copy/}).waitFor();checks++;- await expandTools();await page.getByRole("button",{name:"Users",exact:true}).click();await page.getByRole("button",{name:"Delete user",exact:true}).click();await page.getByRole("textbox",{name:"Confirmation",exact:true}).fill("client-copy");await page.getByRole("button",{name:"Confirm",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").waitFor();assert.equal(users.some(row=>row.id==="client-copy"),false);checks++;+ await expandTools();await page.getByRole("button",{name:"Credential owners",exact:true}).click();await page.getByRole("textbox",{name:"New user ID",exact:true}).fill("client-a");await page.getByRole("textbox",{name:"Display label",exact:true}).fill("Client A");await page.getByRole("button",{name:"Create user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client A/}).waitFor();checks++;+ await expandTools();await page.getByRole("button",{name:"Credential owners",exact:true}).click();await page.getByRole("textbox",{name:"Target user ID",exact:true}).fill("client-main");await page.getByRole("textbox",{name:"New display label",exact:true}).fill("Client Main");await page.getByRole("button",{name:"Rename user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client Main/}).waitFor();checks++;+ await expandTools();await page.getByRole("button",{name:"Credential owners",exact:true}).click();await page.getByRole("textbox",{name:"Target user ID",exact:true}).fill("client-copy");await page.getByRole("textbox",{name:"New display label",exact:true}).fill("Client Copy");await page.getByRole("button",{name:"Duplicate user",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").filter({hasText:/Client Copy/}).waitFor();checks++;+ await expandTools();await page.getByRole("button",{name:"Credential owners",exact:true}).click();await page.getByRole("button",{name:"Delete user",exact:true}).click();await page.getByRole("textbox",{name:"Confirmation",exact:true}).fill("client-copy");await page.getByRole("button",{name:"Confirm",exact:true}).click();await page.getByRole("group",{name:"Credential owner"}).getByRole("button").waitFor();assert.equal(users.some(row=>row.id==="client-copy"),false);checks++;await expandTools();await owner.click();await page.getByRole("option",{name:/Studio/}).click();await waitDelivery("after user CRUD returns to Studio");await page.getByRole("button",{name:"Add GitHub account",exact:true}).count();await page.getByRole("searchbox",{name:"Search services"}).fill("cloudflare");assert.equal(await page.getByRole("navigation",{name:"Services"}).getByRole("button",{includeHidden:true}).count(),14);assert.equal(await page.getByRole("navigation",{name:"Services"}).getByRole("button").filter({visible:true}).count(),1);checks++;diff --git a/scripts/e2e/mcp-page.mjs b/scripts/e2e/mcp-page.mjsindex 4072a1d4..5ad2f1fb 100644--- a/scripts/e2e/mcp-page.mjs+++ b/scripts/e2e/mcp-page.mjs@@ -107,7 +107,7 @@ try {</script><iframe title="MSO Page" src="https://mso-ui.example.com/qa"></iframe></html>`}));await page.goto("https://chatgpt.com/qa");const component=page.frameLocator("iframe"),surface=component.locator(".surface"),body=component.locator("#surface-body");- await component.getByRole("button",{name:"Add MCP",exact:true}).waitFor();+ await component.getByLabel("More integration actions",{exact:true}).waitFor();await page.waitForFunction(()=>window.lastSize?.height===680);assert.equal(await surface.evaluate(el=>el.getBoundingClientRect().height),680);assertions++;assert.equal(await component.locator("html").getAttribute("data-theme"),"dark");assertions++;@@ -153,14 +153,15 @@ try {await component.getByRole("combobox",{name:"MSO page",exact:true}).selectOption("/integrations");await setContext({theme:"dark",containerDimensions:{height:680},styles:{variables:{}}});await page.setViewportSize({width:736,height:900});- await component.getByRole("button",{name:"Add MCP",exact:true}).click();+ await component.getByLabel("More integration actions",{exact:true}).click();+ await component.getByRole("button",{name:"Add project MCP",exact:true}).click();await component.getByRole("heading",{name:"Add MCP to project",exact:true}).waitFor();if(imageDir)await saveScreenshot("mso-page-add-mcp.png");const audit=await new AxeBuilder({page}).withTags(["wcag2a","wcag2aa","wcag21aa"]).analyze();assert.deepEqual(audit.violations.map(v=>({id:v.id,targets:v.nodes.map(n=>n.target)})),[]);assertions++;assert.deepEqual(errors,[]);assertions++;await page.close();- console.log(`MCP Page browser checks: ${assertions} assertions passed (full height, host resize, theme, mobile, logo, Add MCP, fullscreen)`);+ console.log(`MCP Page browser checks: ${assertions} assertions passed (full height, host resize, theme, mobile, logo, progressive Add MCP, fullscreen)`);} finally {await browser.close();}diff --git a/scripts/e2e/release.mjs b/scripts/e2e/release.mjsindex e5feb34a..c28546cd 100644--- a/scripts/e2e/release.mjs+++ b/scripts/e2e/release.mjs@@ -79,8 +79,23 @@ try {await page.locator('input[type="password"]').fill(fixture.password);await page.getByRole("button", { name: "Unlock", exact: true }).click();await expect(page).toHaveURL(fixture.base + "/integrations");- await page.getByLabel("Account and tools", {exact:true}).click();+ await page.getByLabel("More integration actions", {exact:true}).click();await expect(page.getByRole("group", { name: "Credential owner" }).getByRole("button")).toContainText("fixture");+ await page.getByRole("button", { name: "Transfer & backup", exact: true }).click();+ await expect(page.getByRole("heading", { name: "Transfer & backup", exact: true })).toBeVisible();+ await expect(page.getByLabel("Export scope")).toHaveValue("all");+ await page.getByLabel("Export scope").selectOption("custom");+ await expect(page.getByText("Release fixture · fixture", { exact: true })).toBeVisible();+ await page.getByLabel("Export scope").selectOption("all");+ await page.getByLabel("Export format").selectOption("env");+ await page.getByLabel("MSO owner password").fill(fixture.password);+ await page.getByLabel("I understand this download contains plaintext credentials").check();+ const rawDownloadPromise = page.waitForEvent("download");+ await page.getByRole("button", { name: "Re-authenticate & download", exact: true }).click();+ const rawDownload = await rawDownloadPromise;+ expect(rawDownload.suggestedFilename()).toMatch(/\.env$/);+ await expect(page.locator('.portable-transfer [role="status"]')).toContainText("one-time export grant is now invalid");+ await page.getByRole("button", { name: "← Connections", exact: true }).click();await page.getByRole("button", { name: /^Self-hosted Convex(?: 1)?$/ }).click();await page.getByRole("button", { name: "Verify", exact: true }).click();await expect(page.locator(".connection-state")).toHaveText("Verified");