Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
feat(security): unified web surface security — cookie/bearer policy, auth gate, mission WS auth
Ruben Lütke63a80750f3c2
diff --git a/jarvis/ui/web/control_auth.py b/jarvis/ui/web/control_auth.pyindex edafdfee9f..1dbbc87891 100644--- a/jarvis/ui/web/control_auth.py+++ b/jarvis/ui/web/control_auth.py@@ -8,11 +8,9 @@ CLI, Claude Code) drive, is key-gated.- ``require_control_key`` — every control route. Bearer required, constant-timecompared. Never logs the presented or stored key.-- ``require_control_key_or_loopback`` — the key-reveal / rotate endpoints. A- same-host (loopback) request is allowed so the desktop Settings panel can- fetch/rotate the key before the user possesses it; a remote caller still needs- the Bearer. A loopback process can already read the keyring/0600 file, so this- is not a new exposure.+- ``require_control_key_or_session`` — key-reveal / rotate and local permission+ endpoints. A valid authenticated UI session may use them; a raw loopback peer+ is never treated as authenticated.- ``assert_bind_safe`` — fail-closed boot check (cloud-first): never expose anon-loopback bind without a key."""@@ -22,6 +20,9 @@ from fastapi import HTTPException, Request, statusfrom jarvis.core import control_key as ck+from .missions_auth import validate_token+from .surface_security import COOKIE_NAME+_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})_UNAUTHORIZED = {"status_code": status.HTTP_401_UNAUTHORIZED,@@ -39,12 +40,6 @@ def _bearer_token(request: Request) -> str | None:return None-def _is_loopback(request: Request) -> bool:- client = getattr(request, "client", None)- host = getattr(client, "host", None)- return host in _LOOPBACK_HOSTS--async def require_control_key(request: Request) -> None:"""FastAPI dependency: require a valid Bearer control key (401 otherwise).@@ -56,12 +51,10 @@ async def require_control_key(request: Request) -> None:raise HTTPException(**_UNAUTHORIZED)-async def require_control_key_or_loopback(request: Request) -> None:- """Looser dependency for key-reveal / rotate: allow a same-host request OR a- valid Bearer. Lets the desktop Settings panel bootstrap the key; remote- callers still need it.- """- if _is_loopback(request) or ck.verify_control_key(_bearer_token(request)):+async def require_control_key_or_session(request: Request) -> None:+ """Allow a control Bearer or an authenticated HttpOnly UI session."""+ session_token = request.cookies.get(COOKIE_NAME, "")+ if validate_token(session_token) or ck.verify_control_key(_bearer_token(request)):returnraise HTTPException(**_UNAUTHORIZED)diff --git a/jarvis/ui/web/control_routes.py b/jarvis/ui/web/control_routes.pyindex 66285a72bb..62c490c4db 100644--- a/jarvis/ui/web/control_routes.py+++ b/jarvis/ui/web/control_routes.py@@ -43,7 +43,7 @@ from jarvis.core.self_mod import (from jarvis.core.self_mod.pending import PendingMutationStorefrom jarvis.ui.web.control_auth import (require_control_key,- require_control_key_or_loopback,+ require_control_key_or_session,)log = logging.getLogger("jarvis.control")@@ -370,21 +370,24 @@ async def delete_secret_value(key: str, request: Request) -> dict[str, Any]:# -----------------------------------------------------------------------# Control-API key reveal + rotate (loopback OR Bearer)+# Control-API key reveal + rotate (authenticated UI session or Bearer)# ----------------------------------------------------------------------[email protected]("/api-key", dependencies=[Depends(require_control_key_or_loopback)])[email protected]("/api-key", dependencies=[Depends(require_control_key_or_session)])async def get_api_key(request: Request) -> dict[str, Any]:key = control_key.get_control_key()- # Audit every reveal (the loopback exemption means a same-host process can- # read the key without the Bearer — worth a trail on a shared VPS).+ # Audit every reveal without logging either credential.client = getattr(request, "client", None)log.info("control: API key revealed to %s", getattr(client, "host", "unknown"))return {"key": key, "masked": control_key.mask_control_key(key)}[email protected]("/api-key/rotate", dependencies=[Depends(require_control_key_or_loopback)], openapi_extra={"x-jarvis-dangerous": True})+ "/api-key/rotate",+ dependencies=[Depends(require_control_key_or_session)],+ openapi_extra={"x-jarvis-dangerous": True},+)async def rotate_api_key(body: RotateBody) -> dict[str, Any]:if not body.confirm:raise HTTPException(diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsxnew file mode 100644index 0000000000..456f22ab12--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AuthGate.test.tsx@@ -0,0 +1,135 @@+import { act, cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { AuthGate } from "./AuthGate";+import { useI18nStore } from "@/i18n";++function response(status: number): Response {+ return { ok: status >= 200 && status < 300, status } as Response;+}++describe("AuthGate", () => {+ beforeEach(() => {+ useI18nStore.getState().setUi("en", { push: false });+ window.__JARVIS_TOKEN = undefined;+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ window.__JARVIS_TOKEN = undefined;+ });++ it("renders the application when the session cookie is authorized", async () => {+ const fetchMock = vi.fn().mockResolvedValue(response(200));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);++ expect(await screen.findByText("Application")).toBeTruthy();+ expect(fetchMock).toHaveBeenCalledWith("/api/config", {+ cache: "no-store",+ credentials: "same-origin",+ });+ });++ it("exchanges an injected desktop token before showing the login form", async () => {+ window.__JARVIS_TOKEN = "desktop-session";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(response(401))+ .mockResolvedValueOnce(response(204));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);++ expect(await screen.findByText("Application")).toBeTruthy();+ expect(fetchMock).toHaveBeenNthCalledWith(2, "/api/ui/session", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_token: "desktop-session" }),+ });+ expect(window.__JARVIS_TOKEN).toBeUndefined();+ });++ it("waits for the desktop token-ready event before opening the login form", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(response(401))+ .mockResolvedValueOnce(response(204));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);+ await waitFor(() => expect(fetchMock).toHaveBeenCalledTimes(1));+ await act(async () => Promise.resolve());+ act(() => {+ window.__JARVIS_TOKEN = "late-desktop-session";+ window.dispatchEvent(new Event("jarvis-token-ready"));+ });++ expect(await screen.findByText("Application")).toBeTruthy();+ expect(fetchMock).toHaveBeenNthCalledWith(2, "/api/ui/session", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ session_token: "late-desktop-session" }),+ });+ });++ it("accepts a control key without persisting it in the browser", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(response(401))+ .mockResolvedValueOnce(response(204));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);+ const input = await screen.findByLabelText("Control key");+ fireEvent.change(input, { target: { value: "control-secret" } });+ fireEvent.submit(input.closest("form")!);++ await waitFor(() => expect(screen.getByText("Application")).toBeTruthy());+ expect(fetchMock).toHaveBeenNthCalledWith(2, "/api/ui/session", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ control_key: "control-secret" }),+ });+ });++ it("falls back to the login form when desktop token exchange is unavailable", async () => {+ window.__JARVIS_TOKEN = "stale-session";+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(response(401))+ .mockRejectedValueOnce(new Error("backend restarted"));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);++ expect(await screen.findByLabelText("Control key")).toBeTruthy();+ expect(window.__JARVIS_TOKEN).toBeUndefined();+ expect(screen.queryByText("Application")).toBeNull();+ });++ it("keeps the gate closed when the control key is rejected", async () => {+ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(response(401))+ .mockResolvedValueOnce(response(401));+ vi.stubGlobal("fetch", fetchMock);++ render(<AuthGate><div>Application</div></AuthGate>);+ const input = await screen.findByLabelText("Control key");+ fireEvent.change(input, { target: { value: "wrong" } });+ fireEvent.submit(input.closest("form")!);++ expect((await screen.findByRole("alert")).textContent).toBe(+ "That control key was not accepted.",+ );+ expect(screen.queryByText("Application")).toBeNull();+ });+});diff --git a/jarvis/ui/web/frontend/src/components/AuthGate.tsx b/jarvis/ui/web/frontend/src/components/AuthGate.tsxnew file mode 100644index 0000000000..77d3dc6e28--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/AuthGate.tsx@@ -0,0 +1,181 @@+import { type FormEvent, type ReactNode, useEffect, useRef, useState } from "react";+import { LockKeyhole } from "lucide-react";+import { useT } from "@/i18n";++declare global {+ interface Window {+ __JARVIS_TOKEN?: string;+ }+}++type GateState = "checking" | "locked" | "authorized";+const DESKTOP_TOKEN_WAIT_MS = 300;++interface AuthGateProps {+ children: ReactNode;+}++async function createSession(body: { control_key: string } | { session_token: string }) {+ return fetch("/api/ui/session", {+ method: "POST",+ cache: "no-store",+ credentials: "same-origin",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ });+}++function readInjectedToken(): string {+ return window.__JARVIS_TOKEN?.trim() ?? "";+}++function waitForInjectedToken(): Promise<string> {+ const existing = readInjectedToken();+ if (existing) return Promise.resolve(existing);++ return new Promise((resolve) => {+ const finish = () => {+ window.clearTimeout(timer);+ window.removeEventListener("jarvis-token-ready", onReady);+ resolve(readInjectedToken());+ };+ const onReady = () => finish();+ const timer = window.setTimeout(finish, DESKTOP_TOKEN_WAIT_MS);+ window.addEventListener("jarvis-token-ready", onReady);+ });+}++export function AuthGate({ children }: AuthGateProps) {+ const t = useT();+ const started = useRef(false);+ const [state, setState] = useState<GateState>("checking");+ const [controlKey, setControlKey] = useState("");+ const [submitting, setSubmitting] = useState(false);+ const [errorKey, setErrorKey] = useState<string | null>(null);++ useEffect(() => {+ if (started.current) return;+ started.current = true;++ void (async () => {+ let response: Response;+ try {+ response = await fetch("/api/config", {+ cache: "no-store",+ credentials: "same-origin",+ });+ } catch {+ // Authentication is required only when the backend explicitly returns+ // 401. Let the existing application surfaces handle warmup/offline+ // failures instead of trapping the user behind an unrelated gate.+ setState("authorized");+ return;+ }+ if (response.status !== 401) {+ setState("authorized");+ return;+ }++ try {+ const injectedToken = await waitForInjectedToken();+ if (injectedToken) {+ // The WebView credential is single-use. Remove the JavaScript copy+ // before the network round-trip, including failure/restart paths.+ window.__JARVIS_TOKEN = undefined;+ const session = await createSession({ session_token: injectedToken });+ if (session.ok) {+ setState("authorized");+ return;+ }+ }+ } catch {+ // A stale injected token must never bypass the explicit 401 gate.+ }+ setState("locked");+ })();+ }, []);++ const submit = async (event: FormEvent<HTMLFormElement>) => {+ event.preventDefault();+ const value = controlKey.trim();+ if (!value || submitting) return;++ setSubmitting(true);+ setErrorKey(null);+ try {+ const response = await createSession({ control_key: value });+ if (!response.ok) {+ setErrorKey(+ response.status === 401 ? "auth_gate.invalid" : "auth_gate.unavailable",+ );+ return;+ }+ setControlKey("");+ setState("authorized");+ } catch {+ setErrorKey("auth_gate.unavailable");+ } finally {+ setSubmitting(false);+ }+ };++ if (state === "authorized") return <>{children}</>;++ if (state === "checking") {+ return (+ <main className="flex min-h-screen items-center justify-center bg-background text-foreground">+ <span className="text-sm text-muted-foreground" role="status">+ {t("auth_gate.checking")}+ </span>+ </main>+ );+ }++ return (+ <main className="flex min-h-screen items-center justify-center bg-background px-4 text-foreground">+ <form+ className="w-full max-w-sm rounded-xl border border-border bg-card p-6 shadow-xl"+ onSubmit={submit}+ >+ <div className="mb-5 flex items-start gap-3">+ <div className="rounded-lg bg-primary/10 p-2 text-primary">+ <LockKeyhole className="h-5 w-5" aria-hidden="true" />+ </div>+ <div>+ <h1 className="text-base font-semibold">{t("auth_gate.title")}</h1>+ <p className="mt-1 text-sm text-muted-foreground">+ {t("auth_gate.subtitle")}+ </p>+ </div>+ </div>++ <label className="mb-1.5 block text-sm font-medium" htmlFor="control-key">+ {t("auth_gate.control_key")}+ </label>+ <input+ id="control-key"+ autoComplete="current-password"+ autoFocus+ className="w-full rounded-md border border-input bg-background px-3 py-2 text-sm outline-none ring-offset-background focus:ring-2 focus:ring-ring"+ disabled={submitting}+ onChange={(event) => setControlKey(event.target.value)}+ placeholder={t("auth_gate.placeholder")}+ type="password"+ value={controlKey}+ />+ {errorKey && (+ <p className="mt-2 text-sm text-destructive" role="alert">+ {t(errorKey)}+ </p>+ )}+ <button+ className="mt-4 w-full rounded-md bg-primary px-3 py-2 text-sm font-medium text-primary-foreground disabled:cursor-not-allowed disabled:opacity-60"+ disabled={!controlKey.trim() || submitting}+ type="submit"+ >+ {t(submitting ? "auth_gate.submitting" : "auth_gate.submit")}+ </button>+ </form>+ </main>+ );+}diff --git a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.test.tsx b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.test.tsxnew file mode 100644index 0000000000..08c31390c2--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.test.tsx@@ -0,0 +1,80 @@+import { act, cleanup, render, waitFor } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { PtyTerminal } from "./PtyTerminal";++vi.mock("@xterm/xterm", () => ({+ Terminal: class {+ cols = 80;+ rows = 24;+ loadAddon() {}+ open() {}+ write(_data: string, done?: () => void) { done?.(); }+ dispose() {}+ },+}));+vi.mock("@xterm/addon-fit", () => ({+ FitAddon: class { fit() {} },+}));+vi.mock("@xterm/addon-web-links", () => ({+ WebLinksAddon: class {},+}));+vi.mock("@xterm/addon-search", () => ({+ SearchAddon: class {},+}));++class MockWebSocket {+ static OPEN = 1;+ static last: MockWebSocket | null = null;+ readonly url: string;+ readyState = MockWebSocket.OPEN;+ binaryType: BinaryType = "blob";+ send = vi.fn();+ close = vi.fn();+ private listeners: Record<string, Array<(event: Event) => void>> = {};++ constructor(url: string | URL) {+ this.url = String(url);+ MockWebSocket.last = this;+ }++ addEventListener(type: string, listener: (event: Event) => void) {+ (this.listeners[type] ??= []).push(listener);+ }++ fire(type: string, event: Event) {+ for (const listener of this.listeners[type] ?? []) listener(event);+ }+}++describe("PtyTerminal mission authorization", () => {+ beforeEach(() => {+ MockWebSocket.last = null;+ vi.stubGlobal("WebSocket", MockWebSocket);+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: vi.fn().mockResolvedValue({ token: "pty-secret" }),+ }));+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("opens a token-free URL and sends the token as the first hello frame", async () => {+ render(<PtyTerminal workerId="worker/one" />);+ await waitFor(() => expect(MockWebSocket.last).not.toBeNull());++ const socket = MockWebSocket.last!;+ expect(socket.url).toContain("/api/missions/pty/worker%2Fone");+ expect(socket.url).not.toContain("pty-secret");+ expect(new URL(socket.url).search).toBe("");++ act(() => socket.fire("open", new Event("open")));+ expect(socket.send).toHaveBeenCalledTimes(1);+ expect(socket.send).toHaveBeenCalledWith(+ JSON.stringify({ type: "hello", token: "pty-secret" }),+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsxindex 9767e4cfd8..9bf74d46f8 100644--- a/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/missions/PtyTerminal.tsx@@ -20,6 +20,7 @@ import { SearchAddon } from "@xterm/addon-search";import "@xterm/xterm/css/xterm.css";import { AlertCircle, Terminal as TerminalIcon } from "lucide-react";import { useT } from "@/i18n";+import { buildMissionSocketUrl, fetchMissionToken } from "@/lib/missionAuth";import {disposeTerminal,getTerminal,@@ -34,11 +35,9 @@ interface PtyTerminalProps {}function buildPtyUrl(workerId: string): string {- const proto = window.location.protocol === "https:" ? "wss" : "ws";- const host = window.location.host;- const token = window.__JARVIS_TOKEN;- const query = token ? `?token=${encodeURIComponent(token)}` : "";- return `${proto}://${host}/api/missions/pty/${encodeURIComponent(workerId)}${query}`;+ return buildMissionSocketUrl(+ `/api/missions/pty/${encodeURIComponent(workerId)}`,+ );}export function PtyTerminal({ workerId }: PtyTerminalProps) {@@ -114,71 +113,87 @@ export function PtyTerminal({ workerId }: PtyTerminalProps) {window.addEventListener("resize", handleResize);let ws: WebSocket | null = null;- try {- ws = new WebSocket(buildPtyUrl(workerId));- ws.binaryType = "arraybuffer";- wsRef.current = ws;-- ws.addEventListener("open", () => {- setConnected(true);- setStreamError(null);- });-- ws.addEventListener("message", (ev) => {- const term = termRef.current;- if (!term) return;- let data: string;- let size = 0;- if (typeof ev.data === "string") {- data = ev.data;- size = data.length;- } else if (ev.data instanceof ArrayBuffer) {- const decoder = new TextDecoder();- data = decoder.decode(ev.data);- size = ev.data.byteLength;- } else {- return;- }+ let disposed = false;+ const openSocket = (token: string) => {+ try {+ ws = new WebSocket(buildPtyUrl(workerId));+ ws.binaryType = "arraybuffer";+ wsRef.current = ws;++ ws.addEventListener("open", () => {+ ws?.send(JSON.stringify({ type: "hello", token }));+ setConnected(true);+ setStreamError(null);+ });- bytesPendingRef.current += size;- if (- !pausedRef.current &&- bytesPendingRef.current > PAUSE_THRESHOLD- ) {- pausedRef.current = true;- sendControl("pause");- }+ ws.addEventListener("message", (ev) => {+ const term = termRef.current;+ if (!term) return;+ let data: string;+ let size = 0;+ if (typeof ev.data === "string") {+ data = ev.data;+ size = data.length;+ } else if (ev.data instanceof ArrayBuffer) {+ const decoder = new TextDecoder();+ data = decoder.decode(ev.data);+ size = ev.data.byteLength;+ } else {+ return;+ }- term.write(data, () => {- bytesPendingRef.current = Math.max(- 0,- bytesPendingRef.current - size,- );+ bytesPendingRef.current += size;if (- pausedRef.current &&- bytesPendingRef.current < RESUME_THRESHOLD+ !pausedRef.current &&+ bytesPendingRef.current > PAUSE_THRESHOLD) {- pausedRef.current = false;- sendControl("resume");+ pausedRef.current = true;+ sendControl("pause");}++ term.write(data, () => {+ bytesPendingRef.current = Math.max(+ 0,+ bytesPendingRef.current - size,+ );+ if (+ pausedRef.current &&+ bytesPendingRef.current < RESUME_THRESHOLD+ ) {+ pausedRef.current = false;+ sendControl("resume");+ }+ });});- });- ws.addEventListener("error", () => {- setStreamError(t("pty_terminal.stream_unreachable"));- });+ ws.addEventListener("error", () => {+ setStreamError(t("pty_terminal.stream_unreachable"));+ });- ws.addEventListener("close", (ev) => {- setConnected(false);- if (ev.code !== 1000 && ev.code !== 1001) {- setStreamError(`${t("pty_terminal.stream_disconnected")} (Code ${ev.code}).`);+ ws.addEventListener("close", (ev) => {+ setConnected(false);+ if (ev.code !== 1000 && ev.code !== 1001) {+ setStreamError(`${t("pty_terminal.stream_disconnected")} (Code ${ev.code}).`);+ }+ });+ } catch (e) {+ setStreamError(`${t("pty_terminal.connect_failed")}: ${(e as Error).message}`);+ }+ };++ void fetchMissionToken()+ .then((token) => {+ if (!disposed) openSocket(token);+ })+ .catch((error: unknown) => {+ if (!disposed) {+ const message = error instanceof Error ? error.message : String(error);+ setStreamError(`${t("pty_terminal.connect_failed")}: ${message}`);}});- } catch (e) {- setStreamError(`${t("pty_terminal.connect_failed")}: ${(e as Error).message}`);- }return () => {+ disposed = true;window.removeEventListener("resize", handleResize);try {wsRef.current?.close(1000, "unmount");diff --git a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.test.tsx b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.test.tsxnew file mode 100644index 0000000000..98a13f7fbc--- /dev/null+++ b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.test.tsx@@ -0,0 +1,68 @@+import { act, cleanup, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useMissionsStore } from "./store";+import { useMissionWebSocket } from "./useMissionWebSocket";++const socket = vi.hoisted(() => ({+ sendJsonMessage: vi.fn(),+ urlFactory: null as null | (() => Promise<string>),+ options: null as null | { onOpen?: () => void },+}));++vi.mock("react-use-websocket", () => ({+ default: vi.fn((urlFactory, options) => {+ socket.urlFactory = urlFactory;+ socket.options = options;+ return {+ sendJsonMessage: socket.sendJsonMessage,+ lastJsonMessage: null,+ readyState: 1,+ };+ }),+ ReadyState: {+ UNINSTANTIATED: -1,+ CONNECTING: 0,+ OPEN: 1,+ CLOSING: 2,+ CLOSED: 3,+ },+}));++describe("useMissionWebSocket", () => {+ beforeEach(() => {+ socket.sendJsonMessage.mockReset();+ socket.urlFactory = null;+ socket.options = null;+ useMissionsStore.getState().reset();+ });++ afterEach(() => {+ cleanup();+ vi.unstubAllGlobals();+ });++ it("keeps the token out of the URL and sends it only in hello", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: vi.fn().mockResolvedValue({ token: "mission-secret" }),+ });+ vi.stubGlobal("fetch", fetchMock);+ useMissionsStore.setState({ lastSeq: 42 });++ renderHook(() => useMissionWebSocket());+ let url = "";+ await act(async () => {+ url = await socket.urlFactory!();+ });++ expect(url).toBe("ws://localhost:3000/api/missions/ws");+ expect(url).not.toContain("mission-secret");+ act(() => socket.options?.onOpen?.());+ expect(socket.sendJsonMessage).toHaveBeenCalledWith({+ type: "hello",+ last_seq: 42,+ token: "mission-secret",+ });+ });+});diff --git a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.tsindex e255bf445a..8dd2870a28 100644--- a/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts+++ b/jarvis/ui/web/frontend/src/components/missions/useMissionWebSocket.ts@@ -9,25 +9,17 @@* backoff up to 30s, infinite retries). The UI shows "offline" via* store.connected.*- * Auth tokens (`missions_auth.py`) live in server memory only and are- * wiped on restart, so a `window.__JARVIS_TOKEN` captured before a restart- * closes the socket with 4401. `getUrl` is passed as a function (not a- * plain string) so react-use-websocket re-resolves it on every reconnect- * attempt, including scheduled ones — a 4401 close flags the next- * resolution to fetch a fresh token first (mirrors the fallback in- * WorkspaceTerminal.tsx's `getToken()`).+ * Mission tokens (`missions_auth.py`) live in server memory only and are+ * wiped on restart. `getUrl` obtains a fresh token before each connection,+ * while the URL itself stays token-free; the token is sent only in the first+ * hello frame.*/import { useCallback, useEffect, useRef } from "react";import useWebSocket, { ReadyState } from "react-use-websocket";import type { EventEnvelope } from "@/types/missions";+import { buildMissionSocketUrl, fetchMissionToken } from "@/lib/missionAuth";import { useMissionsStore } from "./store";-declare global {- interface Window {- __JARVIS_TOKEN?: string;- }-}-interface ServerHello {type: "hello_ack";resumed_from: number;@@ -49,33 +41,15 @@ function isEventEnvelope(msg: WsMessage): msg is EventEnvelope {* a one-off race with a restart. */const MAX_CONSECUTIVE_AUTH_FAILURES = 3;-async function fetchFreshToken(): Promise<string> {- try {- const res = await fetch("/api/missions/auth/token");- const body = (await res.json()) as { token?: string };- const token = body.token ?? "";- window.__JARVIS_TOKEN = token;- return token;- } catch {- return window.__JARVIS_TOKEN ?? "";- }-}-export function useMissionWebSocket(): { readyState: ReadyState } {const setConnected = useMissionsStore((s) => s.setConnected);const applyEvent = useMissionsStore((s) => s.applyEvent);- const needsFreshToken = useRef(false);+ const token = useRef("");const consecutiveAuthFailures = useRef(0);const getUrl = useCallback(async () => {- const token = needsFreshToken.current- ? await fetchFreshToken()- : (window.__JARVIS_TOKEN ?? "");- needsFreshToken.current = false;- const proto = window.location.protocol === "https:" ? "wss" : "ws";- const host = window.location.host;- const query = token ? `?token=${encodeURIComponent(token)}` : "";- return `${proto}://${host}/api/missions/ws${query}`;+ token.current = await fetchMissionToken();+ return buildMissionSocketUrl("/api/missions/ws");}, []);const { sendJsonMessage, lastJsonMessage, readyState } = useWebSocket(getUrl, {@@ -85,14 +59,9 @@ export function useMissionWebSocket(): { readyState: ReadyState } {sendJsonMessage({type: "hello",last_seq: lastSeq,- token: window.__JARVIS_TOKEN ?? "",+ token: token.current,});},- onClose: (event) => {- if (event.code === 4401) {- needsFreshToken.current = true;- }- },shouldReconnect: (event) => {if (event.code !== 4401) {consecutiveAuthFailures.current = 0;@@ -105,6 +74,7 @@ export function useMissionWebSocket(): { readyState: ReadyState } {return consecutiveAuthFailures.current <= MAX_CONSECUTIVE_AUTH_FAILURES;},reconnectAttempts: Number.POSITIVE_INFINITY,+ retryOnError: true,reconnectInterval: (attempt: number) =>Math.min(1000 * 2 ** attempt, 30000),share: true,diff --git a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsxindex beff1f8b04..778fe4406d 100644--- a/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx+++ b/jarvis/ui/web/frontend/src/components/workspace/WorkspaceTerminal.tsx@@ -27,18 +27,6 @@ interface WorkspaceTerminalProps {title: string;}-async function getToken(): Promise<string> {- const injected = (window as unknown as { __JARVIS_TOKEN?: string }).__JARVIS_TOKEN;- if (injected) return injected;- try {- const res = await fetch("/api/missions/auth/token");- const body = (await res.json()) as { token?: string };- return body.token ?? "";- } catch {- return "";- }-}-function buildUrl(paneKey: string, params: Record<string, string>): string {const proto = window.location.protocol === "https:" ? "wss" : "ws";const query = new URLSearchParams(params).toString();@@ -100,11 +88,8 @@ export function WorkspaceTerminal({}};- void (async () => {- const token = await getToken();- if (disposed) return;+ {const params: Record<string, string> = {- token,cols: String(term.cols || 80),rows: String(term.rows || 24),};@@ -168,7 +153,7 @@ export function WorkspaceTerminal({ws.send(JSON.stringify({ t: "i", d: data }));}});- })();+ }window.addEventListener("resize", sendResize);const ro = new ResizeObserver(() => sendResize());diff --git a/jarvis/ui/web/frontend/src/lib/missionAuth.test.ts b/jarvis/ui/web/frontend/src/lib/missionAuth.test.tsnew file mode 100644index 0000000000..10bf10d98a--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/missionAuth.test.ts@@ -0,0 +1,43 @@+import { afterEach, describe, expect, it, vi } from "vitest";+import { buildMissionSocketUrl, fetchMissionToken } from "./missionAuth";++describe("mission socket authorization", () => {+ afterEach(() => vi.unstubAllGlobals());++ it("fetches a short-lived token with the authenticated session cookie", async () => {+ const fetchMock = vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: vi.fn().mockResolvedValue({ token: " mission-token " }),+ });+ vi.stubGlobal("fetch", fetchMock);++ await expect(fetchMissionToken()).resolves.toBe("mission-token");+ expect(fetchMock).toHaveBeenCalledWith("/api/missions/auth/token", {+ cache: "no-store",+ credentials: "same-origin",+ });+ });++ it("rejects an empty token response", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue({+ ok: true,+ status: 200,+ json: vi.fn().mockResolvedValue({}),+ }));++ await expect(fetchMissionToken()).rejects.toThrow(+ "Mission authorization returned no token",+ );+ });++ it("builds a token-free same-origin WebSocket URL", () => {+ vi.stubGlobal("window", {+ location: { protocol: "https:", host: "app.example" },+ });++ expect(buildMissionSocketUrl("/api/missions/ws")).toBe(+ "wss://app.example/api/missions/ws",+ );+ });+});diff --git a/jarvis/ui/web/frontend/src/lib/missionAuth.ts b/jarvis/ui/web/frontend/src/lib/missionAuth.tsnew file mode 100644index 0000000000..c6a77354c7--- /dev/null+++ b/jarvis/ui/web/frontend/src/lib/missionAuth.ts@@ -0,0 +1,20 @@+const MISSION_TOKEN_ENDPOINT = "/api/missions/auth/token";++export async function fetchMissionToken(): Promise<string> {+ const response = await fetch(MISSION_TOKEN_ENDPOINT, {+ cache: "no-store",+ credentials: "same-origin",+ });+ if (!response.ok) {+ throw new Error(`Mission authorization failed (${response.status})`);+ }+ const payload = (await response.json()) as { token?: unknown };+ const token = typeof payload.token === "string" ? payload.token.trim() : "";+ if (!token) throw new Error("Mission authorization returned no token");+ return token;+}++export function buildMissionSocketUrl(path: string): string {+ const proto = window.location.protocol === "https:" ? "wss" : "ws";+ return `${proto}://${window.location.host}${path}`;+}diff --git a/jarvis/ui/web/missions_auth.py b/jarvis/ui/web/missions_auth.pyindex 1f1d7e70d6..f61d760497 100644--- a/jarvis/ui/web/missions_auth.py+++ b/jarvis/ui/web/missions_auth.py@@ -1,25 +1,20 @@-"""Short-lived in-memory token store for mission WebSocket auth.+"""Process-local tokens for authenticated UI and mission WebSocket sessions.-Localhost-only setup. No secret management needed (single-user browser):-- **No** token is pre-generated at server start; every browser fetches- its own via ``GET /api/missions/auth/token``.-- Tokens live in module memory and are discarded on restart.-- ``validate_token()`` is an O(1) set lookup.--Deliberately no JWT library, no cookies, no sessions — the WS handshake-separates auth (hello frame) from frame validation, which is enough for the-single-user-localhost threat model.+Tokens are minted only behind the global Host/Origin/credential boundary, live+in memory, and disappear on restart. Mission sockets keep their narrower+hello-frame check as defense in depth; the main UI session itself is carried in+an HttpOnly cookie managed by :mod:`jarvis.ui.web.surface_security`."""from __future__ import annotations-import osimport secretsfrom typing import Finalfrom fastapi import APIRouter+from fastapi.responses import JSONResponse# Module-global token store. A set for O(1) lookup. Reset on-# restart — sufficient for the localhost single-user use case.+# restart — sufficient for a process-scoped browser session._TOKENS: set[str] = set()_TOKEN_BYTES: Final[int] = 32 # 256 bits of entropy@@ -41,29 +36,11 @@ def validate_token(tok: str) -> bool:def register_token(tok: str) -> None:"""Register an externally-minted token as valid. Idempotent.- The fast-boot desktop path mints a RAW ``secrets.token_urlsafe`` and injects- it into ``window.__JARVIS_TOKEN`` without ever issuing it through- ``GET /token`` — so without this it fails ``validate_token`` (close 4401) on- every token-gated WebSocket. That is exactly what hung the "Make It Yours"- workspace PTY terminals forever on "connecting".- """- if tok:- _TOKENS.add(tok)---def register_session_token_from_env(env_var: str) -> str | None:- """Read the desktop session token from ``env_var`` and register it as valid.-- Called once at server build with ``cfg.ui.auth_token_env`` so the injected- ``window.__JARVIS_TOKEN`` passes ``validate_token``. Returns the token when- present, else ``None`` (headless / browser-only boots inject no token and- fetch a fresh one via ``GET /token`` instead).+ The fast-boot boundary can mint an authenticated HttpOnly session before the+ full app exists. Registering that issued session preserves it at handoff."""- tok = os.environ.get(env_var)if tok:_TOKENS.add(tok)- return tok- return Nonedef revoke_token(tok: str) -> None:@@ -80,6 +57,9 @@ router = APIRouter(prefix="/api/missions/auth", tags=["missions-auth"])@router.get("/token")-async def get_token() -> dict[str, str]:- """Returns a fresh mission token. The browser holds it in memory."""- return {"token": issue_token()}+async def get_token() -> JSONResponse:+ """Return a fresh in-memory mission token without allowing caching."""+ return JSONResponse(+ {"token": issue_token()},+ headers={"Cache-Control": "no-store"},+ )diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.pynew file mode 100644index 0000000000..59eb6fe681--- /dev/null+++ b/jarvis/ui/web/surface_security.py@@ -0,0 +1,854 @@+"""Global Host, Origin, and credential guard for Jarvis web surfaces.++The desktop UI, a normal browser, ``jarvisctl``, and public provider callbacks+all share one ASGI application. Route-local authentication is therefore not a+safe outer boundary: a newly mounted router or WebSocket can otherwise become+public by accident. :class:`SurfaceSecurity` is the dependency-light outer+guard used by both the serve-first bootstrap and the full FastAPI app.++The module intentionally imports neither FastAPI nor Starlette. Credential+stores are imported lazily only when a protected request presents a credential,+so applying the guard cannot add their import graphs to the boot critical path.+"""++from __future__ import annotations++import ipaddress+import json+import os+import re+import secrets+import sys+import threading+from collections.abc import Awaitable, Callable, Iterable, MutableMapping+from http.cookies import CookieError, SimpleCookie+from typing import Any, Literal+from urllib.parse import urlsplit++COOKIE_NAME = "jarvis_session"++_LOOPBACK_HOSTS = frozenset({"localhost", "127.0.0.1", "::1"})+_SAFE_HTTP_METHODS = frozenset({"GET", "HEAD"})+_UNSAFE_HTTP_METHODS = frozenset({"POST", "PUT", "PATCH", "DELETE"})+_TOKEN_RE = re.compile(r"^[A-Za-z0-9._~-]+$")++Scope = MutableMapping[str, Any]+Receive = Callable[[], Awaitable[dict[str, Any]]]+Send = Callable[[dict[str, Any]], Awaitable[None]]+ASGIApp = Callable[[Scope, Receive, Send], Awaitable[None]]+CredentialValidator = Callable[[str], bool]+AuthKind = Literal["control", "session"]+Origin = tuple[str, str, int | None]++_BOOTSTRAP_TOKEN_LOCK = threading.Lock()+_BOOTSTRAP_TOKENS: set[str] = set()+++def _register_bootstrap_tokens(tokens: Iterable[str]) -> None:+ """Register process-local tokens that may only mint one UI session."""+ valid = {token for token in tokens if isinstance(token, str) and token}+ if not valid:+ return+ with _BOOTSTRAP_TOKEN_LOCK:+ _BOOTSTRAP_TOKENS.update(valid)+++def _bootstrap_token_is_valid(token: str) -> bool:+ with _BOOTSTRAP_TOKEN_LOCK:+ return token in _BOOTSTRAP_TOKENS+++def _consume_bootstrap_token(token: str) -> bool:+ """Atomically consume a bootstrap token so concurrent replay fails."""+ with _BOOTSTRAP_TOKEN_LOCK:+ if token not in _BOOTSTRAP_TOKENS:+ return False+ _BOOTSTRAP_TOKENS.remove(token)+ return True+++def _iter_values(value: str | Iterable[str] | None) -> tuple[str, ...]:+ if value is None:+ return ()+ if isinstance(value, str):+ return (value,)+ return tuple(str(item) for item in value)+++def _headers(scope: Scope, name: str) -> list[str]:+ wanted = name.lower().encode("latin-1")+ values: list[str] = []+ for raw_name, raw_value in scope.get("headers", ()):+ if bytes(raw_name).lower() != wanted:+ continue+ try:+ values.append(bytes(raw_value).decode("latin-1").strip())+ except (AttributeError, UnicodeDecodeError):+ return []+ return values+++def _single_header(scope: Scope, name: str) -> str | None:+ values = _headers(scope, name)+ if len(values) != 1:+ return None+ return values[0]+++def _normalise_hostname(value: str) -> str | None:+ host = value.strip().rstrip(".")+ if not host or any(ch.isspace() for ch in host):+ return None+ try:+ return str(ipaddress.ip_address(host))+ except ValueError:+ pass+ try:+ return host.encode("idna").decode("ascii").lower()+ except (UnicodeError, ValueError):+ return None+++def _parse_authority(value: str) -> tuple[str, int | None] | None:+ """Parse a Host/authority value without accepting URL-like ambiguity."""+ authority = value.strip()+ if (+ not authority+ or any(ch.isspace() for ch in authority)+ or any(ch in authority for ch in "/\\@,?#")+ ):+ return None++ host_text: str+ port: int | None = None+ if authority.startswith("["):+ closing = authority.find("]")+ if closing <= 1:+ return None+ host_text = authority[1:closing]+ suffix = authority[closing + 1 :]+ if suffix:+ if not suffix.startswith(":") or not suffix[1:].isdigit():+ return None+ port = int(suffix[1:])+ elif authority.count(":") == 1:+ host_text, port_text = authority.rsplit(":", 1)+ if not port_text.isdigit():+ return None+ port = int(port_text)+ elif ":" in authority:+ # RFC 3986 requires an IPv6 literal in an authority to be bracketed.+ return None+ else:+ host_text = authority++ if port is not None and not 0 < port <= 65535:+ return None+ host = _normalise_hostname(host_text)+ if host is None:+ return None+ return host, port+++def _parse_url_host(value: str) -> str | None:+ raw = value.strip()+ if not raw:+ return None+ if "://" not in raw:+ parsed = _parse_authority(raw)+ return parsed[0] if parsed is not None else None+ try:+ split = urlsplit(raw)+ if split.scheme.lower() not in {"http", "https", "ws", "wss"}:+ return None+ if split.username is not None or split.password is not None:+ return None+ return _normalise_hostname(split.hostname or "")+ except (ValueError, UnicodeError):+ return None+++def _parse_origin(value: str) -> Origin | None:+ raw = value.strip()+ if not raw or raw.lower() == "null" or any(ch.isspace() for ch in raw):+ return None+ try:+ split = urlsplit(raw)+ scheme = split.scheme.lower()+ if scheme not in {"http", "https"}:+ return None+ if split.username is not None or split.password is not None:+ return None+ if split.path not in {"", "/"} or split.query or split.fragment:+ return None+ host = _normalise_hostname(split.hostname or "")+ if host is None:+ return None+ port = split.port+ except (ValueError, UnicodeError):+ return None+ if port == (80 if scheme == "http" else 443):+ port = None+ return scheme, host, port+++def _scope_authority(scope: Scope) -> tuple[str, int | None] | None:+ host = _single_header(scope, "host") or _single_header(scope, ":authority")+ return _parse_authority(host) if host is not None else None+++def _scope_origin(scope: Scope) -> Origin | None:+ authority = _scope_authority(scope)+ if authority is None:+ return None+ scheme = str(scope.get("scheme", "http") or "http").lower()+ scheme = {"ws": "http", "wss": "https"}.get(scheme, scheme)+ if scheme not in {"http", "https"}:+ return None+ host, port = authority+ if port == (80 if scheme == "http" else 443):+ port = None+ return scheme, host, port+++def _is_ip_literal(host: str) -> bool:+ try:+ ipaddress.ip_address(host)+ except ValueError:+ return False+ return True+++def _env_trusted_hosts() -> tuple[str, ...]:+ raw = os.environ.get("JARVIS_TRUSTED_HOSTS", "")+ return tuple(part.strip() for part in raw.split(",") if part.strip())+++def _trusted_hostnames(+ *,+ trusted_hosts: str | Iterable[str] | None = None,+ public_urls: str | Iterable[str] | None = None,+ vite_dev_url: str | None = None,+) -> frozenset[str]:+ result = set(_LOOPBACK_HOSTS)+ for item in (*_env_trusted_hosts(), *_iter_values(trusted_hosts)):+ host = _parse_url_host(item)+ if host is not None:+ result.add(host)+ for item in (*_iter_values(public_urls), *_iter_values(vite_dev_url)):+ host = _parse_url_host(item)+ if host is not None:+ result.add(host)+ return frozenset(result)+++def _trusted_origin_values(+ *,+ trusted_origins: str | Iterable[str] | None = None,+ public_urls: str | Iterable[str] | None = None,+ vite_dev_url: str | None = None,+) -> frozenset[Origin]:+ result: set[Origin] = set()+ for item in (+ *_iter_values(trusted_origins),+ *_iter_values(public_urls),+ *_iter_values(vite_dev_url),+ ):+ origin = _parse_origin(item)+ if origin is not None:+ result.add(origin)+ return frozenset(result)+++def scope_host_is_trusted(+ scope: Scope,+ *,+ trusted_hosts: str | Iterable[str] | None = None,+ public_urls: str | Iterable[str] | None = None,+ vite_dev_url: str | None = None,+) -> bool:+ """Return whether ``scope`` carries a non-ambiguous trusted Host header.++ Loopback names and syntactically valid IP literals are accepted on any+ port. DNS names must be configured by URL, constructor argument, or the+ comma-separated ``JARVIS_TRUSTED_HOSTS`` environment variable.+ """+ authority = _scope_authority(scope)+ if authority is None:+ return False+ host, _ = authority+ if _is_ip_literal(host):+ return True+ return host in _trusted_hostnames(+ trusted_hosts=trusted_hosts,+ public_urls=public_urls,+ vite_dev_url=vite_dev_url,+ )+++def scope_origin_is_trusted(+ scope: Scope,+ *,+ trusted_origins: str | Iterable[str] | None = None,+ public_urls: str | Iterable[str] | None = None,+ vite_dev_url: str | None = None,+ required: bool = False,+) -> bool:+ """Validate an Origin against the exact request or configured origins.++ A missing Origin is accepted only when ``required`` is false. ``null``,+ malformed, multi-value, and foreign origins always fail.+ """+ values = _headers(scope, "origin")+ if not values:+ return not required+ if len(values) != 1:+ return False+ origin = _parse_origin(values[0])+ if origin is None:+ return False+ if origin == _scope_origin(scope):+ return True+ return origin in _trusted_origin_values(+ trusted_origins=trusted_origins,+ public_urls=public_urls,+ vite_dev_url=vite_dev_url,+ )+++def is_secure_or_loopback(scope: Scope) -> bool:+ """True for HTTPS/WSS or a direct loopback-client-to-loopback-Host request.++ Requiring both loopback endpoints avoids treating a public request forwarded+ by a same-host reverse proxy as local merely because the proxy's peer socket+ is ``127.0.0.1``.+ """+ if str(scope.get("scheme", "")).lower() in {"https", "wss"}:+ return True+ authority = _scope_authority(scope)+ if authority is None:+ return False+ request_host, _ = authority+ try:+ host_is_loopback = ipaddress.ip_address(request_host).is_loopback+ except ValueError:+ host_is_loopback = request_host == "localhost"+ if not host_is_loopback:+ return False+ client = scope.get("client")+ client_host = str(client[0]) if isinstance(client, (tuple, list)) and client else ""+ try:+ return ipaddress.ip_address(client_host).is_loopback+ except ValueError:+ return client_host == "localhost"+++def build_set_cookie_header(token: str, secure: bool) -> str:+ """Build the process-session cookie without importing a web framework."""+ if not token or not _TOKEN_RE.fullmatch(token):+ raise ValueError("session token must be a non-empty URL-safe value")+ cookie = SimpleCookie()+ cookie[COOKIE_NAME] = token+ morsel = cookie[COOKIE_NAME]+ morsel["path"] = "/"+ morsel["httponly"] = True+ morsel["samesite"] = "Strict"+ if secure:+ morsel["secure"] = True+ return morsel.OutputString()+++def append_session_cookie(response: Any, token: str, secure: bool) -> Any:+ """Append a session cookie to a Starlette-like response and return it."""+ value = build_set_cookie_header(token, secure)+ headers = getattr(response, "headers", None)+ append = getattr(headers, "append", None)+ if callable(append):+ append("set-cookie", value)+ return response+ raw_headers = getattr(response, "raw_headers", None)+ if isinstance(raw_headers, list):+ raw_headers.append((b"set-cookie", value.encode("latin-1")))+ return response+ raise TypeError("response does not expose appendable headers")+++def _presented_bearer(scope: Scope) -> tuple[bool, str | None]:+ values = _headers(scope, "authorization")+ if not values:+ return False, None+ if len(values) != 1:+ return True, None+ scheme, separator, token = values[0].partition(" ")+ if separator and scheme.lower() == "bearer" and token.strip():+ return True, token.strip()+ return True, None+++def _presented_session_cookie(scope: Scope) -> str | None:+ found: list[str] = []+ for header in _headers(scope, "cookie"):+ try:+ cookie = SimpleCookie()+ cookie.load(header)+ except (CookieError, ValueError):+ return None+ morsel = cookie.get(COOKIE_NAME)+ if morsel is not None and morsel.value:+ found.append(morsel.value)+ if not found or len(set(found)) != 1:+ return None+ return found[0]+++def _default_control_key_validator(token: str) -> bool:+ try:+ from jarvis.core.control_key import verify_control_key++ return bool(verify_control_key(token))+ except Exception:+ return False+++def _default_session_validator(token: str) -> bool:+ try:+ from jarvis.ui.web.missions_auth import validate_token++ return bool(validate_token(token))+ except Exception:+ return False+++def credentials_valid(scope: Scope) -> bool:+ """Validate the credential carried by ``scope`` without Host/Origin checks.++ This is the route-level defense-in-depth helper for tool-capable sockets.+ A Bearer may be either the persistent control key or a registered ephemeral+ UI token. Cookie credentials are ephemeral UI tokens. Supplying any+ malformed Authorization header is authoritative and prevents cookie+ fallback.+ """+ bearer_present, bearer = _presented_bearer(scope)+ if bearer_present:+ if bearer is None:+ return False+ if _default_control_key_validator(bearer):+ return True+ return _default_session_validator(bearer)++ token = _presented_session_cookie(scope)+ if token is None:+ return False+ return _default_session_validator(token)+++async def _reject(+ scope: Scope,+ send: Send,+ *,+ status_code: int,+ detail: str,+ ws_code: int,+ authenticate: bool = False,+) -> None:+ if scope.get("type") == "websocket":+ await send({"type": "websocket.close", "code": ws_code, "reason": detail})+ return+ body = json.dumps({"detail": detail}, separators=(",", ":")).encode("utf-8")+ headers = [+ (b"content-type", b"application/json"),+ (b"content-length", str(len(body)).encode("ascii")),+ (b"cache-control", b"no-store"),+ ]+ if authenticate:+ headers.append((b"www-authenticate", b"Bearer"))+ await send(+ {+ "type": "http.response.start",+ "status": status_code,+ "headers": headers,+ }+ )+ await send({"type": "http.response.body", "body": body})+++async def reject_host(scope: Scope, send: Send) -> None:+ """Reject an untrusted Host for HTTP or WebSocket before downstream code."""+ await _reject(+ scope,+ send,+ status_code=400,+ detail="Untrusted Host header.",+ ws_code=4403,+ )+++async def reject_origin(scope: Scope, send: Send) -> None:+ """Reject a foreign, null, malformed, or required-but-missing Origin."""+ await _reject(+ scope,+ send,+ status_code=403,+ detail="Untrusted Origin header.",+ ws_code=4403,+ )+++async def reject_unauthorized(scope: Scope, send: Send) -> None:+ """Reject a request that lacks a valid Jarvis credential."""+ await _reject(+ scope,+ send,+ status_code=401,+ detail="Invalid or missing Jarvis credential.",+ ws_code=4401,+ authenticate=True,+ )+++def _is_static_request(path: str, method: str) -> bool:+ if method not in _SAFE_HTTP_METHODS:+ return False+ protected_prefixes = ("/api", "/ws", "/internal")+ return not any(path == prefix or path.startswith(f"{prefix}/") for prefix in protected_prefixes)+++def _is_conductor_hook(path: str, method: str) -> bool:+ prefix = "/api/conductor/hooks/"+ if method != "POST" or not path.startswith(prefix):+ return False+ token = path[len(prefix) :]+ return bool(token) and "/" not in token+++def _external_http_auth(path: str, method: str) -> bool:+ return (+ (path == "/api/telephony/voice" and method == "POST")+ or (path == "/api/marketplace/oauth/callback" and method == "GET")+ or _is_conductor_hook(path, method)+ )+++def _http_auth_exception(path: str, method: str) -> bool:+ return (+ _is_static_request(path, method)+ or (path == "/api/health" and method == "GET")+ or (path == "/api/ui/shell-painted" and method == "POST")+ or _external_http_auth(path, method)+ )+++def _mission_inner_auth_socket(path: str) -> bool:+ if path == "/api/missions/ws":+ return True+ prefix = "/api/missions/pty/"+ worker_id = path[len(prefix) :] if path.startswith(prefix) else ""+ return bool(worker_id) and "/" not in worker_id+++class SurfaceSecurity:+ """Pure-ASGI outer security boundary for every Jarvis HTTP/WS surface."""++ def __init__(+ self,+ app: ASGIApp,+ *,+ vite_dev_url: str | None = None,+ public_urls: str | Iterable[str] | None = None,+ trusted_hosts: str | Iterable[str] | None = None,+ trusted_origins: str | Iterable[str] | None = None,+ bootstrap_tokens: tuple[str, ...] = (),+ control_key_validator: CredentialValidator | None = None,+ session_validator: CredentialValidator | None = None,+ ) -> None:+ self.app = app+ self._trusted_hosts = _trusted_hostnames(+ trusted_hosts=trusted_hosts,+ public_urls=public_urls,+ vite_dev_url=vite_dev_url,+ )+ self._trusted_origins = _trusted_origin_values(+ trusted_origins=trusted_origins,+ public_urls=public_urls,+ vite_dev_url=vite_dev_url,+ )+ # Bootstrap credentials are deliberately separate from authenticated+ # sessions: they are accepted only by POST /api/ui/session, never as a+ # Bearer token or cookie on a protected API/WebSocket.+ _register_bootstrap_tokens(bootstrap_tokens)+ self._local_session_tokens: set[str] = set()+ self._control_key_validator = control_key_validator or _default_control_key_validator+ self._session_validator = session_validator or _default_session_validator++ def host_is_trusted(self, scope: Scope) -> bool:+ authority = _scope_authority(scope)+ if authority is None:+ return False+ host, _ = authority+ return _is_ip_literal(host) or host in self._trusted_hosts++ def origin_is_trusted(self, scope: Scope, *, required: bool = False) -> bool:+ values = _headers(scope, "origin")+ if not values:+ return not required+ if len(values) != 1:+ return False+ origin = _parse_origin(values[0])+ if origin is None:+ return False+ return origin == _scope_origin(scope) or origin in self._trusted_origins++ def _authenticate(self, scope: Scope) -> AuthKind | None:+ bearer_present, bearer = _presented_bearer(scope)+ if bearer_present:+ if bearer is None:+ return None+ if bearer in self._local_session_tokens:+ return "session"+ try:+ if self._control_key_validator(bearer):+ return "control"+ except Exception:+ return None+ try:+ return "session" if self._session_validator(bearer) else None+ except Exception:+ return None+ token = _presented_session_cookie(scope)+ if token is None:+ return None+ if token in self._local_session_tokens:+ return "session"+ try:+ return "session" if self._session_validator(token) else None+ except Exception:+ return None++ def _register_local_tokens_if_available(self) -> None:+ """Mirror bootstrap-issued tokens once the normal token store is loaded.++ Merely checking a bootstrap token must not import FastAPI or the token+ store. Once the full app has naturally imported ``missions_auth``, this+ best-effort sync lets its route-local WebSocket guards recognize tokens+ issued while only the dependency-light holding app existed.+ """+ module = sys.modules.get("jarvis.ui.web.missions_auth")+ register = getattr(module, "register_token", None) if module is not None else None+ if not callable(register):+ return+ for token in tuple(self._local_session_tokens):+ try:+ register(token)+ except Exception: # noqa: S112 - best-effort sync must not block serving+ continue++ def sync_local_tokens(self) -> None:+ """Publish issued bootstrap sessions once the normal store is loaded."""+ self._register_local_tokens_if_available()++ def _consume_session_token(self, token: str) -> None:+ """Invalidate a one-time token after it has minted an HttpOnly session."""+ self._local_session_tokens.discard(token)+ module = sys.modules.get("jarvis.ui.web.missions_auth")+ revoke = getattr(module, "revoke_token", None) if module is not None else None+ if callable(revoke):+ try:+ revoke(token)+ except Exception: # noqa: S110 - invalidation is best effort here+ pass++ def _issued_session_token_valid(self, token: str) -> bool:+ if token in self._local_session_tokens:+ return True+ try:+ return bool(self._session_validator(token))+ except Exception:+ return False++ async def _read_session_request(self, receive: Receive) -> dict[str, Any] | None:+ chunks: list[bytes] = []+ size = 0+ while True:+ message = await receive()+ kind = message.get("type")+ if kind == "http.disconnect":+ return None+ if kind != "http.request":+ return None+ body = bytes(message.get("body", b""))+ size += len(body)+ if size > 16 * 1024:+ return None+ chunks.append(body)+ if not message.get("more_body", False):+ break+ try:+ payload = json.loads(b"".join(chunks).decode("utf-8"))+ except (UnicodeDecodeError, ValueError, TypeError):+ return None+ return payload if isinstance(payload, dict) else None++ async def _handle_session_request(+ self, scope: Scope, receive: Receive, send: Send+ ) -> None:+ if not is_secure_or_loopback(scope):+ await _reject(+ scope,+ send,+ status_code=403,+ detail="UI session bootstrap requires HTTPS or direct loopback.",+ ws_code=4403,+ )+ return++ payload = await self._read_session_request(receive)+ if payload is None:+ await _reject(+ scope,+ send,+ status_code=400,+ detail="Invalid UI session request.",+ ws_code=4400,+ )+ return++ control_value = payload.get("control_key")+ session_value = payload.get("session_token")+ control_token = control_value.strip() if isinstance(control_value, str) else ""+ session_token = session_value.strip() if isinstance(session_value, str) else ""+ if bool(control_token) == bool(session_token):+ await _reject(+ scope,+ send,+ status_code=400,+ detail="Provide exactly one UI session credential.",+ ws_code=4400,+ )+ return++ valid = False+ bootstrap_session = False+ if control_token:+ try:+ valid = bool(self._control_key_validator(control_token))+ except Exception:+ valid = False+ elif session_token:+ bootstrap_session = _bootstrap_token_is_valid(session_token)+ valid = bootstrap_session or self._issued_session_token_valid(session_token)+ if not valid:+ await reject_unauthorized(scope, send)+ return+ if session_token:+ if bootstrap_session and not _consume_bootstrap_token(session_token):+ # A concurrent exchange already consumed the one-time token.+ await reject_unauthorized(scope, send)+ return+ self._consume_session_token(session_token)++ issued = secrets.token_urlsafe(32)+ self._local_session_tokens.add(issued)+ self._register_local_tokens_if_available()+ secure = str(scope.get("scheme", "")).lower() in {"https", "wss"}+ cookie = build_set_cookie_header(issued, secure)+ await send(+ {+ "type": "http.response.start",+ "status": 204,+ "headers": [+ (b"cache-control", b"no-store"),+ (b"content-length", b"0"),+ (b"set-cookie", cookie.encode("latin-1")),+ ],+ }+ )+ await send({"type": "http.response.body", "body": b""})++ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:+ kind = scope.get("type")+ if kind not in {"http", "websocket"}:+ await self.app(scope, receive, send)+ return++ if not self.host_is_trusted(scope):+ await reject_host(scope, send)+ return++ path = str(scope.get("path", "") or "")+ method = str(scope.get("method", "GET") or "GET").upper()+ self._register_local_tokens_if_available()++ # A supplied Origin is never advisory: malformed, null, or foreign+ # values fail even on otherwise-public static and health requests.+ if not self.origin_is_trusted(scope):+ await reject_origin(scope, send)+ return++ if kind == "websocket" and path == "/api/telephony/media":+ await self.app(scope, receive, send)+ return++ if kind == "http":+ # Browser preflights do not carry cookies or Authorization. Once+ # their Origin is known-good, let the inner CORS middleware answer+ # them without weakening the actual request's credential check.+ if method == "OPTIONS":+ if not self.origin_is_trusted(scope, required=True):+ await reject_origin(scope, send)+ return+ await self.app(scope, receive, send)+ return+ if path == "/api/ui/session" and method == "POST":+ await self._handle_session_request(scope, receive, send)+ return+ if path == "/api/ui/shell-painted" and method == "POST":+ if not self.origin_is_trusted(scope, required=True):+ await reject_origin(scope, send)+ return+ await self.app(scope, receive, send)+ return+ if _http_auth_exception(path, method):+ await self.app(scope, receive, send)+ return++ auth_kind = self._authenticate(scope)+ if auth_kind is None:+ await reject_unauthorized(scope, send)+ return+ if auth_kind == "session" and method in _UNSAFE_HTTP_METHODS:+ if not self.origin_is_trusted(scope, required=True):+ await reject_origin(scope, send)+ return+ await self.app(scope, receive, send)+ return++ if _mission_inner_auth_socket(path):+ if not self.origin_is_trusted(scope, required=True):+ await reject_origin(scope, send)+ return+ await self.app(scope, receive, send)+ return++ auth_kind = self._authenticate(scope)+ if auth_kind is None:+ await reject_unauthorized(scope, send)+ return+ if auth_kind == "session" and not self.origin_is_trusted(scope, required=True):+ await reject_origin(scope, send)+ return+ await self.app(scope, receive, send)+++__all__ = [+ "COOKIE_NAME",+ "SurfaceSecurity",+ "append_session_cookie",+ "build_set_cookie_header",+ "credentials_valid",+ "is_secure_or_loopback",+ "reject_host",+ "reject_origin",+ "reject_unauthorized",+ "scope_host_is_trusted",+ "scope_origin_is_trusted",+]diff --git a/jarvis/ui/web/workspace_routes.py b/jarvis/ui/web/workspace_routes.pyindex b7b6cf5cd9..ea8bbe7ce0 100644--- a/jarvis/ui/web/workspace_routes.py+++ b/jarvis/ui/web/workspace_routes.py@@ -30,7 +30,7 @@ from jarvis.workspace.agents import (from jarvis.workspace.launcher import LAYOUT_CHOICES, plan_workspace, validate_splitfrom jarvis.workspace.trust import ensure_trusted-from .missions_auth import validate_token+from .surface_security import credentials_validlog = logging.getLogger(__name__)@@ -111,12 +111,12 @@ async def workspace_pty(ws: WebSocket, key: str) -> None:``{t:"r",cols,rows}`` resize; server → ``{t:"o",d}`` output, ``{t:"ready"}``,``{t:"exit",code}``, ``{t:"error",message}``."""await ws.accept()- qp = ws.query_params-- if not validate_token(qp.get("token", "")):+ if not credentials_valid(ws.scope):await ws.close(code=4401, reason="unauthorized")return+ qp = ws.query_params+agent = qp.get("agent")install = qp.get("install")cols = _safe_int(qp.get("cols"), 80)diff --git a/tests/integration/test_web_surface_security.py b/tests/integration/test_web_surface_security.pynew file mode 100644index 0000000000..be591502f4--- /dev/null+++ b/tests/integration/test_web_surface_security.py@@ -0,0 +1,232 @@+"""Production-assembly regressions for the Personal Jarvis web boundary."""+from __future__ import annotations++import json+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest+from fastapi.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from jarvis.core import control_key+from jarvis.core.bus import EventBus+from jarvis.core.config import JarvisConfig+from jarvis.ui.web.missions_auth import reset_tokens+from jarvis.ui.web.server import WebServer+from jarvis.ui.web.surface_security import COOKIE_NAME++pytestmark = pytest.mark.no_auto_web_auth++_BASE_URL = "http://127.0.0.1:47821"+_SESSION_TOKEN = "desktop-session-token-for-webserver-tests" # noqa: S105+_CONTROL_KEY = "jctl_control_key_for_webserver_tests" # noqa: S105+_TRUSTED_HEADERS = {+ "Host": "127.0.0.1:47821",+ "Origin": _BASE_URL,+}+++def web_server(monkeypatch: pytest.MonkeyPatch) -> WebServer:+ reset_tokens()+ cfg = JarvisConfig()+ cfg.ui.dev_mode = True+ cfg.ui.vite_dev_url = "http://localhost:5173"+ monkeypatch.setenv(cfg.ui.auth_token_env, _SESSION_TOKEN)+ monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)+ server = WebServer(cfg, bus=EventBus())+ try:+ yield server+ finally:+ reset_tokens()+++def _client(server: WebServer) -> TestClient:+ return TestClient(+ server.app,+ base_url=_BASE_URL,+ client=("127.0.0.1", 50_000),+ )+++def test_production_server_does_not_trust_the_vite_development_origin(+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ reset_tokens()+ cfg = JarvisConfig()+ cfg.ui.dev_mode = False+ cfg.ui.vite_dev_url = "http://localhost:5173"+ monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)+ server = WebServer(cfg, bus=EventBus())++ response = _client(server).get(+ "/api/config",+ headers={+ "Host": "127.0.0.1:47821",+ "Origin": cfg.ui.vite_dev_url,+ "Authorization": f"Bearer {_CONTROL_KEY}",+ },+ )++ assert response.status_code == 403+++def test_main_websocket_rejects_unauthenticated_terminal_before_dispatch(+ web_server: WebServer,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ spawn = AsyncMock()+ monkeypatch.setattr(web_server, "_handle_terminal_spawn", spawn)++ with _client(web_server) as client:+ with pytest.raises(WebSocketDisconnect) as exc_info:+ with client.websocket_connect("/ws", headers=_TRUSTED_HEADERS) as ws:+ ws.send_json(+ {+ "type": "command",+ "action": "terminal.spawn",+ "payload": {"shell": "pwsh"},+ }+ )+ ws.receive_json()++ assert exc_info.value.code == 4401+ spawn.assert_not_awaited()+ assert web_server._clients == {} # noqa: SLF001+++def test_main_websocket_welcome_never_contains_a_credential(+ web_server: WebServer,+) -> None:+ with _client(web_server) as client:+ exchange = client.post(+ "/api/ui/session",+ json={"control_key": _CONTROL_KEY},+ headers=_TRUSTED_HEADERS,+ )+ assert exchange.status_code == 204+ cookie = exchange.cookies.get(COOKIE_NAME)+ assert cookie is not None+ with client.websocket_connect(+ "/ws",+ headers={**_TRUSTED_HEADERS, "Cookie": f"{COOKIE_NAME}={cookie}"},+ ) as ws:+ welcome = ws.receive_json()++ assert welcome["type"] == "welcome"+ assert "token" not in welcome+ assert _SESSION_TOKEN not in json.dumps(welcome)+ assert _CONTROL_KEY not in json.dumps(welcome)+++def test_session_exchange_sets_cookie_and_unlocks_protected_rest(+ web_server: WebServer,+) -> None:+ client = _client(web_server)++ exchange = client.post(+ "/api/ui/session",+ json={"control_key": _CONTROL_KEY},+ headers=_TRUSTED_HEADERS,+ )++ assert exchange.status_code == 204+ assert exchange.headers["cache-control"] == "no-store"+ cookie = exchange.headers["set-cookie"]+ assert "HttpOnly" in cookie+ assert "SameSite=Strict" in cookie+ assert "Path=/" in cookie+ assert "Secure" not in cookie+ assert _SESSION_TOKEN not in cookie+ assert _CONTROL_KEY not in cookie+ protected = client.get("/api/config", headers=_TRUSTED_HEADERS)+ assert protected.status_code == 200+++ "payload",+ [+ {},+ {"session_token": _SESSION_TOKEN},+ {"session_token": "wrong-token"},+ {"control_key": "wrong-control-key"},+ ],+)+def test_session_exchange_rejects_missing_or_invalid_credentials(+ web_server: WebServer,+ payload: dict,+) -> None:+ response = _client(web_server).post(+ "/api/ui/session",+ json=payload,+ headers=_TRUSTED_HEADERS,+ )++ expected = 400 if not payload else 401+ assert response.status_code == expected+ assert "set-cookie" not in response.headers+++def test_unauthenticated_raw_mcp_config_is_rejected_before_write(+ web_server: WebServer,+ monkeypatch: pytest.MonkeyPatch,+) -> None:+ from jarvis.mcp import state as mcp_state++ save_config = Mock()+ monkeypatch.setattr(mcp_state, "save_config", save_config)++ response = _client(web_server).put(+ "/api/mcps/config/raw",+ json={"mcpServers": {"hostile": {"command": "powershell"}}},+ headers=_TRUSTED_HEADERS,+ )++ assert response.status_code == 401+ save_config.assert_not_called()+++def test_unauthenticated_mcp_start_is_rejected_before_process_start(+ web_server: WebServer,+) -> None:+ start_enabled = AsyncMock()+ web_server.app.state.mcp_registry = SimpleNamespace(+ get_spec=lambda _name: object(),+ active_clients=lambda: {},+ start_enabled=start_enabled,+ )++ response = _client(web_server).post(+ "/api/mcps/hostile/start",+ headers=_TRUSTED_HEADERS,+ )++ assert response.status_code == 401+ start_enabled.assert_not_awaited()+++def test_unauthenticated_custom_cli_is_rejected_before_registration(+ web_server: WebServer,+) -> None:+ catalog = Mock()+ catalog.get.return_value = None+ registry = Mock()+ registry.catalog.return_value = catalog+ registry.refresh_status = AsyncMock()+ web_server.app.state.cli_registry = registry++ response = _client(web_server).post(+ "/api/clis/custom",+ json={+ "name": "hostile-cli",+ "display_name": "Hostile CLI",+ "binary_name": "powershell",+ "check_command": ["powershell", "-Command", "Write-Output pwned"],+ },+ headers=_TRUSTED_HEADERS,+ )++ assert response.status_code == 401+ catalog.register_custom.assert_not_called()+ registry.refresh_status.assert_not_awaited()diff --git a/tests/unit/ui/web/test_missions_auth_token.py b/tests/unit/ui/web/test_missions_auth_token.pyindex 5f6d6e34b1..e8c4741097 100644--- a/tests/unit/ui/web/test_missions_auth_token.py+++ b/tests/unit/ui/web/test_missions_auth_token.py@@ -1,21 +1,11 @@-"""Regression guard for the workspace-PTY "stuck on connecting" bug.--Root cause: the fast-boot desktop path mints a RAW ``secrets.token_urlsafe``,-injects it into ``window.__JARVIS_TOKEN``, but never issues it through-``GET /api/missions/auth/token`` — so it is absent from the in-memory token set-and every token-gated WebSocket (workspace PTY, missions PTY/stream) rejects it-with close code 4401. The frontend then hangs forever on "connecting".--Fix: the desktop session token is seeded into the token store at server build-via ``register_session_token_from_env`` so ``validate_token`` accepts it.-"""+"""Unit tests for process-local authenticated session tokens."""from __future__ import annotationsfrom jarvis.ui.web.missions_auth import (issue_token,- register_session_token_from_env,register_token,reset_tokens,+ revoke_token,validate_token,)@@ -23,30 +13,18 @@ from jarvis.ui.web.missions_auth import (def test_raw_unissued_token_is_rejected_until_registered() -> None:reset_tokens()raw = "raw-session-token-never-issued-0123456789"- assert validate_token(raw) is False # exactly the 4401 path+ assert validate_token(raw) is Falseregister_token(raw)assert validate_token(raw) is True-def test_register_session_token_from_env_seeds_the_injected_token(monkeypatch) -> None:- reset_tokens()- env_var = "JARVIS_TEST_AUTH_TOKEN_ENV"- injected = "injected-desktop-session-token-abc"- monkeypatch.setenv(env_var, injected)-- # Mirrors the desktop: the token is injected but not issued → invalid.- assert validate_token(injected) is False-- returned = register_session_token_from_env(env_var)- assert returned == injected- assert validate_token(injected) is True---def test_register_session_token_from_env_noops_when_unset(monkeypatch) -> None:+def test_revoke_token_invalidates_registered_token() -> None:reset_tokens()- monkeypatch.delenv("JARVIS_TEST_AUTH_TOKEN_UNSET", raising=False)- assert register_session_token_from_env("JARVIS_TEST_AUTH_TOKEN_UNSET") is None+ raw = "registered-session-that-will-be-revoked"+ register_token(raw)+ revoke_token(raw)+ assert validate_token(raw) is Falsedef test_issued_tokens_still_validate() -> None:diff --git a/tests/unit/ui_web/test_control_auth.py b/tests/unit/ui_web/test_control_auth.pyindex 29e1cfbd1d..52778cce8f 100644--- a/tests/unit/ui_web/test_control_auth.py+++ b/tests/unit/ui_web/test_control_auth.py@@ -1,8 +1,8 @@"""Auth for the Jarvis Control API (step 5).``require_control_key`` guards every /api/control/* route with a Bearer key.-``require_control_key_or_loopback`` additionally lets a same-host request through-so the desktop Settings panel can fetch/rotate the key before the user has it.+``require_control_key_or_session`` additionally accepts an authenticated UI+session so the desktop Settings panel can fetch or rotate the key.``assert_bind_safe`` is the fail-closed boot check: never expose a non-loopbackbind without a key (the key, not the bind address, is the boundary)."""@@ -21,11 +21,20 @@ class _FakeClient:class _FakeRequest:- def __init__(self, *, auth: str | None = None, host: str = "testclient") -> None:+ def __init__(+ self,+ *,+ auth: str | None = None,+ host: str = "testclient",+ session_token: str | None = None,+ ) -> None:self.headers: dict[str, str] = {}if auth is not None:self.headers["authorization"] = authself.client = _FakeClient(host)+ self.cookies = {}+ if session_token is not None:+ self.cookies[ca.COOKIE_NAME] = session_token@pytest.fixture@@ -61,25 +70,36 @@ async def test_loopback_does_not_bypass_main_guard(stored_key) -> None:await ca.require_control_key(_FakeRequest(host="127.0.0.1"))-# --- require_control_key_or_loopback (key-reveal / rotate) ---+# --- require_control_key_or_session (key-reveal / rotate) ----async def test_or_loopback_allows_same_host(stored_key) -> None:- await ca.require_control_key_or_loopback(_FakeRequest(host="127.0.0.1"))- await ca.require_control_key_or_loopback(_FakeRequest(host="::1"))+async def test_raw_loopback_does_not_bypass_session_guard(stored_key) -> None:+ with pytest.raises(HTTPException):+ await ca.require_control_key_or_session(_FakeRequest(host="127.0.0.1"))-async def test_or_loopback_denies_remote_without_key(stored_key) -> None:+async def test_session_guard_denies_remote_without_key(stored_key) -> None:with pytest.raises(HTTPException):- await ca.require_control_key_or_loopback(_FakeRequest(host="203.0.113.7"))+ await ca.require_control_key_or_session(_FakeRequest(host="203.0.113.7"))-async def test_or_loopback_allows_remote_with_valid_key(stored_key) -> None:- await ca.require_control_key_or_loopback(+async def test_session_guard_allows_remote_with_valid_key(stored_key) -> None:+ await ca.require_control_key_or_session(_FakeRequest(auth="Bearer jctl_realkey", host="203.0.113.7"))+async def test_session_guard_accepts_registered_ui_session(stored_key) -> None:+ from jarvis.ui.web.missions_auth import register_token, revoke_token++ token = "ui-session-token" # noqa: S105+ register_token(token)+ try:+ await ca.require_control_key_or_session(_FakeRequest(session_token=token))+ finally:+ revoke_token(token)++# --- assert_bind_safe (fail-closed) ---diff --git a/tests/unit/ui_web/test_surface_security.py b/tests/unit/ui_web/test_surface_security.pynew file mode 100644index 0000000000..4d4a318126--- /dev/null+++ b/tests/unit/ui_web/test_surface_security.py@@ -0,0 +1,546 @@+"""Fail-closed tests for the global HTTP/WebSocket security boundary.++These tests exercise the ASGI middleware directly. They intentionally do not+use a dependency override or a test-only authentication bypass: every accepted+request presents the same desktop-session token, control key, or session cookie+that a production caller must present.+"""+from __future__ import annotations++from http.cookies import SimpleCookie+from typing import Any++import pytest+from fastapi.testclient import TestClient+from starlette.websockets import WebSocketDisconnect++from jarvis.core import control_key+from jarvis.ui.web.missions_auth import register_token, reset_tokens+from jarvis.ui.web.surface_security import (+ COOKIE_NAME,+ SurfaceSecurity,+ build_set_cookie_header,+)++pytestmark = pytest.mark.no_auto_web_auth++_BASE_URL = "http://127.0.0.1:47821"+_SESSION_TOKEN = "desktop-session-token-for-surface-tests" # noqa: S105+_CONTROL_KEY = "jctl_control_key_for_surface_tests" # noqa: S105+++class _ProbeApp:+ """Minimal ASGI app that records whether the protected app was reached."""++ def __init__(self) -> None:+ self.scopes: list[dict[str, Any]] = []++ async def __call__(self, scope, receive, send) -> None: # noqa: ANN001+ self.scopes.append(scope)+ if scope["type"] == "http":+ await send(+ {+ "type": "http.response.start",+ "status": 200,+ "headers": [(b"content-type", b"application/json")],+ }+ )+ await send({"type": "http.response.body", "body": b'{"reached":true}'})+ return+ if scope["type"] == "websocket":+ await receive()+ await send({"type": "websocket.accept"})+ await send({"type": "websocket.send", "text": '{"type":"probe"}'})+ await send({"type": "websocket.close", "code": 1000})++[email protected](autouse=True)+def _auth_state(monkeypatch: pytest.MonkeyPatch):+ reset_tokens()+ register_token(_SESSION_TOKEN)+ monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)+ try:+ yield+ finally:+ reset_tokens()+++def _client(+ *,+ base_url: str = _BASE_URL,+ peer: tuple[str, int] = ("127.0.0.1", 50_000),+ public_urls: tuple[str, ...] = (),+) -> tuple[TestClient, _ProbeApp]:+ inner = _ProbeApp()+ secured = SurfaceSecurity(+ inner,+ vite_dev_url="http://localhost:5173",+ public_urls=public_urls,+ )+ return TestClient(secured, base_url=base_url, client=peer), inner+++def _headers(+ *,+ token: str | None = None,+ origin: str | None = _BASE_URL,+ host: str = "127.0.0.1:47821",+) -> dict[str, str]:+ headers = {"Host": host}+ if origin is not None:+ headers["Origin"] = origin+ if token is not None:+ headers["Authorization"] = f"Bearer {token}"+ return headers++[email protected]("token", [None, "wrong-token", "", "Basic abc"])+def test_internal_http_rejects_missing_or_bad_bearer(token: str | None) -> None:+ client, inner = _client()+ headers = _headers()+ if token == "Basic abc": # noqa: S105 - malformed synthetic auth header+ headers["Authorization"] = token+ elif token is not None:+ headers["Authorization"] = f"Bearer {token}"++ response = client.get("/api/config", headers=headers)++ assert response.status_code == 401+ assert response.headers.get("www-authenticate") == "Bearer"+ assert inner.scopes == []++[email protected]("token", [_SESSION_TOKEN, _CONTROL_KEY])+def test_internal_http_accepts_session_token_and_control_key(token: str) -> None:+ client, inner = _client()++ response = client.get("/api/config", headers=_headers(token=token))++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++def test_native_bearer_client_does_not_need_an_origin_header() -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=_headers(token=_CONTROL_KEY, origin=None),+ )++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++def test_valid_session_cookie_authenticates_internal_http() -> None:+ client, inner = _client()+ client.cookies.set(COOKIE_NAME, _SESSION_TOKEN)++ response = client.get("/api/config", headers=_headers())++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++ "host",+ [+ "attacker.example",+ "127.0.0.1.attacker.example",+ "localhost.attacker.example",+ "[email protected]",+ "127.0.0.1,attacker.example",+ "127.0.0.1:0",+ "[::1]attacker.example",+ ],+)+def test_bad_host_is_rejected_before_valid_credentials_reach_app(host: str) -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=_headers(token=_SESSION_TOKEN, host=host),+ )++ assert response.status_code == 400+ assert inner.scopes == []+++def test_duplicate_host_headers_are_rejected_as_ambiguous() -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=[+ ("Host", "127.0.0.1:47821"),+ ("Host", "attacker.example"),+ ("Origin", _BASE_URL),+ ("Authorization", f"Bearer {_CONTROL_KEY}"),+ ],+ )++ assert response.status_code == 400+ assert inner.scopes == []+++def test_hostile_browser_origin_is_rejected_even_with_valid_token() -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=_headers(token=_SESSION_TOKEN, origin="https://attacker.example"),+ )++ assert response.status_code == 403+ assert inner.scopes == []+++def test_duplicate_origin_headers_are_rejected_as_ambiguous() -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=[+ ("Host", "127.0.0.1:47821"),+ ("Origin", _BASE_URL),+ ("Origin", "https://attacker.example"),+ ("Authorization", f"Bearer {_CONTROL_KEY}"),+ ],+ )++ assert response.status_code == 403+ assert inner.scopes == []+++def test_exact_vite_origin_is_allowed_with_valid_credentials() -> None:+ client, inner = _client()++ response = client.get(+ "/api/config",+ headers=_headers(token=_CONTROL_KEY, origin="http://localhost:5173"),+ )++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++def test_trusted_vite_preflight_reaches_cors_without_a_credential() -> None:+ client, inner = _client()+ headers = _headers(origin="http://localhost:5173")+ headers.update(+ {+ "Access-Control-Request-Method": "GET",+ "Access-Control-Request-Headers": "authorization",+ }+ )++ response = client.options("/api/config", headers=headers)++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++def test_hostile_preflight_is_rejected_before_cors() -> None:+ client, inner = _client()+ headers = _headers(origin="https://attacker.example")+ headers["Access-Control-Request-Method"] = "POST"++ response = client.options("/api/config", headers=headers)++ assert response.status_code == 403+ assert inner.scopes == []+++def test_session_cookie_builder_sets_http_only_strict_flags() -> None:+ raw_cookie = build_set_cookie_header(_SESSION_TOKEN, secure=False)+ parsed = SimpleCookie()+ parsed.load(raw_cookie)+ morsel = parsed[COOKIE_NAME]+ assert morsel.value == _SESSION_TOKEN+ assert morsel["path"] == "/"+ assert morsel["httponly"] is True+ assert morsel["samesite"].lower() == "strict"+ assert not morsel["secure"]+++def test_session_cookie_builder_marks_https_cookie_secure() -> None:+ parsed = SimpleCookie()+ parsed.load(build_set_cookie_header(_SESSION_TOKEN, secure=True))+ assert parsed[COOKIE_NAME]["secure"] is True+++def test_session_exchange_sets_opaque_cookie_and_unlocks_next_request() -> None:+ client, inner = _client()++ response = client.post(+ "/api/ui/session",+ json={"session_token": _SESSION_TOKEN},+ headers=_headers(),+ )++ assert response.status_code == 204+ assert response.headers["cache-control"] == "no-store"+ parsed = SimpleCookie()+ parsed.load(response.headers["set-cookie"])+ morsel = parsed[COOKIE_NAME]+ assert morsel.value not in {_SESSION_TOKEN, _CONTROL_KEY}+ assert len(morsel.value) >= 32+ assert morsel["path"] == "/"+ assert morsel["httponly"] is True+ assert morsel["samesite"].lower() == "strict"+ assert not morsel["secure"]+ assert inner.scopes == []++ protected = client.get("/api/config", headers=_headers())+ assert protected.status_code == 200+ assert len(inner.scopes) == 1+++def test_registered_session_token_cannot_be_replayed_after_exchange() -> None:+ client, inner = _client()++ first = client.post(+ "/api/ui/session",+ json={"session_token": _SESSION_TOKEN},+ headers=_headers(),+ )+ replay = client.post(+ "/api/ui/session",+ json={"session_token": _SESSION_TOKEN},+ headers=_headers(),+ )+ bearer_replay = client.get(+ "/api/config",+ headers=_headers(token=_SESSION_TOKEN),+ )++ assert first.status_code == 204+ assert replay.status_code == 401+ assert bearer_replay.status_code == 401+ assert inner.scopes == []+++def test_bootstrap_token_is_exchange_only_not_a_general_api_credential() -> None:+ bootstrap_token = "exchange-only-bootstrap-token" # noqa: S105+ inner = _ProbeApp()+ client = TestClient(+ SurfaceSecurity(inner, bootstrap_tokens=(bootstrap_token,)),+ base_url=_BASE_URL,+ client=("127.0.0.1", 50_000),+ )++ bearer = client.get(+ "/api/config",+ headers=_headers(token=bootstrap_token),+ )+ client.cookies.set(COOKIE_NAME, bootstrap_token)+ cookie = client.get("/api/config", headers=_headers())+ client.cookies.clear()+ exchange = client.post(+ "/api/ui/session",+ json={"session_token": bootstrap_token},+ headers=_headers(),+ )+ replay = client.post(+ "/api/ui/session",+ json={"session_token": bootstrap_token},+ headers=_headers(),+ )++ assert bearer.status_code == 401+ assert cookie.status_code == 401+ assert exchange.status_code == 204+ assert replay.status_code == 401+ assert inner.scopes == []+++def test_https_control_key_exchange_marks_cookie_secure() -> None:+ public_url = "https://jarvis.example"+ client, inner = _client(+ base_url=public_url,+ peer=("203.0.113.9", 50_000),+ public_urls=(public_url,),+ )++ response = client.post(+ "/api/ui/session",+ json={"control_key": _CONTROL_KEY},+ headers=_headers(origin=public_url, host="jarvis.example"),+ )++ assert response.status_code == 204+ parsed = SimpleCookie()+ parsed.load(response.headers["set-cookie"])+ assert parsed[COOKIE_NAME]["secure"] is True+ assert inner.scopes == []+++ "payload",+ [+ {},+ {"session_token": "wrong-token"},+ {"control_key": "wrong-control-key"},+ {"session_token": _SESSION_TOKEN, "control_key": _CONTROL_KEY},+ ],+)+def test_session_exchange_rejects_missing_invalid_or_ambiguous_credentials(+ payload: dict,+) -> None:+ client, inner = _client()++ response = client.post("/api/ui/session", json=payload, headers=_headers())++ expected = 400 if len(payload) != 1 else 401+ assert response.status_code == expected+ assert "set-cookie" not in response.headers+ assert inner.scopes == []+++def test_non_loopback_plain_http_session_exchange_is_rejected() -> None:+ public_url = "http://jarvis.example"+ client, inner = _client(+ base_url=public_url,+ peer=("203.0.113.9", 50_000),+ public_urls=(public_url,),+ )++ response = client.post(+ "/api/ui/session",+ json={"control_key": _CONTROL_KEY},+ headers=_headers(origin=public_url, host="jarvis.example"),+ )++ assert response.status_code == 403+ assert "set-cookie" not in response.headers+ assert inner.scopes == []+++ ("method", "path"),+ [+ ("GET", "/api/marketplace/oauth/callback?code=x&state=y"),+ ("POST", "/api/telephony/voice"),+ ("POST", "/api/conductor/hooks/route-secret"),+ ],+)+def test_exact_external_callbacks_retain_their_own_auth_boundary(+ method: str,+ path: str,+) -> None:+ client, inner = _client()++ response = client.request(method, path, headers=_headers(origin=None))++ assert response.status_code == 200+ assert len(inner.scopes) == 1+++ ("method", "path"),+ [+ ("GET", "/api/marketplace/oauth/callback?code=x&state=y"),+ ("POST", "/api/telephony/voice"),+ ("POST", "/api/conductor/hooks/route-secret"),+ ],+)+def test_external_callbacks_reject_an_explicit_foreign_origin(+ method: str,+ path: str,+) -> None:+ client, inner = _client()++ response = client.request(+ method,+ path,+ headers=_headers(origin="https://attacker.example"),+ )++ assert response.status_code == 403+ assert inner.scopes == []+++ ("method", "path"),+ [+ ("GET", "/api/marketplace/oauth/callback?code=x&state=y"),+ ("POST", "/api/telephony/voice"),+ ("POST", "/api/conductor/hooks/route-secret"),+ ],+)+def test_external_callbacks_remain_behind_the_host_guard(+ method: str,+ path: str,+) -> None:+ client, inner = _client()++ response = client.request(+ method,+ path,+ headers=_headers(origin=None, host="attacker.example"),+ )++ assert response.status_code == 400+ assert inner.scopes == []+++def test_public_telephony_websocket_allows_a_non_browser_without_origin() -> None:+ client, inner = _client()++ with client.websocket_connect(+ "/api/telephony/media",+ headers={"Host": "127.0.0.1:47821"},+ ) as websocket:+ assert websocket.receive_json() == {"type": "probe"}++ assert len(inner.scopes) == 1+++ "headers",+ [+ {+ "Host": "127.0.0.1:47821",+ "Origin": "https://attacker.example",+ },+ {"Host": "attacker.example"},+ ],+)+def test_public_telephony_websocket_still_enforces_host_and_supplied_origin(+ headers: dict[str, str],+) -> None:+ client, inner = _client()++ with pytest.raises(WebSocketDisconnect) as exc_info:+ with client.websocket_connect(+ "/api/telephony/media",+ headers=headers,+ ):+ pass++ assert exc_info.value.code == 4403+ assert inner.scopes == []+++ ("method", "path"),+ [+ ("POST", "/api/marketplace/oauth/callback"),+ ("GET", "/api/telephony/voice"),+ ("POST", "/api/telephony/voice/"),+ ("POST", "/api/marketplace/oauth/callback/extra"),+ ("GET", "/api/marketplace/oauth/callback/"),+ ("POST", "/api/conductor/hooks"),+ ("POST", "/api/conductor/hooks/route-secret/extra"),+ ],+)+def test_public_callback_allowlist_is_method_and_path_exact(+ method: str,+ path: str,+) -> None:+ client, inner = _client()++ response = client.request(method, path, headers=_headers(origin=None))++ assert response.status_code == 401+ assert inner.scopes == []