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): permanently revoke retired cookie sessions

Rahman362007a524c4
diff --git a/.env.example b/.env.example
index d66b5072..74c789e3 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. 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.
+# session. Signed browser sessions are bound to a durable cookie-policy generation
+# in the private auth store. Every actual scope transition rotates that generation,
+# including returning to an earlier Domain, so older retained/captured tokens never
+# become valid again. 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 b796429a..8b85bc6f 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, cookie_scope: "host" },
+ session: { device_id: "test-device", issued_at: 1, expires_at: 2, cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" },
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 dac857a7..881d6bee 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, cookie_scope: "host" },
+ session: { device_id: CURRENT, issued_at: 1, expires_at: 2, cookie_scope: "host", cookie_epoch: "epoch-0000000000000000" },
device: { label: "current", approvedAt: 1, role: session.current },
role: session.current,
}) : null),
diff --git a/app/api/auth/login/route.test.ts b/app/api/auth/login/route.test.ts
index e7a3e3db..9a21ddf2 100644
--- a/app/api/auth/login/route.test.ts
+++ b/app/api/auth/login/route.test.ts
@@ -85,6 +85,7 @@ describe("rate limiting cannot be turned into a lockout of everyone else", () =>
vi.stubEnv("NEXT_PUBLIC_OS_DEMO", "0");
vi.doMock("@/lib/auth/device-store", async (orig) => ({
...(await orig<Record<string, unknown>>()),
+ currentSessionPolicy: async (scope: string) => ({ scope, epoch: "epoch-0000000000000000", changedAt: 1 }),
isApproved: async () => false,
recordPending: async () => {},
touchApproved: async () => {},
diff --git a/app/api/auth/login/route.ts b/app/api/auth/login/route.ts
index b6aa33e8..9a6af801 100644
--- a/app/api/auth/login/route.ts
+++ b/app/api/auth/login/route.ts
@@ -2,7 +2,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 { configuredSessionCookieScope, sessionCookieAttrs } from "@/lib/auth/session-cookie";
-import { isApproved, isValidDeviceId, recordPending, touchApproved } from "@/lib/auth/device-store";
+import { currentSessionPolicy, isApproved, isValidDeviceId, recordPending, touchApproved } from "@/lib/auth/device-store";
import { audit } from "@/lib/host/audit-api";
import { IS_DEMO } from "@/lib/demo";
@@ -159,11 +159,13 @@ export async function POST(req: NextRequest) {
const parsedHours = parseInt(process.env.SESSION_EXPIRY_HOURS ?? "24", 10);
const hours = Number.isFinite(parsedHours) && parsedHours > 0 ? parsedHours : 24;
const now = Date.now();
+ const policy = await currentSessionPolicy(configuredSessionCookieScope());
const payload: SessionPayload = {
issued_at: now,
expires_at: now + hours * 3600 * 1000,
device_id: deviceId,
- cookie_scope: configuredSessionCookieScope(),
+ cookie_scope: policy.scope,
+ cookie_epoch: policy.epoch,
};
const res = NextResponse.json({ success: true });
// Attributes (incl. the optional Domain for the split-origin app hosts) come
diff --git a/app/api/auth/session-cookie.test.ts b/app/api/auth/session-cookie.test.ts
index fa19a30d..102d4e45 100644
--- a/app/api/auth/session-cookie.test.ts
+++ b/app/api/auth/session-cookie.test.ts
@@ -8,6 +8,7 @@ import { MIN_SECRET_LEN } from "@/lib/auth/session";
vi.mock("@/lib/host/audit-api", () => ({ audit: vi.fn() }));
vi.mock("@/lib/auth/device-store", () => ({
+ currentSessionPolicy: async (scope: string) => ({ scope, epoch: "epoch-0000000000000000", changedAt: 1 }),
isValidDeviceId: (id: unknown) => typeof id === "string" && /^[a-f0-9-]{16,128}$/i.test(id),
isApproved: async () => true,
recordPending: async () => {},
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index c2125d62..03863fd6 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` permanently revoke retired cookie sessions
- `workflows` preserve explicit empty sandbox
- `auth` bind sessions to cookie scope
- `workflows` remount editors when sandbox policy changes
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 4c713d6b..bc85ed76 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,7 @@
+## 2026-09-18 — Permanently revoke prior cookie-policy generations
+
+A follow-up security review found that a deterministic scope label could revive an old signed session if configuration later returned to the same cookie Domain. The private auth-device store now keeps one durable cookie-policy epoch and rotates it on every actual scope transition, including A to host-only to A. Signed browser sessions carry both scope and epoch; route and middleware/WebSocket authorization require both. Existing approved devices and roles are preserved, but pre-epoch sessions require a one-time sign-in. Workflow edits also preserve an existing reviewed MCP Page auth path with query parameters without allowing the Workflow endpoint to create or change that Page-owned metadata.
+
## 2026-09-18 — Preserve the strictest reviewed external-editor sandbox
PR review found that an explicit empty iframe sandbox was normalized as if the owner had
diff --git a/docs/WORKFLOW-GRAPH.md b/docs/WORKFLOW-GRAPH.md
index b364f34c..b5c644c6 100644
--- a/docs/WORKFLOW-GRAPH.md
+++ b/docs/WORKFLOW-GRAPH.md
@@ -231,8 +231,8 @@ Different origins do not by themselves isolate cookies. Reviewed external editor
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/
+are also bound to a durable cookie-policy generation. Widening, narrowing or unsetting the
+Domain rotates that generation in the private auth store; returning later to an earlier Domain
+rotates it again, so retained/captured tokens from that older generation never revive. 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/device-store.test.ts b/lib/auth/device-store.test.ts
index fd53211c..5c7f87b4 100644
--- a/lib/auth/device-store.test.ts
+++ b/lib/auth/device-store.test.ts
@@ -97,6 +97,19 @@ describe("device-store — an unreadable file must never look like an empty one"
await expect(isApproved(DEV)).resolves.toBe(false);
});
+ it("rotates a durable session epoch on every cookie-scope transition, including A to host to A", async () => {
+ const { currentSessionPolicy, listDevices } = await load();
+ const first = await currentSessionPolicy("domain:example.com");
+ const same = await currentSessionPolicy("domain:example.com");
+ const host = await currentSessionPolicy("host");
+ const returned = await currentSessionPolicy("domain:example.com");
+ expect(same.epoch).toBe(first.epoch);
+ expect(host.epoch).not.toBe(first.epoch);
+ expect(returned.epoch).not.toBe(first.epoch);
+ expect(returned.epoch).not.toBe(host.epoch);
+ expect((await listDevices()).sessionPolicy).toEqual(returned);
+ });
+
it("writes the store 0600 inside a 0700 dir", async () => {
const { approveDevice } = await load();
await approveDevice(DEV, "my laptop");
diff --git a/lib/auth/device-store.ts b/lib/auth/device-store.ts
index 6efe08f5..95e34118 100644
--- a/lib/auth/device-store.ts
+++ b/lib/auth/device-store.ts
@@ -1,4 +1,5 @@
import { expandOwnerStorePath } from "@/lib/owner-store-path.js";
+import { randomUUID } from "node:crypto";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
@@ -31,9 +32,16 @@ export interface PendingDevice {
attempts: number;
}
+export interface SessionPolicy {
+ scope: string;
+ epoch: string;
+ changedAt: number;
+}
+
export interface DeviceStore {
approved: Record<string, ApprovedDevice>;
pending: Record<string, PendingDevice>;
+ sessionPolicy?: SessionPolicy;
}
const MAX_PENDING = 50;
@@ -45,6 +53,7 @@ const STORE_PATH =
// Device ids are client-generated 128-bit+ hex/uuid.
const DEVICE_ID_RE = /^[a-f0-9-]{16,128}$/i;
+const COOKIE_SCOPE_RE = /^(?:host|domain:[a-z0-9.-]{1,253})$/;
export function isValidDeviceId(id: unknown): id is string {
return typeof id === "string" && DEVICE_ID_RE.test(id);
@@ -89,6 +98,15 @@ function normalizePending(raw: unknown): Record<string, PendingDevice> {
return out;
}
+function normalizeSessionPolicy(raw: unknown): SessionPolicy | undefined {
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
+ const row = raw as Record<string, unknown>;
+ if (typeof row.scope !== "string" || !COOKIE_SCOPE_RE.test(row.scope)) return undefined;
+ if (typeof row.epoch !== "string" || row.epoch.length < 16 || row.epoch.length > 128) return undefined;
+ if (typeof row.changedAt !== "number" || !Number.isFinite(row.changedAt) || row.changedAt < 0) return undefined;
+ return { scope: row.scope, epoch: row.epoch, changedAt: row.changedAt };
+}
+
// "No file yet" is the ONLY failure that may look like an empty store. Anything else
// — corrupt JSON, EACCES, EIO — must throw. A normalized read also migrates legacy
// role-less entries in memory; the next legitimate mutation persists the role field.
@@ -101,9 +119,11 @@ async function read(): Promise<DeviceStore> {
throw e;
}
const parsed = JSON.parse(raw) as Record<string, unknown>;
+ const sessionPolicy = normalizeSessionPolicy(parsed.sessionPolicy);
return {
approved: normalizeApproved(parsed.approved),
pending: normalizePending(parsed.pending),
+ ...(sessionPolicy ? { sessionPolicy } : {}),
};
}
@@ -114,9 +134,8 @@ async function write(store: DeviceStore): Promise<void> {
await fs.rename(tmp, STORE_PATH);
}
-// Approval/revocation is a security decision, so serialize the entire read-modify-
-// write transaction. A plain atomic rename is not enough: two requests can read the
-// same approved set and a later `touchApproved` can otherwise overwrite a revoke.
+// Approval/revocation and session-policy rotation are security decisions, so serialize
+// the entire read-modify-write transaction. A plain atomic rename is not enough.
let mutationChain: Promise<unknown> = Promise.resolve();
function mutate<T>(fn: () => Promise<T>): Promise<T> {
const locked = () => withSecurityStoreLock(STORE_PATH, fn);
@@ -129,6 +148,23 @@ function ownerCount(store: DeviceStore): number {
return Object.values(store.approved).filter((entry) => entry.role === "owner").length;
}
+/**
+ * Return the durable generation for the current cookie scope. Every actual scope
+ * transition rotates the epoch, so A → host → A can never revive a token minted
+ * during the earlier A generation even if the browser retained that cookie.
+ */
+export function currentSessionPolicy(scope: string): Promise<SessionPolicy> {
+ if (!COOKIE_SCOPE_RE.test(scope)) return Promise.reject(new Error("invalid_session_cookie_scope"));
+ return mutate(async () => {
+ const store = await read();
+ if (store.sessionPolicy?.scope === scope) return store.sessionPolicy;
+ const sessionPolicy = { scope, epoch: randomUUID(), changedAt: Date.now() };
+ store.sessionPolicy = sessionPolicy;
+ await write(store);
+ return sessionPolicy;
+ });
+}
+
export async function getApprovedDevice(deviceId: string): Promise<ApprovedDevice | null> {
const store = await read();
return store.approved[deviceId] ?? null;
diff --git a/lib/auth/require-session.test.ts b/lib/auth/require-session.test.ts
index 1ef7001b..48792af5 100644
--- a/lib/auth/require-session.test.ts
+++ b/lib/auth/require-session.test.ts
@@ -8,6 +8,8 @@ import { MIN_SECRET_LEN, signSession } from "./session";
// still in the jar, unfixable from the UI.
const SECRET = "s".repeat(MIN_SECRET_LEN);
const jar: { name: string; value: string }[] = [];
+const policy = vi.hoisted(() => ({ scope: "host", generation: 0 }));
+const epoch = () => `epoch-${String(policy.generation).padStart(16, "0")}`;
vi.mock("next/headers", () => ({
cookies: async () => ({
@@ -15,15 +17,20 @@ vi.mock("next/headers", () => ({
}),
}));
vi.mock("./device-store", () => ({
+ currentSessionPolicy: async (scope: string) => {
+ if (policy.scope !== scope) { policy.scope = scope; policy.generation += 1; }
+ return { scope, epoch: epoch(), changedAt: policy.generation };
+ },
getApprovedDevice: async (id: string) => id === "dev-1"
? { label: "device", approvedAt: 1, role: "operator" }
: null,
}));
-const valid = () => signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1", cookie_scope: "host" }, SECRET);
+const valid = () => signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1", cookie_scope: "host", cookie_epoch: epoch() }, SECRET);
beforeEach(() => {
jar.length = 0;
+ policy.scope = "host"; policy.generation = 0;
process.env.OS_SESSION_SECRET = SECRET;
delete process.env.OS_SESSION_COOKIE_DOMAIN;
});
@@ -45,18 +52,28 @@ 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", cookie_scope: "host" }, SECRET),
+ value: signSession({ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "revoked", cookie_scope: "host", cookie_epoch: epoch() }, SECRET),
});
expect(await getSession()).toBeNull();
});
- it("rejects a still-signed cookie after its configured cookie scope changes", async () => {
+ it("never revives a retained token when cookie scope changes away and later returns", 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) });
+ process.env.OS_SESSION_COOKIE_DOMAIN = "example.com";
+ policy.scope = "domain:example.com"; policy.generation = 1;
+ const retained = signSession({
+ issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1",
+ cookie_scope: "domain:example.com", cookie_epoch: epoch(),
+ }, SECRET);
+ jar.push({ name: "session", value: retained });
+ expect(await getSession()).toMatchObject({ device_id: "dev-1" });
+
+ delete process.env.OS_SESSION_COOKIE_DOMAIN;
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" });
+ expect(await getSession()).toBeNull();
+ expect(policy.generation).toBe(3);
});
it("rechecks the live device role for every authorization decision", async () => {
const { getSessionContext, requireSession } = await import("./require-session");
diff --git a/lib/auth/require-session.ts b/lib/auth/require-session.ts
index 83ffff7c..34f97d6f 100644
--- a/lib/auth/require-session.ts
+++ b/lib/auth/require-session.ts
@@ -1,7 +1,7 @@
import { cookies } from "next/headers";
import { configuredSessionCookieScope } from "./session-cookie";
import { verifySession, type SessionPayload } from "./session";
-import { getApprovedDevice, type ApprovedDevice } from "./device-store";
+import { currentSessionPolicy, getApprovedDevice, type ApprovedDevice } from "./device-store";
import { roleAtLeast, type DeviceRole } from "./roles";
import { IS_DEMO } from "@/lib/demo";
@@ -23,10 +23,10 @@ export type SessionContext = {
export async function getSessionContext(): Promise<SessionContext | null> {
if (IS_DEMO) return null;
const jar = await cookies();
- const cookieScope = configuredSessionCookieScope();
+ const policy = await currentSessionPolicy(configuredSessionCookieScope());
for (const { value } of jar.getAll(SESSION_COOKIE)) {
const session = verifySession(value, secret());
- if (!session?.device_id || session.cookie_scope !== cookieScope) continue;
+ if (!session?.device_id || session.cookie_scope !== policy.scope || session.cookie_epoch !== policy.epoch) continue;
const device = await getApprovedDevice(session.device_id);
if (!device) continue;
return { session, device, role: device.role };
diff --git a/lib/auth/session.test.ts b/lib/auth/session.test.ts
index fc97ef51..68454680 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", cookie_scope: "host", ...overrides };
+ return { issued_at: now, expires_at: now + 60_000, device_id: "dev-1", cookie_scope: "host", cookie_epoch: "epoch-0000000000000000", ...overrides };
}
function b64url(input: string | Buffer): string {
@@ -48,9 +48,10 @@ describe("signSession / verifySession roundtrip", () => {
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();
+ it("rejects legacy signed payloads that have no cookie scope or durable epoch", () => {
+ const base = { issued_at: Date.now(), expires_at: Date.now() + 60_000, device_id: "dev-1" };
+ expect(verifySession(forgeToken(b64url(JSON.stringify(base)), SECRET), SECRET)).toBeNull();
+ expect(verifySession(forgeToken(b64url(JSON.stringify({ ...base, cookie_scope: "host" })), SECRET), SECRET)).toBeNull();
});
});
diff --git a/lib/auth/session.ts b/lib/auth/session.ts
index 71ccef2e..50eea766 100644
--- a/lib/auth/session.ts
+++ b/lib/auth/session.ts
@@ -36,8 +36,10 @@ 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 policy active when this token was minted. */
cookie_scope: string;
+ /** Durable generation for that policy. Scope changes rotate it permanently. */
+ cookie_epoch: string;
}
function base64urlEncode(input: string | Buffer): string {
@@ -67,7 +69,8 @@ function isSessionPayload(v: unknown): v is SessionPayload {
typeof o.issued_at === "number" &&
typeof o.expires_at === "number" &&
(o.device_id === undefined || typeof o.device_id === "string") &&
- typeof o.cookie_scope === "string" && o.cookie_scope.length > 0 && o.cookie_scope.length <= 260
+ typeof o.cookie_scope === "string" && o.cookie_scope.length > 0 && o.cookie_scope.length <= 260 &&
+ typeof o.cookie_epoch === "string" && o.cookie_epoch.length >= 16 && o.cookie_epoch.length <= 128
);
}
diff --git a/lib/host/screenshot.ts b/lib/host/screenshot.ts
index b1586c82..e89ccfa8 100644
--- a/lib/host/screenshot.ts
+++ b/lib/host/screenshot.ts
@@ -2,7 +2,7 @@ import { spawn, type ChildProcess } from "child_process";
import { promises as fs } from "fs";
import os from "os";
import path from "path";
-import { listDevices } from "@/lib/auth/device-store";
+import { currentSessionPolicy, listDevices } from "@/lib/auth/device-store";
import { signSession, MIN_SECRET_LEN } from "@/lib/auth/session";
import { configuredSessionCookieScope } from "@/lib/auth/session-cookie";
@@ -106,7 +106,8 @@ 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, cookie_scope: configuredSessionCookieScope() }, secret);
+ const policy = await currentSessionPolicy(configuredSessionCookieScope());
+ const session = signSession({ issued_at: now, expires_at: now + 5 * 60_000, device_id: deviceId, cookie_scope: policy.scope, cookie_epoch: policy.epoch }, secret);
const origin = internalOrigin();
const profile = await fs.mkdtemp(path.join(os.tmpdir(), "mso-shot-"));
let chrome: ChildProcess | undefined;
diff --git a/lib/surfaces/manage.test.ts b/lib/surfaces/manage.test.ts
index be81ce47..fdf62fb0 100644
--- a/lib/surfaces/manage.test.ts
+++ b/lib/surfaces/manage.test.ts
@@ -28,6 +28,18 @@ describe("owner-reviewed workflow surface configuration", () => {
await save({ ...app, title: "Updated again" });
expect((await surfaceRegistrySnapshot()).apps[0].placements).toEqual(["workflows", "mcp-page"]);
});
+ it("preserves Page auth metadata with a validated query during workflow updates", async () => {
+ const pageAuth = "/?auth=google";
+ await fs.writeFile(file, JSON.stringify([{ ...app, externalAuthPath: pageAuth, placements: ["workflows", "mcp-page"] }]));
+ await save({ ...app, externalAuthPath: pageAuth, title: "Workflow title" });
+ let saved = (await surfaceRegistrySnapshot()).apps[0];
+ expect(saved.externalAuthPath).toBe(pageAuth);
+ expect(saved.placements).toEqual(["workflows", "mcp-page"]);
+ await save({ ...app, title: "Workflow title again" });
+ saved = (await surfaceRegistrySnapshot()).apps[0];
+ expect(saved.externalAuthPath).toBe(pageAuth);
+ await expect(save({ ...app, externalAuthPath: "/?auth=other" })).rejects.toThrow("workflow_login_path_must_not_contain_query");
+ });
it("never adds Page approval to new or workflow-only entries", async () => {
await save();
expect((await surfaceRegistrySnapshot()).apps[0].placements).toEqual(["workflows"]);
diff --git a/lib/surfaces/manage.ts b/lib/surfaces/manage.ts
index f236b9e2..aed07426 100644
--- a/lib/surfaces/manage.ts
+++ b/lib/surfaces/manage.ts
@@ -37,7 +37,6 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {
const normalized = await configuredSurfaceApps(JSON.stringify([{ ...row, placements: ["workflows"] }]));
if (normalized.length !== 1) throw new SurfaceConfigError("invalid_surface_metadata");
const selected = normalized[0];
- if (selected.externalAuthPath?.includes("?")) throw new SurfaceConfigError("workflow_login_path_must_not_contain_query");
return withSecurityStoreLock(surfaceRegistryPath(), async () => {
const current = await readRegistry();
if (current.managedByEnvironment) throw new SurfaceConfigError("surface_registry_managed_by_environment", 409);
@@ -49,11 +48,19 @@ export async function saveWorkflowSurface(input: Record<string, unknown>) {
if (matches.length > 1) throw new SurfaceConfigError("duplicate_surface_identity", 409);
const replacement = { ...selected };
// Missing placements is legacy Page approval; this workflow-only operation
- // may preserve that grant but cannot create a new Page approval.
+ // may preserve that grant but cannot create or mutate Page-only auth metadata.
const existing = matches[0];
- if (existing && (existing.placements === undefined ||
- (Array.isArray(existing.placements) && existing.placements.includes("mcp-page")))) {
+ const sharesPage = Boolean(existing && (existing.placements === undefined ||
+ (Array.isArray(existing.placements) && existing.placements.includes("mcp-page"))));
+ const existingNormalized = existing ? (await configuredSurfaceApps(JSON.stringify([existing])))[0] : undefined;
+ if (selected.externalAuthPath?.includes("?") && (!sharesPage ||
+ selected.externalAuthPath !== existingNormalized?.externalAuthPath)) {
+ throw new SurfaceConfigError("workflow_login_path_must_not_contain_query");
+ }
+ if (sharesPage) {
replacement.placements = ["workflows", "mcp-page"];
+ if (existingNormalized?.externalAuthPath !== undefined) replacement.externalAuthPath = existingNormalized.externalAuthPath;
+ else delete replacement.externalAuthPath;
}
const next = matches.length ? entries.map((entry) => entry.id === selected.id ? replacement : entry) : [...entries, replacement];
const raw = JSON.stringify(next, null, 2) + "\n";
diff --git a/proxy-websocket.test.ts b/proxy-websocket.test.ts
index 1f4e7738..48f4857f 100644
--- a/proxy-websocket.test.ts
+++ b/proxy-websocket.test.ts
@@ -8,12 +8,11 @@ import { signSession } from "./lib/auth/session";
const approved = vi.hoisted(() => ({ value: true, role: "owner" as "viewer" | "operator" | "owner" }));
vi.mock("@/lib/auth/device-store", () => ({
+ currentSessionPolicy: async (scope: string) => ({ scope, epoch: "epoch-0000000000000000", changedAt: 1 }),
getApprovedDevice: async () => approved.value
? { label: "test device", approvedAt: 1, role: approved.role }
: null,
-}));
-
-const TEMPLATE = "{id}.mso.example.com";
+})); const TEMPLATE = "{id}.mso.example.com";
/** Env is read at module load, so each case needs a fresh module graph. */
async function loadProxy(template: string) {
@@ -43,7 +42,7 @@ describe("WebSocket upgrade on an app host", () => {
/** A real signed cookie — the branch verifies the HMAC, so a placeholder won't do. */
function session(cookieScope = "host"): string {
const now = Date.now();
- return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: cookieScope }, SECRET);
+ return signSession({ issued_at: now, expires_at: now + 3_600_000, device_id: "dev-1", cookie_scope: cookieScope, cookie_epoch: "epoch-0000000000000000" }, SECRET);
}
function upgradeReq(host: string, path = "/", cookie?: string) {
@@ -126,7 +125,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", cookie_scope: "host" }, SECRET);
+ 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 upstream(host: string, path: string, extra: Record<string, string> = {}) {
@@ -191,7 +190,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", cookie_scope: "host" }, secret);
+ 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) {
diff --git a/proxy.ts b/proxy.ts
index afa55f0a..aad8cd10 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -30,7 +30,7 @@ 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 { currentSessionPolicy, getApprovedDevice } from "@/lib/auth/device-store";
import { roleAtLeast, type DeviceRole } from "@/lib/auth/roles";
import { IS_DEMO } from "@/lib/demo";
import { camoufoxViewerCsp, isCamoufoxViewerHost } from "@/lib/camoufox/origin";
@@ -69,10 +69,10 @@ async function hasApprovedSession(
): Promise<boolean> {
if (IS_DEMO) return false;
const secret = process.env.OS_SESSION_SECRET ?? "";
- const cookieScope = configuredSessionCookieScope();
+ const policy = await currentSessionPolicy(configuredSessionCookieScope());
for (const { value } of request.cookies.getAll(SESSION_COOKIE)) {
const payload = verifySession(value, secret);
- if (!payload?.device_id || payload.cookie_scope !== cookieScope) continue;
+ if (!payload?.device_id || payload.cookie_scope !== policy.scope || payload.cookie_epoch !== policy.epoch) continue;
const device = await getApprovedDevice(payload.device_id);
if (device && roleAtLeast(device.role, minimumRole)) return true;
}
diff --git a/scripts/e2e/release-fixture.mjs b/scripts/e2e/release-fixture.mjs
index 29170b83..5ab73f07 100644
--- a/scripts/e2e/release-fixture.mjs
+++ b/scripts/e2e/release-fixture.mjs
@@ -17,9 +17,16 @@ export async function releaseFixture({ live = false, surfaceApps = [] } = {}) {
const providerUrl = `http://127.0.0.1:${provider.address().port}`;
const device = randomBytes(16).toString("hex"), password = randomBytes(24).toString("hex");
const deviceFile = path.join(dir, "devices.json");
- const setRole = role => writeFile(deviceFile, JSON.stringify({
- approved: { [device]: { label: "Release fixture", role, approvedAt: Date.now() } }, pending: {},
- }), { mode: 0o600 });
+ const setRole = async role => {
+ let current = {};
+ try { current = JSON.parse(await readFile(deviceFile, "utf8")); }
+ catch (error) { if (error?.code !== "ENOENT") throw error; }
+ await writeFile(deviceFile, JSON.stringify({
+ ...current,
+ approved: { [device]: { label: "Release fixture", role, approvedAt: current.approved?.[device]?.approvedAt ?? Date.now() } },
+ pending: current.pending ?? {},
+ }), { mode: 0o600 });
+ };
await setRole("owner");
if (live) await writeFile(path.join(dir, "prefs.json"), JSON.stringify({ tweaks: { server: { mode: "live", activeTargetId: "vps", url: "" } } }), { mode: 0o600 });
await writeFile(path.join(dir, "fixture.txt"), "MSO release fixture");
diff --git a/scripts/proxy-session-policy.test.ts b/scripts/proxy-session-policy.test.ts
new file mode 100644
index 00000000..ad7a08a1
--- /dev/null
+++ b/scripts/proxy-session-policy.test.ts
@@ -0,0 +1,37 @@
+import { describe, expect, it, vi } from "vitest";
+import { NextRequest } from "next/server";
+import { signSession } from "../lib/auth/session";
+
+const SECRET = "e".repeat(48);
+const EPOCH = "epoch-0000000000000000";
+vi.mock("@/lib/auth/device-store", () => ({
+ currentSessionPolicy: async (scope: string) => ({ scope, epoch: EPOCH, changedAt: 1 }),
+ getApprovedDevice: async () => ({ label: "owner", approvedAt: 1, role: "owner" }),
+}));
+
+async function loadProxy() {
+ vi.resetModules();
+ vi.stubEnv("OS_SESSION_SECRET", SECRET);
+ vi.stubEnv("NEXT_PUBLIC_MANAGED_APP_HOST_TEMPLATE", "{id}.mso.example.com");
+ vi.stubEnv("OPENCLAW_DASHBOARD_URL", "http://127.0.0.1:18789");
+ return (await import("../proxy")).proxy;
+}
+
+function upgrade(cookieEpoch: string) {
+ const now = Date.now();
+ const token = signSession({
+ issued_at: now, expires_at: now + 60_000, device_id: "dev-1",
+ cookie_scope: "host", cookie_epoch: cookieEpoch,
+ }, SECRET);
+ return new NextRequest("https://openclaw.mso.example.com/chat", {
+ headers: { host: "openclaw.mso.example.com", upgrade: "websocket", connection: "Upgrade", cookie: `session=${token}` },
+ });
+}
+
+describe("proxy session policy epoch", () => {
+ it("rejects a retained token from an older generation of the same scope", async () => {
+ const proxy = await loadProxy();
+ expect((await proxy(upgrade("epoch-9999999999999999"))).status).toBe(404);
+ expect((await proxy(upgrade(EPOCH))).headers.get("x-middleware-rewrite")).toBe("http://127.0.0.1:18789/chat");
+ });
+});