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(browser): isolate sibling Camoufox viewer auth
Rahman6d7c9040382f
diff --git a/.env.example b/.env.exampleindex 74c789e3..70dfa0df 100644--- a/.env.example+++ b/.env.example@@ -275,6 +275,13 @@ OS_SESSION_SECRET=# off-box would turn the viewer proxy into a relay, and proxy.ts rejects it.# CAMOUFOX_NOVNC_URL=http://127.0.0.1:6080#+# Optional dedicated HTTPS origin for the human noVNC viewer when the managed-app+# namespace hostname is not covered by the deployment's edge TLS certificate.+# Keep this on a separate sibling origin (for example camoufox-mso.example.com);+# the cockpit exchanges a short-lived ticket for a host-only viewer cookie, so the+# main MSO session cookie does not need to be widened to unrelated subdomains.+# CAMOUFOX_VIEWER_ORIGIN=https://camoufox-mso.example.com+## Plaintext copy of the VNC password, written beside x11vnc's own passwd blob (which is# not meant to be read back) by scripts/camoufox-vnc-service. 0600, never committed.# The API hands it to the viewer in the URL FRAGMENT, never the query string.diff --git a/app/api/v1/camoufox/session/route.ts b/app/api/v1/camoufox/session/route.tsindex 473fae24..e2b67ed7 100644--- a/app/api/v1/camoufox/session/route.ts+++ b/app/api/v1/camoufox/session/route.ts@@ -3,7 +3,10 @@ import { promises as fs } from "fs";import os from "os";import path from "path";import { NextResponse } from "next/server";-import { requireSession } from "@/lib/auth/require-session";+import { getSessionContext } from "@/lib/auth/require-session";+import { roleAtLeast } from "@/lib/auth/roles";+import { camoufoxViewerOrigin } from "@/lib/camoufox/origin";+import { createCamoufoxViewerTicket } from "@/lib/camoufox/viewer-auth";import { IS_DEMO } from "@/lib/demo";export const runtime = "nodejs";@@ -27,11 +30,20 @@ const PASSWD_FILE = process.env.CAMOUFOX_VNC_PASSWD_TEXTexport async function GET() {// Demo has no host, no display and no session — never hand out a credential there.if (IS_DEMO) return NextResponse.json({ error: "unavailable" }, { status: 404 });- if (!(await requireSession("operator"))) return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ const context = await getSessionContext();+ if (!context?.session.device_id || !roleAtLeast(context.role, "operator")) {+ return NextResponse.json({ error: "Unauthorized" }, { status: 401 });+ }+ const viewerOrigin = camoufoxViewerOrigin();+ const secret = process.env.OS_SESSION_SECRET ?? "";+ if (!viewerOrigin || secret.length < 32) {+ return NextResponse.json({ error: "viewer_unconfigured" }, { status: 503 });+ }+ const viewerTicket = createCamoufoxViewerTicket(context.session.device_id, secret);const password = (await fs.readFile(/* turbopackIgnore: true */ PASSWD_FILE, "utf8").catch(() => "")).trim();// Absent file = the operator has not set one. Say so plainly rather than 500 — the// browser window falls back to letting noVNC prompt.- if (!password) return NextResponse.json({ password: null, reason: "no_password_file" });- return NextResponse.json({ password });+ if (!password) return NextResponse.json({ password: null, viewerOrigin, viewerTicket, reason: "no_password_file" });+ return NextResponse.json({ password, viewerOrigin, viewerTicket });}diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 9e0d6221..06b89c4d 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -15,6 +15,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.**Fixed**+- `browser` isolate sibling Camoufox viewer auth- `integrations` allow Convex snapshot imports- `review` preserve session and surface store invariants- `security` validate cache exceptions from raw reportdiff --git a/frontend/slices/camoufox-browser/app.tsx b/frontend/slices/camoufox-browser/app.tsxindex a9b411f6..57aeb19e 100644--- a/frontend/slices/camoufox-browser/app.tsx+++ b/frontend/slices/camoufox-browser/app.tsx@@ -5,37 +5,33 @@ import { Loader2, Power, ScanEye } from "lucide-react";import { IS_DEMO } from "@/lib/demo";import { PowerPanel } from "./power-panel";import { fetchStatus, setPower, waitForViewer, verifyViewerTransport, type CamoufoxServiceStatus } from "./service-client";-import { camoufoxViewerOrigin } from "@/lib/camoufox/origin";// Camoufox runs on the host, streamed as pixels through a separately authenticated// noVNC origin. Never embed its third-party JS on the cockpit origin.// The full viewer supplies touch keyboard input; resize=remote plus the host// window manager reflows the framebuffer rather than scaling a desktop thumbnail.-const VIEWER_ORIGIN = camoufoxViewerOrigin();-const VIEWER = VIEWER_ORIGIN- ? `${VIEWER_ORIGIN}/vnc.html?path=websockify&autoconnect=1&resize=remote`- : null;-/** The display's VNC password, fetched for this already-authenticated session so* noVNC does not prompt on every open. Absent = none configured; let noVNC ask. */async function viewerSrc(): Promise<string | null> {- if (!VIEWER) return null;try {const response = await fetch("/api/v1/camoufox/session", { cache: "no-store" });- if (response.ok) {- const password = ((await response.json()) as { password?: string | null }).password ?? null;- // `#password=`, never `&password=`. Behind this display sits a live Google session,- // so the VNC password is the second lock on it and must not end up anywhere it can- // be read back: a fragment is never sent to the server, so it cannot land in a- // Traefik access log, a Next.js request log, or a Referer header — a query string- // can do all three the moment anyone enables logging. noVNC reads either, and- // prefers the fragment (WebUtil.getConfigVar → getHashVar first, app/ui.js:997).- if (password) return `${VIEWER}#password=${encodeURIComponent(password)}`;- }+ if (!response.ok) return null;+ const payload = (await response.json()) as {+ password?: string | null;+ viewerOrigin?: string | null;+ viewerTicket?: string | null;+ };+ if (!payload.viewerOrigin || !payload.viewerTicket) return null;+ const viewer = payload.viewerOrigin + "/vnc.html?path=websockify&autoconnect=1&resize=remote";+ const fragment = new URLSearchParams({ viewer_ticket: payload.viewerTicket });+ // Password and viewer ticket live in the URL fragment, never the request/query.+ // The sibling viewer bootstrap exchanges the short-lived ticket for a host-only+ // HttpOnly cookie, removes it from the fragment, then loads noVNC.+ if (payload.password) fragment.set("password", payload.password);+ return viewer + "#" + fragment.toString();} catch {- // Offline or route missing — fall through to the prompting viewer.+ return null;}- return VIEWER;}export default function CamoufoxBrowser() {diff --git a/frontend/slices/camoufox-browser/mobile-layout.test.ts b/frontend/slices/camoufox-browser/mobile-layout.test.tsindex 759dd3a4..2e292723 100644--- a/frontend/slices/camoufox-browser/mobile-layout.test.ts+++ b/frontend/slices/camoufox-browser/mobile-layout.test.ts@@ -7,7 +7,10 @@ describe("Camoufox mobile layout", () => {expect(src).toContain("min-h-0 w-full flex-1 border-0 bg-black");expect(src).toContain("overflow-hidden bg-black");expect(src).toContain("allowFullScreen");- expect(src).toContain("camoufoxViewerOrigin");+ expect(src).toContain("viewerOrigin");+ expect(src).toContain("viewerTicket");+ expect(src).toContain("viewer_ticket");+ expect(src).not.toContain("camoufoxViewerOrigin");expect(src).toContain('sandbox="allow-scripts allow-forms allow-same-origin allow-pointer-lock allow-downloads"');expect(src).toContain('referrerPolicy="no-referrer"');expect(src).not.toContain('src="/camoufox-vnc/');diff --git a/lib/camoufox/origin.test.ts b/lib/camoufox/origin.test.tsindex 2058a4f7..718ac63b 100644--- a/lib/camoufox/origin.test.ts+++ b/lib/camoufox/origin.test.ts@@ -2,10 +2,15 @@ import { afterEach, describe, expect, it, vi } from "vitest";afterEach(() => vi.unstubAllEnvs());-async function load(template: string, publicOrigin = "https://mso.example.com") {+async function load(+ template: string,+ publicOrigin = "https://mso.example.com",+ viewerOrigin = "",+) {vi.resetModules();vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);vi.stubEnv("OS_PUBLIC_ORIGIN", publicOrigin);+ vi.stubEnv("CAMOUFOX_VIEWER_ORIGIN", viewerOrigin);return import("./origin");}@@ -23,6 +28,31 @@ describe("Camoufox split origin", () => {expect(mod.isCamoufoxViewerHost("mso.example.com")).toBe(false);});++ it("can use an explicit sibling viewer origin without changing the managed-app namespace", async () => {+ const mod = await load(+ "{id}.mso.example.com",+ "https://mso.example.com",+ "https://camoufox-mso.example.com",+ );+ expect(mod.camoufoxViewerHost()).toBe("camoufox-mso.example.com");+ expect(mod.camoufoxViewerOrigin()).toBe("https://camoufox-mso.example.com");+ expect(mod.isCamoufoxViewerHost("camoufox-mso.example.com:443")).toBe(true);+ expect(mod.isCamoufoxViewerHost("camoufox.mso.example.com")).toBe(false);+ });++ it("rejects unsafe viewer-origin overrides and keeps the safe namespace fallback", async () => {+ for (const value of [+ "http://camoufox-mso.example.com",+ "https://user:[email protected]",+ "https://camoufox-mso.example.com/path",+ ]) {+ const mod = await load("{id}.mso.example.com", "https://mso.example.com", value);+ expect(mod.camoufoxViewerOrigin()).toBe("https://camoufox.mso.example.com");+ vi.unstubAllEnvs();+ }+ });+it("allows only the cockpit to frame the viewer and no outbound forms", async () => {const mod = await load("{id}.mso.example.com");const csp = mod.camoufoxViewerCsp();diff --git a/lib/camoufox/origin.ts b/lib/camoufox/origin.tsindex 5bcc32c4..c01aa7b8 100644--- a/lib/camoufox/origin.ts+++ b/lib/camoufox/origin.ts@@ -5,13 +5,34 @@ import { appNamespaceHost, cockpitOrigin } from "@/lib/managed-apps/origin";export const CAMOUFOX_VIEWER_LABEL = "camoufox";+function configuredViewerOrigin(): URL | null {+ const raw = process.env.CAMOUFOX_VIEWER_ORIGIN?.trim();+ if (!raw) return null;+ try {+ const url = new URL(raw);+ if (+ url.protocol !== "https:" ||+ url.username ||+ url.password ||+ url.pathname !== "/" ||+ url.search ||+ url.hash+ ) return null;+ return url;+ } catch {+ return null;+ }+}+export function camoufoxViewerHost(): string | null {- return appNamespaceHost(CAMOUFOX_VIEWER_LABEL);+ return configuredViewerOrigin()?.host.toLowerCase() ?? appNamespaceHost(CAMOUFOX_VIEWER_LABEL);}export function camoufoxViewerOrigin(): string | null {+ const configured = configuredViewerOrigin();+ if (configured) return configured.origin;const host = camoufoxViewerHost();- return host ? `https://${host}` : null;+ return host ? "https://" + host : null;}export function isCamoufoxViewerHost(host: string | null | undefined): boolean {diff --git a/lib/camoufox/viewer-auth.test.ts b/lib/camoufox/viewer-auth.test.tsnew file mode 100644index 00000000..c04484d9--- /dev/null+++ b/lib/camoufox/viewer-auth.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from "vitest";+import { signSession } from "@/lib/auth/session";+import {+ CAMOUFOX_VIEWER_COOKIE_TTL_MS,+ CAMOUFOX_VIEWER_TICKET_TTL_MS,+ createCamoufoxViewerCookie,+ createCamoufoxViewerTicket,+ verifyCamoufoxViewerCookie,+ verifyCamoufoxViewerTicket,+} from "./viewer-auth";++describe("Camoufox sibling viewer credentials", () => {+ const secret = "s".repeat(48);+ const deviceId = "dev-1234567890abcdef";++ it("keeps short-lived tickets and viewer cookies cryptographically separate", () => {+ const now = Date.now();+ const ticket = createCamoufoxViewerTicket(deviceId, secret, now);+ const cookie = createCamoufoxViewerCookie(deviceId, secret, now);+ expect(verifyCamoufoxViewerTicket(ticket, secret)?.device_id).toBe(deviceId);+ expect(verifyCamoufoxViewerCookie(cookie, secret)?.device_id).toBe(deviceId);+ expect(verifyCamoufoxViewerCookie(ticket, secret)).toBeNull();+ expect(verifyCamoufoxViewerTicket(cookie, secret)).toBeNull();+ });++ it("expires a ticket much sooner than the host-only viewer cookie", () => {+ const oldTicket = createCamoufoxViewerTicket(deviceId, secret, Date.now() - CAMOUFOX_VIEWER_TICKET_TTL_MS - 1);+ expect(verifyCamoufoxViewerTicket(oldTicket, secret)).toBeNull();+ const stillValidCookie = createCamoufoxViewerCookie(deviceId, secret, Date.now() - CAMOUFOX_VIEWER_COOKIE_TTL_MS + 60_000);+ expect(verifyCamoufoxViewerCookie(stillValidCookie, secret)?.device_id).toBe(deviceId);+ });++ it("never accepts a cockpit session or a weak base secret", () => {+ const now = Date.now();+ const cockpit = signSession({+ issued_at: now,+ expires_at: now + 60_000,+ device_id: deviceId,+ cookie_scope: "host",+ cookie_epoch: "epoch-0000000000000000",+ }, secret);+ expect(verifyCamoufoxViewerTicket(cockpit, secret)).toBeNull();+ expect(verifyCamoufoxViewerCookie(cockpit, secret)).toBeNull();+ expect(verifyCamoufoxViewerTicket("anything", "")).toBeNull();+ expect(() => createCamoufoxViewerTicket(deviceId, "")).toThrow(/not configured/);+ });+});diff --git a/lib/camoufox/viewer-auth.ts b/lib/camoufox/viewer-auth.tsnew file mode 100644index 00000000..232d5ea9--- /dev/null+++ b/lib/camoufox/viewer-auth.ts@@ -0,0 +1,38 @@+import { MIN_SECRET_LEN, signSession, verifySession, type SessionPayload } from "@/lib/auth/session";++export const CAMOUFOX_VIEWER_COOKIE = "__Host-mso-camoufox";+export const CAMOUFOX_VIEWER_TICKET_TTL_MS = 60_000;+export const CAMOUFOX_VIEWER_COOKIE_TTL_MS = 2 * 60 * 60 * 1000;++const ticketSecret = (secret: string) => "camoufox-viewer-ticket:" + secret;+const cookieSecret = (secret: string) => "camoufox-viewer-cookie:" + secret;++function payload(deviceId: string, now: number, ttlMs: number): SessionPayload {+ return {+ issued_at: now,+ expires_at: now + ttlMs,+ device_id: deviceId,+ cookie_scope: "camoufox-viewer",+ cookie_epoch: "camoufox-viewer-v1",+ };+}++export function createCamoufoxViewerTicket(deviceId: string, secret: string, now = Date.now()): string {+ if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");+ return signSession(payload(deviceId, now, CAMOUFOX_VIEWER_TICKET_TTL_MS), ticketSecret(secret));+}++export function verifyCamoufoxViewerTicket(token: string, secret: string): SessionPayload | null {+ if (secret.length < MIN_SECRET_LEN) return null;+ return verifySession(token, ticketSecret(secret));+}++export function createCamoufoxViewerCookie(deviceId: string, secret: string, now = Date.now()): string {+ if (secret.length < MIN_SECRET_LEN) throw new Error("viewer signing secret is not configured");+ return signSession(payload(deviceId, now, CAMOUFOX_VIEWER_COOKIE_TTL_MS), cookieSecret(secret));+}++export function verifyCamoufoxViewerCookie(token: string, secret: string): SessionPayload | null {+ if (secret.length < MIN_SECRET_LEN) return null;+ return verifySession(token, cookieSecret(secret));+}diff --git a/lib/camoufox/viewer-gate.test.ts b/lib/camoufox/viewer-gate.test.tsnew file mode 100644index 00000000..fc187150--- /dev/null+++ b/lib/camoufox/viewer-gate.test.ts@@ -0,0 +1,177 @@+import { describe, expect, it, vi } from "vitest";+import { NextRequest } from "next/server";+import { signSession } from "@/lib/auth/session";+import {+ CAMOUFOX_VIEWER_COOKIE,+ CAMOUFOX_VIEWER_TICKET_TTL_MS,+ createCamoufoxViewerCookie,+ createCamoufoxViewerTicket,+} from "@/lib/camoufox/viewer-auth";++const approved = vi.hoisted(() => ({+ value: true,+ role: "owner" as "viewer" | "operator" | "owner",+}));+vi.mock("@/lib/auth/device-store", () => ({+ getApprovedDevice: async () => approved.value+ ? { label: "test device", approvedAt: 1, role: approved.role }+ : null,+}));++const TEMPLATE = "{id}.mso.example.com";++async function loadProxy(template: string) {+ vi.resetModules();+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", template);+ return (await import("../../proxy")).proxy;+}++function req(host: string, path: string, headers: Record<string, string> = {}): NextRequest {+ const h = new Headers(headers);+ h.set("host", host);+ return new NextRequest("https://" + host + path, { headers: h });+}++const rewriteOf = (res: Response) => res.headers.get("x-middleware-rewrite");++describe("the Camoufox split-origin VNC bridge", () => {+ const SECRET = "y".repeat(48);+ const NOVNC = "http://127.0.0.1:6080";+ const VIEWER_HOST = "camoufox-mso.example.com";+ const DEVICE = "dev-1234567890abcdef";++ function cockpitSession(secret = SECRET): string {+ const now = Date.now();+ return signSession({+ issued_at: now,+ expires_at: now + 3_600_000,+ device_id: DEVICE,+ cookie_scope: "host",+ cookie_epoch: "epoch-0000000000000000",+ }, secret);+ }++ function viewerCookie(): string {+ return createCamoufoxViewerCookie(DEVICE, SECRET);+ }++ function viewerTicket(now = Date.now()): string {+ return createCamoufoxViewerTicket(DEVICE, SECRET, now);+ }++ async function load(novnc = NOVNC) {+ vi.stubEnv("OS_SESSION_SECRET", SECRET);+ vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");+ vi.stubEnv("CAMOUFOX_NOVNC_URL", novnc);+ vi.stubEnv("CAMOUFOX_VIEWER_ORIGIN", "https://" + VIEWER_HOST);+ approved.value = true;+ approved.role = "owner";+ return loadProxy(TEMPLATE);+ }++ const vnc = (cookie?: string, path = "/vnc_lite.html", extra: Record<string, string> = {}) =>+ req(VIEWER_HOST, path, cookie ? { cookie: CAMOUFOX_VIEWER_COOKIE + "=" + cookie, ...extra } : extra);++ it("serves only the inert authorization bootstrap before a viewer cookie exists", async () => {+ const proxy = await load();+ const page = await proxy(vnc(undefined, "/vnc.html"));+ expect(page.status).toBe(200);+ expect(rewriteOf(page)).toBeNull();+ expect(await page.text()).toContain("/__viewer_bootstrap.js");+ expect(page.headers.get("content-security-policy")).toContain("frame-ancestors https://mso.example.com");+ expect(page.headers.get("set-cookie")).toBeNull();++ const asset = await proxy(vnc(undefined, "/app/ui.js"));+ expect(asset.status).toBe(404);+ });++ it("does not accept the cockpit session cookie on the sibling viewer host", async () => {+ const proxy = await load();+ const page = await proxy(req(VIEWER_HOST, "/vnc.html", { cookie: "session=" + cockpitSession() }));+ expect(page.status).toBe(200);+ expect(rewriteOf(page)).toBeNull();+ expect(await page.text()).toContain("Authorizing secure browser viewer");+ });++ it("exchanges a fragment-carried ticket for a host-only HttpOnly cookie", async () => {+ const proxy = await load();+ const auth = new NextRequest("https://" + VIEWER_HOST + "/__viewer_auth", {+ method: "POST",+ headers: { host: VIEWER_HOST, authorization: "Bearer " + viewerTicket() },+ });+ const response = await proxy(auth);+ expect(response.status).toBe(204);+ const setCookie = response.headers.get("set-cookie") ?? "";+ expect(setCookie).toContain(CAMOUFOX_VIEWER_COOKIE + "=");+ expect(setCookie).toContain("HttpOnly");+ expect(setCookie).toContain("Secure");+ expect(setCookie).toContain("SameSite=strict");+ expect(setCookie).toContain("Path=/");+ expect(setCookie.toLowerCase()).not.toContain("domain=");+ });++ it("rejects forged, expired, revoked, and viewer-role credentials", async () => {+ const proxy = await load();+ const forged = new NextRequest("https://" + VIEWER_HOST + "/__viewer_auth", {+ method: "POST",+ headers: { host: VIEWER_HOST, authorization: "Bearer anything.anything" },+ });+ expect((await proxy(forged)).status).toBe(404);++ const expired = new NextRequest("https://" + VIEWER_HOST + "/__viewer_auth", {+ method: "POST",+ headers: {+ host: VIEWER_HOST,+ authorization: "Bearer " + viewerTicket(Date.now() - CAMOUFOX_VIEWER_TICKET_TTL_MS - 1),+ },+ });+ expect((await proxy(expired)).status).toBe(404);++ approved.value = false;+ expect((await proxy(vnc(viewerCookie()))).status).toBe(404);+ approved.value = true;+ approved.role = "viewer";+ expect((await proxy(vnc(viewerCookie()))).status).toBe(404);+ });++ it("maps an approved sibling viewer to loopback noVNC and strips credentials upstream", async () => {+ const proxy = await load();+ const res = await proxy(vnc(viewerCookie(), "/websockify", {+ upgrade: "websocket",+ connection: "Upgrade",+ authorization: "Bearer must-not-leak",+ }));+ const target = new URL(rewriteOf(res)!);+ expect(target.origin).toBe(NOVNC);+ expect(target.pathname).toBe("/websockify");+ expect(res.headers.get("x-middleware-request-cookie")).toBeNull();+ expect(res.headers.get("x-middleware-request-authorization")).toBeNull();+ });++ it("maps root to the full noVNC UI and preserves only viewer query state", async () => {+ const proxy = await load();+ expect(new URL(rewriteOf(await proxy(vnc(viewerCookie(), "/")))!).pathname).toBe("/vnc.html");+ const res = await proxy(vnc(viewerCookie(), "/vnc.html?path=websockify&resize=remote"));+ expect(new URL(rewriteOf(res)!).search).toBe("?path=websockify&resize=remote");+ });++ it("never exposes the retired same-origin bridge", async () => {+ const proxy = await load();+ const res = await proxy(req("mso.example.com", "/camoufox-vnc/vnc.html", { cookie: "session=" + cockpitSession() }));+ expect(res.status).toBe(404);+ expect(rewriteOf(res)).toBeNull();+ });++ it("refuses non-read viewer methods and off-box noVNC destinations", async () => {+ const proxy = await load();+ const post = new NextRequest("https://" + VIEWER_HOST + "/vnc.html", {+ method: "POST",+ headers: { host: VIEWER_HOST, cookie: CAMOUFOX_VIEWER_COOKIE + "=" + viewerCookie() },+ body: "x",+ });+ expect((await proxy(post)).status).toBe(404);++ const offBox = await load("http://evil.example");+ expect((await offBox(vnc(viewerCookie()))).status).toBe(404);+ });+});diff --git a/lib/camoufox/viewer-gate.ts b/lib/camoufox/viewer-gate.tsnew file mode 100644index 00000000..b4968166--- /dev/null+++ b/lib/camoufox/viewer-gate.ts@@ -0,0 +1,140 @@+import { NextResponse, type NextRequest } from "next/server";+import { getApprovedDevice } from "@/lib/auth/device-store";+import { roleAtLeast } from "@/lib/auth/roles";+import { camoufoxViewerCsp } from "./origin";+import {+ CAMOUFOX_VIEWER_COOKIE,+ CAMOUFOX_VIEWER_COOKIE_TTL_MS,+ createCamoufoxViewerCookie,+ verifyCamoufoxViewerCookie,+ verifyCamoufoxViewerTicket,+} from "./viewer-auth";+import { IS_DEMO } from "@/lib/demo";++const AUTHORIZED = Symbol("camoufox-viewer-authorized");+export type CamoufoxViewerGateResult = typeof AUTHORIZED | NextResponse;++function notFound() {+ return new NextResponse("Not Found", {+ status: 404,+ headers: { "content-type": "text/plain; charset=utf-8" },+ });+}++async function approvedDevice(token: string, kind: "ticket" | "cookie"): Promise<string | null> {+ if (IS_DEMO) return null;+ const secret = process.env.OS_SESSION_SECRET ?? "";+ const payload = kind === "ticket"+ ? verifyCamoufoxViewerTicket(token, secret)+ : verifyCamoufoxViewerCookie(token, secret);+ if (!payload?.device_id) return null;+ const device = await getApprovedDevice(payload.device_id);+ return device && roleAtLeast(device.role, "operator") ? payload.device_id : null;+}++async function hasViewerSession(request: NextRequest): Promise<boolean> {+ for (const { value } of request.cookies.getAll(CAMOUFOX_VIEWER_COOKIE)) {+ if (await approvedDevice(value, "cookie")) return true;+ }+ return false;+}++const BOOTSTRAP_HTML = [+ "<!doctype html><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex,nofollow\">",+ "<title>MSO Browser authorization</title>",+ "<body><p>Authorizing secure browser viewer...</p>",+ "<script src=\"/__viewer_bootstrap.js\" defer></script></body>",+].join("");++const BOOTSTRAP_JS = [+ "(async()=>{",+ "const p=new URLSearchParams(location.hash.slice(1));",+ "const t=p.get('viewer_ticket');",+ "if(!t){document.body.textContent='Viewer authorization required.';return;}",+ "p.delete('viewer_ticket');",+ "const r=await fetch('/__viewer_auth',{method:'POST',headers:{authorization:'Bearer '+t},credentials:'include',cache:'no-store'});",+ "if(!r.ok){document.body.textContent='Viewer authorization failed.';return;}",+ "location.replace(location.pathname+location.search+(p.toString()?'#'+p.toString():''));",+ "})().catch(()=>{document.body.textContent='Viewer authorization failed.';});",+].join("");++function bootstrap(method: string) {+ const response = new NextResponse(method === "HEAD" ? null : BOOTSTRAP_HTML, {+ status: 200,+ headers: {+ "content-type": "text/html; charset=utf-8",+ "cache-control": "no-store",+ "content-security-policy": camoufoxViewerCsp(),+ "referrer-policy": "no-referrer",+ "x-content-type-options": "nosniff",+ "cross-origin-resource-policy": "same-origin",+ },+ });+ // The global cockpit header is DENY. This split-origin viewer is the one exception:+ // its CSP frame-ancestors names the exact cockpit and remains the authoritative gate.+ response.headers.delete("x-frame-options");+ return response;+}++function bootstrapScript() {+ return new NextResponse(BOOTSTRAP_JS, {+ status: 200,+ headers: {+ "content-type": "application/javascript; charset=utf-8",+ "cache-control": "no-store",+ "referrer-policy": "no-referrer",+ "x-content-type-options": "nosniff",+ "cross-origin-resource-policy": "same-origin",+ },+ });+}++async function exchangeTicket(request: NextRequest) {+ if (request.method !== "POST") return notFound();+ const match = /^Bearer ([A-Za-z0-9._-]{20,4096})$/.exec(request.headers.get("authorization") ?? "");+ if (!match) return notFound();+ const deviceId = await approvedDevice(match[1], "ticket");+ if (!deviceId) return notFound();++ const response = new NextResponse(null, { status: 204 });+ response.cookies.set(+ CAMOUFOX_VIEWER_COOKIE,+ createCamoufoxViewerCookie(deviceId, process.env.OS_SESSION_SECRET ?? ""),+ {+ httpOnly: true,+ secure: true,+ sameSite: "strict",+ path: "/",+ maxAge: Math.floor(CAMOUFOX_VIEWER_COOKIE_TTL_MS / 1000),+ },+ );+ response.headers.set("cache-control", "no-store");+ return response;+}++/**+ * Authorize the dedicated Camoufox sibling origin without ever sharing the cockpit+ * session cookie. Before authorization, only the inert bootstrap and ticket exchange+ * exist. The returned symbol means the caller may proxy a read-only noVNC request.+ */+export async function gateCamoufoxViewer(+ request: NextRequest,+ pathname: string,+): Promise<CamoufoxViewerGateResult> {+ if (pathname === "/__viewer_bootstrap.js") {+ return request.method === "GET" ? bootstrapScript() : notFound();+ }+ if (pathname === "/__viewer_auth") return exchangeTicket(request);+ if (await hasViewerSession(request)) return AUTHORIZED;+ if (+ (request.method === "GET" || request.method === "HEAD") &&+ (pathname === "/" || pathname === "/vnc.html")+ ) return bootstrap(request.method);+ return notFound();+}++export function camoufoxViewerAuthorized(+ result: CamoufoxViewerGateResult,+): result is typeof AUTHORIZED {+ return result === AUTHORIZED;+}diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.tsindex 48f4857f..7b1ca81f 100644--- a/proxy-websocket.test.ts+++ b/proxy-websocket.test.ts@@ -177,121 +177,3 @@ describe("per-app upgrade adapters", () => {// operator adding this host to that list from working.expect(header("origin")).toBe("https://openclaw.mso.example.com");});});--// The Camoufox VNC bridge — noVNC over websockify in front of x11vnc, i.e. live-// keyboard and mouse on a real browser session. It was hard-403'd because its only-// gate had been a check that a cookie NAMED "session" existed, which any value-// satisfied. It is open again only behind the verified check, so these tests are the-// difference between a browser app and an unauthenticated remote-control relay.-describe("the Camoufox split-origin VNC bridge", () => {- const SECRET = "y".repeat(48);- const NOVNC = "http://127.0.0.1:6080";- const VIEWER_HOST = "camoufox.mso.example.com";-- function session(secret = SECRET): string {- const now = Date.now();- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" }, secret);- }-- async function load(novnc = NOVNC) {- vi.stubEnv("OS_SESSION_SECRET", SECRET);- vi.stubEnv("OS_PUBLIC_ORIGIN", "https://mso.example.com");- vi.stubEnv("CAMOUFOX_NOVNC_URL", novnc);- approved.value = true;- approved.role = "owner";- return loadProxy(TEMPLATE);- }-- const vnc = (cookie?: string, path = "/vnc_lite.html", extra: Record<string, string> = {}) =>- req(VIEWER_HOST, path, cookie ? { cookie: `session=${cookie}`, ...extra } : extra);-- it("404s a request with no cookie at all", async () => {- const proxy = await load();- const res = await proxy(vnc());- expect(res.status).toBe(404);- expect(rewriteOf(res)).toBeNull();- });-- it("404s a forged or wrongly signed cookie", async () => {- const proxy = await load();- expect((await proxy(vnc("anything"))).status).toBe(404);- expect((await proxy(vnc(session("z".repeat(48))))).status).toBe(404);- });-- it("404s a valid signature once the device is revoked", async () => {- const proxy = await load();- approved.value = false;- expect((await proxy(vnc(session()))).status).toBe(404);- });-- it("maps the dedicated host to loopback noVNC without a cockpit prefix", async () => {- const proxy = await load();- const res = await proxy(vnc(session()));- const target = new URL(rewriteOf(res)!);- expect(target.origin).toBe(NOVNC);- expect(target.pathname).toBe("/vnc_lite.html");- expect(res.headers.get("content-security-policy")).toContain("frame-ancestors https://mso.example.com");- expect(res.headers.get("referrer-policy")).toBe("no-referrer");- });-- it("requires operator or owner for the live browser viewer", async () => {- const proxy = await load();- approved.role = "viewer";- expect((await proxy(vnc(session()))).status).toBe(404);- approved.role = "operator";- expect(new URL(rewriteOf(await proxy(vnc(session())))!).origin).toBe(NOVNC);- });-- it("maps the viewer-host root to the full noVNC UI", async () => {- const proxy = await load();- expect(new URL(rewriteOf(await proxy(vnc(session(), "/")))!).pathname).toBe("/vnc.html");- });-- it("carries only the query string noVNC needs", async () => {- const proxy = await load();- const res = await proxy(vnc(session(), "/vnc.html?path=websockify&resize=remote"));- expect(new URL(rewriteOf(res)!).search).toBe("?path=websockify&resize=remote");- });-- it("carries an authenticated upgrade and strips cockpit credentials upstream", async () => {- const proxy = await load();- const res = await proxy(vnc(session(), "/websockify", {- upgrade: "websocket", connection: "Upgrade", authorization: "Bearer must-not-leak",- }));- expect(new URL(rewriteOf(res)!).pathname).toBe("/websockify");- expect(res.headers.get("x-middleware-request-cookie")).toBeNull();- expect(res.headers.get("x-middleware-request-authorization")).toBeNull();- });-- it("strips the Domain session cookie from ordinary noVNC asset requests too", async () => {- const proxy = await load();- const res = await proxy(vnc(session(), "/app/ui.js", { authorization: "Basic must-not-leak" }));- expect(res.headers.get("x-middleware-request-cookie")).toBeNull();- expect(res.headers.get("x-middleware-request-authorization")).toBeNull();- });-- it("never exposes the old same-origin cockpit bridge", async () => {- const proxy = await load();- const res = await proxy(req("mso.example.com", "/camoufox-vnc/vnc.html", { cookie: `session=${session()}` }));- expect(res.status).toBe(404);- expect(rewriteOf(res)).toBeNull();- });-- it("never maps cockpit API names on the viewer host back into MSO", async () => {- const proxy = await load();- const res = await proxy(vnc(session(), "/api/v1/exec/run"));- expect(new URL(rewriteOf(res)!).toString()).toBe(`${NOVNC}/api/v1/exec/run`);- });-- it("refuses non-read methods and an off-box destination", async () => {- const proxy = await load();- const postHeaders = new Headers({ host: VIEWER_HOST, cookie: `session=${session()}` });- const post = new NextRequest(`https://${VIEWER_HOST}/vnc.html`, {- method: "POST", headers: postHeaders, body: "x",- });- expect((await proxy(post)).status).toBe(404);-- const offBox = await load("http://evil.example");- expect((await offBox(vnc(session()))).status).toBe(404);- });-});diff --git a/proxy.ts b/proxy.tsindex aad8cd10..fddc08b0 100644--- a/proxy.ts+++ b/proxy.ts@@ -34,6 +34,10 @@ import { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-storeimport { roleAtLeast, type DeviceRole } from "@/lib/auth/roles";import { IS_DEMO } from "@/lib/demo";import { camoufoxViewerCsp, isCamoufoxViewerHost } from "@/lib/camoufox/origin";+import {+ camoufoxViewerAuthorized,+ gateCamoufoxViewer,+} from "@/lib/camoufox/viewer-gate";import { applyPrivatePageCachePolicy } from "@/lib/auth/page-cache";const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);@@ -176,13 +180,14 @@ export async function proxy(request: NextRequest) {const host = request.headers.get("host") ?? request.nextUrl.host;const managedApp = managedAppIdForHost(host);- // noVNC gets one reserved split-origin host. Every path on it goes ONLY to the- // loopback viewer; no cockpit route exists there. The Domain session cookie is- // used solely at this edge gate and is stripped before noVNC receives the request.+ // noVNC gets one reserved split-origin host. The cockpit session cookie is+ // intentionally NOT shared with a sibling viewer hostname. Instead, an authenticated+ // operator obtains a 60-second ticket on the cockpit, carries it only in the URL+ // fragment, and exchanges it here for a host-only HttpOnly viewer cookie.if (isCamoufoxViewerHost(host)) {- if (!(await hasApprovedSession(request, "operator"))) return notFound();- if (request.method !== "GET" && request.method !== "HEAD")- return notFound();+ const viewerGate = await gateCamoufoxViewer(request, pathname);+ if (!camoufoxViewerAuthorized(viewerGate)) return viewerGate;+ if (request.method !== "GET" && request.method !== "HEAD") return notFound();let base: URL;try {base = new URL(CAMOUFOX_NOVNC_URL);@@ -196,8 +201,6 @@ export async function proxy(request: NextRequest) {return notFound();}const target = new URL(base);- // Assign pathname/search separately: resolving a caller path beginning `//`- // against base would otherwise change the destination host.target.pathname = pathname === "/" ? "/vnc.html" : pathname;target.search = request.nextUrl.search;const response = NextResponse.rewrite(target, {@@ -211,6 +214,7 @@ export async function proxy(request: NextRequest) {response.headers.set("Referrer-Policy", "no-referrer");response.headers.set("X-Content-Type-Options", "nosniff");response.headers.set("Cross-Origin-Resource-Policy", "same-origin");+ response.headers.delete("X-Frame-Options");return response;}diff --git a/scripts/e2e/camoufox-connection.mjs b/scripts/e2e/camoufox-connection.mjsindex d7f7cee1..69996030 100644--- a/scripts/e2e/camoufox-connection.mjs+++ b/scripts/e2e/camoufox-connection.mjs@@ -19,7 +19,15 @@ export async function camoufoxConnectionJourney(page, fixture) {const running = mode !== "stopping" || reads === 1;return route.fulfill({ status: 200, json: { installed: true, running, enabled: false, viewerReady: mode !== "stopping" } });};- const session = route => route.fulfill({ status: 200, json: { password: null } });+ const viewerOrigin = "https://camoufox-fixture.invalid";+ const session = route => route.fulfill({+ status: 200,+ json: {+ password: null,+ viewerOrigin,+ viewerTicket: "fixture-viewer-ticket-0123456789abcdef",+ },+ });const viewer = route => route.fulfill({ status: 200, contentType: "text/html", body: "<!doctype html><title>Private fixture viewer</title><p>Client-only viewer fixture</p>" });page.on("request", observe);await page.route("**/api/v1/camoufox/session", session);@@ -44,6 +52,7 @@ export async function camoufoxConnectionJourney(page, fixture) {await retry.click();const frame = page.locator('iframe[title="Camoufox browser"]');await expect(frame).toBeVisible();+ expect((await frame.getAttribute("src")) ?? "").toContain(viewerOrigin + "/vnc.html?");await expect(page.frameLocator('iframe[title="Camoufox browser"]').getByText("Client-only viewer fixture")).toBeVisible();expect(credentials).toBe(beforeCredentials + 1); expect(posts).toBe(0);mode = "stopping"; reads = 0;