Skip to content

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.

feat(ui): optional browser lock — loopback opens without the Control Key by default

Ruben Lütke45ad6c501f9b
diff --git a/docs/product/privacy-safety-and-support/control-key.md b/docs/product/privacy-safety-and-support/control-key.md
index aa39dd2f2c..1f3069ae25 100644
--- a/docs/product/privacy-safety-and-support/control-key.md
+++ b/docs/product/privacy-safety-and-support/control-key.md
@@ -28,6 +28,29 @@ Every Personal Jarvis installation protects itself with one private key, the
The desktop app itself never asks for the key: it proves it belongs to the
installation through a private startup handshake.
+## The Browser Lock Is Optional (Off by Default)
+
+Out of the box, a browser **on the computer Jarvis runs on** walks straight
+into the interface — no lock screen, no key. Access from anywhere else
+(another device on your network, a server reached over the internet) always
+requires the Control Key, no matter how this switch is set. Network exposure
+is never opt-out.
+
+To require the key on this computer too — for example on a shared machine —
+turn on **Ask for the key in the browser** in the key section (see
+[Find the Key](#find-the-key) below). The confirmation dialog offers to copy
+the key first, and the browser you enable it from stays signed in, so you
+cannot lock yourself out in the same breath. Turning the switch off again
+removes the lock screen for this computer only.
+
+One honest limitation: requests arriving through a proxy or forwarding
+service are recognized and still asked for the key, but a plain
+port-forwarding tunnel running **on the Jarvis machine itself** (an SSH
+tunnel, `socat`, a raw TCP relay) is indistinguishable from a local browser.
+If you forward the Jarvis port to a network in any way, turn the browser lock
+**on** first — the forwarded side is then protected by the key like any other
+remote access.
+
## You Already Have a Key
Nobody sends you a Control Key, and there is no account behind it. The moment
@@ -53,6 +76,9 @@ it can find their way here.
## Unlock Jarvis in a Browser
+The lock screen appears when you connect from another device, or on the
+install computer itself once **Ask for the key in the browser** is turned on.
+
1. Open the Jarvis address in the browser. The lock screen appears.
2. Paste the Control Key and select **Unlock**.
3. The browser receives a private session cookie; the key itself is not stored
@@ -120,15 +146,18 @@ a trusted password manager.
1. Open **API Keys & Providers** and select the key tab named after your
assistant.
2. Select **Show**, then **Copy**.
-3. Open the Jarvis address in a private browser window. The lock screen
- appears.
-4. Paste the key and select **Unlock**. The interface loads, which proves the
- stored key and the unlock exchange both work.
+3. Open the Jarvis address in a private browser window. On the install
+ computer the interface loads directly unless **Ask for the key in the
+ browser** is on; from another device the lock screen always appears.
+4. If the lock screen appears, paste the key and select **Unlock**. The
+ interface loads, which proves the stored key and the unlock exchange both
+ work.
## Troubleshooting
| What you see | What it usually means | What to do |
|---|---|---|
+| No lock screen appears on the install computer | Expected — the browser lock is off by default; local browsers walk straight in | Turn on **Ask for the key in the browser** in the key section if you want the lock |
| The lock screen rejects your key | The key was regenerated or replaced since you copied it | Read the current key in the key section on the install computer and try again |
| You never received a key | Expected — keys are generated locally, not sent | Follow [Find the Key](#find-the-key) above |
| **Setting the key failed** | Neither the OS credential store nor the fallback file accepted the new value | Unlock the credential store, check that Jarvis can write to its data directory, and retry; the old key stays active until a new one is stored |
diff --git a/jarvis/core/config.py b/jarvis/core/config.py
index f025df1d67..43cc51a01d 100644
--- a/jarvis/core/config.py
+++ b/jarvis/core/config.py
@@ -1356,6 +1356,15 @@ class UIConfig(BaseModel):
# WebView exposes it once; AuthGate exchanges it for an unrelated HttpOnly
# session cookie and immediately clears the JavaScript value.
auth_token_env: str = "JARVIS_UI_TOKEN"
+ # Optional browser lock: when True, opening the UI in a browser on THIS
+ # machine (loopback) asks for the Control Key. Off by default — the local
+ # user walks straight in. Non-loopback access (LAN, VPS, reverse proxy)
+ # still requires the key regardless of this flag; forwarded requests are
+ # detected via relay-indicator headers, but a headerless L4 tunnel on the
+ # same machine looks local — whoever forwards the port must turn this ON
+ # (see surface_security.open_access_granted). Toggled live from
+ # Settings → API Keys → Control Key.
+ require_browser_login: bool = False
# On-screen overlay style: "jarvis_bar" (slim default), "mascot" (ghost
# orb), or "none". The mascot remains fully selectable.
orb_style: str = "jarvis_bar"
diff --git a/jarvis/core/config_writer.py b/jarvis/core/config_writer.py
index 6d70d98504..010b6b3f8d 100644
--- a/jarvis/core/config_writer.py
+++ b/jarvis/core/config_writer.py
@@ -734,6 +734,15 @@ def set_sound_effects(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> Non
_patch_table(path, "ui", "sound_effects", bool(enabled))
+def set_require_browser_login(enabled: bool, *, path: Path = DEFAULT_CONFIG_FILE) -> None:
+ """Persist ``[ui] require_browser_login`` (the optional browser lock).
+
+ TOML-only (not drift-guarded); the Settings route applies it live by
+ updating the shared ``surface_security`` boundary flag in the same request.
+ """
+ _patch_table(path, "ui", "require_browser_login", bool(enabled))
+
+
def set_team_proxy(
enabled: bool,
url: str,
diff --git a/jarvis/ui/web/control_auth.py b/jarvis/ui/web/control_auth.py
index 1dbbc87891..a5684631c5 100644
--- a/jarvis/ui/web/control_auth.py
+++ b/jarvis/ui/web/control_auth.py
@@ -21,7 +21,7 @@ from fastapi import HTTPException, Request, status
from jarvis.core import control_key as ck
from .missions_auth import validate_token
-from .surface_security import COOKIE_NAME
+from .surface_security import COOKIE_NAME, open_access_granted
_LOOPBACK_HOSTS = frozenset({"127.0.0.1", "::1", "localhost"})
_UNAUTHORIZED = {
@@ -52,10 +52,18 @@ async def require_control_key(request: Request) -> None:
async def require_control_key_or_session(request: Request) -> None:
- """Allow a control Bearer or an authenticated HttpOnly UI session."""
+ """Allow a control Bearer, an authenticated UI session, or local open access.
+
+ Open access mirrors the outer boundary (``surface_security``): when the
+ optional browser lock is off, a loopback-to-loopback UI has no session
+ cookie at all, yet must still reach the key panel — otherwise the user
+ could never see the key they would need to turn the lock ON.
+ """
session_token = request.cookies.get(COOKIE_NAME, "")
if validate_token(session_token) or ck.verify_control_key(_bearer_token(request)):
return
+ if open_access_granted(request.scope):
+ return
raise HTTPException(**_UNAUTHORIZED)
diff --git a/jarvis/ui/web/frontend/src/hooks/useBrowserLock.ts b/jarvis/ui/web/frontend/src/hooks/useBrowserLock.ts
new file mode 100644
index 0000000000..1e9a57bc59
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useBrowserLock.ts
@@ -0,0 +1,56 @@
+import { useCallback, useEffect, useState } from "react";
+
+/** Optional browser lock (ui.require_browser_login). When ON, opening the UI
+ * in a browser on this machine asks for the Control Key. OFF by default — the
+ * local user walks straight in. Non-loopback access (another device, a VPS)
+ * always requires the key regardless of this switch. */
+export interface BrowserLockResult {
+ ok: boolean;
+ enabled: boolean;
+ persisted: boolean;
+ applied_live: boolean;
+ /** True when the backend attached a fresh session cookie so the browser
+ * that just enabled the lock stays signed in. */
+ session_minted: boolean;
+}
+
+export function useBrowserLock() {
+ const [enabled, setEnabledState] = useState<boolean | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+
+ const refetch = useCallback(async () => {
+ setError(null);
+ try {
+ const res = await fetch("/api/settings/browser-login");
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
+ const data = await res.json();
+ setEnabledState(Boolean(data.enabled));
+ } catch (e) {
+ setError((e as Error).message);
+ } finally {
+ setLoading(false);
+ }
+ }, []);
+
+ useEffect(() => {
+ void refetch();
+ }, [refetch]);
+
+ const setEnabled = useCallback(
+ async (next: boolean): Promise<BrowserLockResult> => {
+ const res = await fetch("/api/settings/browser-login", {
+ method: "PUT",
+ headers: { "Content-Type": "application/json" },
+ body: JSON.stringify({ enabled: next }),
+ });
+ const body = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(body.detail ?? `HTTP ${res.status}`);
+ setEnabledState(Boolean(body.enabled));
+ return body as BrowserLockResult;
+ },
+ [],
+ );
+
+ return { enabled, loading, error, refetch, setEnabled };
+}
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.json
index 1bc118819d..186fbbee8e 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json
@@ -1132,6 +1132,13 @@
"copied_toast": "Control Key in die Zwischenablage kopiert.",
"copy_failed_toast": "Control Key konnte nicht kopiert werden.",
"unlock_hint": "Der Sperrbildschirm im Browser fragt genau nach diesem Key.",
+ "browser_lock_title": "Im Browser nach dem Key fragen",
+ "browser_lock_description": "Aus: Browser auf diesem Computer öffnen {name} ohne Key. Andere Geräte und Fernzugriffe brauchen den Key immer.",
+ "browser_lock_confirm_title": "Control Key im Browser verlangen?",
+ "browser_lock_confirm_body": "Ab jetzt fragt {name} im Browser nach dem Control Key oben. Kopiere ihn vorher an einen sicheren Ort — ein neuer Browser kommt ohne ihn nicht mehr hinein. Dieser Browser bleibt angemeldet.",
+ "browser_lock_confirm_button": "Key verlangen",
+ "browser_lock_on_toast": "Browser-Sperre ist an. Neue Browser brauchen den Control Key.",
+ "browser_lock_off_toast": "Browser-Sperre ist aus. Browser auf diesem Computer kommen ohne Key hinein.",
"regenerate_button": "Zufälligen Key erzeugen",
"regenerate_confirm_title": "Neuen Control Key erzeugen?",
"regenerate_confirm_body": "Der aktuelle Key funktioniert dann sofort nirgendwo mehr. Jeder Browser, jedes Gerät und jeder Agent, der ihn noch nutzt, braucht den neuen Key.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.json
index 8320990a3c..4ffbd8e221 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json
@@ -1133,6 +1133,13 @@
"copied_toast": "Control Key copied to clipboard.",
"copy_failed_toast": "Could not copy the Control Key.",
"unlock_hint": "The lock screen in the browser asks for exactly this key.",
+ "browser_lock_title": "Ask for the key in the browser",
+ "browser_lock_description": "Off: browsers on this computer open {name} without the key. Other devices and remote access always need the key.",
+ "browser_lock_confirm_title": "Require the Control Key in the browser?",
+ "browser_lock_confirm_body": "From now on, opening {name} in a browser will ask for the Control Key above. Copy it somewhere safe first — a fresh browser cannot get in without it. This browser stays signed in.",
+ "browser_lock_confirm_button": "Require the key",
+ "browser_lock_on_toast": "Browser lock is on. New browsers will need the Control Key.",
+ "browser_lock_off_toast": "Browser lock is off. Browsers on this computer get in without the key.",
"regenerate_button": "Generate random key",
"regenerate_confirm_title": "Generate a new Control Key?",
"regenerate_confirm_body": "The current key stops working immediately — everywhere. Every browser, device, and agent still using it will need the new key.",
diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.json
index 573e0e842f..00e49dc9f4 100644
--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json
+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json
@@ -1132,6 +1132,13 @@
"copied_toast": "Clave de control copiada al portapapeles.",
"copy_failed_toast": "No se pudo copiar la clave de control.",
"unlock_hint": "La pantalla de bloqueo del navegador pide exactamente esta clave.",
+ "browser_lock_title": "Pedir la clave en el navegador",
+ "browser_lock_description": "Desactivado: los navegadores de este equipo abren {name} sin la clave. Otros dispositivos y accesos remotos siempre necesitan la clave.",
+ "browser_lock_confirm_title": "¿Exigir la clave de control en el navegador?",
+ "browser_lock_confirm_body": "A partir de ahora, abrir {name} en un navegador pedirá la clave de control de arriba. Cópiala antes en un lugar seguro — un navegador nuevo no podrá entrar sin ella. Este navegador seguirá con la sesión iniciada.",
+ "browser_lock_confirm_button": "Exigir la clave",
+ "browser_lock_on_toast": "El bloqueo del navegador está activado. Los navegadores nuevos necesitarán la clave de control.",
+ "browser_lock_off_toast": "El bloqueo del navegador está desactivado. Los navegadores de este equipo entran sin la clave.",
"regenerate_button": "Generar clave aleatoria",
"regenerate_confirm_title": "¿Generar una nueva clave de control?",
"regenerate_confirm_body": "La clave actual dejará de funcionar de inmediato — en todas partes. Cada navegador, dispositivo y agente que aún la use necesitará la nueva.",
diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx
index 419b6aeb2d..2b8bc551a5 100644
--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.test.tsx
@@ -12,11 +12,23 @@ vi.mock("@/lib/clipboard", () => ({
afterEach(() => vi.restoreAllMocks());
-function stubKeyFetch() {
- vi.stubGlobal(
- "fetch",
- vi.fn().mockResolvedValue({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) }),
- );
+/** URL-aware fetch stub: the component now issues TWO mount-time GETs (the
+ * key itself + the browser-lock state), so ordered `mockResolvedValueOnce`
+ * chains would race. `extra` may claim a call (e.g. the rotate POST) first. */
+function stubKeyFetch(
+ extra?: (url: string, opts?: RequestInit) => unknown,
+ browserLockEnabled = false,
+) {
+ const mock = vi.fn().mockImplementation(async (url: string, opts?: RequestInit) => {
+ const custom = extra?.(url, opts);
+ if (custom) return custom;
+ if (url === "/api/settings/browser-login") {
+ return { ok: true, json: async () => ({ enabled: browserLockEnabled }) };
+ }
+ return { ok: true, json: async () => ({ key: KEY, masked: MASKED }) };
+ });
+ vi.stubGlobal("fetch", mock);
+ return mock;
}
describe("JarvisApiGroup", () => {
@@ -49,14 +61,14 @@ describe("JarvisApiGroup", () => {
});
it("rotates only after the confirmation dialog is accepted", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) })
- .mockResolvedValueOnce({
- ok: true,
- json: async () => ({ ok: true, key: "jctl_rotated9999", masked: "jctl_…9999" }),
- });
- vi.stubGlobal("fetch", fetchMock);
+ const fetchMock = stubKeyFetch((_url, opts) =>
+ opts?.method === "POST"
+ ? {
+ ok: true,
+ json: async () => ({ ok: true, key: "jctl_rotated9999", masked: "jctl_…9999" }),
+ }
+ : undefined,
+ );
render(<JarvisApiGroup />);
await waitFor(() => screen.getByText(MASKED));
@@ -74,11 +86,11 @@ describe("JarvisApiGroup", () => {
});
it("sets a user-chosen key via PUT after both entries match", async () => {
- const fetchMock = vi
- .fn()
- .mockResolvedValueOnce({ ok: true, json: async () => ({ key: KEY, masked: MASKED }) })
- .mockResolvedValueOnce({ ok: true, json: async () => ({ ok: true, masked: "…tery" }) });
- vi.stubGlobal("fetch", fetchMock);
+ const fetchMock = stubKeyFetch((url, opts) =>
+ url === "/api/control/api-key" && opts?.method === "PUT"
+ ? { ok: true, json: async () => ({ ok: true, masked: "…tery" }) }
+ : undefined,
+ );
render(<JarvisApiGroup />);
await waitFor(() => screen.getByText(MASKED));
@@ -124,4 +136,73 @@ describe("JarvisApiGroup", () => {
);
expect(fetchMock.mock.calls.length).toBe(callsBefore);
});
+
+ it("turning the browser lock ON asks for confirmation before the PUT", async () => {
+ const fetchMock = stubKeyFetch((url, opts) =>
+ url === "/api/settings/browser-login" && opts?.method === "PUT"
+ ? {
+ ok: true,
+ json: async () => ({
+ ok: true,
+ enabled: true,
+ persisted: true,
+ applied_live: true,
+ session_minted: true,
+ }),
+ }
+ : undefined,
+ );
+ render(<JarvisApiGroup />);
+ await waitFor(() => screen.getByText(MASKED));
+
+ fireEvent.click(screen.getByRole("switch"));
+ // The dialog must appear WITHOUT any PUT having fired yet.
+ expect(
+ screen.getByRole("heading", { name: /require the control key in the browser\?/i }),
+ ).toBeTruthy();
+ expect(fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT")).toBeUndefined();
+
+ fireEvent.click(screen.getByRole("button", { name: /require the key/i }));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
+ expect(put).toBeTruthy();
+ expect(put?.[0]).toBe("/api/settings/browser-login");
+ expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({ enabled: true });
+ });
+ });
+
+ it("turning the browser lock OFF PUTs immediately, no dialog", async () => {
+ const fetchMock = stubKeyFetch(
+ (url, opts) =>
+ url === "/api/settings/browser-login" && opts?.method === "PUT"
+ ? {
+ ok: true,
+ json: async () => ({
+ ok: true,
+ enabled: false,
+ persisted: true,
+ applied_live: true,
+ session_minted: false,
+ }),
+ }
+ : undefined,
+ true,
+ );
+ render(<JarvisApiGroup />);
+ await waitFor(() => screen.getByText(MASKED));
+ await waitFor(() =>
+ expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("true"),
+ );
+
+ fireEvent.click(screen.getByRole("switch"));
+ await waitFor(() => {
+ const put = fetchMock.mock.calls.find(([, opts]) => opts?.method === "PUT");
+ expect(put).toBeTruthy();
+ expect(put?.[0]).toBe("/api/settings/browser-login");
+ expect(JSON.parse(put?.[1]?.body as string)).toMatchObject({ enabled: false });
+ });
+ expect(
+ screen.queryByRole("heading", { name: /require the control key in the browser\?/i }),
+ ).toBeNull();
+ });
});
diff --git a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
index 3a9796bcff..f143b6e7ac 100644
--- a/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
+++ b/jarvis/ui/web/frontend/src/views/settings/JarvisApiGroup.tsx
@@ -6,10 +6,13 @@ import {
EyeOff,
KeyRound,
Loader2,
+ Lock,
PencilLine,
RefreshCw,
} from "lucide-react";
import { Button } from "@/components/ui/button";
+import { Switch } from "@/components/ui/switch";
+import { useBrowserLock } from "@/hooks/useBrowserLock";
import { useJarvisApi } from "@/hooks/useJarvisApi";
import { robustCopy } from "@/lib/clipboard";
import { useEventStore } from "@/store/events";
@@ -38,10 +41,13 @@ const CUSTOM_KEY_RE = /^[A-Za-z0-9._~-]+$/;
export function JarvisApiGroup() {
const t = useT();
const { data, loading, error, rotate, setKey } = useJarvisApi();
+ const browserLock = useBrowserLock();
const pushToast = useEventStore((s) => s.pushToast);
const [revealed, setRevealed] = useState(false);
const [busy, setBusy] = useState(false);
const [confirmRotate, setConfirmRotate] = useState(false);
+ const [confirmLock, setConfirmLock] = useState(false);
+ const [lockBusy, setLockBusy] = useState(false);
const [formOpen, setFormOpen] = useState(false);
const [newKey, setNewKey] = useState("");
const [repeatKey, setRepeatKey] = useState("");
@@ -52,13 +58,44 @@ export function JarvisApiGroup() {
const display = revealed ? key : (data?.masked ?? "…");
useEffect(() => {
- if (!confirmRotate) return;
+ if (!confirmRotate && !confirmLock) return;
const onKeyDown = (e: KeyboardEvent) => {
- if (e.key === "Escape") setConfirmRotate(false);
+ if (e.key === "Escape") {
+ setConfirmRotate(false);
+ setConfirmLock(false);
+ }
};
window.addEventListener("keydown", onKeyDown);
return () => window.removeEventListener("keydown", onKeyDown);
- }, [confirmRotate]);
+ }, [confirmRotate, confirmLock]);
+
+ async function applyBrowserLock(next: boolean) {
+ setLockBusy(true);
+ try {
+ await browserLock.setEnabled(next);
+ setConfirmLock(false);
+ pushToast(
+ "success",
+ next
+ ? t("settings_view.jarvis_api.browser_lock_on_toast")
+ : t("settings_view.jarvis_api.browser_lock_off_toast"),
+ );
+ } catch (e) {
+ pushToast("error", (e as Error).message);
+ } finally {
+ setLockBusy(false);
+ }
+ }
+
+ function onToggleBrowserLock(next: boolean) {
+ if (next) {
+ // Turning the lock ON means the key is needed from now on — make the
+ // user consciously confirm (and ideally copy the key) first.
+ setConfirmLock(true);
+ return;
+ }
+ void applyBrowserLock(false);
+ }
async function onCopy() {
if (!key) return;
@@ -162,6 +199,23 @@ export function JarvisApiGroup() {
{t("settings_view.jarvis_api.unlock_hint")}
</p>
+ <div className="flex items-start gap-3 rounded-lg border border-border bg-card/60 p-4">
+ <Lock className="mt-0.5 h-4 w-4 shrink-0 text-primary" />
+ <div className="min-w-0 flex-1">
+ <div className="text-sm font-medium">
+ {t("settings_view.jarvis_api.browser_lock_title")}
+ </div>
+ <p className="mt-0.5 text-xs text-muted-foreground">
+ {t("settings_view.jarvis_api.browser_lock_description")}
+ </p>
+ </div>
+ <Switch
+ checked={browserLock.enabled ?? false}
+ disabled={browserLock.loading || lockBusy}
+ onCheckedChange={onToggleBrowserLock}
+ />
+ </div>
+
<div className="flex items-center gap-2">
<Button
size="sm"
@@ -242,6 +296,62 @@ export function JarvisApiGroup() {
{error && <p className="text-xs text-destructive">{error}</p>}
</div>
+ {confirmLock && (
+ <div
+ className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
+ onClick={(e) => {
+ if (e.target === e.currentTarget) setConfirmLock(false);
+ }}
+ >
+ <div className="card-outline mx-4 w-full max-w-md rounded-xl border border-border bg-card p-5 shadow-2xl">
+ <div className="flex items-start gap-3">
+ <div className="flex h-9 w-9 shrink-0 items-center justify-center rounded-md border border-primary/40 bg-primary/10">
+ <Lock className="h-5 w-5 text-primary" />
+ </div>
+ <div className="min-w-0 flex-1">
+ <h3 className="text-base font-semibold">
+ {t("settings_view.jarvis_api.browser_lock_confirm_title")}
+ </h3>
+ <p className="mt-1 text-sm text-muted-foreground">
+ {t("settings_view.jarvis_api.browser_lock_confirm_body")}
+ </p>
+ </div>
+ </div>
+ <div className="mt-5 flex justify-end gap-2">
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={lockBusy}
+ onClick={() => setConfirmLock(false)}
+ >
+ {t("common.cancel")}
+ </Button>
+ <Button
+ variant="outline"
+ size="sm"
+ disabled={lockBusy || !key}
+ onClick={onCopy}
+ >
+ <Copy className="mr-1.5 h-4 w-4" />
+ {t("settings_view.jarvis_api.copy_button")}
+ </Button>
+ <Button
+ size="sm"
+ disabled={lockBusy}
+ onClick={() => void applyBrowserLock(true)}
+ >
+ {lockBusy ? (
+ <Loader2 className="mr-1.5 h-4 w-4 animate-spin" />
+ ) : (
+ <Lock className="mr-1.5 h-4 w-4" />
+ )}
+ {t("settings_view.jarvis_api.browser_lock_confirm_button")}
+ </Button>
+ </div>
+ </div>
+ </div>
+ )}
+
{confirmRotate && (
<div
className="fixed inset-0 z-50 flex items-center justify-center bg-black/60 backdrop-blur-sm"
diff --git a/jarvis/ui/web/server.py b/jarvis/ui/web/server.py
index 5d36196239..344ae3adf9 100644
--- a/jarvis/ui/web/server.py
+++ b/jarvis/ui/web/server.py
@@ -50,7 +50,7 @@ from .schema import (
WSWelcome,
event_to_ws_envelope,
)
-from .surface_security import SurfaceSecurity
+from .surface_security import SurfaceSecurity, set_browser_login_required
if TYPE_CHECKING:
import uvicorn
@@ -209,6 +209,20 @@ class WebServer:
# The security boundary must wrap every router and both HTTP and WS.
# It is added after CORS so Starlette places it outside the CORS layer:
# hostile Host/Origin values never reach route code or preflight logic.
+ # Seed the browser-lock flag from the loaded config so the boundary's
+ # lazy raw-TOML read never disagrees with what the app actually loaded
+ # (JARVIS_CONFIG overrides, in-memory test configs, wizard defaults).
+ _browser_lock_on = bool(
+ getattr(getattr(self.cfg, "ui", None), "require_browser_login", False)
+ )
+ set_browser_login_required(_browser_lock_on)
+ if not _browser_lock_on:
+ logger.info(
+ "Browser lock is off (the default): loopback requests are served "
+ "without a credential. Anything relaying this port to a network "
+ "re-exposes the instance — turn on 'Ask for the key in the "
+ "browser' before forwarding it."
+ )
app.add_middleware(
SurfaceSecurity,
vite_dev_url=vite_dev_url,
diff --git a/jarvis/ui/web/settings_routes.py b/jarvis/ui/web/settings_routes.py
index 750a3e11ae..f86f7463d8 100644
--- a/jarvis/ui/web/settings_routes.py
+++ b/jarvis/ui/web/settings_routes.py
@@ -31,7 +31,7 @@ import threading
from collections.abc import Callable
from typing import TYPE_CHECKING
-from fastapi import APIRouter, HTTPException, Request
+from fastapi import APIRouter, HTTPException, Request, Response
from pydantic import BaseModel, Field, model_validator
from jarvis.brain.manager import SUPPORTED_REPLY_LANGUAGES
@@ -1885,6 +1885,77 @@ async def put_sound_effects(body: BoolToggleBody, request: Request) -> dict[str,
}
+# ---------------------------------------------------------------------------
+# Optional browser lock ("ask for the Control Key in a browser"). Off by
+# default: the local (loopback) user walks straight into the UI; non-loopback
+# access always requires the key regardless. Lives next to the Control Key
+# panel in Settings → API Keys. Applies live via the shared boundary flag in
+# ``surface_security`` — no restart.
+# ---------------------------------------------------------------------------
+
+
[email protected]("/browser-login")
+async def get_browser_login(request: Request) -> dict[str, object]:
+ cfg = _config(request)
+ ui = getattr(cfg, "ui", None)
+ return {"enabled": bool(getattr(ui, "require_browser_login", False))}
+
+
[email protected]("/browser-login")
+async def put_browser_login(
+ body: BoolToggleBody, request: Request, response: Response
+) -> dict[str, object]:
+ """Toggle the browser lock live and persist it to ``[ui]``.
+
+ When the lock is turned ON by a caller that entered through open access
+ (no session cookie — the normal case on loopback), a fresh HttpOnly
+ session is minted onto the response so the very browser that enabled the
+ lock stays signed in instead of instantly locking itself out.
+ """
+ from jarvis.ui.web import missions_auth, surface_security
+
+ enabled = bool(body.enabled)
+ cfg = _config(request)
+ ui = getattr(cfg, "ui", None)
+ if ui is not None:
+ try:
+ ui.require_browser_login = enabled # type: ignore[attr-defined]
+ except Exception as exc: # noqa: BLE001
+ log.debug("in-memory require_browser_login update skipped: %s", exc)
+ surface_security.set_browser_login_required(enabled)
+ persisted = False
+ try:
+ from jarvis.core import config_writer
+
+ config_writer.set_require_browser_login(enabled)
+ persisted = True
+ except Exception as exc: # noqa: BLE001
+ log.warning(
+ "require_browser_login persist failed (live apply still active): %s", exc
+ )
+ session_minted = False
+ if enabled:
+ current = request.cookies.get(surface_security.COOKIE_NAME, "")
+ if not missions_auth.validate_token(current):
+ token = missions_auth.issue_token()
+ response.set_cookie(
+ surface_security.COOKIE_NAME,
+ token,
+ path="/",
+ httponly=True,
+ samesite="strict",
+ secure=request.url.scheme == "https",
+ )
+ session_minted = True
+ return {
+ "ok": True,
+ "enabled": enabled,
+ "persisted": persisted,
+ "applied_live": True,
+ "session_minted": session_minted,
+ }
+
+
# ---------------------------------------------------------------------------
# Wiki curator model picker. GET current + selectable providers/models; PUT to
# change. The dedicated long-term-memory LLM is provider-agnostic: an empty
diff --git a/jarvis/ui/web/surface_security.py b/jarvis/ui/web/surface_security.py
index 2757529b92..035f4cf265 100644
--- a/jarvis/ui/web/surface_security.py
+++ b/jarvis/ui/web/surface_security.py
@@ -38,13 +38,83 @@ 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"]
+AuthKind = Literal["control", "session", "open"]
Origin = tuple[str, str, int | None]
_BOOTSTRAP_TOKEN_LOCK = threading.Lock()
_BOOTSTRAP_TOKENS: set[str] = set()
+# ---------------------------------------------------------------------------
+# Optional browser lock — "ask for the Control Key in a browser".
+#
+# OFF by default: a request whose Host header AND client peer are BOTH
+# loopback — and that carries no forwarding-indicator header — is authorized
+# without any credential, so opening the UI on the very machine Jarvis runs on
+# never shows the lock screen. The Control Key stays mandatory for every
+# non-loopback caller (LAN, VPS, reverse proxy) regardless of this flag; the
+# one caveat is a headerless L4 relay on the same machine, which no request
+# inspection can detect (see open_access_granted). The flag is shared
+# module-globally (like the WS ticket store) so the fast-boot boundary, the
+# full app's boundary, and the live Settings toggle agree within one process.
+# ---------------------------------------------------------------------------
+_BROWSER_LOGIN_LOCK = threading.Lock()
+_BROWSER_LOGIN_REQUIRED: bool | None = None
+
+
+def _read_browser_login_required_from_config() -> bool:
+ """Raw ``[ui].require_browser_login`` read (no ``load_config``).
+
+ Dependency-light on purpose (stdlib ``tomllib`` only) so the fast-boot
+ boundary can answer before the heavy config graph imports. A missing file
+ or field means the schema default (``False`` — no browser lock); an
+ unreadable file fails closed (``True``) until the real config load seeds
+ the value via :func:`set_browser_login_required`.
+ """
+ import tomllib
+
+ path = os.environ.get("JARVIS_CONFIG")
+ if not path:
+ repo_root = os.path.dirname(
+ os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
+ )
+ path = os.path.join(repo_root, "jarvis.toml")
+ if not os.path.exists(path):
+ return False
+ try:
+ with open(path, "rb") as fh:
+ raw = fh.read()
+ # The atomic config writer tolerates a UTF-8 BOM (AP-7); tomllib does not.
+ data = tomllib.loads(raw.removeprefix(b"\xef\xbb\xbf").decode("utf-8"))
+ except Exception:
+ return True
+ value = data.get("ui", {}).get("require_browser_login")
+ return value if isinstance(value, bool) else False
+
+
+def browser_login_required() -> bool:
+ """Whether a loopback browser must present the Control Key (lazy-seeded)."""
+ global _BROWSER_LOGIN_REQUIRED
+ with _BROWSER_LOGIN_LOCK:
+ if _BROWSER_LOGIN_REQUIRED is None:
+ _BROWSER_LOGIN_REQUIRED = _read_browser_login_required_from_config()
+ return _BROWSER_LOGIN_REQUIRED
+
+
+def set_browser_login_required(required: bool) -> None:
+ """Seed/override the browser-lock flag (config load + live Settings toggle)."""
+ global _BROWSER_LOGIN_REQUIRED
+ with _BROWSER_LOGIN_LOCK:
+ _BROWSER_LOGIN_REQUIRED = bool(required)
+
+
+def reset_browser_login_required() -> None:
+ """Test hook: forget the cached flag so the next read re-derives it."""
+ global _BROWSER_LOGIN_REQUIRED
+ with _BROWSER_LOGIN_LOCK:
+ _BROWSER_LOGIN_REQUIRED = None
+
+
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}
@@ -362,15 +432,13 @@ def scope_origin_is_trusted(
)
-def is_secure_or_loopback(scope: Scope) -> bool:
- """True for HTTPS/WSS or a direct loopback-client-to-loopback-Host request.
+def is_loopback_request(scope: Scope) -> bool:
+ """True for 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
@@ -389,6 +457,57 @@ def is_secure_or_loopback(scope: Scope) -> bool:
return client_host == "localhost"
+def is_secure_or_loopback(scope: Scope) -> bool:
+ """True for HTTPS/WSS or a direct loopback-client-to-loopback-Host request."""
+ if str(scope.get("scheme", "")).lower() in {"https", "wss"}:
+ return True
+ return is_loopback_request(scope)
+
+
+# Headers a forwarding intermediary (HTTP reverse proxy, CDN edge, tunnel
+# agent) stamps onto relayed requests. Their presence proves the loopback
+# peer socket belongs to a relay, not to the local user's own client — open
+# access must then refuse, or a remote caller behind the relay could claim
+# ``Host: 127.0.0.1`` and look local.
+_RELAY_INDICATOR_HEADERS = (
+ "forwarded",
+ "x-forwarded-for",
+ "x-forwarded-host",
+ "x-real-ip",
+ "via",
+ "cf-connecting-ip",
+ "true-client-ip",
+ "fly-client-ip",
+)
+
+
+def _relay_indicator_present(scope: Scope) -> bool:
+ for name in _RELAY_INDICATOR_HEADERS:
+ if _headers(scope, name):
+ return True
+ return False
+
+
+def open_access_granted(scope: Scope) -> bool:
+ """True when the optional browser lock is OFF and the request is local.
+
+ "Local" means BOTH ends are loopback (see :func:`is_loopback_request`)
+ AND the request carries no forwarding-indicator header — so a LAN, VPS,
+ or well-behaved reverse-proxy surface never opens. Honest limitation: a
+ raw TCP relay that adds no headers (``ssh -L``, ``socat``, an L4 tunnel)
+ is indistinguishable from a local client at this layer; whoever forwards
+ the Jarvis port to a network re-exposes the instance and must turn the
+ browser lock ON (documented in the Control-Key guide). When open access
+ grants, the validity of any credential the caller happens to present is
+ irrelevant — the machine's own user is trusted by decision, not by token.
+ """
+ return (
+ not browser_login_required()
+ and is_loopback_request(scope)
+ and not _relay_indicator_present(scope)
+ )
+
+
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):
@@ -487,6 +606,8 @@ def credentials_valid(scope: Scope) -> bool:
"""
if scope.get(WS_TICKET_SCOPE_KEY) is True:
return True
+ if open_access_granted(scope):
+ return True
bearer_present, bearer = _presented_bearer(scope)
if bearer_present:
if bearer is None:
@@ -978,10 +1099,16 @@ class SurfaceSecurity:
return
auth_kind = self._authenticate(scope)
+ if auth_kind is None and open_access_granted(scope):
+ auth_kind = "open"
if auth_kind is None:
await reject_unauthorized(scope, send, receive)
return
- if auth_kind == "session" and method in _UNSAFE_HTTP_METHODS:
+ # Cookie- and open-access requests are browser-shaped, so unsafe
+ # methods keep the CSRF defense: a browser always attaches Origin
+ # to POST/PUT/PATCH/DELETE. A local non-browser tool that sends no
+ # Origin must present the control key instead (Bearer is exempt).
+ if auth_kind in ("session", "open") and method in _UNSAFE_HTTP_METHODS:
if not self.origin_is_trusted(scope, required=True):
await reject_origin(scope, send, receive)
return
@@ -1026,10 +1153,14 @@ class SurfaceSecurity:
return
auth_kind = self._authenticate(scope)
+ if auth_kind is None and open_access_granted(scope):
+ auth_kind = "open"
if auth_kind is None:
await reject_unauthorized(scope, send, receive)
return
- if auth_kind == "session" and not self.origin_is_trusted(scope, required=True):
+ if auth_kind in ("session", "open") and not self.origin_is_trusted(
+ scope, required=True
+ ):
await reject_origin(scope, send, receive)
return
await self.app(scope, receive, send)
@@ -1040,13 +1171,18 @@ __all__ = [
"SurfaceSecurity",
"WS_TICKET_SCOPE_KEY",
"append_session_cookie",
+ "browser_login_required",
"build_set_cookie_header",
"credentials_valid",
+ "is_loopback_request",
"is_secure_or_loopback",
+ "open_access_granted",
"reject_host",
"reject_origin",
"reject_unauthorized",
+ "reset_browser_login_required",
"reset_ws_tickets",
"scope_host_is_trusted",
"scope_origin_is_trusted",
+ "set_browser_login_required",
]
diff --git a/tests/conftest.py b/tests/conftest.py
index 7e17dbe51c..a0d1127a9e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -63,6 +63,26 @@ def _authenticated_test_clients(request, monkeypatch): # noqa: ANN001
revoke_token(token)
[email protected](autouse=True)
+def _browser_lock_pinned_on():
+ """Pin the optional browser lock ON for every test, deterministic.
+
+ The production default is OFF (loopback walks in without a credential),
+ which would silently pass requests in any suite that uses a loopback
+ client peer — and the lazy raw-TOML seed would otherwise read the host
+ machine's real ``jarvis.toml``. Tests that exercise the open-access mode
+ flip the flag explicitly and rely on this fixture's teardown reset.
+ """
+ from jarvis.ui.web.surface_security import (
+ reset_browser_login_required,
+ set_browser_login_required,
+ )
+
+ set_browser_login_required(True)
+ yield
+ reset_browser_login_required()
+
+
@pytest.fixture(autouse=True)
def _reset_bus():
"""Reset the global default bus before and after each test."""
diff --git a/tests/integration/test_web_surface_security.py b/tests/integration/test_web_surface_security.py
index be591502f4..ff3e33f363 100644
--- a/tests/integration/test_web_surface_security.py
+++ b/tests/integration/test_web_surface_security.py
@@ -33,6 +33,9 @@ def web_server(monkeypatch: pytest.MonkeyPatch) -> WebServer:
cfg = JarvisConfig()
cfg.ui.dev_mode = True
cfg.ui.vite_dev_url = "http://localhost:5173"
+ # These tests assert the LOCKED boundary; the product default is open on
+ # loopback, which would let the credential-free requests below through.
+ cfg.ui.require_browser_login = True
monkeypatch.setenv(cfg.ui.auth_token_env, _SESSION_TOKEN)
monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)
server = WebServer(cfg, bus=EventBus())
@@ -57,6 +60,7 @@ def test_production_server_does_not_trust_the_vite_development_origin(
cfg = JarvisConfig()
cfg.ui.dev_mode = False
cfg.ui.vite_dev_url = "http://localhost:5173"
+ cfg.ui.require_browser_login = True
monkeypatch.setattr(control_key, "get_control_key", lambda: _CONTROL_KEY)
server = WebServer(cfg, bus=EventBus())
diff --git a/tests/unit/ui/test_browser_login_route.py b/tests/unit/ui/test_browser_login_route.py
new file mode 100644
index 0000000000..6a4a45e2d9
--- /dev/null
+++ b/tests/unit/ui/test_browser_login_route.py
@@ -0,0 +1,91 @@
+"""GET/PUT /api/settings/browser-login — the optional browser lock.
+
+The PUT must apply live (shared ``surface_security`` boundary flag), persist
+via ``config_writer``, and — when the lock is turned ON by a caller without a
+valid session — mint a fresh HttpOnly session cookie so the very browser that
+enabled the lock does not lock itself out.
+"""
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+import pytest
+from fastapi import FastAPI
+from fastapi.testclient import TestClient
+
+from jarvis.ui.web import missions_auth, surface_security
+from jarvis.ui.web.settings_routes import router
+
+# The suite-wide auto-auth fixture would give every client a valid session
+# cookie, hiding exactly the no-session path this file exists to prove.
+pytestmark = pytest.mark.no_auto_web_auth
+
+
+def _client(*, require_browser_login: bool = False) -> TestClient:
+ app = FastAPI()
+ app.include_router(router)
+ app.state.config = SimpleNamespace(
+ ui=SimpleNamespace(require_browser_login=require_browser_login),
+ )
+ return TestClient(app)
+
+
[email protected](autouse=True)
+def _no_toml_writes(monkeypatch):
+ import jarvis.core.config_writer as cw
+
+ written = {}
+ monkeypatch.setattr(
+ cw, "set_require_browser_login", lambda v, **k: written.setdefault("v", v)
+ )
+ yield written
+
+
+def test_get_reports_the_config_value() -> None:
+ assert _client().get("/api/settings/browser-login").json() == {"enabled": False}
+ assert _client(require_browser_login=True).get("/api/settings/browser-login").json() == {
+ "enabled": True
+ }
+
+
+def test_put_enable_without_session_mints_a_cookie(_no_toml_writes) -> None:
+ missions_auth.reset_tokens()
+ r = _client().put("/api/settings/browser-login", json={"enabled": True})
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["enabled"] is True and body["persisted"] is True
+ assert body["session_minted"] is True
+ assert surface_security.browser_login_required() is True
+ assert _no_toml_writes["v"] is True
+ # The minted cookie is a real, registered session token.
+ cookie = r.cookies.get(surface_security.COOKIE_NAME)
+ assert cookie and missions_auth.validate_token(cookie)
+ missions_auth.reset_tokens()
+
+
+def test_put_enable_with_valid_session_mints_nothing() -> None:
+ missions_auth.reset_tokens()
+ token = "already-signed-in" # noqa: S105
+ missions_auth.register_token(token)
+ client = _client()
+ client.cookies.set(surface_security.COOKIE_NAME, token)
+
+ r = client.put("/api/settings/browser-login", json={"enabled": True})
+
+ assert r.status_code == 200
+ assert r.json()["session_minted"] is False
+ assert "set-cookie" not in r.headers
+ missions_auth.reset_tokens()
+
+
+def test_put_disable_applies_live_and_persists(_no_toml_writes) -> None:
+ r = _client(require_browser_login=True).put(
+ "/api/settings/browser-login", json={"enabled": False}
+ )
+
+ assert r.status_code == 200
+ body = r.json()
+ assert body["enabled"] is False and body["session_minted"] is False
+ assert surface_security.browser_login_required() is False
+ assert _no_toml_writes["v"] is False
diff --git a/tests/unit/ui_web/test_control_auth.py b/tests/unit/ui_web/test_control_auth.py
index 52778cce8f..f27c830136 100644
--- a/tests/unit/ui_web/test_control_auth.py
+++ b/tests/unit/ui_web/test_control_auth.py
@@ -35,6 +35,13 @@ class _FakeRequest:
self.cookies = {}
if session_token is not None:
self.cookies[ca.COOKIE_NAME] = session_token
+ # Mirror the ASGI scope a real starlette Request carries; the
+ # open-access check inspects Host header + client peer on it.
+ self.scope = {
+ "type": "http",
+ "headers": [(b"host", host.encode("ascii"))],
+ "client": (host, 50_000),
+ }
@pytest.fixture
@@ -100,6 +107,24 @@ async def test_session_guard_accepts_registered_ui_session(stored_key) -> None:
revoke_token(token)
+async def test_session_guard_grants_loopback_when_browser_lock_off(stored_key) -> None:
+ # Browser lock OFF (the product default): the loopback UI has no session
+ # cookie, yet must reach the key panel — otherwise the user could never
+ # see the key needed to turn the lock ON.
+ from jarvis.ui.web.surface_security import set_browser_login_required
+
+ set_browser_login_required(False)
+ await ca.require_control_key_or_session(_FakeRequest(host="127.0.0.1"))
+
+
+async def test_session_guard_still_denies_remote_when_browser_lock_off(stored_key) -> None:
+ from jarvis.ui.web.surface_security import set_browser_login_required
+
+ set_browser_login_required(False)
+ with pytest.raises(HTTPException):
+ await ca.require_control_key_or_session(_FakeRequest(host="203.0.113.7"))
+
+
# --- assert_bind_safe (fail-closed) ---
diff --git a/tests/unit/ui_web/test_surface_security.py b/tests/unit/ui_web/test_surface_security.py
index 68b4a38010..a0d73788e9 100644
--- a/tests/unit/ui_web/test_surface_security.py
+++ b/tests/unit/ui_web/test_surface_security.py
@@ -776,3 +776,193 @@ def test_non_loopback_plain_ws_ticket_presentation_is_rejected() -> None:
assert exc_info.value.code == 4403
assert inner.scopes == []
+
+
+# ---------------------------------------------------------------------------
+# Optional browser lock — OFF (the product default): loopback-to-loopback
+# requests are authorized without any credential; everything non-loopback
+# keeps demanding the Control Key. The suite-wide conftest fixture pins the
+# lock ON, so these tests flip it OFF explicitly and rely on its reset.
+# ---------------------------------------------------------------------------
+
+
+def test_browser_lock_off_grants_loopback_http_without_credential() -> None:
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ response = client.get("/api/config", headers=_headers())
+
+ assert response.status_code == 200
+ assert len(inner.scopes) == 1
+
+
+def test_browser_lock_off_ignores_invalid_credentials_on_loopback() -> None:
+ # Open access trusts the machine's user by decision, not by token: a
+ # stale key in a local tool must not lock the local user out.
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ response = client.get(
+ "/api/config", headers=_headers(token="jctl_stale") # noqa: S106 — synthetic stale key
+ )
+
+ assert response.status_code == 200
+ assert len(inner.scopes) == 1
+
+
+def test_browser_lock_off_unsafe_method_keeps_csrf_origin_gate() -> None:
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ origin_less = client.post("/api/chat", headers=_headers(origin=None), json={})
+ assert origin_less.status_code == 403
+ assert inner.scopes == []
+
+ same_origin = client.post("/api/chat", headers=_headers(), json={})
+ assert same_origin.status_code == 200
+ assert len(inner.scopes) == 1
+
+
+def test_browser_lock_off_never_opens_non_loopback() -> None:
+ surface_security.set_browser_login_required(False)
+ 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.get(
+ "/api/config", headers=_headers(origin=public_url, host="jarvis.example")
+ )
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+ "relay_header",
+ [
+ ("X-Forwarded-For", "203.0.113.9"),
+ ("Forwarded", "for=203.0.113.9"),
+ ("Via", "1.1 relay"),
+ ("X-Real-IP", "203.0.113.9"),
+ ],
+)
+def test_browser_lock_off_relayed_loopback_is_rejected(
+ relay_header: tuple[str, str],
+) -> None:
+ # A tunnel/proxy on the same machine connects from 127.0.0.1 and lets the
+ # remote caller choose the Host header (e.g. "127.0.0.1"). Any forwarding
+ # indicator proves the peer socket belongs to a relay, so open access must
+ # refuse and demand the key.
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ name, value = relay_header
+ headers = _headers()
+ headers[name] = value
+ response = client.get("/api/config", headers=headers)
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+def test_browser_lock_off_reverse_proxy_public_host_stays_locked() -> None:
+ # A same-host reverse proxy connects from 127.0.0.1 but forwards a public
+ # Host header — both ends must be loopback for open access to grant.
+ surface_security.set_browser_login_required(False)
+ public_url = "http://jarvis.example"
+ client, inner = _client(
+ base_url=public_url,
+ peer=("127.0.0.1", 50_000),
+ public_urls=(public_url,),
+ )
+
+ response = client.get(
+ "/api/config", headers=_headers(origin=public_url, host="jarvis.example")
+ )
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+def test_browser_lock_off_grants_loopback_websocket_with_origin() -> None:
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ with client.websocket_connect("/ws", headers=_headers()) as websocket:
+ assert websocket.receive_json() == {"type": "probe"}
+
+ assert len(inner.scopes) == 1
+ # Route-level defense-in-depth re-checks must agree with the boundary.
+ assert credentials_valid(inner.scopes[0]) is True
+
+
+def test_browser_lock_off_websocket_without_origin_is_rejected() -> None:
+ # A browser always attaches an Origin to a WS handshake; an origin-less
+ # socket is not a browser and must present a real credential instead.
+ surface_security.set_browser_login_required(False)
+ client, inner = _client()
+
+ with client.websocket_connect(
+ "/ws", headers=_headers(origin=None)
+ ) as websocket:
+ with pytest.raises(WebSocketDisconnect) as exc_info:
+ websocket.receive_json()
+
+ assert exc_info.value.code == 4403
+ assert inner.scopes == []
+
+
+def test_browser_lock_on_keeps_loopback_locked() -> None:
+ surface_security.set_browser_login_required(True)
+ client, inner = _client()
+
+ response = client.get("/api/config", headers=_headers())
+
+ assert response.status_code == 401
+ assert inner.scopes == []
+
+
+# ---------------------------------------------------------------------------
+# Lazy raw-TOML seed: before any explicit seed, the boundary derives the flag
+# from ``[ui].require_browser_login`` without importing the config graph.
+# ---------------------------------------------------------------------------
+
+
+def _seed_from_toml(tmp_path, monkeypatch, content: str | None) -> bool:
+ if content is None:
+ monkeypatch.setenv("JARVIS_CONFIG", str(tmp_path / "missing.toml"))
+ else:
+ config_file = tmp_path / "jarvis.toml"
+ config_file.write_bytes(content.encode("utf-8"))
+ monkeypatch.setenv("JARVIS_CONFIG", str(config_file))
+ surface_security.reset_browser_login_required()
+ return surface_security.browser_login_required()
+
+
+def test_toml_seed_field_true_requires_login(tmp_path, monkeypatch) -> None:
+ assert _seed_from_toml(
+ tmp_path, monkeypatch, "[ui]\nrequire_browser_login = true\n"
+ ) is True
+
+
+def test_toml_seed_field_absent_defaults_open(tmp_path, monkeypatch) -> None:
+ assert _seed_from_toml(tmp_path, monkeypatch, "[ui]\ndev_mode = false\n") is False
+
+
+def test_toml_seed_missing_file_defaults_open(tmp_path, monkeypatch) -> None:
+ assert _seed_from_toml(tmp_path, monkeypatch, None) is False
+
+
+def test_toml_seed_unreadable_file_fails_closed(tmp_path, monkeypatch) -> None:
+ assert _seed_from_toml(tmp_path, monkeypatch, "not [valid toml ==") is True
+
+
+def test_toml_seed_tolerates_utf8_bom(tmp_path, monkeypatch) -> None:
+ config_file = tmp_path / "jarvis.toml"
+ config_file.write_bytes(b"\xef\xbb\xbf[ui]\nrequire_browser_login = true\n")
+ monkeypatch.setenv("JARVIS_CONFIG", str(config_file))
+ surface_security.reset_browser_login_required()
+ assert surface_security.browser_login_required() is True