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): harden browser session persistence

Rahman7d94b7fad681
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 01e01bbe..d0029240 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**
+- `auth` harden browser session persistence
- `integrations` synchronize owner-local SC credential snapshots
- `security` eliminate parser gaps and enforce strict SAST coverage
- `gateway` wait for launcher handoff before tracking tunnel identity
diff --git a/docs/DRAWER-MENU-BYOK-PLAN.md b/docs/DRAWER-MENU-BYOK-PLAN.md
index 7eaa608e..7dc3b74a 100644
--- a/docs/DRAWER-MENU-BYOK-PLAN.md
+++ b/docs/DRAWER-MENU-BYOK-PLAN.md
@@ -91,7 +91,7 @@ Codex device-code, not the platform API) — say the word to pull it forward.
- **C3** `ai-section.tsx` — add "Add provider" (custom form), a provider **list + delete**, and a health badge
after save/test. Optionally expose the full ~36 registry providers. *(~60 lines)*
-### Phase D — OAuth `[OpenAI Codex shipped; others scaffolded]`
+### Phase D — OAuth `[historical/deferred: OpenAI Codex shipped; D2–D4 are not active backlog]`
Framework: `OsConfig.oauthTokens` (0600 host file) + in-memory handshake (`lib/ai/oauth/flow-state.ts`) +
`app/api/oauth/[provider]/route.ts` (start/poll). OAuth providers appear in the connected-list (kind
`oauth`), selectable + deletable; the assistant route bypasses `resolveModel` for them and refreshes before each call.
@@ -102,9 +102,9 @@ Framework: `OsConfig.oauthTokens` (0600 host file) + in-memory handshake (`lib/a
**Current correction:** the consumer endpoint remains more fragile than the public Platform API,
but current `app/api/assistant/route.ts` can pass Alfa tools through the Codex adapter; the old
"chat-only" caveat is no longer true. OAuth material remains private host state (0600).
-- **D2 Claude** (PKCE paste) — TODO. `/v1/messages` with Bearer (not x-api-key) + mandatory betas + a "You are Claude Code" system block.
-- **D3 Copilot** (device-code) — TODO. gh→copilot token exchange + 5 editor headers; ToS caveat.
-- **D4 OpenRouter** (PKCE redirect) — TODO, low value (yields a normal `sk-or-` key you can already paste); needs a public callback URL.
+- **D2 Claude** (PKCE paste) — **DEFERRED HISTORICAL IDEA (not an active TODO).** `/v1/messages` with Bearer (not x-api-key) + mandatory betas + a "You are Claude Code" system block.
+- **D3 Copilot** (device-code) — **DEFERRED HISTORICAL IDEA (not an active TODO).** gh→copilot token exchange + 5 editor headers; ToS caveat.
+- **D4 OpenRouter** (PKCE redirect) — **DEFERRED HISTORICAL IDEA (not an active TODO),** low value (yields a normal `sk-or-` key you can already paste); needs a public callback URL.
## 4. Verification
- Playwright (mock shells): iOS in-app "•••" → drawer lists Files actions + runs one; desktop menu bar shows
diff --git a/docs/PROGRESS.md b/docs/PROGRESS.md
index 30ff113d..9f2db43f 100644
--- a/docs/PROGRESS.md
+++ b/docs/PROGRESS.md
@@ -1,3 +1,25 @@
+## 2026-09-09 — Session persistence and auth-sensitive cache resilience
+
+A same-day repeated-login report was reproduced as a client-state resilience problem rather than
+a rotating signing secret. The production `.env.local` still holds the same 64-character
+`OS_SESSION_SECRET` across service rebuilds, while the service restarted repeatedly during active
+development. The browser session probe previously converted **any** `/api/auth/me` failure —
+including a restart-race 502, network error or malformed temporary response — into `status=out`.
+That made a still-valid signed cookie look logged out/mock until a later probe, encouraging an
+unnecessary password login. The client now changes to signed-out only after an authoritative
+successful `authenticated:false` response; indeterminate failures preserve the last verified
+snapshot. It reconciles immediately after SSR and again on focus, visibility, BFCache `pageshow`
+and reconnect, without reintroducing a loading wall. Explicit logout is unchanged.
+
+Cockpit HTML/RSC navigations now carry an explicit private `no-store`, zero-age, must-revalidate
+policy plus no-cache compatibility headers and `Vary: Cookie`. The policy is request-shaped so it
+does not overwrite immutable/cacheable static assets or API-specific response headers; the service
+worker continues to cache only its explicit icon/manifest allowlist. `SESSION_EXPIRY_HOURS` remains
+intentionally bounded at 24 hours by default because an MSO session grants live host control; this
+change fixes false logout/cache drift rather than creating an indefinitely renewable login. Focused
+probe/provider and proxy regression tests cover transient failure preservation, explicit logout
+resolution, immediate reconciliation wiring, document/RSC no-store and static-asset exclusion.
+
## 2026-09-09 — Explicit SC credential synchronization
User reports existing SC credentials absent from MSO Integrations. The prior transfer discovery
diff --git a/docs/SHELL-FIDELITY-PLAN.md b/docs/SHELL-FIDELITY-PLAN.md
index ba3212d2..62e0f43a 100644
--- a/docs/SHELL-FIDELITY-PLAN.md
+++ b/docs/SHELL-FIDELITY-PLAN.md
@@ -1,6 +1,6 @@
# Shell Fidelity Plan — five lightweight, convincing OS clones
-> **Historical design plan / backlog baseline.** The inventory below was written from the
+> **ARCHIVED — historical design plan / backlog baseline.** The inventory below was written from the
> 2026-06-11 shell state and intentionally preserves its original gaps/budgets. Several
> phases subsequently shipped and the AppShell structure changed. Current shell contracts
> live in [`ARCHITECTURE.md`](./ARCHITECTURE.md), the per-shell design files under
diff --git a/docs/TESTING-HANDOFF.md b/docs/TESTING-HANDOFF.md
index 082cd2c5..533a4f47 100644
--- a/docs/TESTING-HANDOFF.md
+++ b/docs/TESTING-HANDOFF.md
@@ -35,7 +35,7 @@ Current verified behavior:
- the terminal separates `Assistant`, `Agent work`, `Local agent`, `Error`, and `Input · @name` with full-width dividers; the composer identity is `@name ›` and permission lives in the bottom footer as `mode ask|auto|yolo`;
- recoverable HTTP/API failures preserve the interaction and correlation state, classify mutation outcome as `not_started`, `completed`, or `uncertain`, redact safe error summaries, and never auto-retry an uncertain write/exec mutation.
-## Copy prompt for Agent Alpha
+## Historical copy prompt for Agent Alpha (do not use as current baseline)
```text
You are taking over MSO testing work in the current repository root (`git rev-parse --show-toplevel`).
@@ -282,7 +282,7 @@ Validation minimum: focused unit tests for success, offline target, absent subsc
- The assistant/client must still emit a user-facing completion, partial-result, or failure message after a tool/API error. If status is uncertain, say so and verify before retrying any write/exec mutation.
- Add focused tests for: HTTP 400 after a successful mutation, HTTP 400 before dispatch, draft preservation, no duplicate write on retry, pending approval preservation, and a visible user-facing error/result message.
-### Template — append for every later session
+### Historical session-note template (reference only)
```md
### YYYY-MM-DD — short title
diff --git a/frontend/slices/auth/lib/session-probe.test.ts b/frontend/slices/auth/lib/session-probe.test.ts
new file mode 100644
index 00000000..88aa9706
--- /dev/null
+++ b/frontend/slices/auth/lib/session-probe.test.ts
@@ -0,0 +1,47 @@
+import { describe, expect, it, vi } from "vitest";
+import { probeSession, resolveSessionProbe } from "./session-probe";
+
+describe("resolveSessionProbe", () => {
+ it("treats an explicit successful unauthenticated response as signed out", () => {
+ expect(resolveSessionProbe(200, { authenticated: false, role: null })).toEqual({
+ status: "out",
+ role: null,
+ });
+ });
+
+ it("treats authenticated responses as signed in and normalizes an invalid role", () => {
+ expect(resolveSessionProbe(200, { authenticated: true, role: "owner" })).toEqual({
+ status: "in",
+ role: "owner",
+ });
+ expect(resolveSessionProbe(200, { authenticated: true, role: "bogus" })).toEqual({
+ status: "in",
+ role: "viewer",
+ });
+ });
+
+ it.each([
+ [502, { authenticated: false }],
+ [503, { authenticated: true, role: "owner" }],
+ [200, {}],
+ [200, null],
+ ])("returns indeterminate for non-authoritative probe %#", (status, body) => {
+ expect(resolveSessionProbe(status, body)).toBeNull();
+ });
+});
+
+describe("probeSession", () => {
+ it("preserves the caller's current state by returning null on network failure", async () => {
+ const fetcher = vi.fn(async () => { throw new Error("restart race"); }) as unknown as typeof fetch;
+ expect(await probeSession(fetcher)).toBeNull();
+ });
+
+ it("uses no-store and same-origin credentials", async () => {
+ const fetcher = vi.fn(async () => new Response(JSON.stringify({ authenticated: true, role: "operator" }), {
+ status: 200,
+ headers: { "content-type": "application/json" },
+ })) as unknown as typeof fetch;
+ await expect(probeSession(fetcher)).resolves.toEqual({ status: "in", role: "operator" });
+ expect(fetcher).toHaveBeenCalledWith("/api/auth/me", { cache: "no-store", credentials: "same-origin" });
+ });
+});
diff --git a/frontend/slices/auth/lib/session-probe.ts b/frontend/slices/auth/lib/session-probe.ts
new file mode 100644
index 00000000..d36db754
--- /dev/null
+++ b/frontend/slices/auth/lib/session-probe.ts
@@ -0,0 +1,38 @@
+import type { DeviceRole } from "@/lib/auth/roles";
+
+export type SessionStatus = "loading" | "out" | "in";
+export type SessionSnapshot = { status: SessionStatus; role: DeviceRole | null };
+
+const DEVICE_ROLES = new Set<DeviceRole>(["viewer", "operator", "owner"]);
+
+/**
+ * Resolve only an authoritative successful auth response. `null` means the
+ * probe was indeterminate (network/5xx/malformed) and callers must preserve
+ * their last known session state instead of inventing a logout.
+ */
+export function resolveSessionProbe(status: number, body: unknown): SessionSnapshot | null {
+ if (status < 200 || status >= 300 || typeof body !== "object" || body === null) return null;
+ const candidate = body as { authenticated?: unknown; role?: unknown };
+ if (typeof candidate.authenticated !== "boolean") return null;
+ if (!candidate.authenticated) return { status: "out", role: null };
+ const role = DEVICE_ROLES.has(candidate.role as DeviceRole)
+ ? (candidate.role as DeviceRole)
+ : "viewer";
+ return { status: "in", role };
+}
+
+export async function probeSession(
+ fetcher: typeof fetch = fetch,
+): Promise<SessionSnapshot | null> {
+ try {
+ const response = await fetcher("/api/auth/me", {
+ cache: "no-store",
+ credentials: "same-origin",
+ });
+ if (!response.ok) return null;
+ const body = await response.json().catch(() => null);
+ return resolveSessionProbe(response.status, body);
+ } catch {
+ return null;
+ }
+}
diff --git a/frontend/slices/auth/lib/use-session-contract.test.ts b/frontend/slices/auth/lib/use-session-contract.test.ts
new file mode 100644
index 00000000..70e7469e
--- /dev/null
+++ b/frontend/slices/auth/lib/use-session-contract.test.ts
@@ -0,0 +1,19 @@
+import { readFileSync } from "node:fs";
+import { fileURLToPath } from "node:url";
+import { describe, expect, it } from "vitest";
+
+const source = readFileSync(fileURLToPath(new URL("./use-session.tsx", import.meta.url)), "utf8");
+
+describe("session provider revalidation contract", () => {
+ it("reconciles immediately even when SSR supplied initial state", () => {
+ expect(source).toContain("void probe().then");
+ expect(source).not.toContain("initialStatus !== undefined) return");
+ });
+
+ it("revalidates browser restores and connectivity recovery", () => {
+ expect(source).toContain('window.addEventListener("pageshow", sync)');
+ expect(source).toContain('window.addEventListener("online", sync)');
+ expect(source).toContain('window.addEventListener("focus", sync)');
+ expect(source).toContain('document.addEventListener("visibilitychange", sync)');
+ });
+});
diff --git a/frontend/slices/auth/lib/use-session.tsx b/frontend/slices/auth/lib/use-session.tsx
index 8e4c8bf3..d5fd9b7e 100644
--- a/frontend/slices/auth/lib/use-session.tsx
+++ b/frontend/slices/auth/lib/use-session.tsx
@@ -4,10 +4,10 @@ import { createContext, useCallback, useContext, useEffect, useMemo, useState, t
import { AUTHED_EVENT } from "@/lib/prefs/use-prefs-sync";
import { IS_DEMO } from "@/lib/demo";
import type { DeviceRole } from "@/lib/auth/roles";
+import { probeSession, type SessionSnapshot, type SessionStatus } from "./session-probe";
-export type SessionStatus = "loading" | "out" | "in";
+export type { SessionStatus } from "./session-probe";
-type SessionSnapshot = { status: SessionStatus; role: DeviceRole | null };
type SessionValue = SessionSnapshot & {
refresh: () => Promise<void>;
signOut: () => Promise<void>;
@@ -34,55 +34,60 @@ export function SessionProvider({
role: IS_DEMO || initialStatus !== "in" ? null : (initialRole ?? "viewer"),
}));
- const probe = useCallback(async (): Promise<SessionSnapshot> => {
- if (IS_DEMO) return { status: "out", role: null };
- try {
- const response = await fetch("/api/auth/me", { cache: "no-store" });
- const body = (await response.json()) as { authenticated?: boolean; role?: DeviceRole | null };
- return body.authenticated
- ? { status: "in", role: body.role ?? "viewer" }
- : { status: "out", role: null };
- } catch {
- return { status: "out", role: null };
- }
- }, []);
+ const probe = useCallback(() => probeSession(), []);
const refresh = useCallback(async () => {
const next = await probe();
+ // `null` is deliberately NOT signed-out. A deploy/restart can race this
+ // request; preserving the last authoritative snapshot keeps a valid cookie
+ // from being presented as a logout while the service recovers.
+ if (!next) return;
setSnapshot(next);
if (next.status === "in") window.dispatchEvent(new Event(AUTHED_EVENT));
}, [probe]);
const signOut = useCallback(async () => {
try {
- await fetch("/api/auth/logout", { method: "POST" });
+ await fetch("/api/auth/logout", { method: "POST", credentials: "same-origin" });
} catch {
/* best-effort — clear locally regardless */
}
setSnapshot({ status: "out", role: null });
}, []);
+ // SSR gives the fast first paint, then the browser immediately reconciles it.
+ // This closes stale HTML/CDN/BFCache windows without reintroducing a loading wall.
useEffect(() => {
- if (IS_DEMO || initialStatus !== undefined) return;
+ if (IS_DEMO) return;
let alive = true;
- probe().then((next) => alive && setSnapshot(next));
- return () => { alive = false; };
- }, [probe, initialStatus]);
+ void probe().then((next) => {
+ if (alive && next) setSnapshot(next);
+ });
+ return () => {
+ alive = false;
+ };
+ }, [probe]);
useEffect(() => {
if (IS_DEMO) return;
let alive = true;
const sync = () => {
if (document.visibilityState !== "visible") return;
- probe().then((next) => { if (alive) setSnapshot(next); });
+ void probe().then((next) => {
+ if (alive && next) setSnapshot(next);
+ });
};
const timer = window.setInterval(sync, 60_000);
window.addEventListener("focus", sync);
+ window.addEventListener("pageshow", sync);
+ window.addEventListener("online", sync);
document.addEventListener("visibilitychange", sync);
return () => {
alive = false;
window.clearInterval(timer);
window.removeEventListener("focus", sync);
+ window.removeEventListener("pageshow", sync);
+ window.removeEventListener("online", sync);
document.removeEventListener("visibilitychange", sync);
};
}, [probe]);
diff --git a/lib/auth/page-cache.test.ts b/lib/auth/page-cache.test.ts
new file mode 100644
index 00000000..031128e0
--- /dev/null
+++ b/lib/auth/page-cache.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from "vitest";
+import { applyPrivatePageCachePolicy } from "./page-cache";
+
+function apply(headers: HeadersInit, method = "GET") {
+ const response = new Response(null);
+ applyPrivatePageCachePolicy(response, new Request("https://mso.example.com/settings", { method, headers }));
+ return response.headers;
+}
+
+describe("auth-sensitive page cache policy", () => {
+ it("marks HTML private/no-store and varies on Cookie", () => {
+ const headers = apply({ accept: "text/html" });
+ expect(headers.get("cache-control")).toBe("private, no-store, max-age=0, must-revalidate");
+ expect(headers.get("pragma")).toBe("no-cache");
+ expect(headers.get("expires")).toBe("0");
+ expect((headers.get("vary") ?? "").toLowerCase()).toContain("cookie");
+ });
+
+ it("marks RSC navigation private/no-store", () => {
+ expect(apply({ accept: "text/x-component", rsc: "1" }).get("cache-control")).toContain("no-store");
+ });
+
+ it("leaves static-byte shaped requests untouched", () => {
+ expect(apply({ accept: "image/avif,image/webp,image/*" }).get("cache-control")).toBeNull();
+ expect(apply({ accept: "*/*" }).get("cache-control")).toBeNull();
+ });
+});
diff --git a/lib/auth/page-cache.ts b/lib/auth/page-cache.ts
new file mode 100644
index 00000000..65f2aa7a
--- /dev/null
+++ b/lib/auth/page-cache.ts
@@ -0,0 +1,31 @@
+type PageRequest = Pick<Request, "method" | "headers">;
+type HeaderResponse = { headers: Headers };
+
+function isAuthSensitivePageRequest(request: PageRequest): boolean {
+ if (request.method !== "GET" && request.method !== "HEAD") return false;
+ const accept = (request.headers.get("accept") ?? "").toLowerCase();
+ return (
+ accept.includes("text/html") ||
+ request.headers.get("rsc") === "1" ||
+ request.headers.has("next-router-prefetch") ||
+ request.headers.has("next-router-state-tree")
+ );
+}
+
+function appendVary(headers: Headers, token: string): void {
+ const current = (headers.get("vary") ?? "")
+ .split(",")
+ .map((value) => value.trim())
+ .filter(Boolean);
+ if (!current.some((value) => value.toLowerCase() === token.toLowerCase())) current.push(token);
+ headers.set("Vary", current.join(", "));
+}
+
+/** Browser documents/RSC contain cookie-derived auth state and must never be shared. */
+export function applyPrivatePageCachePolicy(response: HeaderResponse, request: PageRequest): void {
+ if (!isAuthSensitivePageRequest(request)) return;
+ response.headers.set("Cache-Control", "private, no-store, max-age=0, must-revalidate");
+ response.headers.set("Pragma", "no-cache");
+ response.headers.set("Expires", "0");
+ appendVary(response.headers, "Cookie");
+}
diff --git a/proxy.test.ts b/proxy.test.ts
index 73951d0a..b6c602d1 100644
--- a/proxy.test.ts
+++ b/proxy.test.ts
@@ -259,3 +259,12 @@ describe("the app-host header is never accepted from a client", () => {
expect(stampedHost(res)).toBeNull();
});
});
+
+describe("cockpit document cache boundary", () => {
+ it("applies the private page policy through proxy.ts", async () => {
+ const proxy = await loadProxy(TEMPLATE);
+ const res = await proxy(req("mso.example.com", "/settings", { headers: { accept: "text/html" } }));
+ expect(res.headers.get("cache-control")).toBe("private, no-store, max-age=0, must-revalidate");
+ expect((res.headers.get("vary") ?? "").toLowerCase()).toContain("cookie");
+ });
+});
diff --git a/proxy.ts b/proxy.ts
index 8ee03af1..a20fe0af 100644
--- a/proxy.ts
+++ b/proxy.ts
@@ -33,6 +33,7 @@ import { 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";
+import { applyPrivatePageCachePolicy } from "@/lib/auth/page-cache";
const MUTATING = new Set(["POST", "PUT", "PATCH", "DELETE"]);
@@ -349,6 +350,7 @@ export async function proxy(request: NextRequest) {
requestHeaders.set("content-security-policy", csp);
const response = NextResponse.next({ request: { headers: requestHeaders } });
response.headers.set("Content-Security-Policy", csp);
+ applyPrivatePageCachePolicy(response, request);
return response;
}