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(apps): reuse MSO sessions for private connected apps
Abdurrahman Fakhrul5c2c7e8fbd11
diff --git a/app/api/v1/shell-apps/[id]/session/route.test.ts b/app/api/v1/shell-apps/[id]/session/route.test.tsnew file mode 100644index 00000000..c6db38e1--- /dev/null+++ b/app/api/v1/shell-apps/[id]/session/route.test.ts@@ -0,0 +1,41 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { GET } from "./route";+import { verifyShellAppCredential } from "@/lib/surfaces/session";+const mocks = vi.hoisted(() => ({ context: vi.fn() }));+vi.mock("@/lib/auth/require-session", () => ({ getSessionContext: mocks.context }));+vi.mock("@/lib/demo", () => ({ IS_DEMO: false }));+const app = { id: "private-editor", origin: "https://editor.cockpit.example.test", title: "Editor", description: "", startPath: "/",+ renderer: "iframe", presentation: "inline", environment: "production", placements: ["shell"], sessionUpstream: "http://127.0.0.1:9131" };+const secret = "test-secret".repeat(4);+const context = { params: Promise.resolve({ id: app.id }) };+const request = (query = "") => new Request(`https://cockpit.example.test/api/v1/shell-apps/${app.id}/session${query}`);+beforeEach(() => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://cockpit.example.test"); vi.stubEnv("OS_SESSION_SECRET", secret);+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app])); vi.stubEnv("PORT", "4005");+ mocks.context.mockResolvedValue({ role: "owner", session: { issued_at: Date.now(), expires_at: Date.now() + 3600_000,+ device_id: "owner-device", cookie_scope: "host", cookie_epoch: "test-cookie-epoch00000000" } });+});+afterEach(() => vi.unstubAllEnvs());+describe("connected-app browser handoff", () => {+ it.each([null, "viewer", "operator"])("refuses a handoff for %s", async role => {+ mocks.context.mockResolvedValue(role ? { role } : null);+ const result = await GET(request("?redirect=1"), context);+ expect(result.status).toBe(401); expect(result.headers.get("location")).toBeNull();+ });+ it("issues a minute-long app-bound ticket with no cached credential", async () => {+ const response = await GET(request(), context), body = await response.json();+ expect(body.origin).toBe(app.origin); expect(response.headers.get("cache-control")).toContain("no-store");+ const payload = verifyShellAppCredential(app, body.ticket, secret, "ticket")!;+ expect(payload.device_id).toBe("owner-device"); expect(payload.expires_at - Date.now()).toBeLessThanOrEqual(60_000);+ });+ it("redirects only into the reviewed origin with the ticket in a URL fragment", async () => {+ const response = await GET(request("?redirect=1&url=https://attacker.example.test"), context);+ const target = new URL(response.headers.get("location")!);+ expect(response.status).toBe(302); expect(target.origin).toBe(app.origin); expect(target.search).toBe("");+ expect(target.hash).toMatch(/^#app_ticket=/); expect(response.headers.get("referrer-policy")).toBe("no-referrer");+ });+ it("does not enable login delegation for arbitrary external apps", async () => {+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, sessionUpstream: undefined }]));+ expect((await GET(request(), context)).status).toBe(404);+ });+});diff --git a/app/api/v1/shell-apps/[id]/session/route.ts b/app/api/v1/shell-apps/[id]/session/route.tsnew file mode 100644index 00000000..2a40eaa2--- /dev/null+++ b/app/api/v1/shell-apps/[id]/session/route.ts@@ -0,0 +1,22 @@+import { NextResponse } from "next/server";+import { getSessionContext } from "@/lib/auth/require-session";+import { createShellAppCredential, sessionApps } from "@/lib/surfaces/session";+import { shellSessionHeaders } from "@/lib/surfaces/session-gate";+import { IS_DEMO } from "@/lib/demo";++export const runtime = "nodejs";+export const dynamic = "force-dynamic";+export async function GET(request: Request, context: { params: Promise<{ id: string }> }) {+ const headers = shellSessionHeaders(), { id } = await context.params;+ const app = !IS_DEMO && (await sessionApps()).find(entry => entry.id === id);+ if (!app) return NextResponse.json({ error: "unavailable" }, { status: 404, headers });+ const session = await getSessionContext(), redirect = new URL(request.url).searchParams.get("redirect") === "1";+ if (!session || session.role !== "owner") {+ return NextResponse.json({ error: "unauthorized" }, { status: 401, headers });+ }+ const ticket = createShellAppCredential(app, session.session, process.env.OS_SESSION_SECRET ?? "", "ticket");+ if (!redirect) return NextResponse.json({ origin: app.origin, ticket }, { headers });+ const destination = new URL(app.startPath, app.origin);+ destination.hash = new URLSearchParams({ app_ticket: ticket }).toString();+ return new NextResponse(null, { status: 302, headers: { ...headers, location: destination.href } });+}diff --git a/bin/mso.test.ts b/bin/mso.test.tsindex b809451b..6bc25277 100644--- a/bin/mso.test.ts+++ b/bin/mso.test.ts@@ -128,6 +128,7 @@ describe("bin/mso", () => {"POST /api/integrations/google/start","GET /api/integrations/google/callback","GET /api/sw",+ "GET /api/v1/shell-apps/[id]/session", // Browser-only, origin-bound handoff into a reviewed app; no credential-returning CLI verb."POST /api/v1/channels/telegram/[id]", // Provider callback: requires Telegram webhook signature, not a user CLI action."POST /api/v1/channels/discord/[id]", // Provider callback: requires Discord Ed25519 signature, not a user CLI action."/api/v1/managed-apps/[id]/proxy/[[...path]]",diff --git a/components/external-app-frame.tsx b/components/external-app-frame.tsxindex 66e82acb..1993aa56 100644--- a/components/external-app-frame.tsx+++ b/components/external-app-frame.tsx@@ -29,6 +29,6 @@ export function ExternalAppFrame({ app, frameTitle }: { app: WorkflowEmbed; fram{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}:${app.sandbox}`} src={app.url} title={frameTitle ?? `${app.title} application`} 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>+ <p className="shrink-0 border-t px-3 py-1.5 text-xs text-muted-foreground [@media(max-height:520px)]:sr-only">{app.msoSession ? `${app.title} uses your MSO session.` : `${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/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 79eaf8da..8aa492ca 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -8,6 +8,7 @@ this is the *what*, and it is what Settings → Account → About shows as “Wh**Added**+- `apps` reuse MSO sessions for private connected apps- `agent-vault` isolate repository progress in private Obsidian vaults**Fixed**diff --git a/docs/CONNECTED-APPS.md b/docs/CONNECTED-APPS.mdindex 5e4fdd12..b1a1cd07 100644--- a/docs/CONNECTED-APPS.md+++ b/docs/CONNECTED-APPS.md@@ -6,7 +6,15 @@ MSO is the shell and control surface. Connected applications run in their own seOpen App Store → Apps. Managed applications use the existing reviewed Hermes, OpenClaw and 9Router setup panels and their host preflight checks. For an already running external or custom tool, select Connect app, enter its name, stable ID and address, and choose an embedded window or separate tab. Entries persist on the server and appear in the shell without a rebuild. Edit updates the connection; Disconnect removes only the shell entry.-A subdomain is optional. HTTPS addresses can be embedded when the application permits framing. HTTP addresses open in a separate tab. Applications retain their own login. Addresses sharing the MSO session-cookie scope are rejected, including the same hostname on another port. Query strings, URL credentials and fragments are rejected; enter secrets only through the application's trusted setup flow.+A subdomain is optional. HTTPS addresses can be embedded when the application permits framing. HTTP addresses open in a separate tab. Ordinary external applications retain their own login; reviewed loopback services can opt into MSO sessions as described below. Addresses sharing the MSO session-cookie scope are rejected, including the same hostname on another port. Query strings, URL credentials and fragments are rejected; enter secrets only through the application's trusted setup flow.++## MSO sessions for reviewed loopback services++An operator may add `sessionUpstream` to a shell-only entry in the private surface registry, for example `"sessionUpstream": "http://127.0.0.1:9131"`. This accepts only a concrete HTTP loopback port and an isolated HTTPS application origin. A portable manifest or ordinary connection form cannot enable this mode. The public app view exposes `msoSession: true` and keeps the upstream address private. Metadata edits preserve the setting; changing the public origin removes it and requires fresh operator review.++Point that app's HTTPS ingress at the MSO server with the application's exact public Host and Origin preserved. MSO gates every app path before proxying to its reviewed loopback service. Its bootstrap navigates through the MSO login route, which immediately redirects an already authenticated browser; there is no second password prompt. Owner-only `GET /api/v1/shell-apps/[id]/session` gives a 60-second, origin- and purpose-bound ticket in a URL fragment. The app exchanges it at `/__mso_app_auth` for a Secure, HttpOnly, SameSite=Strict, host-only cookie. This derived session lasts at most two hours and never outlives the parent session. Cockpit cookies and authorization are stripped before the service sees a request.++The HTTP and WebSocket gates require a current Owner device, original session generation and live approval. Logout, device revocation, expiry and role demotion invalidate subsequent requests and close existing sockets through MSO's continuously authorized relay. The app host cannot serve cockpit APIs or framework assets. A TLS proxy must preserve WebSocket upgrades and the app's derived cookie; it must strip any cockpit cookie and must not cache authenticated responses. Backends, selected vaults, operator domains and user data remain installation state outside portable MSO source.## Current API and lifecyclediff --git a/docs/PROGRESS.md b/docs/PROGRESS.mdindex 2f3d6278..f3075bcc 100644--- a/docs/PROGRESS.md+++ b/docs/PROGRESS.md@@ -1,3 +1,9 @@+## 2026-10-09: Reuse MSO login for reviewed private applications++The Vault window previously used a separate Basic login even after the Owner signed into MSO. Reviewed shell-only loopback applications can now opt into an isolated MSO-derived session through private registry state. The existing browser session supplies a short-lived, exact-origin ticket; its app exchanges that fragment-only ticket for a host-only cookie without sharing the cockpit cookie or password. Normal external connections keep their own authentication and portable manifests cannot grant this mode.++Every app HTTP request requires the current Owner role and durable device/session generation. WebSockets use the existing continuously authorized server relay, so demotion, logout, revocation and expiry stop both directions rather than authorizing only the initial upgrade. App cookies cannot authenticate cockpit APIs, upstream requests strip all MSO credentials, and duplicate hosts/off-box targets fail closed. The derived cookie retains the parent expiry independently of the one-minute ticket. Regression coverage checks purpose/origin separation, expiry, role changes, cookie stripping, proxy routing and production HTTP/socket handoff with synthetic stores. Instance ingress, domain and vault data remain outside source.+## 2026-10-09: Preserve security regressions without synthetic scanner noisePost-release GitHub checks found two test-only matches. The growing-file regression now changes bytes through the already-open descriptor, preserving the actual-byte limit assertion without introducing a pathname check/reopen race in its fixture. Agent Vault constructs its deterministic redaction fixture from pieces; the original historical Gitleaks fingerprint is narrowly recorded after verifying every reachable commit. No production credential, scanner rule or release gate is excluded.diff --git a/lib/contracts/surface-app.ts b/lib/contracts/surface-app.tsindex 50e72ae5..8f739e9f 100644--- a/lib/contracts/surface-app.ts+++ b/lib/contracts/surface-app.ts@@ -17,9 +17,12 @@ export type SurfaceApp = {reason?: string;project?: string;placements?: SurfacePlacement[];+ /** Owner-reviewed loopback application using an isolated MSO-derived session. */+ sessionUpstream?: string;};export type WorkflowEmbed = {id: string; title: string; description: string; origin: string; url?: string; blocked?: boolean;loginUrl?: string; renderer: SurfaceRenderer; sandbox: string; reason?: string;+ msoSession?: boolean;};diff --git a/lib/managed-apps/socket-policy.ts b/lib/managed-apps/socket-policy.tsindex d13dfef7..c53bd6d7 100644--- a/lib/managed-apps/socket-policy.ts+++ b/lib/managed-apps/socket-policy.ts@@ -12,6 +12,7 @@ import { getManagedAppDefinition } from "./catalog";import { managedAppUpstream } from "./upstream-target";import { upstreamSocketHeaders } from "./proxy-headers";import { IS_DEMO } from "@/lib/demo";+import { shellAppSocketPolicy } from "@/lib/surfaces/socket-policy";export async function socketPolicy(request: NextRequest) {if (IS_DEMO || request.method !== "GET") return null;@@ -19,7 +20,7 @@ export async function socketPolicy(request: NextRequest) {if (origin) { try { if (new URL(origin).host !== host) return null; } catch { return null; } }if (!/(?:^|,)\s*websocket\s*(?:,|$)/i.test(request.headers.get("upgrade") ?? "")) return null;const viewer = isCamoufoxViewerHost(host), app = managedAppIdForHost(host);- if (!viewer && !app) return null;+ if (!viewer && !app) return shellAppSocketPolicy(request);const secret = process.env.OS_SESSION_SECRET ?? "";let identity: string | undefined;for (const { value } of request.cookies.getAll(viewer ? CAMOUFOX_VIEWER_COOKIE : MANAGED_APP_SESSION_COOKIE)) {diff --git a/lib/surfaces/config.ts b/lib/surfaces/config.tsindex 03b0351d..5094aa12 100644--- a/lib/surfaces/config.ts+++ b/lib/surfaces/config.ts@@ -74,12 +74,23 @@ function parseApp(entry: unknown, seen: Set<string>): SurfaceApp | null {if (row.project !== undefined && !project) return null;if (row.placements !== undefined && (!Array.isArray(row.placements) || row.placements.some((value) => value !== "workflows" && value !== "n8n" && value !== "mcp-page" && value !== "shell"))) return null;const placements = row.placements === undefined ? undefined : [...new Set(row.placements)] as SurfacePlacement[];+ let sessionUpstream: string | undefined;+ if (row.sessionUpstream !== undefined) {+ try {+ const target = new URL(String(row.sessionUpstream));+ if (!shellOnly || renderer !== "iframe" || !origin.startsWith("https://") || target.protocol !== "http:" ||+ !["127.0.0.1", "localhost", "[::1]"].includes(target.hostname) || !target.port ||+ target.username || target.password || target.pathname !== "/" || target.search || target.hash) return null;+ sessionUpstream = target.origin;+ } catch { 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,...(placements ? { placements } : {}), ...(project ? { project } : {}), ...(sandbox !== undefined ? { sandbox } : {}), ...(externalAuthPath ? { externalAuthPath } : {}), ...(reason ? { reason } : {}),+ ...(sessionUpstream ? { sessionUpstream } : {}),};}diff --git a/lib/surfaces/session-gate.ts b/lib/surfaces/session-gate.tsnew file mode 100644index 00000000..fe613d6b--- /dev/null+++ b/lib/surfaces/session-gate.ts@@ -0,0 +1,41 @@+import { NextResponse, type NextRequest } from "next/server";+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import type { SurfaceApp } from "@/lib/contracts/surface-app";+import { createShellAppCredential, verifyShellAppCredential, shellAppSession, SHELL_APP_COOKIE, SHELL_APP_COOKIE_TTL } from "./session";++export function shellSessionHeaders() {+ return { "cache-control": "no-store, no-transform", "cdn-cache-control": "no-store", "cloudflare-cdn-cache-control": "no-store",+ "referrer-policy": "no-referrer", "x-content-type-options": "nosniff" };+}+export function shellAppResponseHeaders() {+ return { ...shellSessionHeaders(), "content-security-policy": `frame-ancestors ${new URL(process.env.OS_PUBLIC_ORIGIN!).origin}` };+}+function response(body: string | null, status: number, contentType = "text/plain; charset=utf-8") {+ return new NextResponse(body, { status, headers: { ...shellAppResponseHeaders(), "content-type": contentType,+ "content-security-policy": `default-src 'none'; script-src 'self'; connect-src 'self'; frame-ancestors ${new URL(process.env.OS_PUBLIC_ORIGIN!).origin}` } });+}+function script(app: SurfaceApp) {+ const cockpit = new URL(process.env.OS_PUBLIC_ORIGIN!).origin;+ const login = new URL("/login", cockpit);+ login.searchParams.set("returnTo", `/api/v1/shell-apps/${encodeURIComponent(app.id)}/session?redirect=1`);+ return `(async()=>{const p=new URLSearchParams(location.hash.slice(1));const t=p.get('app_ticket');p.delete('app_ticket');history.replaceState(null,'',location.pathname+location.search+(p.toString()?'#'+p.toString():''));if(!t){location.replace(${JSON.stringify(login)});return;}const r=await fetch('/__mso_app_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});if(!r.ok){document.body.textContent='MSO session expired. Reopen this application from MSO.';return;}location.reload();})().catch(()=>{document.body.textContent='Application authorization failed.';});`;+}+export async function gateShellApp(request: NextRequest, app: SurfaceApp) {+ const pathname = request.nextUrl.pathname;+ if (pathname === "/__mso_app_bootstrap.js") return request.method === "GET" ? response(script(app), 200, "application/javascript; charset=utf-8") : response(null, 404);+ if (pathname === "/__mso_app_auth") {+ if (request.method !== "POST" || request.headers.get("origin") !== app.origin) return response(null, 403);+ const token = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "")?.[1];+ const secret = process.env.OS_SESSION_SECRET ?? "";+ const session = token ? verifyShellAppCredential(app, token, secret, "ticket") : null;+ if (!session || !await liveSessionAuthorized(session, "owner")) return response(null, 401);+ const result = response(null, 204);+ result.cookies.set(SHELL_APP_COOKIE, createShellAppCredential(app, session, secret, "cookie"), {+ httpOnly: true, secure: true, sameSite: "strict", path: "/", maxAge: Math.floor(Math.max(0, Math.min(SHELL_APP_COOKIE_TTL, session.parent_expires_at - Date.now()) / 1000)),+ });+ return result;+ }+ if (await shellAppSession(request, app)) return null;+ if (request.method !== "GET" || !["document", "iframe"].includes(request.headers.get("sec-fetch-dest") ?? "")) return response(null, 401);+ return response('<!doctype html><meta charset="utf-8"><title>MSO application authorization</title><body><p>Authorizing application...</p><script src="/__mso_app_bootstrap.js" defer></script></body>', 200, "text/html; charset=utf-8");+}diff --git a/lib/surfaces/session-proxy.test.ts b/lib/surfaces/session-proxy.test.tsnew file mode 100644index 00000000..f304e4d7--- /dev/null+++ b/lib/surfaces/session-proxy.test.ts@@ -0,0 +1,46 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { createShellAppCredential, SHELL_APP_COOKIE } from "./session";+import { proxy } from "../../proxy";+import { socketPolicy } from "@/lib/managed-apps/socket-policy";++vi.mock("@/lib/auth/device-store", () => ({+ currentSessionPolicy: async () => ({ scope: "host", epoch: "test-cookie-epoch00000000" }),+ getApprovedDevice: async () => ({ approvedAt: 1, role: "owner" }),+}));+const app = { id: "private-editor", origin: "https://editor.cockpit.example.test", title: "Editor", description: "", startPath: "/",+ renderer: "iframe", presentation: "inline", environment: "production", placements: ["shell"], sessionUpstream: "http://127.0.0.1:9131" };+const secret = "test-secret".repeat(4);+const credential = () => createShellAppCredential(app, { issued_at: Date.now(), expires_at: Date.now() + 3600_000,+ device_id: "owner-device", cookie_scope: "host", cookie_epoch: "test-cookie-epoch00000000" }, secret, "cookie");+const request = (path = "/", method = "GET", origin = app.origin, cookie = credential()) => new NextRequest(app.origin + path, {+ method, headers: { host: new URL(app.origin).host, origin, cookie: `${SHELL_APP_COOKIE}=${cookie}; session=cockpit-cookie`, authorization: "Bearer cockpit-secret", upgrade: method === "GET" ? "h2c" : "" },+});+beforeEach(() => {+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://cockpit.example.test"); vi.stubEnv("OS_SESSION_SECRET", secret);+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app])); vi.stubEnv("PORT", "4005");+});+afterEach(() => vi.unstubAllEnvs());+describe("connected-app proxy authority", () => {+ it("routes a private app to its reviewed loopback target without forwarding MSO credentials", async () => {+ const result = await proxy(request("/api/settings?view=1"));+ expect(result.headers.get("x-middleware-rewrite")).toBe("http://127.0.0.1:9131/api/settings?view=1");+ expect(result.headers.get("x-middleware-request-cookie")).toBeNull();+ expect(result.headers.get("x-middleware-request-authorization")).toBeNull();+ expect(result.headers.get("content-security-policy")).toBe("frame-ancestors https://cockpit.example.test");+ });+ it("rejects cross-origin app mutations and missing derived credentials", async () => {+ expect((await proxy(request("/api/settings", "POST", "https://other.example.test"))).status).toBe(403);+ expect((await proxy(request("/api/settings", "POST", app.origin, ""))).status).toBe(401);+ });+ it("never makes the cockpit API or framework assets available on the private app host", async () => {+ expect((await proxy(request("/api/v1/exec"))).headers.get("x-middleware-rewrite")).toBe("http://127.0.0.1:9131/api/v1/exec");+ expect((await proxy(request("/_next/static/script.js"))).status).toBe(404);+ });+ it("sends the upgrade through the existing continuously authorized relay", async () => {+ const req = request("/api/websockets"); req.headers.set("upgrade", "websocket");+ expect((await proxy(req)).status).toBe(404);+ expect((await socketPolicy(req))?.target).toBe("http://127.0.0.1:9131/api/websockets");+ req.headers.set("cookie", "session=cockpit-cookie"); expect(await socketPolicy(req)).toBeNull();+ });+});diff --git a/lib/surfaces/session.test.ts b/lib/surfaces/session.test.tsnew file mode 100644index 00000000..ca8ebdad--- /dev/null+++ b/lib/surfaces/session.test.ts@@ -0,0 +1,94 @@+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { createShellAppCredential, verifyShellAppCredential, sessionApps, shellAppSession, SHELL_APP_COOKIE, shellAppUpstreamHeaders } from "./session";+import { gateShellApp } from "./session-gate";+import { shellAppSocketPolicy } from "./socket-policy";+import { verifySession } from "@/lib/auth/session";+import type { SurfaceApp } from "@/lib/contracts/surface-app";++const authority = vi.hoisted(() => ({ role: "owner", revoked: false, epoch: "epoch-0000000000000000" }));+vi.mock("@/lib/auth/device-store", () => ({+ currentSessionPolicy: async () => ({ scope: "host", epoch: authority.epoch }),+ getApprovedDevice: async () => ({ approvedAt: 1, role: authority.role, ...(authority.revoked ? { sessionsRevokedAt: Date.now() } : {}) }),+}));+const secret = "test-signing-key".repeat(4), now = 1_800_000_000_000;+const app: SurfaceApp = { id: "private-vault", title: "Vault", description: "", origin: "https://vault.cockpit.example.test", startPath: "/",+ renderer: "iframe", presentation: "inline", environment: "production", placements: ["shell"], sessionUpstream: "http://127.0.0.1:9131" };+const parent = () => ({ issued_at: now - 1000, expires_at: now + 86_400_000, device_id: "owner-device", cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" });+const token = (kind: "ticket" | "cookie" = "cookie") => createShellAppCredential(app, parent(), secret, kind);+const request = (path = "/", cookie = token(), extra: Record<string, string> = {}, method = "GET") => new NextRequest(app.origin + path, {+ method, headers: { host: new URL(app.origin).host, cookie: `${SHELL_APP_COOKIE}=${cookie}`, ...extra },+});+beforeEach(() => {+ vi.useFakeTimers(); vi.setSystemTime(now); authority.role = "owner"; authority.revoked = false; authority.epoch = parent().cookie_epoch;+ vi.stubEnv("OS_SESSION_SECRET", secret); vi.stubEnv("OS_PUBLIC_ORIGIN", "https://cockpit.example.test");+ vi.stubEnv("OS_SESSION_COOKIE_DOMAIN", ""); vi.stubEnv("PORT", "4005"); vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app]));+});+afterEach(() => { vi.useRealTimers(); vi.unstubAllEnvs(); });+describe("isolated connected-app sessions", () => {+ it("binds credentials to purpose, exact app identity and origin, never cockpit authority", () => {+ const ticket = token("ticket"), cookie = token();+ expect(verifyShellAppCredential(app, ticket, secret, "ticket")).not.toBeNull();+ expect(verifyShellAppCredential(app, ticket, secret, "cookie")).toBeNull();+ expect(verifyShellAppCredential({ ...app, origin: "https://other.example.test" }, cookie, secret, "cookie")).toBeNull();+ expect(verifyShellAppCredential({ ...app, id: "other" }, cookie, secret, "cookie")).toBeNull();+ expect(verifySession(cookie, secret)).toBeNull();+ });+ it("expires tickets after one minute without shortening the derived session to ticket lifetime", () => {+ const ticket = token("ticket"), session = verifyShellAppCredential(app, ticket, secret, "ticket")!;+ const cookie = createShellAppCredential(app, session, secret, "cookie");+ vi.setSystemTime(now + 61_000);+ expect(verifyShellAppCredential(app, ticket, secret, "ticket")).toBeNull();+ expect(verifyShellAppCredential(app, cookie, secret, "cookie")?.expires_at).toBe(now + 7_200_000);+ const short = createShellAppCredential(app, { ...parent(), expires_at: now + 120_000 }, secret, "cookie");+ expect(verifyShellAppCredential(app, short, secret, "cookie")?.expires_at).toBe(now + 120_000);+ });+ it("requires the current owner role and durable session generation on every request", async () => {+ const req = request(); expect(await shellAppSession(req, app)).not.toBeNull();+ authority.role = "operator"; expect(await shellAppSession(req, app)).toBeNull();+ authority.role = "viewer"; expect(await shellAppSession(req, app)).toBeNull();+ authority.role = "owner"; authority.revoked = true; expect(await shellAppSession(req, app)).toBeNull();+ authority.revoked = false; authority.epoch = "epoch-replaced0000000000"; expect(await shellAppSession(req, app)).toBeNull();+ });+ it("admits only unambiguous reviewed HTTPS hosts and bounded loopback targets", async () => {+ expect(await sessionApps()).toHaveLength(1);+ for (const sessionUpstream of ["https://127.0.0.1:9131", "http://10.0.0.1:9131", "http://user:[email protected]:9131", "http://127.0.0.1:4005", "http://127.0.0.1:9131/?token=x"]) {+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, sessionUpstream }])); expect(await sessionApps()).toEqual([]);+ }+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([app, { ...app, id: "second" }])); expect(await sessionApps()).toEqual([]);+ vi.stubEnv("MSO_SURFACE_APPS_JSON", JSON.stringify([{ ...app, origin: "https://cockpit.example.test:9443" }])); expect(await sessionApps()).toEqual([]);+ });+ it("exchanges an origin-bound ticket for a Secure host-only cookie and strips it upstream", async () => {+ const result = await gateShellApp(request("/__mso_app_auth", "", { origin: app.origin, authorization: `Bearer ${token("ticket")}` }, "POST"), app);+ expect(result?.status).toBe(204);+ const cookie = result!.headers.get("set-cookie")!;+ for (const value of [SHELL_APP_COOKIE, "HttpOnly", "Secure", "SameSite=strict", "Path=/", "Max-Age=7200"]) expect(cookie).toContain(value);+ expect(cookie).not.toContain("Domain=");+ const upstream = shellAppUpstreamHeaders(new Headers({ cookie, authorization: "Bearer private", referer: "https://cockpit.example.test/" }), app);+ for (const name of ["cookie", "authorization", "referer"]) expect(upstream.has(name)).toBe(false);+ });+ it("refuses forged, wrong-origin, demoted and expired ticket exchanges", async () => {+ const ticket = token("ticket");+ expect((await gateShellApp(request("/__mso_app_auth", "", { origin: "https://other.example.test", authorization: `Bearer ${ticket}` }, "POST"), app))?.status).toBe(403);+ expect((await gateShellApp(request("/__mso_app_auth", "", { origin: app.origin, authorization: "Bearer forged-token00000000000" }, "POST"), app))?.status).toBe(401);+ authority.role = "operator";+ expect((await gateShellApp(request("/__mso_app_auth", "", { origin: app.origin, authorization: `Bearer ${ticket}` }, "POST"), app))?.status).toBe(401);+ authority.role = "owner"; vi.setSystemTime(now + 61_000);+ expect((await gateShellApp(request("/__mso_app_auth", "", { origin: app.origin, authorization: `Bearer ${ticket}` }, "POST"), app))?.status).toBe(401);+ });+ it("bootstraps documents through MSO and refuses unauthenticated API/data reads", async () => {+ expect((await gateShellApp(request("/", "", { "sec-fetch-dest": "iframe" }), app))?.status).toBe(200);+ expect((await gateShellApp(request("/api/websockets", ""), app))?.status).toBe(401);+ const script = await gateShellApp(request("/__mso_app_bootstrap.js", ""), app);+ expect(await script!.text()).toContain("returnTo");+ });+ it("authorizes sockets with app credentials and stops authorizing after revocation or demotion", async () => {+ const req = request("/api/websockets", token(), { origin: app.origin, upgrade: "websocket" });+ const decision = await shellAppSocketPolicy(req);+ expect(decision?.target).toBe("http://127.0.0.1:9131/api/websockets");+ expect(decision?.headers.cookie).toBeUndefined(); expect(decision?.headers.authorization).toBeUndefined();+ authority.revoked = true; expect(await shellAppSocketPolicy(req)).toBeNull();+ authority.revoked = false; authority.role = "operator"; expect(await shellAppSocketPolicy(req)).toBeNull();+ authority.role = "owner"; expect(await shellAppSocketPolicy(request("/api/websockets", token(), { origin: "https://other.example.test" }))).toBeNull();+ });+});diff --git a/lib/surfaces/session.ts b/lib/surfaces/session.tsnew file mode 100644index 00000000..c31a22d0--- /dev/null+++ b/lib/surfaces/session.ts@@ -0,0 +1,66 @@+import { MIN_SECRET_LEN, signSession, verifySession, type SessionPayload } from "@/lib/auth/session";+import { liveSessionAuthorized } from "@/lib/auth/live-authorization";+import type { SurfaceApp } from "@/lib/contracts/surface-app";+import { configuredSurfaceApps } from "./config";+import { externalSurfaceSharesSession } from "./cookie-policy";++export const SHELL_APP_COOKIE = "__Host-mso-shell-app";+export const SHELL_APP_TICKET_TTL = 60_000;+export const SHELL_APP_COOKIE_TTL = 2 * 60 * 60 * 1000;+type App = Pick<SurfaceApp, "id" | "origin">;+type Kind = "ticket" | "cookie";+type Credential = SessionPayload & { parent_expires_at: number };+function key(app: App, kind: Kind, secret: string) {+ if (secret.length < MIN_SECRET_LEN) throw new Error("application signing secret is unavailable");+ return `shell-app:${app.id}:${app.origin}:${kind}:${secret}`;+}+export function createShellAppCredential(app: App, session: SessionPayload, secret: string, kind: Kind, now = Date.now()) {+ const ttl = kind === "ticket" ? SHELL_APP_TICKET_TTL : SHELL_APP_COOKIE_TTL;+ const parentExpiry = (session as Partial<Credential>).parent_expires_at ?? session.expires_at;+ const payload = { ...session, parent_expires_at: parentExpiry, expires_at: Math.min(parentExpiry, now + ttl) };+ return signSession(payload, key(app, kind, secret));+}+export function verifyShellAppCredential(app: App, token: string, secret: string, kind: Kind) {+ if (token.length > 4096) return null;+ try {+ const session = verifySession(token, key(app, kind, secret)) as Credential | null;+ return session && Number.isFinite(session.parent_expires_at) && session.parent_expires_at >= session.expires_at ? session : null;+ } catch { return null; }+}+export async function sessionApps() {+ const cockpit = process.env.OS_PUBLIC_ORIGIN;+ if (!cockpit) return [];+ let origin: URL;+ try { origin = new URL(cockpit); } catch { return []; }+ if (origin.protocol !== "https:") return [];+ const apps = (await configuredSurfaceApps()).filter(app => app.sessionUpstream && app.origin !== origin.origin &&+ !externalSurfaceSharesSession(app.origin, [origin.origin]) &&+ new URL(app.sessionUpstream!).port !== (process.env.PORT ?? "4005"));+ // Ambiguous hostname ownership fails closed for every duplicate, never first-match wins.+ return apps.filter(app => apps.filter(other => new URL(other.origin).host === new URL(app.origin).host).length === 1);+}+export async function sessionAppForHost(host: string) {+ return (await sessionApps()).find(app => new URL(app.origin).host === host.toLowerCase());+}+export async function shellAppSession(request: Request, app: App): Promise<SessionPayload | null> {+ const secret = process.env.OS_SESSION_SECRET ?? "";+ for (const candidate of (request.headers.get("cookie") ?? "").split(";")) {+ const [name, ...parts] = candidate.trim().split("=");+ if (name !== SHELL_APP_COOKIE) continue;+ const session = verifyShellAppCredential(app, parts.join("="), secret, "cookie");+ if (session && await liveSessionAuthorized(session, "owner")) return session;+ }+ return null;+}+export function shellAppUpstreamHeaders(incoming: Headers, app: SurfaceApp) {+ const headers = new Headers(incoming), target = new URL(app.sessionUpstream!);+ for (const name of ["cookie", "authorization", "referer", "x-os-managed-app-host", "x-forwarded-host"]) headers.delete(name);+ headers.set("host", target.host);+ headers.set("origin", target.origin);+ return headers;+}+export function shellAppTarget(app: SurfaceApp, url: URL) {+ const target = new URL(app.sessionUpstream!);+ target.pathname = url.pathname; target.search = url.search;+ return target;+}diff --git a/lib/surfaces/shell-apps.test.ts b/lib/surfaces/shell-apps.test.tsindex c496e09d..fdbc7749 100644--- a/lib/surfaces/shell-apps.test.ts+++ b/lib/surfaces/shell-apps.test.ts@@ -19,6 +19,18 @@ beforeEach(async () => {afterEach(async () => { vi.unstubAllEnvs(); await fs.rm(dir, { recursive: true, force: true }); });describe("server-owned connected applications", () => {+ it("exposes the MSO login mode without disclosing the loopback target and preserves it on metadata edits", async () => {+ await save();+ const entries = JSON.parse(await fs.readFile(file, "utf8"));+ entries[0].sessionUpstream = "http://127.0.0.1:9131";+ await fs.writeFile(file, JSON.stringify(entries), { mode: 0o600 });+ expect((await shellAppSettings(origin)).apps[0]).toMatchObject({ msoSession: true });+ expect(JSON.stringify(await shellAppSettings(origin))).not.toContain("127.0.0.1");+ await save({ title: "Renamed" }, "update");+ expect((await configuredSurfaceApps())[0].sessionUpstream).toBe("http://127.0.0.1:9131");+ await save({ url: "https://replacement.example.test/" }, "update");+ expect((await configuredSurfaceApps())[0].sessionUpstream).toBeUndefined();+ });it("persists a reviewed embed, edits it by revision and disconnects only its metadata", async () => {const before = await shellAppSettings(origin);await save();diff --git a/lib/surfaces/shell-apps.ts b/lib/surfaces/shell-apps.tsindex f65359e9..4f0a99ef 100644--- a/lib/surfaces/shell-apps.ts+++ b/lib/surfaces/shell-apps.ts@@ -34,7 +34,8 @@ function definition(value: unknown): ShellAppDefinition {function view(app: SurfaceApp, requestOrigin: string): ShellAppView {const url = new URL(app.startPath, app.origin).href;const def: ShellAppDefinition = { id: app.id, title: app.title, description: app.description, url, mode: app.renderer === "iframe" ? "embed" : "tab" };- const base = { id: app.id, title: app.title, description: app.description, origin: app.origin, sandbox: SANDBOX, definition: def };+ const base = { id: app.id, title: app.title, description: app.description, origin: app.origin, sandbox: SANDBOX, definition: def,+ ...(app.sessionUpstream ? { msoSession: true } : {}) };if (blocked(app.origin, requestOrigin)) return { ...base, renderer: "remote", blocked: true, reason: "This address shares MSO's session cookie scope. Use a separate host address." };const insecure = new URL(app.origin).protocol !== "https:";return { ...base, url, renderer: insecure ? "remote" : app.renderer,@@ -82,7 +83,10 @@ export async function manageShellApp(input: Record<string, unknown>, requestOrigif (!adding && matches.length !== 1) throw new SurfaceConfigError("app_not_found_or_ambiguous", 409);if (matches.some(entry => !Array.isArray(entry.placements) || entry.placements.length !== 1 || entry.placements[0] !== "shell")) throw new SurfaceConfigError("app_owned_by_another_surface", 409);if (removing) return entries.filter(entry => entry.id !== id);- return adding ? [...entries, { ...row!, ...(manifest ? { manifest } : {}) }] : entries.map(entry => entry.id === id ? { ...row!, ...(entry.manifest ? { manifest: entry.manifest } : {}) } : entry);+ return adding ? [...entries, { ...row!, ...(manifest ? { manifest } : {}) }] : entries.map(entry => entry.id === id ? {+ ...row!, ...(entry.manifest ? { manifest: entry.manifest } : {}),+ ...(entry.origin === row!.origin && entry.sessionUpstream ? { sessionUpstream: entry.sessionUpstream } : {}),+ } : entry);});return { ...result, id, schemaVersion: 1 };}diff --git a/lib/surfaces/socket-policy.ts b/lib/surfaces/socket-policy.tsnew file mode 100644index 00000000..1259d907--- /dev/null+++ b/lib/surfaces/socket-policy.ts@@ -0,0 +1,13 @@+import type { NextRequest } from "next/server";+import { sessionAppForHost, shellAppSession, shellAppTarget, shellAppUpstreamHeaders } from "./session";++/** The shared server socket relay rechecks this authority before every delivery. */+export async function shellAppSocketPolicy(request: NextRequest) {+ const app = await sessionAppForHost(request.headers.get("host") ?? "");+ if (!app || request.headers.get("origin") !== app.origin || request.nextUrl.pathname.startsWith("/__mso_") ||+ request.nextUrl.pathname.startsWith("/_next")) return null;+ const session = await shellAppSession(request, app);+ if (!session?.device_id) return null;+ return { identity: session.device_id, target: shellAppTarget(app, request.nextUrl).toString(),+ headers: Object.fromEntries(shellAppUpstreamHeaders(request.headers, app)) };+}diff --git a/proxy.ts b/proxy.tsindex 71b28774..7979b571 100644--- a/proxy.ts+++ b/proxy.ts@@ -35,6 +35,9 @@ import {} from "@/lib/camoufox/viewer-gate";import { applyPrivatePageCachePolicy } from "@/lib/auth/page-cache";import { gateManagedApp } from "@/lib/managed-apps/session";+import { sessionAppForHost, shellAppTarget, shellAppUpstreamHeaders } from "@/lib/surfaces/session";+import { gateShellApp, shellAppResponseHeaders } from "@/lib/surfaces/session-gate";+import { IS_DEMO } from "@/lib/demo";const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);@@ -155,6 +158,19 @@ export async function proxy(request: NextRequest) {// lie (claiming an app host while on the cockpit) only restricts the request.const host = request.headers.get("host") ?? request.nextUrl.host;const managedApp = managedAppIdForHost(host);+ const sessionApp = !IS_DEMO && await sessionAppForHost(host);+ if (sessionApp && !managedApp && !isCamoufoxViewerHost(host)) {+ if (WEBSOCKET_UPGRADE.test(request.headers.get("upgrade") ?? "")) return notFound();+ if (pathname === "/_next" || pathname.startsWith("/_next/")) return notFound();+ if (MUTATING.has(request.method) && request.headers.get("origin") !== sessionApp.origin) return blocked();+ const gate = await gateShellApp(request, sessionApp);+ if (gate) return gate;+ const result = NextResponse.rewrite(shellAppTarget(sessionApp, request.nextUrl), {+ request: { headers: shellAppUpstreamHeaders(request.headers, sessionApp) },+ });+ for (const [name, value] of Object.entries(shellAppResponseHeaders())) result.headers.set(name, value);+ return result;+ }// noVNC gets one reserved split-origin host. The cockpit session cookie is// intentionally NOT shared with a sibling viewer hostname. Instead, an authenticateddiff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjsindex 4afd4cb0..26feafc0 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, surfaceApps = [] } = {}) {+export async function releaseFixture({ live = false, surfaceApps = [], publicOrigin } = {}) {const dir = await mkdtemp(path.join(tmpdir(), "mso-release-e2e-"));let providerStatus = 200;const provider = createServer((req, res) => {@@ -72,7 +72,7 @@ export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {const port = reservation.address().port;await new Promise(resolve => reservation.close(resolve));const base = `http://localhost:${port}`;- env.OS_PUBLIC_ORIGIN = base;+ env.OS_PUBLIC_ORIGIN = publicOrigin ?? base;const server = spawn(process.execPath, ["scripts/server.mjs", "--hostname", "127.0.0.1", "--port", String(port)], { env, stdio: ["ignore", "pipe", "pipe"] });let logs = "";const capture = chunk => { logs = (logs + chunk.toString()).slice(-8000); };diff --git a/scripts/e2e/socket-authority.mjs b/scripts/e2e/socket-authority.mjsindex 80e53a20..752554fc 100644--- a/scripts/e2e/socket-authority.mjs+++ b/scripts/e2e/socket-authority.mjs@@ -6,6 +6,10 @@ import { releaseFixture } from "./release-fixture.mjs";const sockets = new Set();const upstream = createServer();+upstream.on("request", (request, response) => {+ assert.equal(request.headers.cookie, undefined); assert.equal(request.headers.authorization, undefined);+ response.writeHead(200, { "content-type": "text/plain" }); response.end("private editor");+});let remote;upstream.on("upgrade", (request, socket) => {assert.equal(request.headers.cookie, undefined);@@ -19,7 +23,9 @@ const previous = process.env.HERMES_DASHBOARD_URL;process.env.HERMES_DASHBOARD_URL = `http://127.0.0.1:${upstream.address().port}`;let fixture;try {- fixture = await releaseFixture();+ const native = { id: "fixture-editor", title: "Private editor", description: "", origin: "https://editor.cockpit.example.test", startPath: "/",+ renderer: "iframe", presentation: "inline", environment: "production", placements: ["shell"], sessionUpstream: process.env.HERMES_DASHBOARD_URL };+ fixture = await releaseFixture({ surfaceApps: [native], publicOrigin: "https://cockpit.example.test" });const response = await fetch(fixture.base + "/api/auth/login", { method: "POST", headers: { "content-type": "application/json", origin: fixture.base }, body: JSON.stringify({ password: fixture.password, deviceId: fixture.device }) });assert.equal(response.status, 200);const cookie = response.headers.get("set-cookie").split(";")[0];@@ -36,11 +42,25 @@ try {assert.match(appCookie, /^__Host-mso-managed-app=/);assert.equal((await fetch(fixture.base + "/api/v1/exec/run", { method: "POST", headers: { cookie: appCookie, origin: fixture.base, "content-type": "application/json" }, body: JSON.stringify({ command: "true" }) })).status, 401);assert.equal((await fetch(fixture.base + "/api/internal/socket-policy", { method: "POST" })).status, 404);- async function open() {+ const nativeResponse = await fetch(fixture.base + `/api/v1/shell-apps/${native.id}/session`, { headers: { cookie } });+ assert.equal(nativeResponse.status, 200); const nativeAuthorization = await nativeResponse.json();+ const nativeExchange = await new Promise((resolve, reject) => {+ const hop = request(fixture.base + "/__mso_app_auth", { method: "POST", headers: { host: new URL(native.origin).host, origin: native.origin, authorization: "Bearer " + nativeAuthorization.ticket } }, response => { response.resume(); resolve(response); });+ hop.once("error", reject); hop.end();+ });+ assert.equal(nativeExchange.statusCode, 204);+ const nativeCookie = nativeExchange.headers["set-cookie"][0].split(";")[0]; assert.match(nativeCookie, /^__Host-mso-shell-app=/);+ assert.equal((await fetch(fixture.base + "/api/v1/shell-apps", { headers: { cookie: nativeCookie } })).status, 401);+ const nativeHttp = await new Promise((resolve, reject) => {+ const hop = request(fixture.base + "/private-note", { headers: { host: new URL(native.origin).host, cookie: nativeCookie + "; session=must-not-forward", authorization: "must-not-forward" } }, response => { let body = ""; response.on("data", data => { body += data; }); response.on("end", () => resolve({ status: response.statusCode, body })); });+ hop.once("error", reject); hop.end();+ });+ assert.deepEqual(nativeHttp, { status: 200, body: "private editor" });+ async function open(host = "hermes.mso.example.com", origin = "http://hermes.mso.example.com", credential = appCookie) {const client = connect(Number(new URL(fixture.base).port), "127.0.0.1"); sockets.add(client);client.on("error", () => {});const first = Promise.race([once(client, "data").then(([data]) => data.toString()), once(client, "close").then(() => "")]);- client.write(`GET /socket HTTP/1.1\r\nHost: hermes.mso.example.com\r\nOrigin: http://hermes.mso.example.com\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nCookie: ${appCookie}\r\nAuthorization: must-not-forward\r\n\r\n`);+ client.write(`GET /socket HTTP/1.1\r\nHost: ${host}\r\nOrigin: ${origin}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nCookie: ${credential}\r\nAuthorization: must-not-forward\r\n\r\n`);return { client, handshake: await first };}const { client, handshake } = await open(); assert.match(handshake, /101 Switching Protocols/);@@ -50,11 +70,20 @@ try {assert.equal(delivered, "");await fixture.setRole("owner");const idle = await open(); assert.match(idle.handshake, /101 Switching Protocols/);+ const nativeOpen = () => open(new URL(native.origin).host, native.origin, nativeCookie);+ const nativeActive = await nativeOpen(); assert.match(nativeActive.handshake, /101 Switching Protocols/);+ let nativeDelivered = ""; nativeActive.client.on("data", chunk => { nativeDelivered += chunk.toString(); });+ const nativeClosed = once(nativeActive.client, "close"); await fixture.setRole("operator"); remote.write("private-after-owner-demotion"); await nativeClosed;+ assert.equal(nativeDelivered, ""); assert.doesNotMatch((await nativeOpen()).handshake, /101/);+ await fixture.setRole("owner");+ const nativeIdle = await nativeOpen(); assert.match(nativeIdle.handshake, /101 Switching Protocols/);+ const nativeIdleClosed = once(nativeIdle.client, "close");const idleClosed = once(idle.client, "close");assert.equal((await fetch(fixture.base + "/api/auth/logout", { method: "POST", headers: { cookie, origin: fixture.base } })).status, 200);await idleClosed;+ await nativeIdleClosed; assert.doesNotMatch((await nativeOpen()).handshake, /101/);assert.doesNotMatch((await open()).handshake, /101/);- console.log("PASS production socket authority: real login/policy RPC, cookie stripping, live demotion, idle logout and replay refusal");+ console.log("PASS production socket authority: managed/connected app handoff, isolated HTTP, cookie stripping, live demotion, idle logout and replay refusal");} finally {for (const socket of sockets) socket.destroy();await fixture?.close();