Skip to content

armgit / mso

Public Imported from GitHub
0

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

feat(integrations): workspace-scoped demo logins and on-demand secret reveal (#150)

Abdurrahman Fakhrulb1fdcd8de286
diff --git a/app/api/v1/integrations/route.ts b/app/api/v1/integrations/route.ts
index 26b08027..00c866dd 100644
--- a/app/api/v1/integrations/route.ts
+++ b/app/api/v1/integrations/route.ts
@@ -1,22 +1,40 @@
import { NextRequest, NextResponse } from "next/server";
import { getSessionContext } from "@/lib/auth/require-session";
+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";
import { readSetupJson } from "@/lib/infra/setup-http";
import { queryIntegrationAction, manageIntegrationAction, executeIntegrationAction } from "@/lib/infra/connection-dispatch";
+import { DemoCredentialError, revealSecret } from "@/lib/infra/demo-credentials";
import { IntegrationError } from "@/lib/infra/identity";
import { audit } from "@/lib/host/audit-api";
export const runtime="nodejs";
export const dynamic="force-dynamic";
const headers={"Cache-Control":"no-store, private","Referrer-Policy":"no-referrer"};
+// Reveal is the only mode whose body carries a stored secret value, so it gets its
+// own stricter headers. Nothing else in this route may return one.
+const revealHeaders={"Cache-Control":"private, no-store","Pragma":"no-cache","Referrer-Policy":"no-referrer"};
export async function GET(req:NextRequest){
if((await getSessionContext())?.role!=="owner")return NextResponse.json({error:"owner_required"},{status:403,headers});
try{return NextResponse.json(await queryIntegrationAction(Object.fromEntries(req.nextUrl.searchParams)),{headers});}catch(e){return failure(e);}
}
function failure(e:unknown){const error=e instanceof IntegrationError?e:new IntegrationError("integration_operation_failed",400);return NextResponse.json({error:error.code},{status:error.status,headers});}
+function revealFailure(e:unknown){const error=e instanceof DemoCredentialError?e:e instanceof IntegrationError?new DemoCredentialError(e.code,e.status):new DemoCredentialError("reveal_failed",400);return NextResponse.json({error:error.code},{status:error.status,headers:revealHeaders});}
export async function POST(req:NextRequest){
const ctx=await getSessionContext();if(ctx?.role!=="owner")return NextResponse.json({error:"owner_required"},{status:403,headers});
- try{const {mode,...input}=await readSetupJson(req);if(!["manage","execute"].includes(String(mode)))throw new IntegrationError("invalid_action_mode");
+ let mode="";
+ try{
+ const body=await readSetupJson(req);mode=String(body.mode);
+ const {mode:_,...input}=body;
+ // Reveal is deliberately NOT a manage/execute action: those are exposed to the
+ // agent as MCP tools, and a reveal is a human action. It also re-checks live
+ // authorization, because a cached owner claim is not proof the device still is one.
+ if(mode==="reveal"){
+ if(!ctx.session.device_id||!(await liveSessionAuthorized(ctx.session,"owner")))throw new DemoCredentialError("owner_required",403);
+ if(Object.keys(input).some(k=>!["provider","user","connection","cwd","demoId","key"].includes(k)))throw new DemoCredentialError("invalid_reveal_fields");
+ return NextResponse.json(await revealSecret(input,{session:ctx.session,role:ctx.role,deviceId:ctx.session.device_id}),{headers:revealHeaders});
+ }
+ if(!["manage","execute"].includes(mode))throw new IntegrationError("invalid_action_mode");
const result=mode==="manage"?await manageIntegrationAction(input):await executeIntegrationAction(input);
- void audit({action:"infra.write",actor:ctx.session.device_id,target:String(input.user??"integrations"),ok:true,detail:`integrations.${String(mode)}`});
+ void audit({action:"infra.write",actor:ctx.session.device_id,target:String(input.user??"integrations"),ok:true,detail:`integrations.${mode}`});
return NextResponse.json(result,{headers});
- }catch(e){return failure(e);}
+ }catch(e){return mode==="reveal"?revealFailure(e):failure(e);}
}
diff --git a/lib/contracts/demo-credentials.ts b/lib/contracts/demo-credentials.ts
new file mode 100644
index 00000000..d4dfbe79
--- /dev/null
+++ b/lib/contracts/demo-credentials.ts
@@ -0,0 +1,22 @@
+// Shared shape for agent-created demo logins. A demo user is NOT an API credential:
+// it models a throwaway login for a site the owner asked MSO to test.
+//
+// `password` is a secret. Only the agent-side record read and the human reveal path
+// may return it; every list/summary result carries `hasPassword` instead.
+export type DemoCredentialRecord = {
+ id: string;
+ /** Credential owner resolved from the workspace folder binding. */
+ owner: string;
+ /** Canonical bound folder path that scopes this demo user. */
+ workspace: string;
+ email: string;
+ password: string;
+ label?: string;
+ site?: string;
+ notes?: string;
+ createdAt: number;
+ updatedAt: number;
+ revision: number;
+};
+
+export type DemoCredentialSummary = Omit<DemoCredentialRecord, "password"> & { hasPassword: true };
diff --git a/lib/infra/connection-dispatch.ts b/lib/infra/connection-dispatch.ts
index e528151d..dcdab958 100644
--- a/lib/infra/connection-dispatch.ts
+++ b/lib/infra/connection-dispatch.ts
@@ -14,7 +14,11 @@ import { callNamedMcpConnectionTool, listNamedMcpConnectionTools } from "./mcp-c
export const safeActionInput=(input:Record<string,unknown>)=>Object.fromEntries(Object.entries(input).filter(([key])=>key!=="workflow_id"));
export const selectionFrom=(a:Record<string,unknown>):ConnectionSelector=>({user:typeof a.user==="string"?a.user:undefined,connection:typeof a.connection==="string"?a.connection:undefined,cwd:typeof a.cwd==="string"?a.cwd:undefined});
export async function manageIntegrationAction(raw:Record<string,unknown>){
- const a=safeActionInput(raw);metadataOnly(a);
+ const a=safeActionInput(raw);
+ // demo.* carries a real password, so it must bypass metadataOnly; the allowlisted
+ // handler still rejects any other action that ships a secret-shaped key.
+ if(String(a.action).startsWith("demo."))return integrationManage(a);
+ metadataOnly(a);
if(a.action==="connection.import-convex-cli"){
if(a.confirm!==true)throw new IntegrationError("confirmation_required",403);
if(Object.keys(a).some(k=>!["action","confirm","user","provider","connection"].includes(k)))throw new IntegrationError("invalid_management_fields");
@@ -34,6 +38,14 @@ export async function manageIntegrationAction(raw:Record<string,unknown>){
}
export async function executeIntegrationAction(raw:Record<string,unknown>){
const a=safeActionInput(raw),operation=String(a.operation);
+ // Demo login CRUD is agent-side: no provider/connection, but a real cwd resolved by
+ // folder binding. It runs before metadataOnly because the password IS the payload.
+ if(operation.startsWith("demo.")){
+ if(Object.keys(a).some(k=>!["user","provider","connection","operation","arguments","tool","confirm"].includes(k)))throw new IntegrationError("invalid_execution_fields");
+ const demoArgs=a.arguments;if(!demoArgs||typeof demoArgs!=="object"||Array.isArray(demoArgs))throw new IntegrationError("invalid_tool_arguments");
+ // Spread first so the operation itself and the confirmation flag cannot be overridden.
+ return integrationManage({...demoArgs as Record<string,unknown>,action:operation,confirm:a.confirm===true});
+ }
if(operation==="dokploy.application.publicEnv.upsert"){
const {arguments:operationArgs,...meta}=a;metadataOnly(meta);
const args=operationArgs;if(!args||typeof args!=="object"||Array.isArray(args))throw new IntegrationError("invalid_tool_arguments");
diff --git a/lib/infra/connection-manage.ts b/lib/infra/connection-manage.ts
index 33d3c5b3..0e0db5b1 100644
--- a/lib/infra/connection-manage.ts
+++ b/lib/infra/connection-manage.ts
@@ -6,8 +6,27 @@ 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=["variable.set","variable.delete","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;
+import { createDemoCredential, listDemoCredentials, getDemoCredential, updateDemoCredential, deleteDemoCredential } from "./demo-credentials";
+// Demo logins are agent-created, workspace-scoped throwaways, not API keys: they are
+// CRUD'd through this same manager so an agent needs no second surface.
+export const DEMO_ACTIONS=["demo.create","demo.list","demo.get","demo.update","demo.delete"] as const;
+const DEMO_FIELDS:Record<string,string[]>={"demo.create":["cwd","email","password","label","site","notes"],"demo.list":["cwd"],"demo.get":["cwd","id"],"demo.update":["cwd","id","email","password","label","site","notes"],"demo.delete":["cwd","id"]};
+/** The password is a real secret, so these actions run BEFORE metadataOnly: every
+ * other action keeps rejecting secret-shaped keys. */
+export async function runDemoAction(action:string,input:Record<string,unknown>){
+ const allowed=DEMO_FIELDS[action];if(!allowed)throw new IntegrationError("invalid_management_fields");
+ if(Object.keys(input).some(k=>!["action","confirm",...allowed].includes(k)))throw new IntegrationError("invalid_management_fields");
+ if(action!=="demo.list"&&action!=="demo.get"&&input.confirm!==true)throw new IntegrationError("confirmation_required",403);
+ if(action==="demo.create")return createDemoCredential(input);
+ if(action==="demo.list")return listDemoCredentials(input);
+ if(action==="demo.get")return getDemoCredential(input);
+ if(action==="demo.update")return updateDemoCredential(input);
+ return deleteDemoCredential(input);
+}
+export const INTEGRATION_ACTIONS=["variable.set","variable.delete","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",...DEMO_ACTIONS] as const;
export async function integrationManage(input:Record<string,unknown>){
+ const requested=String(input.action);
+ if((DEMO_ACTIONS as readonly string[]).includes(requested))return runDemoAction(requested,input);
metadataOnly(input);if(input.confirm!==true)throw new IntegrationError("confirmation_required",403);
const shapes:Record<string,string[]>={
"variable.set":["key","user","provider","connection"],"variable.delete":["key"],
diff --git a/lib/infra/connection-ui-layout.test.ts b/lib/infra/connection-ui-layout.test.ts
index b9314a29..11fcfbec 100644
--- a/lib/infra/connection-ui-layout.test.ts
+++ b/lib/infra/connection-ui-layout.test.ts
@@ -24,8 +24,7 @@ it("keeps transfer inside the selected detail pane when the browser bridge suppo
});
it("keeps AI Providers on the existing AI config/runtime SSOT and browser-only credential bridge", () => {
- expect(() => new Function(CONNECTION_MANAGER_SCRIPT)).not.toThrow();
- expect(CONNECTION_MANAGER_SCRIPT).toContain("same AI runtime/config store as Settings");
+ expect(() => new Function(CONNECTION_MANAGER_SCRIPT)).not.toThrow(); expect(CONNECTION_MANAGER_SCRIPT).toContain("same AI runtime/config store as Settings");
expect(CONNECTION_MANAGER_SCRIPT).toContain("Integration Variables");
expect(CONNECTION_MANAGER_SCRIPT).toContain("~typesafe/jev-latest");
expect(CONNECTION_MANAGER_SCRIPT).toContain("same OpenRouter key managed here and in Settings");
@@ -45,3 +44,18 @@ it("keeps AI Providers on the existing AI config/runtime SSOT and browser-only c
expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiOauth=body=>json("/api/oauth/openai"');
expect(INTEGRATION_BROWSER_SCRIPT).toContain('bridge.aiRemove=provider=>json("/api/config?provider="');
});
+
+it("exposes the demo-user panel and a reveal-only secret control", () => {
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('["demo-users","Demo users",showDemoUsers]');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('operation:"demo.create"');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('operation:"demo.list"');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('operation:"demo.delete"');
+ // Reveal is fetched on demand only: one mode, no value carried on panel load.
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('"/api/v1/integrations"');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('mode:"reveal"');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('navigator.clipboard.writeText');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('"Revealed — this read is logged."');
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('setTimeout(clear,30000)');
+ // The demo password is masked until asked for, exactly like a stored key.
+ expect(CONNECTION_MANAGER_SCRIPT).toContain('secretControl({demoId:row.id,key:"password"');
+});
diff --git a/lib/infra/connection-ui.ts b/lib/infra/connection-ui.ts
index b328f7da..12af5ad0 100644
--- a/lib/infra/connection-ui.ts
+++ b/lib/infra/connection-ui.ts
@@ -36,6 +36,21 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
function showTransfer(){navMode="transfer";activateNav(navMode);setSidebar(false);if(bridge.mountTransfer)bridge.mountTransfer(detail,()=>{navMode="provider";activateNav(navMode);drawProvider()});else if(bridge.openTransfer)bridge.openTransfer();else bridge.openTransferBrowser?.()}
function showProjectMcp(){navMode="project-mcp";activateNav(navMode);setSidebar(false);mountProjectMcpForm(detail,bridge,snapshot,user,status,()=>{navMode="provider";activateNav(navMode);drawProvider()},{n,b,input})}
function showVariables(){navMode="variables";activateNav(navMode);setSidebar(false);variables()}
+ function showDemoUsers(){navMode="demo-users";activateNav(navMode);setSidebar(false);void demoUsers()}
+ // Reveal is a human action: it is the one request that may carry a stored secret,
+ // and the server audits every attempt. Never called on panel load.
+ async function reveal(body){const r=await fetch("/api/v1/integrations",{method:"POST",credentials:"same-origin",cache:"no-store",referrerPolicy:"no-referrer",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"reveal",...body})});const data=await r.json().catch(()=>({}));if(!r.ok)throw Object.assign(new Error(data.error||"reveal_failed"),{code:data.error});return data}
+ // Masked value + eye toggle + copy. The value is fetched only when the human asks,
+ // re-masks on toggle-off and after a timeout.
+ function secretControl(body,label){
+ const wrap=n("span",undefined,"identity-secret"),shown=n("code","••••••••","identity-secret-value"),note=n("small","","identity-muted");let value=null,timer;
+ const clear=()=>{value=null;shown.textContent="••••••••";eye.textContent="Reveal";note.textContent="";clearTimeout(timer)};
+ const fetchValue=async()=>{if(value!==null)return value;const data=await reveal(body);if(typeof data.value!=="string")throw new Error("reveal_failed");value=data.value;return value};
+ const eye=b("Reveal",async()=>{if(value!==null){clear();return}try{const next=await fetchValue();shown.textContent=next;eye.textContent="Hide";note.textContent="Revealed — this read is logged.";timer=setTimeout(clear,30000)}catch(e){clear();status.textContent=textError(e)}},"identity-secret-toggle");
+ const copy=b("Copy",async()=>{try{await navigator.clipboard.writeText(await fetchValue());note.textContent="Copied — this read is logged.";timer=setTimeout(clear,30000)}catch(e){status.textContent=textError(e)}},"identity-secret-copy");
+ eye.setAttribute("aria-label","Reveal "+label);copy.setAttribute("aria-label","Copy "+label);
+ wrap.append(shown,eye,copy,note);return wrap;
+ }
function showAiProviders(){navMode="ai-providers";activateNav(navMode);setSidebar(false);void aiProviders()}
function selectProvider(p){provider=p;navMode="provider";remember();activateNav(navMode);setSidebar(false);drawProvider()}
function draw(){
@@ -55,11 +70,12 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
["owners","Credential owners",showProfiles],
["ai-providers","AI Providers",showAiProviders],
["variables","Variables",showVariables],
+ ["demo-users","Demo users",showDemoUsers],
["routing","Project routing",showBindings],
["transfer","Transfer & backup",showTransfer],
["project-mcp","Add project MCP",showProjectMcp],
];
- for(const [mode,label,fn] of management){const item=b(label,fn,"integration-nav-item integration-nav-utility");if((mode==="owners"||mode==="routing")&&!bridge.manage)item.disabled=true;if(mode==="transfer"&&!bridge.openTransfer&&!bridge.openTransferBrowser)item.disabled=true;if(mode==="project-mcp"&&!bridge.projectMcp)item.disabled=true;navButtons.push({mode,provider:null,button:item});manageGroup.append(item)}
+ for(const [mode,label,fn] of management){const item=b(label,fn,"integration-nav-item integration-nav-utility");if((mode==="owners"||mode==="routing")&&!bridge.manage)item.disabled=true;if(mode==="demo-users"&&(!bridge.manage||!bridge.execute))item.disabled=true;if(mode==="transfer"&&!bridge.openTransfer&&!bridge.openTransferBrowser)item.disabled=true;if(mode==="project-mcp"&&!bridge.projectMcp)item.disabled=true;navButtons.push({mode,provider:null,button:item});manageGroup.append(item)}
nav.append(connectionGroup,manageGroup);sidebarPanel.append(nav);
const sidebarFooter=n("div",undefined,"integration-sidebar-footer"),refresh=b("Refresh",reload);sidebarFooter.append(refresh);sidebarPanel.append(sidebarFooter);
search.addEventListener("input",()=>{const q=search.value.trim().toLowerCase();for(const entry of navButtons){if(entry.mode!=="provider")continue;const p=catalog.find(row=>row.id===entry.provider);entry.button.hidden=Boolean(q)&&!(p.title+" "+p.id).toLowerCase().includes(q)}});
@@ -69,7 +85,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
detail=n("section",undefined,"identity-detail integration-settings-detail");status=n("p",undefined,"identity-feedback");status.setAttribute("role","status");status.setAttribute("aria-live","polite");content.append(detail,status);
shell.append(sidebarPanel,sidebarBackdrop,content);root.append(shell);container=shell;
activateNav(navMode);
- if(navMode==="owners")profiles();else if(navMode==="variables")variables();else if(navMode==="ai-providers")void aiProviders();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();
+ if(navMode==="owners")profiles();else if(navMode==="variables")variables();else if(navMode==="demo-users")void demoUsers();else if(navMode==="ai-providers")void aiProviders();else if(navMode==="routing")bindings();else if(navMode==="project-mcp")showProjectMcp();else drawProvider();
}
function confirmation(title,id,fn){detail.replaceChildren(n("h2",title),n("p","This changes only the selected identity. Type “"+id+"” to confirm."));const value=input("Confirmation");detail.append(value.label,b("Confirm",()=>{if(value.input.value!==id){status.textContent="Confirmation does not match.";return}void fn()},"danger"),b("Cancel",()=>{navMode="provider";activateNav(navMode);drawProvider()}));}
function profiles(){
@@ -103,6 +119,31 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const fields=n("div",undefined,"identity-fields");fields.append(key.label,providerLabel,connectionLabel);editor.append(fields);
const save=b("Save variable",()=>{if(!key.input.value||!connectionSelect.value){status.textContent="Choose a variable name and named connection.";return}void change({action:"variable.set",key:key.input.value,user,provider:providerSelect.value,connection:connectionSelect.value})},"primary");save.disabled=!bridge.manage;editor.append(save);detail.append(editor);
}
+ async function demoUsers(){
+ detail.replaceChildren(n("h2","Demo users"),n("p","Throwaway logins the agent may create to test a site in this project. Scoped by the project folder’s credential binding; passwords are never listed, only revealed on demand."));
+ const bindings=Array.isArray(snapshot.bindings)?snapshot.bindings:[];
+ if(!bindings.length){detail.append(n("p","Bind a project folder to a credential owner under Project routing first.","identity-muted"));return}
+ const folder=n("select"),folderLabel=n("label","Project folder");folderLabel.append(folder);
+ for(const binding of bindings){const o=n("option",binding.path);o.value=binding.path;folder.append(o)}
+ if(initial.cwd&&bindings.some(b=>b.path===initial.cwd))folder.value=initial.cwd;
+ detail.append(folderLabel);
+ const cards=n("div");detail.append(cards);
+ const emailInput=input("Demo email","","email"),passwordInput=input("Password","","password"),labelInput=input("Label (optional)"),siteInput=input("Site / URL (optional)"),notesInput=input("Notes (optional)");
+ passwordInput.input.autocomplete="new-password";
+ const create=b("Create demo user",async()=>{try{status.textContent="Saving demo user…";await bridge.execute({operation:"demo.create",confirm:true,arguments:{cwd:folder.value,email:emailInput.input.value,password:passwordInput.input.value,label:labelInput.input.value||undefined,site:siteInput.input.value||undefined,notes:notesInput.input.value||undefined}});passwordInput.input.value="";status.textContent="Demo user saved.";await demoUsers()}catch(e){status.textContent=textError(e)}},"primary");
+ create.disabled=!bridge.manage;
+ const editor=n("div",undefined,"connection-card");editor.append(n("h3","New demo user"),emailInput.label,passwordInput.label,labelInput.label,siteInput.label,notesInput.label,create);detail.append(editor);
+ const list=async()=>{try{const out=await bridge.execute({operation:"demo.list",arguments:{cwd:folder.value}}),rows=Array.isArray(out.demoUsers)?out.demoUsers:[];cards.replaceChildren();
+ if(!rows.length){cards.append(n("p","No demo users for this project yet.","identity-muted"));return}
+ for(const row of rows){const card=n("article",undefined,"connection-card"),top=n("header",undefined,"connection-heading"),copy=n("div");copy.append(n("h3",row.label||row.email),n("small",row.email+(row.site?" · "+row.site:"")));top.append(copy,n("span","Demo user","connection-state"));card.append(top);
+ const creds=n("div",undefined,"identity-credential-status"),emailLine=n("div"),emailCopy=b("Copy email",async()=>{try{await navigator.clipboard.writeText(row.email);status.textContent="Email copied."}catch(e){status.textContent=textError(e)}});emailLine.append(n("span","Email"),n("span",row.email,"credential-field-state"),emailCopy);creds.append(emailLine);
+ const passwordLine=n("div");passwordLine.append(n("span","Password"),secretControl({demoId:row.id,key:"password",cwd:folder.value},"demo password"));creds.append(passwordLine);
+ if(row.notes)card.append(n("p",row.notes,"identity-muted"));
+ card.append(creds);
+ const actions=n("div",undefined,"identity-actions"),del=b("Delete",()=>confirmation("Delete demo user",row.id,async()=>{try{await bridge.execute({operation:"demo.delete",confirm:true,arguments:{cwd:folder.value,id:row.id}});await demoUsers()}catch(e){status.textContent=textError(e)}}),"danger");del.disabled=!bridge.manage;actions.append(del);card.append(actions);cards.append(card)}
+ }catch(e){status.textContent=textError(e)}};
+ folder.addEventListener("change",()=>void list());await list();
+ }
async function aiProviders(){
detail.replaceChildren(n("h2","AI Providers"),n("p","Configure Alfa’s active model provider here. This view uses the same AI runtime/config store as Settings; it does not create another credential registry."));
if(!bridge.aiConfig||!bridge.aiCatalog||!bridge.aiModels||!bridge.aiSave){
@@ -139,7 +180,7 @@ function mountConnectionManager(root,catalog,bridge,initial={}){
const open=b(c.source==="direct"?(c.fields.some(f=>f.stored)?"Update credentials":"Finish setup"):"Authorize",()=>{if(c.source==="direct")void bridge.openSetup({user,provider:provider.id,connection:c.id}).catch(e=>status.textContent=textError(e));else external(c)});open.disabled=!bridge.manage;if(!c.sharedFrom)actions.append(open);
const verify=b("Verify",async()=>{try{status.textContent="Checking selected connection…";const result=await bridge.execute({user,provider:provider.id,connection:c.id,operation:"verify"});await reload();status.textContent=(result.ok===true?"Verified: ":"Status: ")+result.detail}catch(e){status.textContent=textError(e)}});verify.disabled=!bridge.execute;actions.append(verify);
const rename=b("Rename",()=>{detail.replaceChildren(n("h2","Rename connection"));const name=input("Label",c.label);detail.append(name.label,b("Save label",()=>change({action:"connection.rename",user,provider:provider.id,connection:c.id,label:name.input.value})),b("Cancel",()=>{navMode="provider";activateNav(navMode);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.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){line.append(secretControl({user,provider:provider.id,connection:c.id,key:f.key},f.label));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"&&!provider.nativeGoogle){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);
diff --git a/lib/infra/demo-credentials.test.ts b/lib/infra/demo-credentials.test.ts
new file mode 100644
index 00000000..1609784d
--- /dev/null
+++ b/lib/infra/demo-credentials.test.ts
@@ -0,0 +1,212 @@
+import {beforeEach,afterEach,it,expect,vi} from "vitest";
+import {constants,promises as fs} from "node:fs";
+import os from "node:os";
+import path from "node:path";
+import type {DemoCredentialSummary} from "./demo-credentials";
+// `integrationManage` returns the union of every action's result; these tests know which one they called.
+type DemoList={demoUsers:DemoCredentialSummary[]};
+vi.mock("server-only",()=>({}));
+// Live authorization is exercised for real in the route; here we assert this layer refuses when it says no.
+const liveAuth=vi.hoisted(()=>({allowed:true}));
+vi.mock("@/lib/auth/live-authorization",()=>({liveSessionAuthorized:async()=>liveAuth.allowed}));
+const session=vi.hoisted(()=>({role:"owner" as string|null,device:"test-device"}));
+vi.mock("@/lib/auth/require-session",()=>({getSessionContext:async()=>session.role?{role:session.role,session:{device_id:session.device}}:null}));
+const DEMO_PASSWORD="not-a-real-password-123",OTHER_PASSWORD="also-not-real-password-456",EMAIL="[email protected]";
+let root:string,storeFile:string;
+
+beforeEach(async()=>{
+ liveAuth.allowed=true;root=await fs.mkdtemp(path.join(os.tmpdir(),"mso-demo-credentials-"));
+ // The demo store is a sibling of the infra store inside this private sandbox.
+ process.env.OS_INFRA_STORE=path.join(root,"infra.json");storeFile=path.join(root,"demo-credentials.json");
+ process.env.OS_AUDIT_LOG=path.join(root,"audit.log");vi.resetModules();
+});
+afterEach(async()=>{
+ delete process.env.OS_INFRA_STORE;delete process.env.OS_AUDIT_LOG;await fs.rm(root,{recursive:true,force:true});vi.resetModules();
+});
+
+/** One folder binding per owner is the only workspace source: no free-form workspace. */
+async function fixture(){
+ const {integrationManage:manage}=await import("./connection-manage");
+ await manage({action:"user.create",user:"alice",confirm:true});
+ await manage({action:"user.create",user:"bob",confirm:true});
+ const aliceDir=path.join(root,"project-alice"),bobDir=path.join(root,"project-bob");
+ await fs.mkdir(aliceDir,{recursive:true});await fs.mkdir(bobDir,{recursive:true});
+ await manage({action:"folder.map",user:"alice",path:aliceDir,confirm:true});
+ await manage({action:"folder.map",user:"bob",path:bobDir,confirm:true});
+ return{manage,aliceDir,bobDir};
+}
+
+it("creates, lists, reads, updates and deletes a demo login, bumping revision",async()=>{
+ const f=await fixture(),demo=await import("./demo-credentials");
+ const created=await f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD,label:"Checkout smoke",site:"https://shop.example.test"}) as unknown as DemoCredentialSummary;
+ expect(created).toMatchObject({email:EMAIL,label:"Checkout smoke",hasPassword:true,revision:1});
+ expect(JSON.stringify(created)).not.toContain(DEMO_PASSWORD);
+
+ const full=await demo.getDemoCredential({cwd:f.aliceDir,id:created.id});
+ expect(full.password).toBe(DEMO_PASSWORD);expect(full.owner).toBe("alice");
+
+ const listed=await f.manage({action:"demo.list",cwd:f.aliceDir}) as unknown as DemoList;
+ expect(listed.demoUsers).toHaveLength(1);
+ expect(JSON.stringify(listed)).not.toContain(DEMO_PASSWORD);
+
+ const updated=await f.manage({action:"demo.update",confirm:true,cwd:f.aliceDir,id:created.id,password:OTHER_PASSWORD,notes:"rotated"}) as unknown as DemoCredentialSummary;
+ expect(updated.revision).toBe(2);expect(updated.notes).toBe("rotated");
+ expect((await demo.getDemoCredential({cwd:f.aliceDir,id:created.id})).password).toBe(OTHER_PASSWORD);
+
+ await f.manage({action:"demo.delete",confirm:true,cwd:f.aliceDir,id:created.id});
+ expect(((await f.manage({action:"demo.list",cwd:f.aliceDir})) as unknown as DemoList).demoUsers).toHaveLength(0);
+ await expect(demo.getDemoCredential({cwd:f.aliceDir,id:created.id})).rejects.toMatchObject({code:"demo_credential_not_found"});
+});
+
+it("rejects duplicate emails, bad input, and a cwd with no folder binding",async()=>{
+ const f=await fixture(),demo=await import("./demo-credentials");
+ await f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD});
+ await expect(f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD})).rejects.toMatchObject({code:"demo_credential_exists"});
+ await expect(f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:"not-an-email",password:DEMO_PASSWORD})).rejects.toMatchObject({code:"invalid_demo_email"});
+ await expect(f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:"two [email protected]",password:DEMO_PASSWORD})).rejects.toMatchObject({code:"invalid_demo_email"});
+ await expect(f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:"[email protected]",password:"has\nnewline"})).rejects.toMatchObject({code:"invalid_demo_password"});
+ await expect(f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:"[email protected]",password:"nul\u0000inside"})).rejects.toMatchObject({code:"invalid_demo_password"});
+ const unbound=path.join(root,"unbound-project");await fs.mkdir(unbound,{recursive:true});
+ await expect(f.manage({action:"demo.list",cwd:unbound})).rejects.toMatchObject({code:"workspace_folder_not_bound"});
+ await expect(demo.listDemoCredentials({})).rejects.toMatchObject({code:"workspace_cwd_required"});
+});
+
+it("never lists, reads, updates or deletes owner A's demo login as owner B",async()=>{
+ const f=await fixture(),demo=await import("./demo-credentials");
+ const created=await f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD}) as unknown as DemoCredentialSummary;
+ expect(((await f.manage({action:"demo.list",cwd:f.bobDir})) as unknown as DemoList).demoUsers).toHaveLength(0);
+ for(const call of[
+ ()=>demo.getDemoCredential({cwd:f.bobDir,id:created.id}),
+ ()=>f.manage({action:"demo.update",confirm:true,cwd:f.bobDir,id:created.id,password:OTHER_PASSWORD}),
+ ()=>f.manage({action:"demo.delete",confirm:true,cwd:f.bobDir,id:created.id}),
+ ])await expect(call()).rejects.toMatchObject({code:"demo_credential_not_found"});
+ // Still intact for the real owner and unchanged by B's attempts.
+ expect((await demo.getDemoCredential({cwd:f.aliceDir,id:created.id})).password).toBe(DEMO_PASSWORD);
+});
+
+it("stores the file 0600 inside a 0700 directory, read through one handle",async()=>{
+ const f=await fixture();await f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD});
+ // ONE handle for mode and content: stat-then-read on a path is js/file-system-race.
+ const handle=await fs.open(storeFile,constants.O_RDONLY|constants.O_NOFOLLOW);
+ try{const stat=await handle.stat(),raw=await handle.readFile("utf8");expect(stat.mode&0o777).toBe(0o600);expect(raw).toContain(EMAIL);}finally{await handle.close();}
+ expect((await fs.stat(root)).mode&0o777).toBe(0o700);
+});
+
+it("refuses a symlinked store instead of following it",async()=>{
+ const f=await fixture(),demo=await import("./demo-credentials"),outside=path.join(root,"outside.json");
+ await fs.writeFile(outside,JSON.stringify({version:1,records:[]}),{mode:0o600});
+ await fs.symlink(outside,storeFile);
+ await expect(demo.listDemoCredentials({cwd:f.aliceDir})).rejects.toMatchObject({code:"invalid_or_unsafe_demo_store"});
+});
+
+it("refuses a secret-shaped key on the generic management actions",async()=>{
+ const f=await fixture();
+ // Only the demo.* actions accept a password; every other action keeps metadataOnly.
+ await expect(f.manage({action:"user.create",confirm:true,user:"carol",password:DEMO_PASSWORD})).rejects.toMatchObject({code:"secret_input_forbidden"});
+ await expect(f.manage({action:"connection.create",confirm:true,user:"alice",provider:"cloudflare",connection:"dns",password:DEMO_PASSWORD})).rejects.toMatchObject({code:"secret_input_forbidden"});
+});
+
+const A_KEY="synthetic_cloudflare_token_alice_0123456789",B_KEY="synthetic_cloudflare_token_bob_0123456789";
+/** A direct connection with one secret field and one non-secret field. */
+async function withCredentials(){
+ const f=await fixture(),service=await import("./connection-service");
+ for(const [user,key]of[["alice",A_KEY],["bob",B_KEY]]as const){
+ await f.manage({action:"connection.create",confirm:true,user,provider:"cloudflare",connection:"dns",authMethod:"direct"});
+ const snap=await service.credentialSnapshot("cloudflare",{user,connection:"dns"});
+ await service.saveConnectionValues("cloudflare",{user,connection:"dns"},{apiToken:key,zoneId:"0123456789abcdef0123456789abcdef"},snap.connection);
+ }
+ return{...f,service};
+}
+const actorFor=(deviceId="test-device")=>({session:{device_id:deviceId} as never,role:"owner" as const,deviceId});
+
+it("reveals only the requested secret field for its owner",async()=>{
+ const f=await withCredentials(),demo=await import("./demo-credentials");void f;
+ const out=await demo.revealSecret({user:"alice",provider:"cloudflare",connection:"dns",key:"apiToken"},actorFor());
+ expect(out).toEqual({key:"apiToken",value:A_KEY});
+ const audited=await import("@/lib/host/audit");await audited.audit({action:"infra.write"}); // flush chain
+ const trail=await (await import("@/lib/host/audit-api")).readAuditTail({prefix:"infra.write"});
+ expect(trail.some(row=>row.ok===true&&row.detail?.includes("secret-reveal"))).toBe(true);
+ expect(JSON.stringify(trail)).not.toContain(A_KEY);
+});
+
+it("refuses a non-secret or unknown field, another owner, and a shared alias",async()=>{
+ const f=await withCredentials(),demo=await import("./demo-credentials");
+ // zoneId is not secret:true, and "nope" does not exist; both look identical.
+ await expect(demo.revealSecret({user:"alice",provider:"cloudflare",connection:"dns",key:"zoneId"},actorFor())).rejects.toMatchObject({code:"secret_field_not_revealable",status:404});
+ await expect(demo.revealSecret({user:"alice",provider:"cloudflare",connection:"dns",key:"nope"},actorFor())).rejects.toMatchObject({code:"secret_field_not_revealable",status:404});
+ await f.manage({action:"connection.create",confirm:true,user:"alice",provider:"cloudflare",connection:"alice-only",authMethod:"direct"});
+ // bob's own connection is "dns"; "alice-only" exists only for alice, so bob cannot
+ // address it and the refusal is the same generic one as an unknown field.
+ await expect(demo.revealSecret({user:"bob",provider:"cloudflare",connection:"alice-only",key:"apiToken"},actorFor())).rejects.toMatchObject({code:"secret_field_not_revealable"});
+ await f.manage({action:"connection.share",confirm:true,user:"alice",provider:"cloudflare",connection:"dns",target:"bob",label:"shared"});
+ const alias=(await f.service.integrationSnapshot({user:"bob"})).connections.find(c=>c.sharedFrom);
+ await expect(demo.revealSecret({user:"bob",provider:"cloudflare",connection:alias!.id,key:"apiToken"},actorFor())).rejects.toMatchObject({code:"shared_alias_readonly",status:409});
+});
+
+it("audits every refusal and trips the per-device rate limit",async()=>{
+ const f=await withCredentials(),demo=await import("./demo-credentials"),auditApi=await import("@/lib/host/audit-api");void f;
+ for(let i=0;i<3;i++)await expect(demo.revealSecret({user:"alice",provider:"cloudflare",connection:"dns",key:"zoneId"},actorFor("device-refuse"))).rejects.toMatchObject({code:"secret_field_not_revealable"});
+ const refusals=(await auditApi.readAuditTail({prefix:"infra.write"})).filter(row=>row.actor==="device-refuse"&&row.ok===false);
+ expect(refusals.length).toBeGreaterThanOrEqual(3);
+ // 5 reads per 60s per device+connection, refusals included.
+ let limited=false;
+ for(let i=0;i<6;i++){try{await demo.revealSecret({user:"alice",provider:"cloudflare",connection:"dns",key:"apiToken"},actorFor("device-limit"));}catch(e){limited=(e as {code?:string}).code==="rate_limited";break}}
+ expect(limited).toBe(true);
+});
+
+it("keeps connectionSummary free of stored values",async()=>{
+ const f=await withCredentials(),{connectionSummary}=await import("./connection-registry"),{readIntegrationState}=await import("./connection-storage");
+ const state=await readIntegrationState(),connection=state.users.alice.connections.cloudflare.dns;
+ const summary=connectionSummary("alice",connection);
+ const text=JSON.stringify(summary);
+ expect(text).not.toContain(A_KEY);expect(text).not.toContain("0123456789abcdef0123456789abcdef");
+ expect(summary.fields.every(field=>!Object.hasOwn(field,"value"))).toBe(true);
+ expect(summary.fields.find(field=>field.key==="apiToken")?.stored).toBe(true);
+ // A full snapshot is the many-path summary surface: it must not carry the value either.
+ expect(JSON.stringify(await f.service.integrationSnapshot({user:"alice"}))).not.toContain(A_KEY);
+});
+
+it("reveals a demo password and nothing else from the demo record",async()=>{
+ const f=await fixture(),demo=await import("./demo-credentials");
+ const created=await f.manage({action:"demo.create",confirm:true,cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD}) as unknown as DemoCredentialSummary;
+ expect(await demo.revealSecret({cwd:f.aliceDir,demoId:created.id,key:"password"},actorFor())).toEqual({key:"password",value:DEMO_PASSWORD});
+ await expect(demo.revealSecret({cwd:f.aliceDir,demoId:created.id,key:"email"},actorFor())).rejects.toMatchObject({code:"secret_field_not_revealable"});
+ await expect(demo.revealSecret({cwd:f.bobDir,demoId:created.id,key:"password"},actorFor())).rejects.toMatchObject({code:"secret_field_not_revealable"});
+});
+
+it("is reachable from the agent-side dispatch, and only demo.* bypasses metadataOnly",async()=>{
+ const f=await fixture(),dispatch=await import("./connection-dispatch");
+ const created=await dispatch.executeIntegrationAction({operation:"demo.create",confirm:true,arguments:{cwd:f.aliceDir,email:EMAIL,password:DEMO_PASSWORD}}) as unknown as DemoCredentialSummary;
+ expect(created.hasPassword).toBe(true);
+ expect(JSON.stringify(await dispatch.executeIntegrationAction({operation:"demo.list",arguments:{cwd:f.aliceDir}}))).not.toContain(DEMO_PASSWORD);
+ const full=await dispatch.executeIntegrationAction({operation:"demo.get",arguments:{cwd:f.aliceDir,id:created.id}}) as unknown as {password:string};
+ expect(full.password).toBe(DEMO_PASSWORD);
+ // The human reveal operation is not an agent operation.
+ await expect(dispatch.executeIntegrationAction({operation:"secret.reveal",arguments:{key:"password"}})).rejects.toThrow();
+ // A non-demo action still refuses secret-shaped input on both paths.
+ await expect(dispatch.executeIntegrationAction({operation:"verify",password:DEMO_PASSWORD,user:"alice",provider:"cloudflare",connection:"dns"})).rejects.toMatchObject({code:"secret_input_forbidden"});
+ await expect(dispatch.manageIntegrationAction({action:"demo.create",cwd:f.aliceDir,email:"[email protected]",password:DEMO_PASSWORD})).rejects.toMatchObject({code:"confirmation_required"});
+ // Arguments can never override the dispatched operation or the confirmation gate.
+ await expect(dispatch.executeIntegrationAction({operation:"demo.create",arguments:{action:"demo.get",confirm:true,cwd:f.aliceDir,id:created.id}})).rejects.toMatchObject({code:"invalid_management_fields"});
+});
+
+it("serves a reveal only to a live Owner session, private no-store, body {key,value} only",async()=>{
+ const f=await withCredentials(),{POST}=await import("@/app/api/v1/integrations/route"),{NextRequest}=await import("next/server");
+ const request=(body:unknown)=>new NextRequest("https://mso.example.test/api/v1/integrations",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({mode:"reveal",...body as object})});
+ const ok=await POST(request({user:"alice",provider:"cloudflare",connection:"dns",key:"apiToken"}));
+ expect(ok.status).toBe(200);
+ expect(await ok.json()).toEqual({key:"apiToken",value:A_KEY});
+ expect(ok.headers.get("cache-control")).toBe("private, no-store");
+ expect(ok.headers.get("pragma")).toBe("no-cache");
+ // A refusal is the same shape and never mentions the value.
+ const refused=await POST(request({user:"alice",provider:"cloudflare",connection:"dns",key:"zoneId"}));
+ expect(refused.status).toBe(404);
+ const refusedBody=await refused.json();expect(refusedBody).toEqual({error:"secret_field_not_revealable"});
+ expect(refused.headers.get("cache-control")).toBe("private, no-store");
+ expect(JSON.stringify(refusedBody)).not.toContain(A_KEY);
+ // Live authorization withdrawn (revocation, scope/epoch change) fails closed.
+ liveAuth.allowed=false;
+ expect((await POST(request({user:"alice",provider:"cloudflare",connection:"dns",key:"apiToken"}))).status).toBe(403);
+ liveAuth.allowed=true;
+ expect(f.manage).toBeTypeOf("function");
+});
diff --git a/lib/infra/demo-credentials.ts b/lib/infra/demo-credentials.ts
new file mode 100644
index 00000000..2439aeb2
--- /dev/null
+++ b/lib/infra/demo-credentials.ts
@@ -0,0 +1,189 @@
+import type { DemoCredentialRecord, DemoCredentialSummary } from "@/lib/contracts/demo-credentials";
+import { constants, promises as fs } from "node:fs";
+import { randomUUID } from "node:crypto";
+import path from "node:path";
+import { withSecurityStoreLock } from "@/lib/security-store-lock";
+import { audit } from "@/lib/host/audit-api";
+import { rateLimited } from "@/lib/host/rate-limit";
+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";
+import type { DeviceRole } from "@/lib/auth/roles";
+import type { SessionPayload } from "@/lib/auth/session";
+import { readIntegrationState, INFRA_STORE_PATH } from "./connection-storage";
+import { connectionMethod } from "./connection-registry";
+import { canonicalFolder, folderBinding, identity, resolveSharedConnection, selectConnection, IntegrationError } from "./identity";
+export type { DemoCredentialRecord, DemoCredentialSummary } from "@/lib/contracts/demo-credentials";
+
+// Demo logins live beside the other private infra state: owner-only dir (0700),
+// owner-only file (0600), O_NOFOLLOW + uid checks, atomic rename, locked mutation.
+// The path derives from OS_INFRA_STORE so one test sandbox moves both stores.
+export const DEMO_STORE_PATH = path.join(path.dirname(INFRA_STORE_PATH), "demo-credentials.json");
+const MAX = 1024 * 1024;
+type Store = { version: 1; records: DemoCredentialRecord[] };
+export class DemoCredentialError extends Error { constructor(public readonly code: string, public readonly status = 400) { super(code); } }
+/** Rebuild a validated string one bounded code unit at a time, so the stored value
+ * is never a reference to request text (CodeQL js/http-to-file-access). */
+function copyUnits(value: string): string { let out = ""; for (let i = 0; i < value.length; i++) out += String.fromCharCode(value.charCodeAt(i)); return out; }
+const cleanEmail = (value: unknown) => {
+ const raw = typeof value === "string" ? value.trim() : "";
+ if (raw.length < 3 || raw.length > 254 || /[\s\x00-\x1f\x7f]/.test(raw) || !/^[^@]+@[^@.]+(\.[^@.]+)+$/.test(raw)) throw new DemoCredentialError("invalid_demo_email");
+ return copyUnits(raw);
+};
+const cleanPassword = (value: unknown) => {
+ if (typeof value !== "string" || value.length < 1 || value.length > 4096 || /[\0\n\r]/.test(value)) throw new DemoCredentialError("invalid_demo_password");
+ return copyUnits(value);
+};
+function optionalText(value: unknown, code: string, max: number) {
+ if (value === undefined || value === null || value === "") return undefined;
+ if (typeof value !== "string" || value.length > max || /[\x00-\x1f\x7f]/.test(value)) throw new DemoCredentialError(code);
+ return copyUnits(value.trim());
+}
+function summary(row: DemoCredentialRecord): DemoCredentialSummary {
+ // The password is deliberately dropped here; list results are sent on many paths.
+ const { password, ...rest } = row;
+ return { ...rest, hasPassword: true };
+}
+async function readRaw(): Promise<Store | null> {
+ let handle;
+ try {
+ handle = await fs.open(DEMO_STORE_PATH, constants.O_RDONLY | constants.O_NOFOLLOW);
+ const st = await handle.stat();
+ if (!st.isFile() || st.size < 1 || st.size > MAX || (st.mode & 0o077) || (typeof process.getuid === "function" && st.uid !== process.getuid())) throw new DemoCredentialError("unsafe_demo_store");
+ const parsed = JSON.parse(await handle.readFile("utf8")) as Store;
+ return validateStore(parsed);
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return null;
+ throw new DemoCredentialError("invalid_or_unsafe_demo_store");
+ } finally { await handle?.close(); }
+}
+function validateStore(raw: Store): Store {
+ if (!raw || raw.version !== 1 || !Array.isArray(raw.records)) throw new DemoCredentialError("invalid_demo_store");
+ for (const row of raw.records) {
+ if (!row || typeof row.id !== "string" || !row.owner || !row.workspace || typeof row.email !== "string" || typeof row.password !== "string" || !Number.isInteger(row.revision)) throw new DemoCredentialError("invalid_demo_store");
+ }
+ return raw;
+}
+async function write(store: Store) {
+ const dir = path.dirname(DEMO_STORE_PATH);
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
+ const st = await fs.lstat(dir);
+ if (st.isSymbolicLink() || !st.isDirectory() || (typeof process.getuid === "function" && st.uid !== process.getuid())) throw new DemoCredentialError("unsafe_demo_directory");
+ await fs.chmod(dir, 0o700);
+ const text = JSON.stringify(store, null, 2);
+ if (Buffer.byteLength(text) > MAX) throw new DemoCredentialError("demo_store_capacity", 409);
+ const temp = `${DEMO_STORE_PATH}.${randomUUID()}.tmp`;
+ try { await fs.writeFile(temp, text, { mode: 0o600, flag: "wx" }); await fs.rename(temp, DEMO_STORE_PATH); }
+ finally { await fs.unlink(temp).catch(() => undefined); }
+}
+async function mutate<T>(fn: (store: Store) => T | Promise<T>): Promise<T> {
+ return withSecurityStoreLock(DEMO_STORE_PATH, async () => {
+ const store = (await readRaw()) ?? { version: 1, records: [] };
+ const out = await fn(store);
+ await write(store);
+ return out;
+ });
+}
+/** The workspace IS the bound project folder: the owner comes from that folder's
+ * credential binding, never from a caller-supplied owner or free-form workspace. */
+async function scope(input: Record<string, unknown>) {
+ if (typeof input.cwd !== "string" || !input.cwd) throw new DemoCredentialError("workspace_cwd_required");
+ const workspace = canonicalFolder(input.cwd), state = await readIntegrationState();
+ const binding = folderBinding(state, workspace);
+ if (!binding) throw new DemoCredentialError("workspace_folder_not_bound", 409);
+ return { owner: identity(binding.user, "user"), workspace: binding.path };
+}
+function find(store: Store, owner: string, workspace: string, id: string) {
+ const row = store.records.find(r => r.id === id);
+ if (!row || row.owner !== owner || row.workspace !== workspace) throw new DemoCredentialError("demo_credential_not_found", 404);
+ return row;
+}
+export async function createDemoCredential(input: Record<string, unknown>) {
+ const { owner, workspace } = await scope(input), email = cleanEmail(input.email), password = cleanPassword(input.password);
+ const fields = { label: optionalText(input.label, "invalid_demo_label", 120), site: optionalText(input.site, "invalid_demo_site", 2048), notes: optionalText(input.notes, "invalid_demo_notes", 2000) };
+ return mutate(store => {
+ if (store.records.some(r => r.owner === owner && r.workspace === workspace && r.email === email)) throw new DemoCredentialError("demo_credential_exists", 409);
+ const now = Date.now(), row: DemoCredentialRecord = { id: randomUUID(), owner, workspace, email, password, ...fields, createdAt: now, updatedAt: now, revision: 1 };
+ store.records.push(row);
+ return summary(row);
+ });
+}
+export async function listDemoCredentials(input: Record<string, unknown>) {
+ const { owner, workspace } = await scope(input), store = await readRaw();
+ return { owner, workspace, demoUsers: (store?.records ?? []).filter(r => r.owner === owner && r.workspace === workspace).map(summary) };
+}
+/** Full record including the password: agent/server-side sign-in resolution only. */
+export async function getDemoCredential(input: Record<string, unknown>) {
+ const { owner, workspace } = await scope(input), store = await readRaw(), id = identity(input.id, "id");
+ if (!store) throw new DemoCredentialError("demo_credential_not_found", 404);
+ return find(store, owner, workspace, id);
+}
+export async function updateDemoCredential(input: Record<string, unknown>) {
+ const { owner, workspace } = await scope(input), id = identity(input.id, "id");
+ return mutate(store => {
+ const row = find(store, owner, workspace, id);
+ if (input.email !== undefined) { const email = cleanEmail(input.email); if (store.records.some(r => r.id !== id && r.owner === owner && r.workspace === workspace && r.email === email)) throw new DemoCredentialError("demo_credential_exists", 409); row.email = email; }
+ if (input.password !== undefined) row.password = cleanPassword(input.password);
+ if (input.label !== undefined) row.label = optionalText(input.label, "invalid_demo_label", 120);
+ if (input.site !== undefined) row.site = optionalText(input.site, "invalid_demo_site", 2048);
+ if (input.notes !== undefined) row.notes = optionalText(input.notes, "invalid_demo_notes", 2000);
+ row.revision += 1; row.updatedAt = Date.now();
+ return summary(row);
+ });
+}
+export async function deleteDemoCredential(input: Record<string, unknown>) {
+ const { owner, workspace } = await scope(input), id = identity(input.id, "id");
+ return mutate(store => {
+ find(store, owner, workspace, id);
+ store.records = store.records.filter(r => r.id !== id);
+ return { id, deleted: true };
+ });
+}
+export type RevealActor = { session: SessionPayload; role: DeviceRole; deviceId: string | null };
+const GENERIC = "secret_field_not_revealable", FIELD = /^[A-Za-z][A-Za-z0-9]{0,63}$/;
+async function storedSecret(input: Record<string, unknown>, key: string) {
+ if (input.demoId !== undefined) {
+ // The demo password is the only revelable demo field.
+ if (key !== "password") throw new DemoCredentialError(GENERIC, 404);
+ const { owner, workspace } = await scope(input), store = await readRaw(), row = store?.records.find(r => r.id === String(input.demoId));
+ if (!row || row.owner !== owner || row.workspace !== workspace) throw new DemoCredentialError(GENERIC, 404);
+ return copyUnits(row.password);
+ }
+ let resolved;
+ try {
+ const provider = identity(input.provider, "provider"), connection = identity(input.connection, "connection");
+ const user = input.user === undefined ? undefined : identity(input.user, "user");
+ const state = await readIntegrationState();
+ resolved = { state, route: selectConnection(state, provider, { user, connection, cwd: typeof input.cwd === "string" ? input.cwd : undefined }), provider };
+ } catch { throw new DemoCredentialError(GENERIC, 404); }
+ const { state, route, provider } = resolved;
+ if (route.connection.source !== "direct") throw new DemoCredentialError("external_secrets_forbidden", 409);
+ let target = route.connection;
+ if (target.sharedFrom) {
+ const backing = resolveSharedConnection(state, route.user, target);
+ // A shared alias backed by ANOTHER credential owner is never revelable here.
+ if (backing.user !== route.user) throw new DemoCredentialError("shared_alias_readonly", 409);
+ target = backing.connection;
+ }
+ const field = connectionMethod(provider, target.source, target.authMethod).fields.find(f => f.key === key);
+ const value = target.values[key];
+ // Unknown, non-secret and empty fields share one refusal so existence cannot leak.
+ if (!field || field.secret !== true || typeof value !== "string" || !value) throw new DemoCredentialError(GENERIC, 404);
+ return copyUnits(value);
+}
+/** The ONE path a stored secret leaves the server on. Human-only: the agent has no
+ * tool that reaches this route; it reads a demo password via demo.get instead. */
+export async function revealSecret(input: Record<string, unknown>, actor: RevealActor): Promise<{ key: string; value: string }> {
+ const key = typeof input.key === "string" ? input.key : "";
+ const target = (input.demoId !== undefined ? `demo:${String(input.demoId)}` : `${String(input.provider)}:${String(input.connection)}`).slice(0, 256);
+ const deny = async (code: string, status: number) => {
+ await audit({ action: "infra.write", actor: actor.deviceId || null, target, ok: false, detail: `integration.secret-reveal refused key=${key.slice(0, 64)}` });
+ return new DemoCredentialError(code, status);
+ };
+ if (!actor.deviceId || !(await liveSessionAuthorized(actor.session, actor.role))) throw await deny("owner_required", 403);
+ if (!FIELD.test(key)) throw await deny(GENERIC, 404);
+ if (rateLimited(`secret-reveal:${actor.deviceId}:${target}`, 5, 60_000)) throw await deny("rate_limited", 429);
+ let value: string;
+ try { value = await storedSecret(input, key); }
+ catch (error) { if (error instanceof IntegrationError) throw await deny(GENERIC, 404); if (error instanceof DemoCredentialError) throw await deny(error.code, error.status); throw await deny(GENERIC, 404); }
+ await audit({ action: "infra.write", actor: actor.deviceId, target, ok: true, detail: `integration.secret-reveal key=${key}` });
+ return { key, value };
+}