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
import { googleConnectionMetadata, clearGoogleRuntime } from "./google-native-state";
import { isGoogleProvider, GOOGLE_APP_PROVIDER } from "./google-native-config";
import { variableKey } from "./connection-variables";
import { randomUUID } from "node:crypto";
import { AsyncLocalStorage } from "node:async_hooks";
import { connectionCatalog, connectionMethod, connectionSummary, nativeDefinition } from "./connection-registry";
import { readIntegrationState, mutateIntegrationState } from "./connection-storage";
import { IntegrationError, identity, connectionLabel, selectConnection, resolveUser, folderBinding, metadataOnly, assertNotBusy, resolveSharedConnection, type ConnectionSelector, type IntegrationState, type IntegrationConnection, type ConnectionSource } from "./identity";
import { projectKey } from "./convex-project-link";
import { normalizeInfraValues, isInfraProviderId } from "./catalog";
const CONTEXT=new AsyncLocalStorage<{selector:ConnectionSelector; pinned:Map<string,Record<string,string>>}>();
export function withIntegrationSelection<T>(selector:ConnectionSelector,fn:()=>T){return CONTEXT.run({selector,pinned:new Map()},fn);}
export function currentIntegrationSelection():ConnectionSelector{return CONTEXT.getStore()?.selector??{};}
export async function directConnectionValues(provider:string,selector:ConnectionSelector=currentIntegrationSelection()):Promise<Record<string,string>>{
const context=CONTEXT.getStore(),cached=context?.selector===selector?context.pinned.get(provider):undefined;if(cached)return{...cached};
const state=await readIntegrationState();if(!Object.keys(state.users).length&&!selector.user&&!selector.connection)return{};
let result;try{result=selectConnection(state,provider,selector);}catch(e){if(e instanceof IntegrationError&&e.code==="connection_not_found"&&!selector.connection&&!folderBinding(state,selector.cwd)?.connections[provider]&&!state.users[resolveUser(state,selector)]?.defaults[provider])return{};throw e;}
if(result.connection.source!=="direct")throw new IntegrationError("external_source_requires_own_executor",409);
const copy={...resolveSharedConnection(state,result.user,result.connection).connection.values};if(context&&context.selector===selector)context.pinned.set(provider,copy);return copy;
}
export function summaryIn(state:IntegrationState,user:string,c:IntegrationConnection){return {...connectionSummary(user,c,state.users[user].defaults[c.provider]===c.id,resolveSharedConnection(state,user,c).connection.values),...googleConnectionMetadata(state,user,c)};}
export async function resolveIntegration(provider:string,selector:ConnectionSelector={}){
const state=await readIntegrationState(),resolved=selectConnection(state,provider,selector),c=resolved.connection;
return{...summaryIn(state,resolved.user,c),resolution:resolved.reason,execution:c.source==="direct"?{route:"native-direct"}:c.source==="composio"?{route:"composio",connectedAccountId:c.external?.connectedAccountId??null,toolkit:c.external?.toolkit??null}:{route:"provider-mcp",endpoint:nativeDefinition(provider)?.url??null,authorization:"provider-client-owned"}};
}
export async function resolveIntegrationVariable(key:string){
const name=variableKey(key),state=await readIntegrationState(),ref=state.variables?.[name];
if(!ref)throw new IntegrationError("integration_variable_not_found",404);
const selected=selectConnection(state,ref.provider,{user:ref.user,connection:ref.connection});
const summary=summaryIn(state,selected.user,selected.connection);
return{key:name,provider:ref.provider,user:ref.user,connection:ref.connection,label:summary.label,state:summary.state};
}
export async function integrationSnapshot(selector:ConnectionSelector={}){
const state=await readIntegrationState();let user:string|null=null;try{user=resolveUser(state,selector);}catch(e){if(selector.user)throw e;}
const profiles=Object.values(state.users).map(u=>({id:u.id,label:u.label,isDefault:state.defaultUser===u.id,connectionCount:Object.values(u.connections).reduce((n,rows)=>n+Object.keys(rows).length,0)}));
const connections=user?Object.values(state.users[user].connections).flatMap(rows=>Object.values(rows).map(c=>summaryIn(state,user!,c))):[];
return{version:2,variables:state.variables??{},users:profiles,user,bindings:state.bindings,connections,resolution:user?(selector.user?"explicit":folderBinding(state,selector.cwd)?"folder":"default"):"choose-user"};
}
export function createConnectionIn(state:IntegrationState,input:{user:string;provider:string;connection:string;label?:string;source?:ConnectionSource;authMethod?:string;makeDefault?:boolean}){
const user=identity(input.user,"user"),provider=identity(input.provider,"provider"),id=identity(input.connection,"connection"),profile=state.users[user];if(!profile)throw new IntegrationError("user_not_found",404);
const source=input.source??"direct",method=connectionMethod(provider,source,input.authMethod),rows=profile.connections[provider]??{};
if(Object.hasOwn(rows,id))throw new IntegrationError("connection_exists",409);
const c:IntegrationConnection={id,uid:randomUUID(),label:connectionLabel(input.label??id),provider,source,authMethod:method.id,scope:method.scope,revision:1,values:{},createdAt:Date.now(),updatedAt:Date.now()};
profile.connections[provider]={...rows,[id]:c};if(input.makeDefault||!Object.keys(rows).length)profile.defaults[provider]=id;return c;
}
export async function credentialSnapshot(provider:string,selector:ConnectionSelector){
const state=await readIntegrationState(),r=selectConnection(state,provider,selector);
if(r.connection.source!=="direct")throw new IntegrationError("external_secrets_forbidden",409);if(r.connection.sharedFrom)throw new IntegrationError("shared_alias_readonly",409);
return{user:r.user,connection:structuredClone(r.connection)};
}
export async function saveConnectionValues(provider:string,selector:ConnectionSelector,values:Record<string,unknown>,expected:{uid:string;revision:number},verified=true){
return mutateIntegrationState(state=>{
const r=selectConnection(state,provider,selector),c=r.connection;assertNotBusy(c);if(c.source!=="direct")throw new IntegrationError("external_secrets_forbidden",409);if(c.sharedFrom)throw new IntegrationError("shared_alias_readonly",409);
if(c.uid!==expected.uid||c.revision!==expected.revision)throw new IntegrationError("connection_changed_reopen_setup",409);
if(!isInfraProviderId(provider))throw new IntegrationError("unknown_provider",404);
const method=connectionMethod(provider,c.source,c.authMethod),allowed=new Set(method.fields.map(f=>f.key));
if(Object.keys(values).some(k=>!allowed.has(k)))throw new IntegrationError("invalid_credential_fields");
const normalized=normalizeInfraValues(provider,values),candidate={...c.values,...normalized};
if(method.fields.some(f=>f.required&&!candidate[f.key]))throw new IntegrationError("required_fields_missing");
delete c.lastCheck; clearGoogleRuntime(c); c.values=candidate;c.revision++;c.updatedAt=Date.now();if(verified&&provider!==GOOGLE_APP_PROVIDER)c.verifiedAt=Date.now();else delete c.verifiedAt;
return summaryIn(state,r.user,c);
});
}
/**
* Per-project view over the SAME store. A connection carries zero or more project
* associations, so "one deployment, several projects" is representable without a
* duplicate row. No `kind` filter: cloud and self-hosted rows come back together.
*
* `state` keeps "the deployment is down" (`deployment-unreachable`) apart from "the
* credential was rejected" (`credential-rejected`) — different operator fixes.
*/
export type ProjectProviderState = "linked-healthy" | "deployment-unreachable" | "credential-rejected" | "unverified";
export type ProjectProviderRow = {
user: string; provider: string; connection: string; label: string;
kind: "cloud" | "self-hosted" | null; scope: string; state: ProjectProviderState;
projects: string[]; projectCount: number; verifiedAt: number | null;
};
const deploymentKind=(provider:string):ProjectProviderRow["kind"]=>provider==="convex-cloud"?"cloud":provider==="convex"?"self-hosted":null;
const healthOf=(state:string):ProjectProviderState=>state==="verified"?"linked-healthy":state==="unavailable"?"deployment-unreachable":state==="invalid"?"credential-rejected":"unverified";
const isProjectKey=(value:unknown):value is string=>{try{projectKey(value);return true;}catch{return false;}};
export async function projectProviderQuery(input:{project?:string;selector?:ConnectionSelector}={}){
const state=await readIntegrationState(),project=input.project;
const users=input.selector?.user?[identity(input.selector.user,"user")]:Object.keys(state.users);
const rows:ProjectProviderRow[]=users.filter(u=>Object.hasOwn(state.users,u)).flatMap(user=>
Object.values(state.users[user].connections).flatMap(connections=>
Object.values(connections).map(c=>{
// The store validator does not own this additive field, so re-validate here:
// a hand-edited or foreign state file cannot smuggle an arbitrary string out.
const summary=summaryIn(state,user,c),projects=[...new Set((c.projects??[]).filter(isProjectKey))].sort();
return{user,provider:c.provider,connection:c.id,label:summary.label,kind:deploymentKind(c.provider),scope:c.scope,state:healthOf(String(summary.state)),projects,projectCount:projects.length,verifiedAt:c.verifiedAt??null};
})
)
).filter(row=>!project||row.projects.includes(project));
return{...(project?{project}:{}),providers:rows.sort((a,b)=>a.provider.localeCompare(b.provider)||a.connection.localeCompare(b.connection))};
}
/** Idempotent association write; the linker decides, this only stores. */
export async function setConnectionProjects(userInput:string,provider:string,connectionId:string,projects:string[]){
const want=[...new Set(projects.map(projectKey))].sort();
return mutateIntegrationState(state=>{
const user=identity(userInput,"user"),r=selectConnection(state,provider,{user,connection:identity(connectionId,"connection")});
if(r.connection.sharedFrom)throw new IntegrationError("shared_alias_readonly",409);
const previous=[...(r.connection.projects??[])].sort();
if(JSON.stringify(previous)!==JSON.stringify(want)){r.connection.projects=want;r.connection.updatedAt=Date.now();}
return{user,provider,connection:r.connection.id,projects:want,changed:JSON.stringify(previous)!==JSON.stringify(want)};
});
}
export async function integrationQuery(input:Record<string,unknown>){
metadataOnly(input);const allowed=["view","user","provider","connection","cwd","source","authMethod","project"];
if(Object.keys(input).some(k=>!allowed.includes(k)))throw new IntegrationError("invalid_query_fields");
const selection=input as ConnectionSelector,view=input.view??"snapshot";
if(view==="catalog")return{catalog:connectionCatalog()};
if(view==="projects")return projectProviderQuery({project:input.project===undefined?undefined:projectKey(input.project),selector:selection});
if(view==="resolve")return resolveIntegration(identity(input.provider,"provider"),selection);
if(view==="request"){
const provider=identity(input.provider,"provider");const catalog=connectionCatalog().find(p=>p.id===provider);if(!catalog)throw new IntegrationError("unknown_provider",404);
if(!input.connection)return{provider,user:input.user??null,sources:catalog.sources,next:"choose named connection, source and auth; never pass keys through tool JSON"};
const route=await resolveIntegration(provider,selection);return{...route,guidance:connectionMethod(provider,route.source,route.authMethod).guidance,next:isGoogleProvider(provider)?"Open native MSO Integrations to bind an OAuth app and authorize Google; never paste user tokens":route.source==="direct"?"integration_setup_open with this user and connection":route.source==="composio"?"authorize, then sync until ACTIVE":"authorize the provider-owned MCP in your client"};
}
if(!["snapshot","variables","users","connections","which"].includes(String(view)))throw new IntegrationError("unknown_query_view");
const out=await integrationSnapshot(selection);if(view==="variables")return{variables:out.variables};if(view==="users")return{users:out.users,user:out.user};if(view==="which")return{user:out.user,resolution:out.resolution,bindings:out.bindings};if(view==="connections")return{user:out.user,connections:out.connections.filter(c=>!input.provider||c.provider===input.provider)};return out;
}