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(workflows): add reviewed external editor tabs
Rahman8919bf86400b
diff --git a/app/api/v1/workflow-embeds/route.test.ts b/app/api/v1/workflow-embeds/route.test.tsnew file mode 100644index 00000000..8c1b35cc--- /dev/null+++ b/app/api/v1/workflow-embeds/route.test.ts@@ -0,0 +1,32 @@+import { NextRequest } from "next/server";+import { beforeEach, describe, expect, it, vi } from "vitest";+const mocks = vi.hoisted(() => ({ session: vi.fn(), apps: vi.fn(), metadata: vi.fn(), save: vi.fn() }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.session }));+vi.mock("@/lib/host/workflow-embeds-api", () => ({ workflowEmbedSettings: mocks.apps, saveWorkflowSurface: mocks.save, SurfaceConfigError: class extends Error {} }));+import { GET, POST } from "./route";+const request = () => new NextRequest("https://cockpit.example.test/api/v1/workflow-embeds");+beforeEach(() => { vi.clearAllMocks(); mocks.apps.mockResolvedValue({ apps: [], revision: "test", configurable: true }); });+describe("workflow embed metadata access", () => {+ it("requires an authenticated approved device", async () => {+ mocks.session.mockResolvedValue(null);+ const response = await GET(request());+ expect(response.status).toBe(401); expect(mocks.apps).not.toHaveBeenCalled();+ expect(response.headers.get("cache-control")).toContain("no-store");+ });+ it.each(["viewer", "operator"])("refuses %s access to owner reviewed endpoints", async (role) => {+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role });+ expect((await GET(request())).status).toBe(403); expect(mocks.apps).not.toHaveBeenCalled();+ });+ it("returns the current registry without caching for the owner", async () => {+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role: "owner" });+ const response = await GET(request());+ expect(response.status).toBe(200); expect(await response.json()).toEqual({ apps: [], revision: "test", configurable: true });+ expect(response.headers.get("cache-control")).toBe("no-store, private");+ expect(mocks.apps).toHaveBeenCalledWith("https://cockpit.example.test");+ });+});++it("rejects a viewer write before parsing or changing the registry", async () => {+ mocks.session.mockResolvedValue({ session: { device_id: "fixture" }, role: "viewer" });+ expect((await POST(request())).status).toBe(403); expect(mocks.save).not.toHaveBeenCalled();+});diff --git a/app/api/v1/workflow-embeds/route.ts b/app/api/v1/workflow-embeds/route.tsnew file mode 100644index 00000000..995091ee--- /dev/null+++ b/app/api/v1/workflow-embeds/route.ts@@ -0,0 +1,33 @@+import { NextRequest, NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { readSetupJson } from "@/lib/infra/setup-http";+import { audit } from "@/lib/host/audit-api";+import { IS_DEMO } from "@/lib/demo";+import { rateLimited } from "@/lib/host/limits-api";+import { roleAtLeast } from "@/lib/auth/roles";+import { workflowEmbedSettings, saveWorkflowSurface, SurfaceConfigError } from "@/lib/host/workflow-embeds-api";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+const headers = { "Cache-Control": "no-store, private" };+export async function GET(request: NextRequest) {+ const context = await getSessionContext();+ if (!context?.session.device_id) return NextResponse.json({ error: "unauthorized" }, { status: 401, headers });+ if (!roleAtLeast(context.role, "owner")) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });+ try {+ return NextResponse.json(await workflowEmbedSettings(request.nextUrl.origin), { headers });+ } catch { return NextResponse.json({ error: "surface_registry_unavailable" }, { status: 503, headers }); }+}++export async function POST(request: NextRequest) {+ const context = await getSessionContext();+ if (IS_DEMO || !context?.session.device_id || !roleAtLeast(context.role, "owner")) return NextResponse.json({ error: "owner_required" }, { status: 403, headers });+ if (rateLimited(`workflow-embed:${context.session.device_id}`, 20, 60_000)) return NextResponse.json({ error: "rate_limited" }, { status: 429, headers });+ try {+ const result = await saveWorkflowSurface(await readSetupJson(request));+ void audit({ action: "infra.write", actor: context.session.device_id, target: result.id, ok: true, detail: "workflow-embed.reviewed" });+ return NextResponse.json(result, { headers });+ } catch (error) {+ return NextResponse.json({ error: error instanceof SurfaceConfigError ? error.message : "surface_update_failed" }, { status: error instanceof SurfaceConfigError ? error.status : 400, headers });+ }+}diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.mdindex d9ebb127..352b79d1 100644--- a/docs/ARCHITECTURE.md+++ b/docs/ARCHITECTURE.md@@ -173,7 +173,7 @@ lookup, collision detection, tracing, evidence, and learning, but no longer bindwidgets; prior Block/Page URIs plus the previous workflow/surface resource URIs remain readable aliases but are not advertised. Page tools use the standard MCP Apps `ui.resourceUri` binding only; the legacy ChatGPT `openai/outputTemplate` alias is intentionally absent so one tool result maps to one Page mount.Reviewed Page apps honor their iframe/remote renderer. Iframes use exact registry origins, fixed sandbox permissions, no-referrer and a visible direct/browser fallback. Cockpit/widget origins remain remote-only.-The owner-local registry (`~/.mso/surface-apps.json`, or explicit `MSO_SURFACE_APPS_JSON` override)+The shared `lib/surfaces/config.ts` owner-local registry (`~/.mso/surface-apps.json`, or explicit `MSO_SURFACE_APPS_JSON` override)validates app identity, origin and approved path; portable source defaults to no external Page apps.This trust catalog is deliberately separate from Store/runtime `AppManifest` data. A locally installed `runtime:"html"` app or HTML widget is user-controlled presentation dataand cannot grant itself a ChatGPT nested-frame origin. `srcDoc` HTML remains opaque-origindiff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 68441db4..f977a6a6 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**+- `workflows` add reviewed external editor tabs- `organization` add internal project flows with callable CRUD**Fixed**diff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex dab0f247..ff31ef07 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,11 @@+## 2026-09-18 — Reviewed workflow provider tabs++- Keep the native automation/session editor unchanged and mounted while switching to external workflow editors such as n8n. The new wrapper consumes explicit workflow placements in the existing owner-reviewed surface registry, not app-store HTML or credential values.+- Share the registry outside the MCP transport without adding another store. Owner-only no-store metadata and revision-checked, explicitly reviewed configuration APIs/CLI preserve exact origins, unrelated entries, safe sandbox permissions and remote-only fallback. Configuration input cannot carry paths or credentials.+- Workflow-only placements never grant an MCP Page nested-frame origin. Load frames only on demand, preserve editor state when switching, expose top-level sign-in/open/reload actions and keyboard-accessible tabs. Browser login remains external-service-owned; framing never means MCP token forwarding or authentication bypass.+- Add registry/access tests and an isolated browser journey with synthetic stores; keep live n8n signed-out frame evidence separate from logged-in editor claims.+- The strict release build caught project-wide tracing of the dynamic registry path. Mark that owner-local runtime read as a non-build input, matching other private stores; the warning-fatal release gate remains unchanged.+## 2026-09-18 — Keep private viewer routing client-verifiableThe PR review reproduced a deployment-compatibility regression: a hostname resolvingdiff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.mdindex a2255117..a7e333bd 100644--- a/docs/WORKFLOW-GRAPH.md+++ b/docs/WORKFLOW-GRAPH.md@@ -141,10 +141,50 @@ AI assistance has an isolated workflow-design system prompt, receives no impliciRun automatically saves a dirty graph before execution, so execution always uses the revision visible in the editor. Disabled connections remain visible in the graph and receipts but are excluded from runtime traversal, cycle checks and tidy layout; a target reachable only through disabled connections is skipped rather than silently promoted to a new root.+## Reviewed external workflow tabs++The Workflows workspace keeps the native MSO automation/session editor and can add+external editors such as n8n as sibling tabs. External tabs are **off by default**.+The owner-reviewed Page registry is shared through `lib/surfaces/config.ts`; add+`"placements": ["workflows"]` to an approved external app in the existing+`~/.mso/surface-apps.json` (or its configured override). Preserve existing entries.+Workflow-only placements do not appear in the MCP Page catalog or grant ChatGPT a+nested-frame origin. Legacy entries without placements retain their Page behavior;+explicit `"mcp-page"` is a separate reviewed placement.+For example, a private installation could add:++```json+{+ "id": "n8n", "title": "n8n", "description": "External workflow editor",+ "origin": "https://automation.example.test", "startPath": "/home/workflows",+ "renderer": "iframe", "presentation": "inline", "environment": "production",+ "externalAuthPath": "/signin", "placements": ["workflows"],+ "sandbox": "allow-scripts allow-same-origin allow-forms allow-downloads allow-popups allow-popups-to-escape-sandbox"+}+```++`GET /api/v1/workflow-embeds` and `mso workflow embeds` return only reviewed+presentation metadata to an approved Owner device. They never return Integration+credentials. The Owner-only POST and `mso workflow embed-save` accept `{app, expectedRevision, confirm:true}`; they validate metadata, preserve unrelated entries and reject stale revisions or environment-managed configuration. No raw file or credential access is exposed.+The registry is refreshed when the window regains focus, without a+rebuild. External frames load on first selection; switching tabs preserves both+the native editor's unsaved state and the external editor's frame. Keyboard tab+navigation and narrow viewport layouts use the same workspace wrapper.++MCP authorization does not sign the browser into n8n. Use the visible **Sign in**+link to authenticate directly with the external service, then reload its frame.+**Open** remains available if its frame policy or browser cookie policy prevents+embedding. MSO does not strip upstream security headers, proxy credentials, or+claim that an iframe load proves authentication. Own-cockpit origins and+remote-only registry entries never become embedded frames.+## CLI```bashmso workflow list+mso workflow embeds+# Review a metadata-only app and use the revision above:+mso workflow embed-save --input @reviewed-embed.jsonmso workflow show <id>mso workflow catalog --query webhookmso workflow templatesdiff --git a/frontend/slices/workflows/components/workflow-embed-panel.tsx b/frontend/slices/workflows/components/workflow-embed-panel.tsxnew file mode 100644index 00000000..95c85dc9--- /dev/null+++ b/frontend/slices/workflows/components/workflow-embed-panel.tsx@@ -0,0 +1,30 @@+"use client";++import { useEffect, useState } from "react";+import { ExternalLink, LogIn, RefreshCw } from "lucide-react";+import type { WorkflowEmbed } from "@/lib/contracts/surface-app";+import { Button } from "@/components/ui/button";++export function WorkflowEmbedPanel({ app }: { app: WorkflowEmbed }) {+ const [revision, setRevision] = useState(0);+ const [loading, setLoading] = useState(true);+ const [slow, setSlow] = useState(false);+ useEffect(() => {+ const timer = setTimeout(() => setSlow(true), 15000);+ return () => clearTimeout(timer);+ }, [revision]);+ const reload = () => { setLoading(true); setSlow(false); setRevision((value) => value + 1); };+ return <div className="flex h-full min-h-0 min-w-0 flex-col" data-slot="workflow-embed-panel">+ <div className="flex min-h-11 shrink-0 flex-wrap items-center gap-2 border-b px-3 py-1.5">+ <span className="min-w-0 flex-1 truncate text-xs text-muted-foreground" title={app.origin}>{app.origin}</span>+ {app.loginUrl ? <Button asChild variant="ghost" size="sm"><a href={app.loginUrl} target="_blank" rel="noopener noreferrer"><LogIn className="size-4"/><span>Sign in</span></a></Button> : null}+ <Button asChild variant="outline" size="sm"><a href={app.url} target="_blank" rel="noopener noreferrer"><ExternalLink className="size-4"/><span>Open {app.title}</span></a></Button>+ {app.renderer === "iframe" ? <Button variant="ghost" size="icon" onClick={reload} aria-label={`Reload ${app.title}`} title={`Reload ${app.title}`}><RefreshCw className="size-4"/></Button> : null}+ </div>+ {app.renderer === "iframe" ? <div className="relative min-h-0 min-w-0 flex-1">+ {loading ? <div className="absolute inset-x-0 top-0 z-10 border-b bg-background px-3 py-2 text-xs text-muted-foreground" role="status">{slow ? `Taking longer than expected. Open ${app.title} in a new tab if its login or frame policy blocks embedding.` : `Loading ${app.title}…`}</div> : null}+ <iframe key={revision} src={app.url} title={`${app.title} workflow editor`} sandbox={app.sandbox} referrerPolicy="no-referrer" className="h-full w-full border-0 bg-background" onLoad={() => setLoading(false)} onError={() => { setLoading(true); setSlow(true); }}/>+ </div> : <div className="flex min-h-0 flex-1 items-center justify-center p-6 text-center text-sm text-muted-foreground">{app.reason || `${app.title} opens in a separate tab. Embedded access is not enabled for this provider.`}</div>}+ <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.title} keeps its own login. Sign in in a new tab, then reload here. If embedding is blocked, use Open {app.title}.</p>+ </div>;+}diff --git a/frontend/slices/workflows/index.ts b/frontend/slices/workflows/index.tsindex d9dc05bb..380c1e4c 100644--- a/frontend/slices/workflows/index.ts+++ b/frontend/slices/workflows/index.ts@@ -7,6 +7,6 @@ export const workflowsApp: AppDescriptor = {icon: Workflow,gradient: "var(--primary)",prefetch: "never",- load: () => import("./app"),+ load: () => import("./workspace"),defaultSize: { w: 1180, h: 760 },};diff --git a/frontend/slices/workflows/workspace.tsx b/frontend/slices/workflows/workspace.tsxnew file mode 100644index 00000000..449084d6--- /dev/null+++ b/frontend/slices/workflows/workspace.tsx@@ -0,0 +1,51 @@+"use client";++import { useEffect, useId, useState } from "react";+import type { AppProps } from "@/features/appshell";+import type { WorkflowEmbed } from "@/lib/contracts/surface-app";+import { Button } from "@/components/ui/button";+import { cn } from "@/lib/utils";+import NativeWorkflowsApp from "./app";+import { WorkflowEmbedPanel } from "./components/workflow-embed-panel";++export default function WorkflowsWorkspace(props: AppProps) {+ const [apps, setApps] = useState<WorkflowEmbed[]>([]);+ const [selected, setSelected] = useState("__native");+ const [visited, setVisited] = useState<string[]>([]);+ const prefix = useId();+ useEffect(() => {+ const controller = new AbortController();+ const load = async () => {+ try {+ const response = await fetch("/api/v1/workflow-embeds", { cache: "no-store", signal: controller.signal });+ if (!response.ok) { if ([401, 403].includes(response.status)) setApps([]); return; }+ const data = await response.json() as { apps: WorkflowEmbed[] };+ setApps(data.apps);+ } catch { /* Keep mounted editors on transient network failures; authorization failures clear them above. */ }+ };+ void load(); window.addEventListener("focus", load);+ return () => { controller.abort(); window.removeEventListener("focus", load); };+ }, []);+ useEffect(() => {+ if (!props.payload || typeof props.payload !== "object" || !("view" in props.payload) || props.payload.view !== "sessions") return;+ const frame = requestAnimationFrame(() => setSelected("__native"));+ return () => cancelAnimationFrame(frame);+ }, [props.payload]);+ const active = apps.some((app) => app.id === selected) ? selected : "__native";+ const choices = [{ id: "__native", title: "MSO" }, ...apps];+ const select = (id: string) => { setSelected(id); setVisited((ids) => ids.includes(id) ? ids : [...ids, id]); };+ return <div className="flex h-full min-h-0 min-w-0 flex-col overflow-hidden" data-slot="workflows-workspace">+ {apps.length ? <div role="tablist" aria-label="Workflow providers" className="flex shrink-0 gap-1 overflow-x-auto border-b px-2 py-1">+ {choices.map((choice, index) => <Button key={choice.id} id={`${prefix}-tab-${choice.id}`} role="tab" aria-selected={active === choice.id} aria-controls={`${prefix}-panel-${choice.id}`} tabIndex={active === choice.id ? 0 : -1} variant={active === choice.id ? "secondary" : "ghost"} size="sm" className="shrink-0" onClick={() => select(choice.id)} onKeyDown={(event) => {+ const offset = event.key === "ArrowRight" ? 1 : event.key === "ArrowLeft" ? -1 : 0;+ const next = event.key === "Home" ? 0 : event.key === "End" ? choices.length - 1 : offset ? (index + offset + choices.length) % choices.length : -1;+ if (next < 0) return;+ event.preventDefault(); select(choices[next].id); document.getElementById(`${prefix}-tab-${choices[next].id}`)?.focus();+ }}>{choice.title}</Button>)}+ </div> : null}+ <section id={`${prefix}-panel-__native`} role={apps.length ? "tabpanel" : undefined} aria-labelledby={apps.length ? `${prefix}-tab-__native` : undefined} hidden={active !== "__native"} className={cn("min-h-0 min-w-0 flex-1 overflow-hidden", active !== "__native" && "hidden")}>+ <NativeWorkflowsApp {...props}/>+ </section>+ {apps.map((app) => <section key={app.id + app.url} id={`${prefix}-panel-${app.id}`} role="tabpanel" aria-labelledby={`${prefix}-tab-${app.id}`} hidden={active !== app.id} className={cn("min-h-0 min-w-0 flex-1 overflow-hidden", active !== app.id && "hidden")}>{visited.includes(app.id) ? <WorkflowEmbedPanel app={app}/> : null}</section>)}+ </div>;+}diff --git a/lib/config/env-example.test.ts b/lib/config/env-example.test.tsindex d70ba0f7..9b6587e3 100644--- a/lib/config/env-example.test.ts+++ b/lib/config/env-example.test.ts@@ -44,6 +44,9 @@ const NOT_A_KNOB: Record<string, string> = {WATCHDOG_USEC: "systemd's",// Test + tooling only, never part of a deployment.E2E_BASE_URL: "test harness",+ E2E_EVIDENCE_DIR: "workflow embed browser harness only: screenshot/report output directory, never runtime configuration",+ E2E_WORKFLOW_EMBED_PARENT_ORIGIN: "workflow embed browser harness only: explicitly approved synthetic parent origin for live policy checks",+ E2E_WORKFLOW_EMBED_ORIGIN: "workflow embed browser harness only: explicit signed-out live provider smoke target, never production configuration",MSO_SCREENSHOT_DIR: "injected per-session artifact staging path for browser tooling; never persistent app configuration",E2E_DEMO: "desktop browser harness only: preview has no authentication; never production configuration",E2E_CAPTURE_ONLY: "desktop browser harness only: capture baseline before native behavior assertions",diff --git a/lib/contracts/surface-app.ts b/lib/contracts/surface-app.tsnew file mode 100644index 00000000..7055a38f--- /dev/null+++ b/lib/contracts/surface-app.ts@@ -0,0 +1,25 @@+export type SurfaceRenderer = "iframe" | "remote";+export type SurfacePresentation = "inline" | "fullscreen" | "pip";+export type SurfaceEnvironment = "development" | "preview" | "production" | "other";++export type SurfaceApp = {+ id: string;+ title: string;+ description: string;+ origin: string;+ startPath: string;+ renderer: SurfaceRenderer;+ presentation: SurfacePresentation;+ environment: SurfaceEnvironment;+ sandbox?: string;+ externalAuthPath?: string;+ reason?: string;+ project?: string;+ placements?: Array<"workflows" | "mcp-page">;+};+++export type WorkflowEmbed = {+ id: string; title: string; description: string; origin: string; url: string;+ loginUrl?: string; renderer: SurfaceRenderer; sandbox: string; reason?: string;+};diff --git a/lib/host/workflow-embeds-api.test.ts b/lib/host/workflow-embeds-api.test.tsnew file mode 100644index 00000000..2de08d3d--- /dev/null+++ b/lib/host/workflow-embeds-api.test.ts@@ -0,0 +1,38 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { configuredSurfaceApps } from "@/lib/surfaces/config";+import { listWorkflowEmbeds, workflowEmbeds } from "./workflow-embeds-api";+const app = { id: "automation", title: "Automation", description: "Owner workspace", origin: "https://automation.example.test", startPath: "/home/workflows", renderer: "iframe" as const, presentation: "inline" as const, environment: "production" as const };+afterEach(() => vi.unstubAllEnvs());+describe("reviewed Workflows embed registry", () => {+ it("is disabled by default and requires explicit placement", () => {+ expect(workflowEmbeds([app], [])).toEqual([]);+ expect(workflowEmbeds([{ ...app, placements: ["workflows"] }], [])).toHaveLength(1);+ });+ it("shares the Page registry and only returns approved non-secret presentation metadata", async () => {+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, placements: ["workflows"], externalAuthPath: "/signin", accessToken: "must-not-leak" }]));+ const result = await listWorkflowEmbeds("https://cockpit.example.test");+ expect(result[0]).toMatchObject({ id: "automation", url: "https://automation.example.test/home/workflows", loginUrl: "https://automation.example.test/signin", renderer: "iframe" });+ expect(JSON.stringify(result)).not.toContain("must-not-leak");+ });+ it("never frames the cockpit or explicitly configured widget origin", async () => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", app.origin);+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, placements: ["workflows"] }]));+ expect((await listWorkflowEmbeds("http://localhost:4005"))[0].renderer).toBe("remote");+ expect(workflowEmbeds([{ ...app, placements: ["workflows"] }], [app.origin])[0].renderer).toBe("remote");+ });+ it("honors a remote-only provider rather than bypassing its frame policy", () => {+ expect(workflowEmbeds([{ ...app, placements: ["workflows"], renderer: "remote" }], [])[0].renderer).toBe("remote");+ });+ it.each(["workflows", ["settings"], [1], null])("rejects invalid placement metadata %j", async (placements) => {+ expect(await configuredSurfaceApps(JSON.stringify([{ ...app, placements }]))).toEqual([]);+ });+ it.each([{ origin: "http://automation.example.test" }, { startPath: "//evil.example.test" }, { sandbox: "allow-top-navigation" }])("rejects unsafe destination or frame permission %j", async (change) => {+ expect(await configuredSurfaceApps(JSON.stringify([{ ...app, placements: ["workflows"], ...change }]))).toEqual([]);+ });+ it("keeps non-workflow apps and approved sandbox permissions unchanged", async () => {+ const apps = await configuredSurfaceApps(JSON.stringify([app, { ...app, id: "reviewed", placements: ["workflows", "workflows"], sandbox: "allow-scripts allow-forms" }]));+ expect(apps[0]).toEqual(app);+ expect(apps[1].placements).toEqual(["workflows"]);+ expect(workflowEmbeds(apps, [])[0].sandbox).toBe("allow-scripts allow-forms");+ });+});diff --git a/lib/host/workflow-embeds-api.ts b/lib/host/workflow-embeds-api.tsnew file mode 100644index 00000000..eaa9265a--- /dev/null+++ b/lib/host/workflow-embeds-api.ts@@ -0,0 +1,35 @@+import type { SurfaceApp, WorkflowEmbed } from "@/lib/contracts/surface-app";+import { configuredSurfaceApps } from "@/lib/surfaces/config";+import { surfaceRegistrySnapshot } from "@/lib/surfaces/manage";++/** Presentation metadata only. An embed never inherits the cockpit's credentials. */+export function workflowEmbeds(apps: SurfaceApp[], cockpitOrigins: string[]): WorkflowEmbed[] {+ return apps.filter((app) => app.placements?.includes("workflows")).map((app) => {+ const ownOrigin = cockpitOrigins.includes(app.origin);+ return {+ id: app.id, title: app.title, description: app.description, origin: app.origin,+ url: new URL(app.startPath, app.origin).href,+ ...(app.externalAuthPath ? { loginUrl: new URL(app.externalAuthPath, app.origin).href } : {}),+ renderer: ownOrigin ? "remote" as const : app.renderer,+ sandbox: app.sandbox ?? "allow-scripts allow-same-origin allow-forms",+ ...(ownOrigin ? { reason: "Open the cockpit in a separate tab." } : app.reason ? { reason: app.reason } : {}),+ };+ });+}+function cockpitOrigins(requestOrigin: string): string[] {+ const origins = [requestOrigin];+ for (const value of [process.env.OS_PUBLIC_ORIGIN, process.env.OS_MCP_UI_ORIGIN]) {+ if (value) { try { origins.push(new URL(value).origin); } catch { /* Invalid config cannot grant framing. */ } }+ }+ return origins;+}++export async function listWorkflowEmbeds(requestOrigin: string): Promise<WorkflowEmbed[]> {+ return workflowEmbeds(await configuredSurfaceApps(), cockpitOrigins(requestOrigin));+}+export async function workflowEmbedSettings(requestOrigin: string) {+ const { apps, ...metadata } = await surfaceRegistrySnapshot();+ return { ...metadata, apps: workflowEmbeds(apps, cockpitOrigins(requestOrigin)) };+}++export { saveWorkflowSurface, SurfaceConfigError } from "@/lib/surfaces/manage";diff --git a/lib/mcp/surface-catalog.test.ts b/lib/mcp/surface-catalog.test.tsindex cc2b6cb2..2bc8b4fe 100644--- a/lib/mcp/surface-catalog.test.ts+++ b/lib/mcp/surface-catalog.test.ts@@ -13,6 +13,15 @@ describe("MSO Page trusted app catalog", () => {beforeEach(() => { process.env.MSO_SURFACE_APPS_JSON = JSON.stringify(configured); });afterEach(() => { delete process.env.MSO_SURFACE_APPS_JSON; });+ it("does not promote a workflow-only editor into the MCP Page trust catalog", async () => {+ process.env.MSO_SURFACE_APPS_JSON = JSON.stringify([{ ...configured[0], placements: ["workflows"] }]);+ expect(await publicSurfaceApps()).toEqual([]);+ expect(await surfaceFrameDomains()).toEqual([]);+ await expect(resolveSurfaceRoute("/apps/demo")).rejects.toThrow("unknown MSO Page app");+ process.env.MSO_SURFACE_APPS_JSON = JSON.stringify([{ ...configured[0], placements: ["workflows", "mcp-page"] }]);+ expect(await publicSurfaceApps()).toHaveLength(1);+ });+it("uses only instance-configured reviewed origins", async () => {expect(await surfaceFrameDomains()).toEqual(["https://demo.example.test"]);const apps = await publicSurfaceApps();diff --git a/lib/mcp/surface-catalog.ts b/lib/mcp/surface-catalog.tsindex 98edfbda..3332ab07 100644--- a/lib/mcp/surface-catalog.ts+++ b/lib/mcp/surface-catalog.ts@@ -3,7 +3,7 @@ import { configuredSurfaceApps, type SurfaceApp } from "./surface-config";export type { SurfaceApp, SurfaceRenderer, SurfacePresentation, SurfaceEnvironment } from "./surface-config";export async function surfaceApps(): Promise<readonly SurfaceApp[]> {- return (await configuredSurfaceApps()).map(app => [mcpUiOrigin(), publicMsoOrigin()].includes(app.origin) ? { ...app, renderer: "remote" as const, reason: "MSO authentication stays in the owner browser." } : app);+ return (await configuredSurfaceApps()).filter(app => !app.placements || app.placements.includes("mcp-page")).map(app => [mcpUiOrigin(), publicMsoOrigin()].includes(app.origin) ? { ...app, renderer: "remote" as const, reason: "MSO authentication stays in the owner browser." } : app);}const ROUTE_MAX = 1024;diff --git a/lib/mcp/surface-config.ts b/lib/mcp/surface-config.tsindex 2f333d5b..9ab55d06 100644--- a/lib/mcp/surface-config.ts+++ b/lib/mcp/surface-config.ts@@ -1,124 +1,3 @@-import { promises as fs } from "node:fs";-import { homedir } from "node:os";-import { resolve } from "node:path";--export type SurfaceRenderer = "iframe" | "remote";-export type SurfacePresentation = "inline" | "fullscreen" | "pip";-export type SurfaceEnvironment = "development" | "preview" | "production" | "other";--export type SurfaceApp = {- id: string;- title: string;- description: string;- origin: string;- startPath: string;- renderer: SurfaceRenderer;- presentation: SurfacePresentation;- environment: SurfaceEnvironment;- sandbox?: string;- externalAuthPath?: string;- reason?: string;- project?: string;-};--const MAX_APPS = 16;-const MAX_TEXT = 240;-const MAX_RAW_BYTES = 16_384;-const DEFAULT_REGISTRY = resolve(homedir(), ".mso", "surface-apps.json");-const REGISTRY_PATH = (() => {- const value = process.env.MSO_SURFACE_APPS_FILE?.trim();- if (!value) return DEFAULT_REGISTRY;- return resolve(value === "~" ? homedir() : value.startsWith("~/") ? `${homedir()}/${value.slice(2)}` : value);-})();-const SAFE_SANDBOX = new Set([- "allow-downloads", "allow-forms", "allow-modals", "allow-orientation-lock",- "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox",- "allow-presentation", "allow-same-origin", "allow-scripts",-]);-const PRESENTATIONS = new Set<SurfacePresentation>(["inline", "fullscreen", "pip"]);-const ENVIRONMENTS = new Set<SurfaceEnvironment>(["development", "preview", "production", "other"]);--function safeOrigin(value: unknown): string | null {- if (typeof value !== "string") return null;- try {- const url = new URL(value);- if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;- return url.origin;- } catch { return null; }-}--function safePath(value: unknown): string | null {- if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.length > 768 || /[\\\u0000-\u001f]/.test(value)) return null;- try {- const url = new URL(value, "https://surface.invalid");- if (url.origin !== "https://surface.invalid" || url.search || url.hash || url.pathname.split("/").some((part) => part === "." || part === "..")) return null;- return url.pathname;- } catch { return null; }-}--function safeAuthPath(value: unknown): string | null {- if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.length > 768 || /[\\\u0000-\u001f]/.test(value)) return null;- try {- const url = new URL(value, "https://surface.invalid");- if (url.origin !== "https://surface.invalid" || url.username || url.password || url.hash || url.pathname.split("/").some((part) => part === "." || part === "..")) return null;- return `${url.pathname}${url.search}`;- } catch { return null; }-}--function boundedText(value: unknown, required = false): string | undefined {- if (typeof value !== "string") return required ? undefined : "";- const result = value.trim();- return result && result.length <= MAX_TEXT ? result : required ? undefined : "";-}--function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {- if (!entry || typeof entry !== "object") return null;- const row = entry as Record<string, unknown>;- const id = boundedText(row.id, true), title = boundedText(row.title, true);- const origin = safeOrigin(row.origin), startPath = safePath(row.startPath);- const renderer = row.renderer, presentation = row.presentation, environment = row.environment;- if (!id || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id) || seen.has(id) || !title || !origin || !startPath) return null;- if (renderer !== "iframe" && renderer !== "remote") return null;- if (!PRESENTATIONS.has(presentation as SurfacePresentation) || !ENVIRONMENTS.has(environment as SurfaceEnvironment)) return null;- const sandbox = typeof row.sandbox === "string" ? row.sandbox.trim() : undefined;- if (sandbox && (sandbox.length > 240 || !sandbox.split(/\s+/).every((token) => SAFE_SANDBOX.has(token)))) return null;- const externalAuthPath = row.externalAuthPath === undefined ? undefined : safeAuthPath(row.externalAuthPath);- if (row.externalAuthPath !== undefined && !externalAuthPath) return null;- const project = boundedText(row.project, true);- if (row.project !== undefined && !project) return null;- seen.add(id);- const reason = boundedText(row.reason);- return {- id, title, description: boundedText(row.description) ?? "", origin, startPath, renderer,- presentation: presentation as SurfacePresentation, environment: environment as SurfaceEnvironment,- ...(project ? { project } : {}), ...(sandbox ? { sandbox } : {}), ...(externalAuthPath ? { externalAuthPath } : {}), ...(reason ? { reason } : {}),- };-}--async function readOwnerRegistry(): Promise<string | undefined> {- try {- const raw = await fs.readFile(REGISTRY_PATH, "utf8");- return Buffer.byteLength(raw, "utf8") <= MAX_RAW_BYTES ? raw : undefined;- } catch {- return undefined;- }-}--function parseRegistry(raw: string | undefined): SurfaceApp[] {- if (!raw || Buffer.byteLength(raw, "utf8") > MAX_RAW_BYTES) return [];- let entries: unknown;- try { entries = JSON.parse(raw); } catch { return []; }- if (!Array.isArray(entries)) return [];- const seen = new Set<string>();- return entries.slice(0, MAX_APPS).map((entry) => parseApp(entry, seen)).filter((app): app is SurfaceApp => app !== null);-}--/**- * Per-instance reviewed Page registry. An explicitly defined env value remains a- * backwards-compatible deployment override (including an intentionally empty value).- * Otherwise the owner-local registry is read on every call so adding/removing a- * reviewed surface does not require changing portable source or rebuilding MSO.- */-export async function configuredSurfaceApps(raw = process.env.MSO_SURFACE_APPS_JSON): Promise<SurfaceApp[]> {- return parseRegistry(raw !== undefined ? raw : await readOwnerRegistry());-}+// Compatibility entry point; the reviewed registry is shared with the authenticated cockpit.+export { configuredSurfaceApps } from "@/lib/surfaces/config";+export type { SurfaceApp, SurfaceRenderer, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";diff --git a/lib/surfaces/config.ts b/lib/surfaces/config.tsnew file mode 100644index 00000000..5b9b8a27--- /dev/null+++ b/lib/surfaces/config.ts@@ -0,0 +1,111 @@+import { promises as fs } from "node:fs";+import { homedir } from "node:os";+import { resolve } from "node:path";++import type { SurfaceApp, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";+export type { SurfaceApp, SurfaceRenderer, SurfacePresentation, SurfaceEnvironment } from "@/lib/contracts/surface-app";++const MAX_APPS = 16;+const MAX_TEXT = 240;+const MAX_RAW_BYTES = 16_384;+const DEFAULT_REGISTRY = resolve(homedir(), ".mso", "surface-apps.json");+export function surfaceRegistryPath(): string {+ const value = process.env.MSO_SURFACE_APPS_FILE?.trim();+ if (!value) return DEFAULT_REGISTRY;+ return resolve(value === "~" ? homedir() : value.startsWith("~/") ? `${homedir()}/${value.slice(2)}` : value);+}+const SAFE_SANDBOX = new Set([+ "allow-downloads", "allow-forms", "allow-modals", "allow-orientation-lock",+ "allow-pointer-lock", "allow-popups", "allow-popups-to-escape-sandbox",+ "allow-presentation", "allow-same-origin", "allow-scripts",+]);+const PRESENTATIONS = new Set<SurfacePresentation>(["inline", "fullscreen", "pip"]);+const ENVIRONMENTS = new Set<SurfaceEnvironment>(["development", "preview", "production", "other"]);++function safeOrigin(value: unknown): string | null {+ if (typeof value !== "string") return null;+ try {+ const url = new URL(value);+ if (url.protocol !== "https:" || url.username || url.password || url.pathname !== "/" || url.search || url.hash) return null;+ return url.origin;+ } catch { return null; }+}++function safePath(value: unknown): string | null {+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.length > 768 || /[\\\u0000-\u001f]/.test(value)) return null;+ try {+ const url = new URL(value, "https://surface.invalid");+ if (url.origin !== "https://surface.invalid" || url.search || url.hash || url.pathname.split("/").some((part) => part === "." || part === "..")) return null;+ return url.pathname;+ } catch { return null; }+}++function safeAuthPath(value: unknown): string | null {+ if (typeof value !== "string" || !value.startsWith("/") || value.startsWith("//") || value.length > 768 || /[\\\u0000-\u001f]/.test(value)) return null;+ try {+ const url = new URL(value, "https://surface.invalid");+ if (url.origin !== "https://surface.invalid" || url.username || url.password || url.hash || url.pathname.split("/").some((part) => part === "." || part === "..")) return null;+ return `${url.pathname}${url.search}`;+ } catch { return null; }+}++function boundedText(value: unknown, required = false): string | undefined {+ if (typeof value !== "string") return required ? undefined : "";+ const result = value.trim();+ return result && result.length <= MAX_TEXT ? result : required ? undefined : "";+}++function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {+ if (!entry || typeof entry !== "object") return null;+ const row = entry as Record<string, unknown>;+ const id = boundedText(row.id, true), title = boundedText(row.title, true);+ const origin = safeOrigin(row.origin), startPath = safePath(row.startPath);+ const renderer = row.renderer, presentation = row.presentation, environment = row.environment;+ if (!id || !/^[a-z0-9][a-z0-9-]{0,63}$/.test(id) || seen.has(id) || !title || !origin || !startPath) return null;+ if (renderer !== "iframe" && renderer !== "remote") return null;+ if (!PRESENTATIONS.has(presentation as SurfacePresentation) || !ENVIRONMENTS.has(environment as SurfaceEnvironment)) return null;+ const sandbox = typeof row.sandbox === "string" ? row.sandbox.trim() : undefined;+ if (sandbox && (sandbox.length > 240 || !sandbox.split(/\s+/).every((token) => SAFE_SANDBOX.has(token)))) return null;+ const externalAuthPath = row.externalAuthPath === undefined ? undefined : safeAuthPath(row.externalAuthPath);+ if (row.externalAuthPath !== undefined && !externalAuthPath) return null;+ const project = boundedText(row.project, true);+ if (row.project !== undefined && !project) return null;+ if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "mcp-page"))) return null;+ const placements = row.placements === undefined ? undefined : [...new Set(row.placements)] as Array<"workflows" | "mcp-page">;+ seen.add(id);+ const reason = boundedText(row.reason);+ return {+ id, title, description: boundedText(row.description) ?? "", origin, startPath, renderer,+ presentation: presentation as SurfacePresentation, environment: environment as SurfaceEnvironment,+ ...(placements ? { placements } : {}), ...(project ? { project } : {}), ...(sandbox ? { sandbox } : {}), ...(externalAuthPath ? { externalAuthPath } : {}), ...(reason ? { reason } : {}),+ };+}++async function readOwnerRegistry(): Promise<string | undefined> {+ try {+ // Owner-local runtime configuration is not a build asset or a project-wide glob.+ const raw = await fs.readFile(/* turbopackIgnore: true */ surfaceRegistryPath(), "utf8");+ return Buffer.byteLength(raw, "utf8") <= MAX_RAW_BYTES ? raw : undefined;+ } catch {+ return undefined;+ }+}++function parseRegistry(raw: string | undefined): SurfaceApp[] {+ if (!raw || Buffer.byteLength(raw, "utf8") > MAX_RAW_BYTES) return [];+ let entries: unknown;+ try { entries = JSON.parse(raw); } catch { return []; }+ if (!Array.isArray(entries)) return [];+ const seen = new Set<string>();+ return entries.slice(0, MAX_APPS).map((entry) => parseApp(entry, seen)).filter((app): app is SurfaceApp => app !== null);+}++/**+ * Per-instance reviewed Page registry. An explicitly defined env value remains a+ * backwards-compatible deployment override (including an intentionally empty value).+ * Otherwise the owner-local registry is read on every call so adding/removing a+ * reviewed surface does not require changing portable source or rebuilding MSO.+ */+export async function configuredSurfaceApps(raw = process.env.MSO_SURFACE_APPS_JSON): Promise<SurfaceApp[]> {+ return parseRegistry(raw !== undefined ? raw : await readOwnerRegistry());+}diff --git a/lib/surfaces/manage.test.ts b/lib/surfaces/manage.test.tsnew file mode 100644index 00000000..d10d546f--- /dev/null+++ b/lib/surfaces/manage.test.ts@@ -0,0 +1,57 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { promises as fs } from "node:fs";+import os from "node:os";+import path from "node:path";+import { saveWorkflowSurface, surfaceRegistrySnapshot } from "./manage";+let dir: string, file: string;+const app = { id: "workflow-editor", title: "Editor", description: "Owner-approved editor", origin: "https://automation.example.test", startPath: "/editor", externalAuthPath: "/signin", renderer: "iframe", presentation: "inline", environment: "production" };+beforeEach(async () => { dir = await fs.mkdtemp(path.join(os.tmpdir(), "mso-surface-test-")); file = path.join(dir, "registry.json"); vi.stubEnv("MSO_SURFACE_APPS_FILE", file); vi.stubEnv("MSO_SURFACE_APPS_JSON", undefined); });+afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });+const save = async (value: Record<string, unknown> = app) => saveWorkflowSurface({ app: value, expectedRevision: (await surfaceRegistrySnapshot()).revision, confirm: true });+describe("owner-reviewed workflow surface configuration", () => {+ it("starts empty and preserves unrelated entries through an exact revision update", async () => {+ expect((await surfaceRegistrySnapshot()).apps).toEqual([]);+ const unrelated = { ...app, id: "existing-page", arbitraryFutureField: "preserve" };+ await fs.writeFile(file, JSON.stringify([unrelated]));+ const before = await surfaceRegistrySnapshot();+ const out = await save();+ const entries = JSON.parse(await fs.readFile(file, "utf8"));+ expect(entries[0]).toEqual(unrelated); expect(entries[1]).toMatchObject({ ...app, placements: ["workflows"] });+ expect(out.revision).not.toBe(before.revision); expect((await fs.stat(file)).mode & 0o777).toBe(0o600);+ });+ it("rejects stale updates and concurrent lost writes", async () => {+ const revision = (await surfaceRegistrySnapshot()).revision;+ await save();+ await expect(saveWorkflowSurface({ app: { ...app, title: "Changed" }, expectedRevision: revision, confirm: true })).rejects.toThrow("surface_registry_changed_reload");+ expect((await surfaceRegistrySnapshot()).apps[0].title).toBe("Editor");+ });+ it("replaces only the selected id and retains one stable identity", async () => {+ await save(); await save({ ...app, title: "Renamed" });+ expect((await surfaceRegistrySnapshot()).apps).toHaveLength(1);+ expect((await surfaceRegistrySnapshot()).apps[0].title).toBe("Renamed");+ });+ it("refuses environment-managed registries without writing a file", async () => {+ vi.stubEnv("MSO_SURFACE_APPS_JSON", "[]");+ await expect(save()).rejects.toThrow("surface_registry_managed_by_environment");+ expect((await surfaceRegistrySnapshot()).configurable).toBe(false);+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });+ });+ it.each([{ accessToken: "not-accepted" }, { origin: "http://unsafe.example.test" }, { externalAuthPath: "/signin?token=bad" }, { placements: ["settings"] }])("refuses unsafe or secret-bearing configuration %j", async (change) => {+ await expect(save({ ...app, ...change })).rejects.toThrow();+ await expect(fs.stat(file)).rejects.toMatchObject({ code: "ENOENT" });+ });+ it("requires explicit review and refuses caller-provided filesystem paths", async () => {+ await expect(saveWorkflowSurface({ app, expectedRevision: "x", confirm: false })).rejects.toThrow("explicit_review_required");+ await expect(saveWorkflowSurface({ app, expectedRevision: "x", confirm: true, path: file })).rejects.toThrow("explicit_review_required");+ });+ it("does not overwrite malformed existing configuration", async () => {+ await fs.writeFile(file, "{broken");+ await expect(save()).rejects.toThrow("invalid_existing_surface_registry");+ expect(await fs.readFile(file, "utf8")).toBe("{broken");+ });+ it("refuses duplicate identities and registry overflow", async () => {+ await fs.writeFile(file, JSON.stringify([app, app])); await expect(save()).rejects.toThrow("duplicate_surface_identity");+ await fs.writeFile(file, JSON.stringify(Array.from({ length: 16 }, (_, i) => ({ ...app, id: `other-${i}` }))));+ await expect(save()).rejects.toThrow("surface_registry_capacity");+ });+});diff --git a/lib/surfaces/manage.ts b/lib/surfaces/manage.tsnew file mode 100644index 00000000..c4eeecd9--- /dev/null+++ b/lib/surfaces/manage.ts@@ -0,0 +1,58 @@+import { constants, promises as fs } from "node:fs";+import { createHash, randomUUID } from "node:crypto";+import { configuredSurfaceApps, surfaceRegistryPath } from "./config";+import { withSecurityStoreLock } from "@/lib/security-store-lock";++const MAX_BYTES = 16_384;+const APP_FIELDS = new Set(["id", "title", "description", "origin", "startPath", "renderer", "presentation", "environment", "sandbox", "externalAuthPath", "reason", "project", "placements"]);+export class SurfaceConfigError extends Error {+ constructor(message: string, readonly status = 400) { super(message); }+}+async function readRegistry() {+ const env = process.env.MSO_SURFACE_APPS_JSON;+ if (env !== undefined) return { raw: env, managedByEnvironment: true };+ let handle;+ try {+ handle = await fs.open(/* turbopackIgnore: true */ surfaceRegistryPath(), constants.O_RDONLY | constants.O_NOFOLLOW);+ const stat = await handle.stat();+ if (!stat.isFile() || stat.size > MAX_BYTES || stat.uid !== process.getuid?.()) throw new SurfaceConfigError("unsafe_surface_registry", 409);+ return { raw: await handle.readFile("utf8"), managedByEnvironment: false };+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { raw: "[]", managedByEnvironment: false };+ throw error;+ } finally { await handle?.close(); }+}+const revision = (raw: string) => createHash("sha256").update(raw).digest("hex");+export async function surfaceRegistrySnapshot() {+ const state = await readRegistry();+ return { revision: revision(state.raw), configurable: !state.managedByEnvironment, apps: await configuredSurfaceApps(state.raw) };+}+/** Explicit owner operation. Never accepts a filesystem path or credential values. */+export async function saveWorkflowSurface(input: Record<string, unknown>) {+ if (Object.keys(input).some((key) => !["app", "expectedRevision", "confirm"].includes(key)) || input.confirm !== true) throw new SurfaceConfigError("explicit_review_required");+ const app = input.app;+ if (!app || typeof app !== "object" || Array.isArray(app) || Object.keys(app).some((key) => !APP_FIELDS.has(key))) throw new SurfaceConfigError("invalid_surface_metadata");+ const row = app as Record<string, unknown>;+ if (row.placements !== undefined && JSON.stringify(row.placements) !== JSON.stringify(["workflows"])) throw new SurfaceConfigError("invalid_workflow_placement");+ const normalized = await configuredSurfaceApps(JSON.stringify([{ ...row, placements: ["workflows"] }]));+ if (normalized.length !== 1) throw new SurfaceConfigError("invalid_surface_metadata");+ const selected = normalized[0];+ if (selected.externalAuthPath?.includes("?")) throw new SurfaceConfigError("workflow_login_path_must_not_contain_query");+ return withSecurityStoreLock(surfaceRegistryPath(), async () => {+ const current = await readRegistry();+ if (current.managedByEnvironment) throw new SurfaceConfigError("surface_registry_managed_by_environment", 409);+ if (input.expectedRevision !== revision(current.raw)) throw new SurfaceConfigError("surface_registry_changed_reload", 409);+ let entries: Array<Record<string, unknown>>;+ try { entries = JSON.parse(current.raw); } catch { throw new SurfaceConfigError("invalid_existing_surface_registry", 409); }+ if (!Array.isArray(entries) || entries.some((entry) => !entry || typeof entry !== "object" || Array.isArray(entry))) throw new SurfaceConfigError("invalid_existing_surface_registry", 409);+ const matches = entries.filter((entry) => entry.id === selected.id);+ if (matches.length > 1) throw new SurfaceConfigError("duplicate_surface_identity", 409);+ const next = matches.length ? entries.map((entry) => entry.id === selected.id ? selected : entry) : [...entries, selected];+ const raw = JSON.stringify(next, null, 2) + "\n";+ if (next.length > 16 || Buffer.byteLength(raw) > MAX_BYTES) throw new SurfaceConfigError("surface_registry_capacity", 409);+ const file = surfaceRegistryPath(), temporary = `${file}.${randomUUID()}.tmp`;+ try { await fs.writeFile(temporary, raw, { mode: 0o600, flag: "wx" }); await fs.rename(temporary, file); }+ finally { await fs.unlink(temporary).catch(() => undefined); }+ return { revision: revision(raw), configurable: true, id: selected.id };+ });+}diff --git a/scripts/cli/commands.sh b/scripts/cli/commands.shindex 3c827cf8..b2c32f0a 100755--- a/scripts/cli/commands.sh+++ b/scripts/cli/commands.sh@@ -25,7 +25,7 @@ U_camoufox="camoufox status|start|stop|session"U_gateway="gateway start [--config <cloudflared.yml> --tunnel <name|uuid>]|stop|status|url|doctor|install|domain show|set <https://host>|clear"U_doctor="doctor [--fix]"U_flow="flow list|inspect <id> [--project <project>]|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|save|delete <id> --revision <revision> [--input <JSON|@file>]"-U_workflow="workflow list|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"+U_workflow="workflow list|embeds|embed-save --input <JSON|@file>|show <id>|create --input <JSON|@file>|save <id> --revision <revision> --input <JSON|@file>|clone <id>|delete <id> --revision <revision>|run <id> --input <JSON|@file> --key <id> [--wait]|status <run-id> [--wait]|runs <id>|versions <id>|restore <id> --revision <current> --version <saved>|catalog [--query q]|templates|template <id>|variables|variable-set <KEY> --input <JSON> [--secret]|variable-delete <KEY>|ai --prompt <text>"U_integrations="integrations [interactive]|transfer|status|users|catalog|connections [user] [provider]|which [folder]|request|resolve <user> <provider> [connection]|create-user <id> [label]|create-connection <user> <provider> <id> <source> <auth>|manage <JSON>|setup|verify <user> <provider> <connection>|hostinger-mail-orders|hostinger-mail-list|hostinger-mail-logs|execute <JSON>"U_provider="provider list|show <id>|setup <provider> <user> <connection>|set <id>|rm <id>|doctor [id]|projects|zones"U_model="model [current|list [provider]|set <provider> <model>|set <provider/model>|<model-or-ref>]"diff --git a/scripts/cli/workflows.sh b/scripts/cli/workflows.shindex cbcae61a..5f67bccb 100644--- a/scripts/cli/workflows.sh+++ b/scripts/cli/workflows.sh@@ -22,6 +22,8 @@ run_workflow() {if [ "${input:0:1}" = "@" ]; then input=$(cat -- "${input:1}"); ficase "$sub" inlist) jget "/api/v1/workflows"; return ;;+ embeds) jget "/api/v1/workflow-embeds"; return ;;+ embed-save) jpost "/api/v1/workflow-embeds" "$input"; return ;;show) jget "/api/v1/workflows?graph_id=$(enc "$id")"; return ;;runs) jget "/api/v1/workflows?runs=1&graph_id=$(enc "$id")"; return ;;versions) jget "/api/v1/workflows?versions=$(enc "$id")"; return ;;diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjsindex fc8740e5..29170b83 100644--- a/scripts/e2e/release-fixture.mjs+++ b/scripts/e2e/release-fixture.mjs@@ -6,7 +6,7 @@ import { createServer } from "node:http";import { createHash, randomUUID, randomBytes } from "node:crypto";import { spawn } from "node:child_process";-export async function releaseFixture({ live = false } = {}) {+export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {const dir = await mkdtemp(path.join(tmpdir(), "mso-release-e2e-"));let providerStatus = 200;const provider = createServer((req, res) => {@@ -36,10 +36,13 @@ export async function releaseFixture({ live = false } = {}) {createdAt: Date.now(), updatedAt: Date.now(), verifiedAt: Date.now() } } } } },}), { mode: 0o600 });// Never read deployment .env.local or borrow its credential/device stores.+ const surfaceRegistry = path.join(dir, "surface-apps.json");+ await writeFile(surfaceRegistry, JSON.stringify(surfaceApps), { mode: 0o600 });const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !/^(OS_|MSO_|NEXT_PUBLIC_)/.test(key)));const example = await readFile(path.join(process.cwd(), ".env.example"), "utf8");for (const [, key] of example.matchAll(/\b((?:OS|MSO)_[A-Z_]*(?:STORE|PATH|DIR|LOG))=/g)) env[key] = path.join(dir, key.toLowerCase());Object.assign(env, {+ MSO_SURFACE_APPS_FILE: surfaceRegistry,OS_DEVICE_STORE: deviceFile, OS_INFRA_STORE: path.join(dir, "infra.json"),OS_CONFIG_STORE: path.join(dir, "config.json"), OS_PREFS_PATH: path.join(dir, "prefs.json"),OS_AUDIT_LOG: path.join(dir, "audit.jsonl"), OS_LOGIN_PASSWORD: password,diff --git a/scripts/e2e/workflow-embeds.mjs b/scripts/e2e/workflow-embeds.mjsnew file mode 100644index 00000000..2ce7204e--- /dev/null+++ b/scripts/e2e/workflow-embeds.mjs@@ -0,0 +1,130 @@+#!/usr/bin/env node+import { chromium, expect } from '@playwright/test';+import { mkdir, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { releaseFixture } from './release-fixture.mjs';++const app = { id: 'automation', title: 'n8n', description: 'Reviewed test provider', origin: 'https://automation.example.test', startPath: '/editor', externalAuthPath: '/signin', renderer: 'iframe', presentation: 'inline', environment: 'production', placements: ['workflows'], sandbox: 'allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox allow-downloads' };+const liveOrigin = process.env.E2E_WORKFLOW_EMBED_ORIGIN;+const parentOrigin = process.env.E2E_WORKFLOW_EMBED_PARENT_ORIGIN;+if (liveOrigin && (!parentOrigin || !parentOrigin.startsWith('https://') || new URL(parentOrigin).origin !== parentOrigin)) throw new Error('Exact approved HTTPS E2E_WORKFLOW_EMBED_PARENT_ORIGIN required for live policy verification');+if (liveOrigin && (new URL(liveOrigin).origin !== liveOrigin || !liveOrigin.startsWith('https://'))) throw new Error('Exact HTTPS E2E_WORKFLOW_EMBED_ORIGIN required');+const fixture = await releaseFixture({ surfaceApps: [app] });+let browser;+const evidence = [];+try {+ browser = await chromium.launch({ headless: true });+ const context = await browser.newContext({ viewport: { width: 1280, height: 900 } });+ await context.addInitScript(device => { if (window !== window.top) return; localStorage.setItem('mso.device.id', device); localStorage.setItem('mso:onboarding:v1', 'done'); }, fixture.device);+ let frameRequests = 0;+ await context.route('https://automation.example.test/**', async route => {+ frameRequests++;+ await route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><head><title>Fixture editor</title></head><body><h1>Fixture editor</h1><label>External draft <input aria-label="External draft"></label></body></html>' });+ });+ const page = await context.newPage();+ page.setDefaultTimeout(15000);+ page.setDefaultNavigationTimeout(30000);+ const frameNetwork = [];+ page.on("requestfailed", request => { if (liveOrigin && request.url().startsWith(liveOrigin)) frameNetwork.push({ path: new URL(request.url()).pathname, error: request.failure()?.errorText }); });+ page.on("response", response => { if (liveOrigin && response.url().startsWith(liveOrigin) && response.status() >= 400) frameNetwork.push({ path: new URL(response.url()).pathname, status: response.status() }); });+ const errors = [];+ page.on('pageerror', error => errors.push(error.message));+ await page.goto(fixture.base + '/login?returnTo=%2Fworkflows');+ await page.locator('input[type="password"]').fill(fixture.password);+ await page.getByRole('button', { name: 'Unlock', exact: true }).click();+ await expect(page).toHaveURL(fixture.base + '/workflows');+ await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toBeVisible();+ expect(frameRequests).toBe(0);+ const saved = await page.evaluate(async app => {+ const state = await (await fetch('/api/v1/workflow-embeds')).json();+ const input = { app, expectedRevision: state.revision, confirm: true };+ const write = () => fetch('/api/v1/workflow-embeds', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(input) });+ const response = await write();+ return { status: response.status, updated: await response.json(), staleStatus: (await write()).status };+ }, app);+ expect(saved.status).toBe(200); expect(saved.updated.id).toBe(app.id); expect(saved.staleStatus).toBe(409);+ evidence.push({ ownerReviewedConfiguration: true, staleRevisionRejected: true });+ console.log('PASS owner metadata save and stale-revision refusal');+ const result = await page.evaluate(async () => {+ const res = await fetch('/api/v1/workflows', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ action: 'create', graph: { name: 'Native fixture', description: 'Private fixture', status: 'draft', inputs: {}, metadata: { provenance: 'user' }, nodes: [{ id: 'manual', name: 'Manual', type: 'manual', position: { x: 80, y: 160 }, config: {} }, { id: 'output', name: 'Output', type: 'output', position: { x: 420, y: 160 }, config: {} }], edges: [{ id: 'start', source: 'manual', target: 'output' }] } }) });+ return res.status;+ });+ expect(result).toBe(200);+ for (const viewport of [{ width: 1280, height: 900 }, { width: 390, height: 844 }, { width: 844, height: 390 }]) {+ await page.setViewportSize(viewport);+ await page.reload();+ await expect(page.getByLabel('Workflow name')).toHaveValue('Native fixture');+ await page.getByLabel('Workflow name').fill('Unsaved fixture');+ await page.getByRole('tab', { name: 'n8n', exact: true }).click();+ const frame = page.frameLocator('iframe[title="n8n workflow editor"]');+ await expect(frame.getByRole('heading', { name: 'Fixture editor' })).toBeVisible();+ await frame.getByLabel('External draft').fill('External unsaved draft');+ const requestsBeforeSwitch = frameRequests;+ await page.getByRole('tab', { name: 'MSO', exact: true }).click();+ await expect(page.getByLabel('Workflow name')).toHaveValue('Unsaved fixture');+ await page.getByRole('tab', { name: 'MSO', exact: true }).press('ArrowRight');+ await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toBeFocused();+ await expect(frame.getByLabel('External draft')).toHaveValue('External unsaved draft');+ expect(frameRequests).toBe(requestsBeforeSwitch);+ expect(await page.locator('[data-slot="workflows-workspace"]').evaluate(el => el.scrollWidth <= el.clientWidth + 1)).toBe(true);+ const iframeBox = await page.locator('iframe[title="n8n workflow editor"]').boundingBox();+ if (iframeBox.height <= 120 && process.env.E2E_EVIDENCE_DIR) {+ await mkdir(process.env.E2E_EVIDENCE_DIR, { recursive: true });+ await page.screenshot({ path: path.join(process.env.E2E_EVIDENCE_DIR, 'embed-height-diagnostic.png'), fullPage: true });+ console.log(JSON.stringify({ viewport, iframeBox, layout: await page.locator('[data-slot="workflows-workspace"]').evaluate(el => ({ workspace: el.getBoundingClientRect().toJSON(), children: [...el.children].map(x => ({ tag: x.tagName, hidden: x.hidden, rect: x.getBoundingClientRect().toJSON() })) })) }));+ }+ expect(iframeBox.height).toBeGreaterThan(120);+ await expect(page.getByRole('link', { name: 'Sign in', exact: true })).toHaveAttribute('href', app.origin + '/signin');+ await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toHaveAttribute('target', '_blank');+ await page.getByRole('button', { name: 'Reload n8n', exact: true }).click();+ await expect(frame.getByLabel('External draft')).toHaveValue('');+ evidence.push({ viewport, nativeDraftPreserved: true, externalDraftPreserved: true, reload: true, keyboard: true, reflow: true, frameHeight: iframeBox.height });+ }+ console.log('PASS provider tabs, native/external draft preservation and all three viewport sizes');+ await fixture.setRole('viewer');+ expect(await page.evaluate(async () => (await fetch('/api/v1/workflow-embeds')).status)).toBe(403);+ await page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await expect(page.getByRole('tab', { name: 'n8n', exact: true })).toHaveCount(0);+ await expect(page.locator('iframe[title="n8n workflow editor"]')).toHaveCount(0);+ console.log('PASS demotion response and removed frame');+ await fixture.setRole('owner');+ await writeFile(path.join(fixture.dir, 'surface-apps.json'), JSON.stringify([{ ...app, renderer: 'remote', reason: 'Fixture provider requires top-level access' }]));+ await page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await page.getByRole('tab', { name: 'n8n', exact: true }).click();+ await expect(page.getByText('Fixture provider requires top-level access')).toBeVisible();+ await expect(page.locator('iframe[title="n8n workflow editor"]')).toHaveCount(0);+ evidence.push({ ownerDemotion: '403 and frame removed', remoteOnly: 'no iframe' });+ console.log('PASS remote-only fallback');+ if (liveOrigin) {+ await writeFile(path.join(fixture.dir, 'surface-apps.json'), JSON.stringify([{ ...app, id: 'live-n8n', origin: liveOrigin, startPath: '/home/workflows' }]));+ await page.setViewportSize({ width: 1280, height: 900 });+ await page.evaluate(() => window.dispatchEvent(new Event('focus')));+ await page.locator('[role="tab"][id$="-tab-live-n8n"]').click();+ await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toHaveAttribute('href', liveOrigin + '/home/workflows');+ await expect.poll(() => frameNetwork.some(row => row.error === 'net::ERR_BLOCKED_BY_RESPONSE'), {timeout:20000}).toBe(true);+ await expect(page.getByRole('link', { name: 'Open n8n', exact: true })).toBeVisible();+ evidence.push({ unapprovedLocalParentBlocked: true, fallbackVisible: true });+ const probe = await browser.newContext({ viewport: { width: 1280, height: 900 } });+ const probePage = await probe.newPage();+ probePage.setDefaultTimeout(15000);+ const probeUrl = parentOrigin + '/__workflow_embed_policy_probe__';+ // Synthetic parent document at the explicitly approved origin; the child is+ // live n8n. No owner session, response-header rewrite or browser-security flag.+ await probe.route(probeUrl, route => route.fulfill({ contentType: 'text/html', body: '<!doctype html><html><head><title>n8n frame policy verification</title></head><body style="margin:0"><iframe title="Live n8n" style="width:100vw;height:100vh;border:0" referrerpolicy="no-referrer" sandbox="' + app.sandbox + '" src="' + liveOrigin + '/home/workflows"></iframe></body></html>' }));+ await probePage.goto(probeUrl);+ await expect(probePage.frameLocator('iframe').locator('input[type="password"]')).toBeVisible({ timeout:30000 });+ evidence.push({ liveProvider: liveOrigin, approvedParentOrigin: parentOrigin, parentDocumentIsSynthetic: true, signedOutLoginRendered: true, authenticatedEditorTested: false });+ if (process.env.E2E_EVIDENCE_DIR) {+ await mkdir(process.env.E2E_EVIDENCE_DIR, { recursive: true });+ await probePage.screenshot({ path: path.join(process.env.E2E_EVIDENCE_DIR, 'n8n-approved-parent-desktop.png'), fullPage: true });+ await probePage.setViewportSize({ width: 390, height: 844 });+ await expect(probePage.frameLocator('iframe').locator('input[type="password"]')).toBeVisible();+ await probePage.screenshot({ path: path.join(process.env.E2E_EVIDENCE_DIR, 'n8n-approved-parent-mobile.png'), fullPage: true });+ }+ await probe.close();+ }+ expect(errors).toEqual([]);+ if (process.env.E2E_EVIDENCE_DIR) await writeFile(path.join(process.env.E2E_EVIDENCE_DIR, 'workflow-embed-browser.json'), JSON.stringify({ passed: true, evidence }, null, 2));+ console.log(JSON.stringify({ passed: true, evidence }, null, 2));+ await context.close();+} finally { await browser?.close(); await fixture.close(); }