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
fix(managed-apps): say why a dashboard is missing instead of silently opening a terminal
rahmanef63eb0b74d14338
diff --git a/.env.example b/.env.exampleindex de123e19..7f5894a3 100644--- a/.env.example+++ b/.env.example@@ -120,6 +120,15 @@ OS_SESSION_SECRET=# the restart. Built without it, the browser still points the iframe at the old# same-origin proxy URL while the server has already stopped answering there, and# the app window comes up blank.+#+# AND THEN SIGN OUT AND BACK IN. The Domain is attached to the cookie when it is+# ISSUED and never afterwards — there is no sliding refresh — so every session that+# existed before you set this stays host-only and is never sent to the app hosts.+# The cockpit keeps working perfectly and only the dashboards 401, which reads as+# "the app host is broken" and is not. Nothing server-side can detect it either: a+# Cookie header carries no Domain, so a cookie that was never sent looks exactly+# like one that never existed. Turning this on is a three-step change — set, build,+# re-login — and skipping the third is the one that wastes an afternoon.# NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE={id}.mso.rahmanef.com# OS_SESSION_COOKIE_DOMAIN=mso.rahmanef.comdiff --git a/.gitignore b/.gitignoreindex 10135018..de9b2fcd 100644--- a/.gitignore+++ b/.gitignore@@ -5,6 +5,11 @@ build/.env.env.local.env*.local+# `.env*.local` stops at the `.local`, so a hand-made `.env.local.bak` — or the dated+# copy any sane person takes before editing secrets — lands in `git status` as untracked+# and is one `git add -A` away from being published. The file it copies is ignored; the+# copy has the same contents and none of the protection.+.env.local.**.tsbuildinfonext-env.d.ts.DS_Storediff --git a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.tsindex 194d7e5b..75858b8e 100644--- a/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts+++ b/app/api/v1/managed-apps/[id]/proxy/[[...path]]/route.ts@@ -8,6 +8,7 @@ import {splitOriginEnabled,} from "@/lib/managed-apps/origin";import { contentSecurityPolicy } from "@/lib/managed-apps/proxy-csp";+import { errorPage, wantsErrorPage } from "@/lib/managed-apps/proxy-error-page";import {buildUpstreamHeaders,isSecureRequest,@@ -37,14 +38,19 @@ function failAncestors(): string {return cockpit ? `'self' ${cockpit}` : "'self'";}-const fail = (error: string, status: number) =>- NextResponse.json(- { error },- {- status,- headers: { "content-security-policy": `default-src 'none'; frame-ancestors ${failAncestors()}` },- },- );+// Same failure, two audiences, one policy. A navigation (the app window's own frame, or a+// tab) gets a page that says what to DO about it; the upstream SPA's fetches — which land+// on this very route — keep getting the JSON they parse. `wantsErrorPage` decides on+// Sec-Fetch-Dest, never on status, so no failure is readable in one caller and cryptic in+// the other. See proxy-error-page.ts for the case that made this worth the branch.+const fail = (req: Request, error: string, status: number) => {+ const headers: Record<string, string> = {+ "content-security-policy": `default-src 'none'; frame-ancestors ${failAncestors()}`,+ };+ if (!wantsErrorPage(req)) return NextResponse.json({ error }, { status, headers });+ headers["content-type"] = "text/html; charset=utf-8";+ return new NextResponse(errorPage(error, status), { status, headers });+};// A chunked request has no content-length, so the header check alone would let an// arbitrarily large body buffer into memory before the size test could reject it.@@ -69,9 +75,9 @@ async function readBody(req: Request, limit: number): Promise<ArrayBuffer | null}async function proxy(req: Request, context: { params: Promise<{ id: string; path?: string[] }> }) {- if (!(await verifyAuth(req))) return fail("unauthorized", 401);+ if (!(await verifyAuth(req))) return fail(req, "unauthorized", 401);const params = await context.params;- if (!isManagedAppId(params.id)) return fail("unknown managed application", 404);+ if (!isManagedAppId(params.id)) return fail(req, "unknown managed application", 404);// The dashboard is served from its OWN host and nowhere else. The middleware// rewrite is invisible from in here, so it stamps the app host it matched — and it// deletes any inbound copy on every request, so the header can only have come from@@ -85,10 +91,10 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; path// whole cockpit realm from `window.open('/')` in a tab. Only a separate origin// closes it, so without one the dashboards are not proxied — the feature windows// fall back to the CLI view and to opening the app in a browser of the user's own.- if (!splitOriginEnabled()) return fail("managed application dashboards are not served on this origin", 404);- if (req.headers.get(MANAGED_APP_HOST_HEADER) !== params.id) return fail("not found", 404);+ if (!splitOriginEnabled()) return fail(req, "managed application dashboards are not served on this origin", 404);+ if (req.headers.get(MANAGED_APP_HOST_HEADER) !== params.id) return fail(req, "not found", 404);const appOrigin = managedAppOrigin(params.id);- if (!appOrigin) return fail("managed application origin is unavailable", 500);+ if (!appOrigin) return fail(req, "managed application origin is unavailable", 500);// On the app's own host the app IS the origin root — cookies at Path=/, Locations// unchanged, policy scoped to the origin. Deployment env (the host template), never// a request header: this URL is what every fetch directive is scoped to, so a@@ -96,17 +102,17 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; pathconst prefixUrl = `${appOrigin}/`;const segments = params.path ?? [];if (segments.some((segment) => !segment || segment === "." || segment === ".." || segment.includes("\\") || segment.includes("\0"))) {- return fail("invalid upstream path", 400);+ return fail(req, "invalid upstream path", 400);}// A service worker registered from proxied bytes installs on the MSO origin// and keeps serving after the window closes. Never hand one to the browser.if (isServiceWorkerPath(segments)) {- return fail("service workers are not proxied", 404);+ return fail(req, "service workers are not proxied", 404);}const definition = getManagedAppDefinition(params.id);const base = new URL(definition.dashboardUrl);if (base.protocol !== "http:" || !["127.0.0.1", "localhost", "::1"].includes(base.hostname)) {- return fail("upstream target is not loopback", 502);+ return fail(req, "upstream target is not loopback", 502);}const target = new URL(`/${segments.map(encodeURIComponent).join("/")}`, base);target.search = new URL(req.url).search;@@ -114,9 +120,9 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; pathlet body: ArrayBuffer | undefined;if (!['GET', 'HEAD'].includes(req.method)) {const length = Number(req.headers.get("content-length") ?? "0");- if (length > BODY_LIMIT) return fail("upstream request body too large", 413);+ if (length > BODY_LIMIT) return fail(req, "upstream request body too large", 413);const read = await readBody(req, BODY_LIMIT);- if (read === null) return fail("upstream request body too large", 413);+ if (read === null) return fail(req, "upstream request body too large", 413);body = read;}try {@@ -152,7 +158,7 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; pathif (rewritten === null) {// Refusal is a loopable path — release the socket instead of waiting for GC.void upstream.body?.cancel();- return fail("upstream redirect leaves the managed application", 502);+ return fail(req, "upstream redirect leaves the managed application", 502);}responseHeaders.set("location", rewritten);return new Response(null, { status: upstream.status, headers: responseHeaders });@@ -163,7 +169,7 @@ async function proxy(req: Request, context: { params: Promise<{ id: string; path// shipped them. Everything streams.return new Response(upstream.body, { status: upstream.status, headers: responseHeaders });} catch {- return fail("managed application upstream unavailable", 502);+ return fail(req, "managed application upstream unavailable", 502);}}diff --git a/app/api/v1/managed-apps/proxy.test.ts b/app/api/v1/managed-apps/proxy.test.tsindex 513d52d3..115fe572 100644--- a/app/api/v1/managed-apps/proxy.test.ts+++ b/app/api/v1/managed-apps/proxy.test.ts@@ -216,6 +216,24 @@ describe("managed-app proxy guards", () => {expect(res.headers.get("content-security-policy")).toContain("frame-ancestors 'self'");});+ // Displaying the error was half the job; the frame is a surface a person reads. A+ // 401 here is most often a session issued before OS_SESSION_COOKIE_DOMAIN was set —+ // host-only, so never sent to this host — which no status code can convey.+ it("renders a failure as a page for the frame and as JSON for the upstream's fetch", async () => {+ const { verifyAuth } = await import("@/lib/agent/server");+ const { GET } = await import("./[id]/proxy/[[...path]]/route");++ vi.mocked(verifyAuth).mockResolvedValueOnce(false);+ const framed = await GET(req("chat", { headers: { "sec-fetch-dest": "iframe" } }), ctx(["chat"]));+ expect(framed.headers.get("content-type")).toContain("text/html");+ expect(await framed.text()).toContain("sign in again");++ vi.mocked(verifyAuth).mockResolvedValueOnce(false);+ const xhr = await GET(req("api/status", { headers: { "sec-fetch-dest": "empty" } }), ctx(["api", "status"]));+ expect(xhr.headers.get("content-type")).toContain("application/json");+ expect(await xhr.json()).toEqual({ error: "unauthorized" });+ });+it("refuses a non-loopback upstream target", async () => {dashboardUrl.current = "http://evil.example.com";const { GET } = await import("./[id]/proxy/[[...path]]/route");diff --git a/bin/mso b/bin/msoindex 3a052088..51602928 100755--- a/bin/mso+++ b/bin/mso@@ -308,6 +308,20 @@ case "$cmd" inchk "env file" "[ -f '$ENVF' ]" "no $ENVF — copy .env.example and fill it"chk "login password" "[ -n '$PASS' ]" "OS_LOGIN_PASSWORD unset in $ENVF"chk "session secret" "[ -n \"\${OS_SESSION_SECRET-}\" ]" "OS_SESSION_SECRET unset in $ENVF"+ # Not a chk with a pass/fail: serving NO managed-app dashboards is a supported+ # deployment, not a fault — but it is the reason a Hermes/OpenClaw window opens on a+ # terminal, and nothing else anywhere says so out loud. Half-configured IS a fault,+ # and a security one: a cookie domain without the host template hands the session to+ # every host under that name while each still serves a whole cockpit.+ tpl="${NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE-}"; dom="${OS_SESSION_COOKIE_DOMAIN-}"+ if [ -n "$tpl" ] && [ -n "$dom" ]; then+ echo " ok app dashboards ($tpl) — after changing this, REBUILD and sign in again"+ elif [ -z "$tpl$dom" ]; then+ echo " -- app dashboards (off: no app host — managed-app windows open on the CLI view)"+ else+ printf ' FAIL app dashboards — set BOTH NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE and OS_SESSION_COOKIE_DOMAIN, or neither\n'+ fails=$((fails+1))+ fichk "service unit" "systemctl is-active --quiet mso.service" "mso.service not active — mso service start"chk "reachable" "curl -fsS --max-time 5 '$B/api/health'" "nothing answering at $B"d=$(cli_device)diff --git a/docs/MANAGED-APPS.md b/docs/MANAGED-APPS.mdindex 02400b1a..081a7293 100644--- a/docs/MANAGED-APPS.md+++ b/docs/MANAGED-APPS.md@@ -315,6 +315,38 @@ Without a host template the dashboards are simply not proxied — the windows fathe CLI view and to opening the app in the user's own browser. **Do not reintroduce acockpit-origin path proxy as a convenience.**+### Turning it on is THREE steps, and the third one has no error message++Reported by the same operator as §7's user-bus gap, and it cost an afternoon: the Hermes+window showed a terminal, so the dashboard looked broken. It was not — this deployment had+no app host, and nothing anywhere said so.++| Step | Skipping it looks like |+|---|---|+| 1. Set **both** `NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE` and `OS_SESSION_COOKIE_DOMAIN`, add the DNS record + a reverse-proxy route per app host | The window opens a terminal, silently |+| 2. **Rebuild**, not just restart — `NEXT_PUBLIC_*` is baked into the client bundle | Same terminal: the server is in split mode and the browser is still running the old bundle |+| 3. **Sign out and back in** | The frame 401s while the cockpit keeps working |++Step 3 is the one with no signal, and it cannot be given one server-side. `Domain=` is+attached to the session cookie only when it is ISSUED (`login/route.ts`, via+`sessionCookieAttrs`) and there is no sliding refresh, so every pre-existing session stays+host-only and is never sent to `<id>.<parent>`. A Cookie header carries no Domain, so a+cookie that was never sent is indistinguishable from one that never existed — the server+cannot tell "stale session" from "not logged in".++So all three now say it where it will be read, none of them relying on this file:++- **Step 1** — the window itself. `feature-app.tsx` renders one line above the terminal+ when `featureSource()` is null, naming the variable. Only in that case: with a dashboard+ configured nothing renders, so it cannot become the always-on banner that was removed.+- **Steps 2 and 3** — the failure page. The proxy route's errors are what the frame+ displays (that is what `failAncestors()` is for), and `proxy-error-page.ts` turns them+ from `{"error":"unauthorized"}` into a page that names the re-login. Navigations only,+ chosen by `Sec-Fetch-Dest`: an upstream SPA's own `fetch()` hits the same route and keeps+ getting JSON.+- **Before any of it** — `mso doctor` prints the template when set, `off` when neither var+ is set, and FAILS when exactly one is, which is the configuration §5 warns is unsafe.+Live verification (unauthenticated, so 401 is the expected success signal):```diff --git a/frontend/slices/managed-apps/feature-app.tsx b/frontend/slices/managed-apps/feature-app.tsxindex b7f32f85..e315049d 100644--- a/frontend/slices/managed-apps/feature-app.tsx+++ b/frontend/slices/managed-apps/feature-app.tsx@@ -36,9 +36,24 @@ export function ManagedFeatureApp({ feature }: AppProps & { feature: ManagedAppF</header>{/* `|| !source` is explicit, not defensive: with no dashboard origin the CLI IS theapp's surface here, and the alternative was an iframe with a null src. The panel- of prose that used to sit in this slot was unreachable anyway — `view` initialises+ of prose that used to sit in THIS slot was unreachable anyway — `view` initialisesto "cli" whenever `source` is null and the toggle that could change it only- renders when `source` is not. */}+ renders when `source` is not; the note above sits outside the branch for exactly+ that reason. */}+ {/* Only when there is no origin at all, so this can never become the banner that got+ removed for appearing on every feature view: with a dashboard configured — the+ normal case — nothing renders here. Without one, the window silently opens a+ terminal, and a terminal is indistinguishable from a dashboard that broke. It+ reads as a fault in the app and sends the operator to look at the app. It is not:+ it is a deployment that serves no dashboards, and only this file knows that. */}+ {!source ? (+ <p className="shrink-0 border-b border-border px-3 py-1.5 text-[11px] leading-snug text-muted-foreground">+ No dashboard on this deployment — the CLI below is the view.{" "}+ <span className="font-mono">NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE</span> is unset, so{" "}+ {feature.applicationId} has no host of its own to be framed from. Setting it needs a+ rebuild, not just a restart. See docs/MANAGED-APPS.md §5.+ </p>+ ) : null}{view === "cli" || !source ? (<div className="min-h-0 flex-1"><Suspense fallback={null}>diff --git a/lib/managed-apps/proxy-error-page.test.ts b/lib/managed-apps/proxy-error-page.test.tsnew file mode 100644index 00000000..c332fcca--- /dev/null+++ b/lib/managed-apps/proxy-error-page.test.ts@@ -0,0 +1,64 @@+// The proxy's failures have two audiences and must not be readable to only one of them:+// a human reading the app window's frame, and the upstream SPA's own fetch() landing on+// the same route. These pin the split and the one hint that exists because a server+// cannot detect the condition it describes.+import { describe, expect, it } from "vitest";+import { errorPage, wantsErrorPage } from "./proxy-error-page";++const req = (headers: Record<string, string>) => new Request("https://hermes.example.com/", { headers });++describe("wantsErrorPage", () => {+ it("serves a page to the frame and to a tab", () => {+ expect(wantsErrorPage(req({ "sec-fetch-dest": "iframe" }))).toBe(true);+ expect(wantsErrorPage(req({ "sec-fetch-dest": "document" }))).toBe(true);+ });++ // The regression that matters: an upstream SPA polling its own API must keep receiving+ // JSON, and its requests carry `Accept: */*` with dest `empty`.+ it("leaves the upstream's own requests on JSON", () => {+ expect(wantsErrorPage(req({ "sec-fetch-dest": "empty", accept: "*/*" }))).toBe(false);+ expect(wantsErrorPage(req({ "sec-fetch-dest": "script" }))).toBe(false);+ });++ // Fetch Metadata wins over Accept when both are present: a browser navigating to a+ // JS chunk sends `Accept: */*` but also dest=script, and a page there would be wrong.+ it("prefers Sec-Fetch-Dest over Accept, and errs toward JSON without either", () => {+ expect(wantsErrorPage(req({ "sec-fetch-dest": "style", accept: "text/html" }))).toBe(false);+ expect(wantsErrorPage(req({ accept: "text/html,application/xhtml+xml" }))).toBe(true);+ expect(wantsErrorPage(req({}))).toBe(false);+ });+});++describe("errorPage", () => {+ // The whole reason this module exists. A session issued before OS_SESSION_COOKIE_DOMAIN+ // was set is host-only and is never sent to the app host; the server cannot tell that+ // from "never logged in", so the page has to say it.+ it("tells a 401 to sign in again, because nothing else can", () => {+ const html = errorPage("unauthorized", 401);+ expect(html).toContain("Sign out of the cockpit and sign in again");+ expect(html).toContain("OS_SESSION_COOKIE_DOMAIN");+ });++ it("names the rebuild when the deployment serves no dashboards", () => {+ const html = errorPage("managed application dashboards are not served on this origin", 404);+ expect(html).toContain("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE");+ expect(html).toContain("REBUILD");+ });++ it("still renders a failure it has no hint for", () => {+ const html = errorPage("invalid upstream path", 400);+ expect(html).toContain("invalid upstream path");+ expect(html).toContain("HTTP 400");+ });++ // The page is served under `default-src 'none'`, so anything it referenced would be+ // blocked. It must stay self-contained rather than quietly render as a blank frame.+ it("carries no script, style or external reference the policy would block", () => {+ const html = errorPage("unauthorized", 401);+ expect(html).not.toMatch(/<script|<link|<style|style=|https?:\/\//);+ });++ it("escapes the failure string rather than trusting it as markup", () => {+ expect(errorPage('<img src=x onerror="1">', 400)).not.toContain("<img");+ });+});diff --git a/lib/managed-apps/proxy-error-page.ts b/lib/managed-apps/proxy-error-page.tsnew file mode 100644index 00000000..0d74ae8a--- /dev/null+++ b/lib/managed-apps/proxy-error-page.ts@@ -0,0 +1,78 @@+// The proxy's failures, rendered for the OPERATOR who is looking at them — because in+// the app window, they ARE the window.+//+// `failAncestors()` in the proxy route exists so the browser DISPLAYS these responses+// instead of refusing the frame outright, which was the whole point: a blank frame says+// nothing, "unauthorized" says something. It stopped one step short. What actually+// renders is `{"error":"unauthorized"}`, which names the HTTP fact and none of the causes+// an operator can act on — and the most expensive cause is invisible from that string:+//+// A session issued BEFORE `OS_SESSION_COOKIE_DOMAIN` was set is host-only. The browser+// never sends it to the app host, so the dashboard 401s while the cockpit that minted+// it keeps working perfectly. Nothing is broken and nothing looks fixable. The remedy+// is to sign out and back in, and there is no way to guess that from "unauthorized".+//+// A server cannot detect that case — a Cookie header carries no Domain, so a cookie that+// was never sent is indistinguishable from one that never existed. It can only be said.+//+// NAVIGATIONS ONLY. An upstream SPA's own `fetch()` lands on this same route, root+// mounted, and must keep receiving JSON it can parse; that is why the page is selected by+// Sec-Fetch-Dest and never by status code.++/** A request whose response a HUMAN will read: the app window's frame, or a tab. */+export function wantsErrorPage(req: Request): boolean {+ const dest = req.headers.get("sec-fetch-dest");+ // Fetch Metadata is sent by every browser that can run this cockpit, so when the+ // header is present it is the answer. The Accept sniff below is only for the clients+ // that send no Sec-Fetch-Dest at all (curl, a proxy that strips it), and it errs+ // toward JSON when it cannot tell — a machine given HTML is worse off than a human+ // given JSON.+ if (dest) return dest === "document" || dest === "iframe" || dest === "frame";+ return (req.headers.get("accept") ?? "").includes("text/html");+}++// Keyed by the exact `fail()` string in the route, so a hint can never drift onto the+// wrong failure the way a status-code key would (three different 404s live in there).+// Anything absent renders without a hint rather than with a guessed one. The values are+// authored here and are the only markup on the page, so they are interpolated raw while+// the failure string — which is also authored here, but sits next to path input — is not.+const HINTS: Record<string, string> = {+ unauthorized:+ "Sign out of the cockpit and sign in again. The session cookie is only given " ++ "<code>Domain=</code> at the moment it is ISSUED, so a session created before " ++ "<code>OS_SESSION_COOKIE_DOMAIN</code> was configured is host-only and is never sent " ++ "to this host — the cockpit keeps working, and only the dashboard fails.",+ "managed application dashboards are not served on this origin":+ "This deployment serves no managed-app dashboards. Set " ++ "<code>NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE</code> and " ++ "<code>OS_SESSION_COOKIE_DOMAIN</code> (both, or neither), then REBUILD — the " ++ "template is baked into the client bundle at build time, so a restart alone leaves " ++ "the browser pointed at the old URL.",+ "managed application upstream unavailable":+ "The application is not answering on its loopback port. Start it from its MSO " ++ "window (Details → Start), or check its logs there.",+};++const ESCAPES: Record<string, string> = { "&": "&", "<": "<", ">": ">", '"': """ };++const escapeHtml = (value: string): string => value.replace(/[&<>"]/g, (ch) => ESCAPES[ch]);++/** The failure as a page. No CSS: the policy on these responses is `default-src 'none'`,+ * which covers style-src too, so a stylesheet or a `style=` attribute would be blocked+ * and the page would render exactly as it does now, minus the pretence. `color-scheme`+ * is a meta tag rather than CSS, so it survives the policy and the page follows the+ * operator's dark/light preference instead of flashing white inside a dark cockpit. */+export function errorPage(error: string, status: number): string {+ const hint = HINTS[error];+ return [+ "<!doctype html>",+ '<html lang="en"><head><meta charset="utf-8">',+ '<meta name="color-scheme" content="dark light">',+ `<title>${status} — ${escapeHtml(error)}</title>`,+ "</head><body>",+ `<h1>${escapeHtml(error)}</h1>`,+ `<p>HTTP ${status} from MSO's managed-app proxy — not from the application.</p>`,+ hint ? `<p>${hint}</p>` : "",+ "</body></html>",+ ].join("");+}