Skip to content

armgit / mso

Public Imported from GitHub
0

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

fix(auth): bind sessions to cookie scope

Rahman27811bf1aeb8
diff --git a/.env.example b/.env.example
index 25713293..d66b5072 100644
--- a/.env.example
+++ b/.env.example
@@ -192,10 +192,10 @@ OS_SESSION_SECRET=
# Malformed values fail closed to host-only rather than emitting a broken header:
# the domain must be ≥2 DNS labels, not an IP, and must domain-match the request
# host, otherwise the browser drops the whole cookie and login 200s with no
-# session. Note also that logout can only clear cookies it knows about — after
-# UNSETTING the domain, an already-issued domain cookie can no longer be cleared
-# by logout; revoke the device (Settings → Devices) to kill those sessions, or
-# wait out SESSION_EXPIRY_HOURS.
+# session. Signed browser sessions are bound to the normalized cookie policy that
+# minted them. Changing/unsetting this value therefore invalidates older session
+# tokens server-side even if the browser keeps a broader Domain cookie in its jar
+# until natural expiry. Sign in again after every scope change.
#
# NEXT_PUBLIC_ is baked into the CLIENT bundle at BUILD time (the server and the
# middleware read it at runtime), so set it BEFORE `bun run build` — not just before
diff --git a/app/api/assistant/route.test.ts b/app/api/assistant/route.test.ts
index 8f2f6b53..b796429a 100644
--- a/app/api/assistant/route.test.ts
+++ b/app/api/assistant/route.test.ts
@@ -8,7 +8,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
// per-process rate-limit bucket starts clean (otherwise tests leak state via
// the singleton Map in lib/host/rate-limit).
const stableContext = {
- session: { device_id: "test-device", issued_at: 1, expires_at: 2 },
+ session: { device_id: "test-device", issued_at: 1, expires_at: 2, cookie_scope: "host" },
device: { label: "test owner", approvedAt: 1, role: "owner" as const },
role: "owner" as const,
};
diff --git a/app/api/auth/devices/route.test.ts b/app/api/auth/devices/route.test.ts
index 4d332093..dac857a7 100644
--- a/app/api/auth/devices/route.test.ts
+++ b/app/api/auth/devices/route.test.ts
@@ -16,7 +16,7 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/auth/require-session", () => ({
getSessionContext: vi.fn(async () => session.current ? ({
- session: { device_id: CURRENT, issued_at: 1, expires_at: 2 },
+ session: { device_id: CURRENT, issued_at: 1, expires_at: 2, cookie_scope: "host" },
device: { label: "current", approvedAt: 1, role: session.current },
role: session.current,
}) : null),
diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts
index 82a4200f..b6aa33e8 100644
--- a/app/api/auth/login/route.ts
+++ b/app/api/auth/login/route.ts
@@ -1,7 +1,7 @@
import { NextRequest, NextResponse } from "next/server";
import { constantTimeEq, MAX_COMPARE_BYTES, MIN_SECRET_LEN, signSession, type SessionPayload } from "@/lib/auth/session";
import { SESSION_COOKIE } from "@/lib/auth/require-session";
-import { sessionCookieAttrs } from "@/lib/auth/session-cookie";
+import { configuredSessionCookieScope, sessionCookieAttrs } from "@/lib/auth/session-cookie";
import { isApproved, isValidDeviceId, recordPending, touchApproved } from "@/lib/auth/device-store";
import { audit } from "@/lib/host/audit-api";
import { IS_DEMO } from "@/lib/demo";
@@ -163,6 +163,7 @@ export async function POST(req: NextRequest) {
issued_at: now,
expires_at: now + hours * 3600 * 1000,
device_id: deviceId,
+ cookie_scope: configuredSessionCookieScope(),
};
const res = NextResponse.json({ success: true });
// Attributes (incl. the optional Domain for the split-origin app hosts) come
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index e76f3169..cc6c1be2 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -13,6 +13,7 @@ this is the *what*, and it is what Settings → About shows as “What's new”.
**Fixed**
+- `auth` bind sessions to cookie scope
- `workflows` remount editors when sandbox policy changes
- `workflows` retain approved shared surface placements
- `browser` keep Camoufox automation on demand
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 5dc57169..6806a983 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,15 @@
+## 2026-09-18 — Bind signed sessions to their cookie policy
+
+The external-editor security review found a migration edge case: after a broad Domain cookie
+is narrowed or unset, the browser can retain the old cookie until its original expiry even
+though logout no longer knows its former Domain. Session payloads now carry the normalized
+cookie policy that minted them, and both route authorization and middleware/WebSocket gates
+reject a valid HMAC when that policy no longer matches current configuration. Legacy tokens
+without a scope are intentionally invalidated once. This preserves safe host-only sibling
+editors such as a separately hosted n8n while making a retained broader Owner cookie unusable
+against MSO after a scope change. No cookie is widened, no secret is rotated, and current
+domain-match/host collision checks remain in place.
+
## 2026-09-18 — Remount reviewed workflow editors when sandbox policy changes
A focus refresh can tighten an existing external editor's sandbox without changing its id or origin.
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index 5a97449f..b364f34c 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -228,9 +228,11 @@ Organization is not owned by Workflow Graph. An `agent` node may set `orgSeatId`
### External editor credential isolation
Different origins do not by themselves isolate cookies. Reviewed external editors must
-be outside `OS_SESSION_COOKIE_DOMAIN` and must not reuse a cockpit hostname on another
-port, including when cookies are host-only. MSO blocks both framing and editor/login links
-for colliding destinations and shows the configuration reason. Shared MCP Page discovery
-also excludes them. Use a distinct cookie-isolated editor hostname; registry review is not
-a credential-sharing exception. Native managed-app/browser proxy routes keep their separate
-existing authentication boundaries and are not granted trust by a registry entry.
+be outside the currently validated `OS_SESSION_COOKIE_DOMAIN` and must not reuse a cockpit
+hostname on another port when cookies are host-only. MSO blocks both framing and editor/login
+links for colliding destinations and shows the configuration reason. Signed browser sessions
+are also bound to the normalized cookie policy that minted them: widening, narrowing or
+unsetting the Domain invalidates older tokens server-side, so a broader cookie retained by
+the browser cannot authenticate after the scope change. Shared MCP Page discovery uses the
+same boundary. Registry review is not a credential-sharing exception; native managed-app/
+browser proxy routes keep their separate existing authentication boundaries.
diff --git a/lib/auth/require-session.test.ts b/lib/auth/require-session.test.ts
index 0a2a92a2..1ef7001b 100644
--- a/lib/auth/require-session.test.ts
+++ b/lib/auth/require-session.test.ts
@@ -20,11 +20,12 @@ vi.mock("./device-store", () => ({
: null,
}));
-const valid = () => signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1" }, SECRET);
+const valid = () => signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1", cookie_scope: "host" }, SECRET);
beforeEach(() => {
jar.length = 0;
process.env.OS_SESSION_SECRET = SECRET;
+ delete process.env.OS_SESSION_COOKIE_DOMAIN;
});
describe("getSession with a shadowed cookie", () => {
@@ -44,11 +45,19 @@ describe("getSession with a shadowed cookie", () => {
const { getSession } = await import("./require-session");
jar.push({
name: "session",
- value: signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "revoked" }, SECRET),
+ value: signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "revoked", cookie_scope: "host" }, SECRET),
});
expect(await getSession()).toBeNull();
});
+
+ it("rejects a still-signed cookie after its configured cookie scope changes", async () => {
+ const { getSession } = await import("./require-session");
+ jar.push({ name: "session", value: signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1", cookie_scope: "domain:example.com" }, SECRET) });
+ expect(await getSession()).toBeNull();
+ process.env.OS_SESSION_COOKIE_DOMAIN = "example.com";
+ expect(await getSession()).toMatchObject({ device_id: "dev-1", cookie_scope: "domain:example.com" });
+ });
it("rechecks the live device role for every authorization decision", async () => {
const { getSessionContext, requireSession } = await import("./require-session");
jar.push({ name: "session", value: valid() });
diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.ts
index fac2a130..83ffff7c 100644
--- a/lib/auth/require-session.ts
+++ b/lib/auth/require-session.ts
@@ -1,4 +1,5 @@
import { cookies } from "next/headers";
+import { configuredSessionCookieScope } from "./session-cookie";
import { verifySession, type SessionPayload } from "./session";
import { getApprovedDevice, type ApprovedDevice } from "./device-store";
import { roleAtLeast, type DeviceRole } from "./roles";
@@ -22,9 +23,10 @@ export type SessionContext = {
export async function getSessionContext(): Promise<SessionContext | null> {
if (IS_DEMO) return null;
const jar = await cookies();
+ const cookieScope = configuredSessionCookieScope();
for (const { value } of jar.getAll(SESSION_COOKIE)) {
const session = verifySession(value, secret());
- if (!session?.device_id) continue;
+ if (!session?.device_id || session.cookie_scope !== cookieScope) continue;
const device = await getApprovedDevice(session.device_id);
if (!device) continue;
return { session, device, role: device.role };
diff --git a/lib/auth/session-cookie.test.ts b/lib/auth/session-cookie.test.ts
index 1814b8da..e7f14ba7 100644
--- a/lib/auth/session-cookie.test.ts
+++ b/lib/auth/session-cookie.test.ts
@@ -3,7 +3,7 @@
// waves through lands verbatim in a Set-Cookie header, and anything it wrongly
// rejects only falls back to today's host-only cookie (fail closed).
import { afterEach, describe, expect, it } from "vitest";
-import { hostOnlyClearHeader, sessionCookieAttrs, sessionCookieDomain } from "./session-cookie";
+import { configuredSessionCookieScope, hostOnlyClearHeader, sessionCookieAttrs, sessionCookieDomain } from "./session-cookie";
const req = (host: string, forwarded?: string) =>
new Request("http://internal/api/auth/login", {
@@ -21,6 +21,18 @@ afterEach(() => {
delete process.env.OS_SESSION_COOKIE_DOMAIN;
});
+
+describe("configuredSessionCookieScope", () => {
+ it("canonicalizes the policy that signed sessions are bound to", () => {
+ delete process.env.OS_SESSION_COOKIE_DOMAIN;
+ expect(configuredSessionCookieScope()).toBe("host");
+ process.env.OS_SESSION_COOKIE_DOMAIN = " .MSO.Example.com ";
+ expect(configuredSessionCookieScope()).toBe("domain:mso.example.com");
+ process.env.OS_SESSION_COOKIE_DOMAIN = "bad; Domain=evil.test";
+ expect(configuredSessionCookieScope()).toBe("host");
+ });
+});
+
describe("sessionCookieDomain", () => {
it("is host-only when unset or blank", () => {
expect(domainFor(undefined)).toBeUndefined();
diff --git a/lib/auth/session-cookie.ts b/lib/auth/session-cookie.ts
index 8e27fc6d..4991a4ec 100644
--- a/lib/auth/session-cookie.ts
+++ b/lib/auth/session-cookie.ts
@@ -60,17 +60,20 @@ function requestHostname(req: Request): string {
return raw.split(",")[0].trim().split(":")[0].replace(/\.$/, "").toLowerCase();
}
-/**
- * The validated Domain for this request, or undefined for host-only.
- * A Domain the request host does not domain-match would be dropped by the
- * browser, so that case degrades to host-only instead of shipping a dead cookie.
- */
-export function sessionCookieDomain(req: Request): string | undefined {
+/** Stable signature scope for every browser session minted under this config.
+ * Changing the cookie Domain invalidates existing signed sessions, including a
+ * broader Domain cookie the browser may retain until its original expiry. */
+export function configuredSessionCookieScope(): string {
const raw = process.env.OS_SESSION_COOKIE_DOMAIN?.trim().toLowerCase() ?? "";
- // A leading dot is legacy syntax and ignored by RFC 6265 §5.2.3; normalise
- // rather than reject, since operators still write it out of habit.
const domain = raw.startsWith(".") ? raw.slice(1) : raw;
- if (!isCookieDomain(domain)) return undefined;
+ return isCookieDomain(domain) ? `domain:${domain}` : "host";
+}
+
+/** The validated Domain for this request, or undefined for host-only. */
+export function sessionCookieDomain(req: Request): string | undefined {
+ const scope = configuredSessionCookieScope();
+ if (!scope.startsWith("domain:")) return undefined;
+ const domain = scope.slice("domain:".length);
const host = requestHostname(req);
return host && domainMatches(host, domain) ? domain : undefined;
}
diff --git a/lib/auth/session.test.ts b/lib/auth/session.test.ts
index 02f0cced..fc97ef51 100644
--- a/lib/auth/session.test.ts
+++ b/lib/auth/session.test.ts
@@ -6,7 +6,7 @@ const SECRET = "s".repeat(MIN_SECRET_LEN);
function freshPayload(overrides: Partial<SessionPayload> = {}): SessionPayload {
const now = Date.now();
- return { issued_at: now, expires_at: now + 60_000, device_id: "dev-1", ...overrides };
+ return { issued_at: now, expires_at: now + 60_000, device_id: "dev-1", cookie_scope: "host", ...overrides };
}
function b64url(input: string | Buffer): string {
@@ -47,6 +47,11 @@ describe("signSession / verifySession roundtrip", () => {
delete payload.device_id;
expect(verifySession(signSession(payload, SECRET), SECRET)).toEqual(payload);
});
+
+ it("rejects legacy signed payloads that have no cookie scope", () => {
+ const encoded = b64url(JSON.stringify({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1" }));
+ expect(verifySession(forgeToken(encoded, SECRET), SECRET)).toBeNull();
+ });
});
describe("verifySession rejects forgery", () => {
diff --git a/lib/auth/session.ts b/lib/auth/session.ts
index 231fd9c6..71ccef2e 100644
--- a/lib/auth/session.ts
+++ b/lib/auth/session.ts
@@ -36,6 +36,8 @@ export interface SessionPayload {
expires_at: number;
/** Approved device this session was issued to (traceability). */
device_id?: string;
+ /** Cookie policy active when this token was minted. Config changes revoke it. */
+ cookie_scope: string;
}
function base64urlEncode(input: string | Buffer): string {
@@ -64,7 +66,8 @@ function isSessionPayload(v: unknown): v is SessionPayload {
return (
typeof o.issued_at === "number" &&
typeof o.expires_at === "number" &&
- (o.device_id === undefined || typeof o.device_id === "string")
+ (o.device_id === undefined || typeof o.device_id === "string") &&
+ typeof o.cookie_scope === "string" && o.cookie_scope.length > 0 && o.cookie_scope.length <= 260
);
}
diff --git a/lib/host/screenshot.ts b/lib/host/screenshot.ts
index a2202989..b1586c82 100644
--- a/lib/host/screenshot.ts
+++ b/lib/host/screenshot.ts
@@ -4,6 +4,7 @@ import os from "os";
import path from "path";
import { listDevices } from "@/lib/auth/device-store";
import { signSession, MIN_SECRET_LEN } from "@/lib/auth/session";
+import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";
export type ScreenshotShell = "macos" | "windows" | "dashboard";
@@ -105,7 +106,7 @@ export async function captureMsoScreen(opts?: {
if (secret.length < MIN_SECRET_LEN) throw new Error("OS_SESSION_SECRET is not configured strongly enough");
const deviceId = await approvedDeviceId();
const now = Date.now();
- const session = signSession({ issued_at: now, expires_at: now + 5 * 60_000, device_id: deviceId }, secret);
+ const session = signSession({ issued_at: now, expires_at: now + 5 * 60_000, device_id: deviceId, cookie_scope: configuredSessionCookieScope() }, secret);
const origin = internalOrigin();
const profile = await fs.mkdtemp(path.join(os.tmpdir(), "mso-shot-"));
let chrome: ChildProcess | undefined;
diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.ts
index 2edc4f09..1f4e7738 100644
--- a/proxy-websocket.test.ts
+++ b/proxy-websocket.test.ts
@@ -41,9 +41,9 @@ describe("WebSocket upgrade on an app host", () => {
const GATEWAY = "http://127.0.0.1:18789";
/** A real signed cookie — the branch verifies the HMAC, so a placeholder won't do. */
- function session(): string {
+ function session(cookieScope = "host"): string {
const now = Date.now();
- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1" }, SECRET);
+ return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: cookieScope }, SECRET);
}
function upgradeReq(host: string, path = "/", cookie?: string) {
@@ -75,6 +75,9 @@ describe("WebSocket upgrade on an app host", () => {
expect(rewriteOf(await proxy(upgradeReq("openclaw.mso.example.com", "/chat", session())))).toBe(`${GATEWAY}/chat`);
});
+ it("rejects a still-valid HMAC minted under a previous cookie scope", async () =>
+ expect((await (await load())(upgradeReq("openclaw.mso.example.com", "/chat", session("domain:mso.example.com")))).status).toBe(404));
+
it("refuses an upgrade carrying no session — nothing downstream would have", async () => {
const proxy = await load();
const res = await proxy(upgradeReq("openclaw.mso.example.com"));
@@ -123,7 +126,7 @@ describe("per-app upgrade adapters", () => {
function signed(): string {
const now = Date.now();
- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1" }, SECRET);
+ return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: "host" }, SECRET);
}
async function upstream(host: string, path: string, extra: Record<string, string> = {}) {
@@ -188,7 +191,7 @@ describe("the Camoufox split-origin VNC bridge", () => {
function session(secret = SECRET): string {
const now = Date.now();
- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1" }, secret);
+ return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: "host" }, secret);
}
async function load(novnc = NOVNC) {
diff --git a/proxy.ts b/proxy.ts
index 955044df..afa55f0a 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -29,6 +29,7 @@ import {
import { getManagedAppDefinition } from "@/lib/managed-apps/catalog";
import { projectIngressDecision } from "@/lib/managed-apps/project-ingress";
import { verifySession } from "@/lib/auth/session";
+import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";
import { getApprovedDevice } from "@/lib/auth/device-store";
import { roleAtLeast, type DeviceRole } from "@/lib/auth/roles";
import { IS_DEMO } from "@/lib/demo";
@@ -68,9 +69,10 @@ async function hasApprovedSession(
): Promise<boolean> {
if (IS_DEMO) return false;
const secret = process.env.OS_SESSION_SECRET ?? "";
+ const cookieScope = configuredSessionCookieScope();
for (const { value } of request.cookies.getAll(SESSION_COOKIE)) {
const payload = verifySession(value, secret);
- if (!payload?.device_id) continue;
+ if (!payload?.device_id || payload.cookie_scope !== cookieScope) continue;
const device = await getApprovedDevice(payload.device_id);
if (device && roleAtLeast(device.role, minimumRole)) return true;
}