Skip to content

Open-source AI teammates in Slack, Teams, Discord, Telegram and Mattermost. Self-host it, with any agent harness and any model.

feat(switch): silent session token refresh, always-signed-in local server, authenticated gateway window (CHOO-1435) (#29)

Louis Amaudruz327a8c68e934
diff --git a/core/switch_core/gateway/auth_routes.py b/core/switch_core/gateway/auth_routes.py
index 738c590dd..705164176 100644
--- a/core/switch_core/gateway/auth_routes.py
+++ b/core/switch_core/gateway/auth_routes.py
@@ -56,6 +56,30 @@ async def login(
)
[email protected]("/auth/refresh")
+async def refresh(
+ response: Response,
+ user: Annotated[User, Depends(get_current_user)],
+ config: Annotated[SwitchConfig, Depends(get_config)],
+) -> UserResponse:
+ # Re-mint the switch_auth cookie from the still-valid session so an active
+ # client renews before expiry without re-authenticating — provider-agnostic
+ # (works for password and OIDC users alike, since it re-issues from the User
+ # rather than replaying either login flow). get_current_user rejects a
+ # missing/expired/invalid cookie with 401, so an expired session cannot renew
+ # itself; the client falls back to interactive sign-in in that case.
+ set_session_cookie(
+ response, user, config.jwt_secret_key, config.gateway_cookie_secure
+ )
+ return UserResponse(
+ id=user.id,
+ name=user.name,
+ email=user.email,
+ role=user.role,
+ created_at=str(user.created_at),
+ )
+
+
@router.post("/auth/logout")
async def logout(response: Response) -> dict[str, bool]:
response.delete_cookie("switch_auth", path="/")
diff --git a/core/tests/switch_core/gateway/test_auth_refresh.py b/core/tests/switch_core/gateway/test_auth_refresh.py
new file mode 100644
index 000000000..deb6f784a
--- /dev/null
+++ b/core/tests/switch_core/gateway/test_auth_refresh.py
@@ -0,0 +1,68 @@
+"""Tests for the silent session-renewal endpoint (CHOO-1435).
+
+`POST /gateway/auth/refresh` re-mints the `switch_auth` cookie for a caller
+whose current cookie is still valid, so an active switchdash client renews its
+session before expiry without bouncing the user to sign-in. The route depends
+on `get_current_user`, which already rejects a missing/expired/invalid cookie
+with 401 — so an expired session cannot renew itself. Here we exercise the
+route coroutine directly against a lightweight config stub.
+"""
+
+from __future__ import annotations
+
+from types import SimpleNamespace
+
+from fastapi import Response
+
+from switch_core.db.models import User
+from switch_core.gateway.auth import decode_jwt
+from switch_core.gateway.auth_routes import refresh
+
+# Dummy HS256 signing key for these unit tests only — not a real secret.
+_SECRET = "unit-test-jwt-key-unit-test-jwt-key-unit-test" # gitleaks:allow
+
+
+def _config(*, cookie_secure: bool = False) -> SimpleNamespace:
+ # refresh() only touches these two config attributes.
+ return SimpleNamespace(jwt_secret_key=_SECRET, gateway_cookie_secure=cookie_secure)
+
+
+def _extract_cookie(response: Response) -> str:
+ raw = response.headers.get("set-cookie")
+ assert raw is not None, "refresh did not set a cookie"
+ pair = raw.split(";")[0]
+ key, _, value = pair.partition("=")
+ assert key == "switch_auth"
+ return value
+
+
+async def test_refresh_remints_cookie_for_current_user() -> None:
+ user = User(id="u-1", name="Ada", email="[email protected]", role="user")
+ response = Response()
+
+ result = await refresh(response, user, _config())
+
+ token = _extract_cookie(response)
+ payload = decode_jwt(token, _SECRET)
+ assert payload["sub"] == "u-1"
+ assert payload["email"] == "[email protected]"
+ assert payload["role"] == "user"
+ # The renewed token carries a fresh expiry.
+ assert payload["exp"] > payload["iat"]
+ # And the response body echoes the renewed user.
+ assert result.id == "u-1"
+ assert result.email == "[email protected]"
+
+
+async def test_refresh_cookie_is_httponly_and_respects_secure_flag() -> None:
+ user = User(id="u-2", name="Bo", email="[email protected]", role="admin")
+
+ insecure = Response()
+ await refresh(insecure, user, _config(cookie_secure=False))
+ header = insecure.headers.get("set-cookie") or ""
+ assert "httponly" in header.lower()
+ assert "secure" not in header.lower()
+
+ secure = Response()
+ await refresh(secure, user, _config(cookie_secure=True))
+ assert "secure" in (secure.headers.get("set-cookie") or "").lower()
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/auth.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/auth.ts
index cca3785fa..df0c201f5 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/auth.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/auth.ts
@@ -1,8 +1,11 @@
import { randomUUID } from 'node:crypto';
import { err, ok, type Result } from '@switchdash/shared';
import { BrowserWindow, session as electronSession } from 'electron';
+import { LOCAL_SERVER_ADMIN_EMAIL } from '@main/core/local-switch-server/constants';
+import { loadOrCreateSecrets } from '@main/core/local-switch-server/secrets';
+import { log } from '@main/lib/logger';
import type { SwitchServer, SwitchUser } from '@shared/core/switch-servers/switch-servers';
-import { setSessionCookie } from './servers-store';
+import { getSessionCookie, setSessionCookie } from './servers-store';
const SWITCH_AUTH_COOKIE = 'switch_auth';
const OIDC_LOGIN_TIMEOUT_MS = 300_000;
@@ -80,6 +83,84 @@ export async function passwordLogin(
return ok(user);
}
+/**
+ * Silent session renewal: exchange a still-valid `switch_auth` cookie for a
+ * fresh one via `POST /auth/refresh`, persisting the new cookie with the same
+ * encrypted per-server storage login uses. Provider-agnostic — the gateway
+ * re-mints from the session, so it renews password and OIDC sessions alike
+ * without replaying either login flow.
+ *
+ * Returns the new JWT, or `null` when renewal did not happen: a network failure
+ * (transient — keep using the current token, retry next call) or a rejection
+ * (the session is already expired/revoked, so the triggering call will 401 and
+ * the caller falls back to interactive sign-in). Best-effort by design: it
+ * never throws, so proactive renewal cannot break the call that triggered it.
+ */
+export async function refreshSession(
+ server: SwitchServer,
+ currentJwt: string
+): Promise<string | null> {
+ let response: Response;
+ try {
+ response = await fetch(gatewayUrl(server, '/auth/refresh'), {
+ method: 'POST',
+ headers: { Accept: 'application/json', Cookie: `${SWITCH_AUTH_COOKIE}=${currentJwt}` },
+ redirect: 'manual',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (cause) {
+ log.warn('Switch session renewal could not reach the gateway; keeping current token', {
+ server: server.id,
+ cause: cause instanceof Error ? cause.message : String(cause),
+ });
+ return null;
+ }
+
+ if (!response.ok) {
+ log.warn('Switch session renewal was rejected; will fall back to sign-in once expired', {
+ server: server.id,
+ status: response.status,
+ });
+ return null;
+ }
+
+ const jwt = extractAuthCookie(response.headers.getSetCookie());
+ if (!jwt) {
+ log.warn('Switch session renewal succeeded but returned no cookie', { server: server.id });
+ return null;
+ }
+
+ await setSessionCookie(server.id, jwt);
+ return jwt;
+}
+
+/**
+ * Silent re-login for the managed local server. switchdash generated that
+ * server's admin password, so when its session is missing or expired we can
+ * sign in again with no user interaction — the local server is meant to be
+ * always signed in. Persists the fresh cookie (via `passwordLogin`) and returns
+ * it for immediate reuse, or `null` when re-login failed (the caller then falls
+ * back to the normal sign-in path). No-op for non-managed servers, whose
+ * credentials switchdash does not hold.
+ */
+export async function reauthenticateManagedServer(server: SwitchServer): Promise<string | null> {
+ if (!server.managed) return null;
+ const secrets = await loadOrCreateSecrets();
+ const result = await passwordLogin(
+ server,
+ LOCAL_SERVER_ADMIN_EMAIL,
+ secrets.gatewayAdminPassword
+ );
+ if (!result.success) {
+ log.warn('Managed Switch server silent re-login failed; falling back to sign-in', {
+ server: server.id,
+ error: result.error,
+ });
+ return null;
+ }
+ return getSessionCookie(server.id);
+}
+
/**
* OIDC login: the gateway is the OIDC client, so we ride its server-mediated
* flow in an embedded window — open `/auth/oidc/login`, let the gateway + IdP
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
index 505bc3682..d3f2faab6 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/controller.ts
@@ -3,6 +3,7 @@ import { suggestAgentDefaults } from '@main/core/agents/agent-defaults';
import { resolveAgentServers } from '@main/core/agents/resolve-servers';
import { writeRemoteSwitchSettings } from '@main/core/agents/write-remote-switch-settings';
import { writeSwitchSettings } from '@main/core/agents/write-switch-settings';
+import { appService } from '@main/core/app/service';
import { SshFileSystem } from '@main/core/fs/impl/ssh-fs';
import { sshConnectionIdForHost } from '@main/core/locations/location-transport';
import { ensureSshConnected } from '@main/core/ssh/connect/connect-agent-ssh';
@@ -38,6 +39,7 @@ import {
GatewayError,
registerKnownAgent,
} from './gateway-client';
+import { openAuthenticatedGatewayPage } from './gateway-web';
import {
addServer,
deleteSessionCookie,
@@ -138,6 +140,24 @@ export const switchServersController = createRPCController({
logout: (serverId: string): Promise<void> => deleteSessionCookie(serverId),
+ /**
+ * Open a gateway web page (operator dashboard). For the managed local server —
+ * whose session switchdash owns — this opens an in-app window with the
+ * `switch_auth` cookie injected, so the dashboard loads already signed in.
+ * Remote servers open in the OS browser as before: we can't inject our
+ * httponly cookie into the system browser, so an authenticated in-app window
+ * is reserved for the local server. `url` must be on the server's gateway
+ * origin.
+ */
+ openGatewayPage: async (params: { serverId: string; url: string }): Promise<void> => {
+ const server = await requireServer(params.serverId);
+ if (server.managed) {
+ await openAuthenticatedGatewayPage(server, params.url);
+ } else {
+ await appService.openExternal(params.url);
+ }
+ },
+
getConnectionStatus: async (serverId: string): Promise<ServerConnectionStatus> => {
const server = await requireServer(serverId);
try {
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
new file mode 100644
index 000000000..62aac0bad
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.test.ts
@@ -0,0 +1,198 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const refreshSession = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ refreshSession, reauthenticateManagedServer }));
+
+const { fetchMe } = await import('./gateway-client');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'https://switch.example.com',
+ managed: false,
+} as never;
+const MANAGED = {
+ id: 'srv-local',
+ name: 'Local',
+ gatewayUrl: 'https://switch.example.com',
+ managed: true,
+} as never;
+
+/** A structurally-valid JWT whose payload `exp` is `secondsFromNow` in the
+ * future (or past when negative). Signature is a placeholder — the client only
+ * base64-decodes the payload to read `exp`. */
+function makeJwt(secondsFromNow: number): string {
+ const header = Buffer.from(JSON.stringify({ alg: 'HS256', typ: 'JWT' })).toString('base64url');
+ const exp = Math.floor(Date.now() / 1000) + secondsFromNow;
+ const payload = Buffer.from(JSON.stringify({ sub: 'u1', exp })).toString('base64url');
+ return `${header}.${payload}.sig`;
+}
+
+function okMeResponse(): Response {
+ return {
+ status: 200,
+ ok: true,
+ json: async () => ({ id: 'u1', name: 'Ada', email: '[email protected]', role: 'user' }),
+ headers: { getSetCookie: () => [] },
+ text: async () => '',
+ } as unknown as Response;
+}
+
+function unauthorizedResponse(): Response {
+ return {
+ status: 401,
+ ok: false,
+ json: async () => ({}),
+ headers: { getSetCookie: () => [] },
+ text: async () => 'Token expired',
+ } as unknown as Response;
+}
+
+function cookieHeaderOf(call: unknown[]): string {
+ const init = call[1] as { headers: Record<string, string> };
+ return init.headers.Cookie;
+}
+
+const fetchMock = vi.fn(async () => okMeResponse());
+
+describe('gatewayFetch proactive session renewal', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ fetchMock.mockImplementation(async () => okMeResponse());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('attaches the stored token without renewing when it is far from expiry', async () => {
+ const jwt = makeJwt(2 * 60 * 60); // 2h out, beyond the 1h leeway
+ getSessionCookie.mockResolvedValue(jwt);
+
+ await fetchMe(SERVER);
+
+ expect(refreshSession).not.toHaveBeenCalled();
+ expect(cookieHeaderOf(fetchMock.mock.calls[0])).toBe(`switch_auth=${jwt}`);
+ });
+
+ it('renews and attaches the fresh token when the stored token is near expiry', async () => {
+ const stale = makeJwt(10 * 60); // 10min out, inside the 1h leeway
+ const fresh = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(stale);
+ refreshSession.mockResolvedValue(fresh);
+
+ await fetchMe(SERVER);
+
+ expect(refreshSession).toHaveBeenCalledExactlyOnceWith(SERVER, stale);
+ expect(cookieHeaderOf(fetchMock.mock.calls[0])).toBe(`switch_auth=${fresh}`);
+ });
+
+ it('falls back to the current token when renewal does not succeed', async () => {
+ const stale = makeJwt(5 * 60);
+ getSessionCookie.mockResolvedValue(stale);
+ refreshSession.mockResolvedValue(null);
+
+ await fetchMe(SERVER);
+
+ expect(refreshSession).toHaveBeenCalledOnce();
+ // Call still goes out (with the stale token) — it will 401 and the caller
+ // prompts an interactive sign-in rather than the renewal silently faking it.
+ expect(cookieHeaderOf(fetchMock.mock.calls[0])).toBe(`switch_auth=${stale}`);
+ });
+
+ it('dedupes concurrent renewals into a single refresh round-trip', async () => {
+ const stale = makeJwt(5 * 60);
+ const fresh = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(stale);
+ let resolveRefresh: (value: string) => void = () => {};
+ refreshSession.mockReturnValue(
+ new Promise<string>((resolve) => {
+ resolveRefresh = resolve;
+ })
+ );
+
+ const calls = Promise.all([fetchMe(SERVER), fetchMe(SERVER), fetchMe(SERVER)]);
+ resolveRefresh(fresh);
+ await calls;
+
+ expect(refreshSession).toHaveBeenCalledOnce();
+ for (const call of fetchMock.mock.calls) {
+ expect(cookieHeaderOf(call)).toBe(`switch_auth=${fresh}`);
+ }
+ });
+
+ it('throws unauthorized without renewing when no token is stored', async () => {
+ getSessionCookie.mockResolvedValue(null);
+
+ await expect(fetchMe(SERVER)).rejects.toMatchObject({ kind: 'unauthorized' });
+ expect(refreshSession).not.toHaveBeenCalled();
+ expect(reauthenticateManagedServer).not.toHaveBeenCalled();
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+});
+
+describe('gatewayFetch managed-server silent re-auth', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ vi.stubGlobal('fetch', fetchMock);
+ fetchMock.mockImplementation(async () => okMeResponse());
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('mints a session for the managed server when none is stored', async () => {
+ const minted = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(null);
+ reauthenticateManagedServer.mockResolvedValue(minted);
+
+ await fetchMe(MANAGED);
+
+ expect(reauthenticateManagedServer).toHaveBeenCalledExactlyOnceWith(MANAGED);
+ expect(cookieHeaderOf(fetchMock.mock.calls[0])).toBe(`switch_auth=${minted}`);
+ });
+
+ it('re-logins and retries once on a 401 for the managed server', async () => {
+ const stored = makeJwt(24 * 60 * 60); // fresh, so no proactive renewal
+ const reissued = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(stored);
+ reauthenticateManagedServer.mockResolvedValue(reissued);
+ fetchMock.mockResolvedValueOnce(unauthorizedResponse());
+
+ const user = await fetchMe(MANAGED);
+
+ expect(user.id).toBe('u1');
+ expect(reauthenticateManagedServer).toHaveBeenCalledOnce();
+ expect(fetchMock).toHaveBeenCalledTimes(2);
+ expect(cookieHeaderOf(fetchMock.mock.calls[0])).toBe(`switch_auth=${stored}`);
+ expect(cookieHeaderOf(fetchMock.mock.calls[1])).toBe(`switch_auth=${reissued}`);
+ });
+
+ it('surfaces unauthorized when the managed re-login fails', async () => {
+ const stored = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(stored);
+ reauthenticateManagedServer.mockResolvedValue(null);
+ fetchMock.mockResolvedValue(unauthorizedResponse());
+
+ await expect(fetchMe(MANAGED)).rejects.toMatchObject({ kind: 'unauthorized' });
+ expect(reauthenticateManagedServer).toHaveBeenCalledOnce();
+ // Only the initial attempt — no retry when re-login yields no token.
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+
+ it('does not attempt re-login on a 401 for a non-managed server', async () => {
+ const stored = makeJwt(24 * 60 * 60);
+ getSessionCookie.mockResolvedValue(stored);
+ fetchMock.mockResolvedValue(unauthorizedResponse());
+
+ await expect(fetchMe(SERVER)).rejects.toMatchObject({ kind: 'unauthorized' });
+ expect(reauthenticateManagedServer).not.toHaveBeenCalled();
+ expect(fetchMock).toHaveBeenCalledOnce();
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
index 820a1de90..10bf7ffa2 100644
--- a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-client.ts
@@ -7,6 +7,7 @@ import type {
SwitchServer,
SwitchUser,
} from '@shared/core/switch-servers/switch-servers';
+import { reauthenticateManagedServer, refreshSession } from './auth';
import { getSessionCookie } from './servers-store';
/** The gateway management API is mounted under `/gateway` on the server. */
@@ -14,6 +15,54 @@ function gatewayUrl(server: SwitchServer, path: string): string {
return `${server.gatewayUrl}/gateway${path}`;
}
+/** Renew the session once the stored JWT is within this window of its `exp`, so
+ * an active client refreshes before the token dies rather than after a 401. */
+const SESSION_REFRESH_LEEWAY_MS = 60 * 60 * 1000;
+
+/**
+ * Read the `exp` (as ms since epoch) out of a JWT without verifying it — we only
+ * need the expiry to decide when to renew; the gateway still verifies the
+ * signature on every call. Returns null if the token is malformed or carries no
+ * numeric `exp`, in which case we skip proactive renewal and let the call fall
+ * through to the normal 401 path.
+ */
+function decodeJwtExpMs(jwt: string): number | null {
+ const parts = jwt.split('.');
+ if (parts.length !== 3) return null;
+ try {
+ const payload = JSON.parse(Buffer.from(parts[1], 'base64url').toString('utf8')) as {
+ exp?: unknown;
+ };
+ return typeof payload.exp === 'number' ? payload.exp * 1000 : null;
+ } catch {
+ return null;
+ }
+}
+
+/** Dedupe concurrent renewals per server so a burst of authenticated calls
+ * triggers at most one refresh round-trip (and one cookie write). */
+const inflightRefresh = new Map<string, Promise<string | null>>();
+
+/**
+ * Given the stored JWT, return the token to attach: the same JWT if it is not
+ * near expiry, otherwise a freshly renewed one (falling back to the current
+ * token if renewal did not succeed — the call then 401s and the caller prompts
+ * a sign-in).
+ */
+async function renewIfExpiring(server: SwitchServer, jwt: string): Promise<string> {
+ const expMs = decodeJwtExpMs(jwt);
+ if (expMs === null || expMs - Date.now() > SESSION_REFRESH_LEEWAY_MS) {
+ return jwt;
+ }
+ let pending = inflightRefresh.get(server.id);
+ if (!pending) {
+ pending = refreshSession(server, jwt).finally(() => inflightRefresh.delete(server.id));
+ inflightRefresh.set(server.id, pending);
+ }
+ const renewed = await pending;
+ return renewed ?? jwt;
+}
+
export type GatewayErrorKind = 'unauthorized' | 'http' | 'network';
/** Raised for any failed gateway call. `kind === 'unauthorized'` means the
@@ -38,38 +87,66 @@ type FetchOptions = {
body?: unknown;
};
+/**
+ * Resolve the `switch_auth` cookie to attach to an authenticated call, renewing
+ * proactively when near expiry. When no session is stored, the managed local
+ * server mints one silently (switchdash holds its admin creds); any other server
+ * has no way to authenticate silently, so this raises `unauthorized`.
+ */
+async function resolveAuthCookie(server: SwitchServer): Promise<string> {
+ const stored = await getSessionCookie(server.id);
+ if (stored) {
+ return renewIfExpiring(server, stored);
+ }
+ if (server.managed) {
+ const minted = await reauthenticateManagedServer(server);
+ if (minted) return minted;
+ }
+ throw new GatewayError('unauthorized', 'Not signed in to this Switch server.');
+}
+
async function gatewayFetch(
server: SwitchServer,
path: string,
options: FetchOptions
): Promise<Response> {
- const headers: Record<string, string> = { Accept: 'application/json' };
- if (options.body !== undefined) {
- headers['Content-Type'] = 'application/json';
- }
- if (options.authenticated) {
- const jwt = await getSessionCookie(server.id);
- if (!jwt) {
- throw new GatewayError('unauthorized', 'Not signed in to this Switch server.');
+ const sendOnce = async (cookie: string | null): Promise<Response> => {
+ const headers: Record<string, string> = { Accept: 'application/json' };
+ if (options.body !== undefined) {
+ headers['Content-Type'] = 'application/json';
}
- headers.Cookie = `switch_auth=${jwt}`;
- }
+ if (cookie) {
+ headers.Cookie = `switch_auth=${cookie}`;
+ }
+ try {
+ return await fetch(gatewayUrl(server, path), {
+ method: options.method ?? 'GET',
+ headers,
+ body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
+ // We attach the cookie explicitly; don't let the runtime manage a jar.
+ redirect: 'manual',
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch (cause) {
+ throw new GatewayError(
+ 'network',
+ `Could not reach ${server.gatewayUrl}: ${cause instanceof Error ? cause.message : String(cause)}`
+ );
+ }
+ };
- let response: Response;
- try {
- response = await fetch(gatewayUrl(server, path), {
- method: options.method ?? 'GET',
- headers,
- body: options.body !== undefined ? JSON.stringify(options.body) : undefined,
- // We attach the cookie explicitly; don't let the runtime manage a jar.
- redirect: 'manual',
- signal: AbortSignal.timeout(30_000),
- });
- } catch (cause) {
- throw new GatewayError(
- 'network',
- `Could not reach ${server.gatewayUrl}: ${cause instanceof Error ? cause.message : String(cause)}`
- );
+ const cookie = options.authenticated ? await resolveAuthCookie(server) : null;
+ let response = await sendOnce(cookie);
+
+ // Reactive silent re-auth for the managed local server: a 401 means the token
+ // is dead (e.g. the app reopened after the stack outlived it past the TTL).
+ // We hold its admin creds, so re-login and retry the call once rather than
+ // bouncing the user to a sign-in screen for a password they never saw.
+ if (response.status === 401 && options.authenticated && server.managed) {
+ const renewed = await reauthenticateManagedServer(server);
+ if (renewed) {
+ response = await sendOnce(renewed);
+ }
}
if (response.status === 401) {
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.test.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.test.ts
new file mode 100644
index 000000000..1d672f069
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.test.ts
@@ -0,0 +1,90 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const getSessionCookie = vi.hoisted(() => vi.fn());
+const reauthenticateManagedServer = vi.hoisted(() => vi.fn());
+const cookiesSet = vi.hoisted(() => vi.fn(async () => {}));
+const fromPartition = vi.hoisted(() => vi.fn(() => ({ cookies: { set: cookiesSet } })));
+const loadURL = vi.hoisted(() => vi.fn(async () => {}));
+const BrowserWindow = vi.hoisted(() =>
+ vi.fn(function () {
+ return { loadURL };
+ })
+);
+
+vi.mock('electron', () => ({ BrowserWindow, session: { fromPartition } }));
+vi.mock('./servers-store', () => ({ getSessionCookie }));
+vi.mock('./auth', () => ({ reauthenticateManagedServer }));
+vi.mock('@main/lib/logger', () => ({ log: { warn: vi.fn(), error: vi.fn() } }));
+
+const { openAuthenticatedGatewayPage } = await import('./gateway-web');
+
+const SERVER = {
+ id: 'srv-1',
+ name: 'S',
+ gatewayUrl: 'http://127.0.0.1:8080',
+ managed: false,
+} as never;
+const MANAGED = {
+ id: 'srv-local',
+ name: 'Local',
+ gatewayUrl: 'http://127.0.0.1:8080',
+ managed: true,
+} as never;
+
+describe('openAuthenticatedGatewayPage', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('rejects a url that is not on the gateway origin, before opening anything', async () => {
+ getSessionCookie.mockResolvedValue('jwt');
+
+ await expect(
+ openAuthenticatedGatewayPage(SERVER, 'http://evil.example.com/agents/1')
+ ).rejects.toThrow(/gateway origin/);
+ expect(BrowserWindow).not.toHaveBeenCalled();
+ expect(cookiesSet).not.toHaveBeenCalled();
+ });
+
+ it('injects the stored cookie for the gateway origin and opens the page', async () => {
+ getSessionCookie.mockResolvedValue('stored-jwt');
+
+ await openAuthenticatedGatewayPage(SERVER, 'http://127.0.0.1:8080/agents/abc');
+
+ expect(cookiesSet).toHaveBeenCalledWith(
+ expect.objectContaining({
+ url: 'http://127.0.0.1:8080',
+ name: 'switch_auth',
+ value: 'stored-jwt',
+ httpOnly: true,
+ secure: false,
+ })
+ );
+ expect(fromPartition).toHaveBeenCalledWith('persist:switch-gateway:srv-1');
+ expect(loadURL).toHaveBeenCalledWith('http://127.0.0.1:8080/agents/abc');
+ expect(reauthenticateManagedServer).not.toHaveBeenCalled();
+ });
+
+ it('mints a session for the managed server when none is stored', async () => {
+ getSessionCookie.mockResolvedValue(null);
+ reauthenticateManagedServer.mockResolvedValue('minted-jwt');
+
+ await openAuthenticatedGatewayPage(MANAGED, 'http://127.0.0.1:8080/');
+
+ expect(reauthenticateManagedServer).toHaveBeenCalledExactlyOnceWith(MANAGED);
+ expect(cookiesSet).toHaveBeenCalledWith(
+ expect.objectContaining({ name: 'switch_auth', value: 'minted-jwt' })
+ );
+ expect(loadURL).toHaveBeenCalledWith('http://127.0.0.1:8080/');
+ });
+
+ it('still opens the page (unauthenticated) when no session can be obtained', async () => {
+ getSessionCookie.mockResolvedValue(null);
+
+ await openAuthenticatedGatewayPage(SERVER, 'http://127.0.0.1:8080/');
+
+ // Non-managed with no stored session: no cookie injected, page still opens.
+ expect(cookiesSet).not.toHaveBeenCalled();
+ expect(loadURL).toHaveBeenCalledWith('http://127.0.0.1:8080/');
+ });
+});
diff --git a/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.ts b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.ts
new file mode 100644
index 000000000..759ef5a55
--- /dev/null
+++ b/dash/apps/switchdash-desktop/src/main/core/switch-servers/gateway-web.ts
@@ -0,0 +1,69 @@
+import { BrowserWindow, session as electronSession } from 'electron';
+import { log } from '@main/lib/logger';
+import type { SwitchServer } from '@shared/core/switch-servers/switch-servers';
+import { reauthenticateManagedServer } from './auth';
+import { getSessionCookie } from './servers-store';
+
+const SWITCH_AUTH_COOKIE = 'switch_auth';
+
+/**
+ * Open a gateway web page (the operator dashboard) in an in-app window that is
+ * already signed in. The system browser can't be handed our httponly
+ * `switch_auth` cookie, so we open an Electron window and inject the stored
+ * cookie into its isolated session before loading — the reverse of what OIDC
+ * login does when it reads the cookie back out. For the managed local server we
+ * mint a session first (switchdash holds its admin creds) so the page is always
+ * authenticated; other servers open with whatever session is stored, falling
+ * back to the gateway's own sign-in page if none.
+ *
+ * `url` must live on the server's gateway origin — the caller builds it from
+ * `server.gatewayUrl` — so the injected cookie is only ever exposed to the
+ * gateway itself.
+ */
+export async function openAuthenticatedGatewayPage(
+ server: SwitchServer,
+ url: string
+): Promise<void> {
+ const gatewayOrigin = new URL(server.gatewayUrl).origin;
+ if (new URL(url).origin !== gatewayOrigin) {
+ throw new Error(`Refusing to open ${url}: not on the gateway origin ${gatewayOrigin}`);
+ }
+
+ let jwt = await getSessionCookie(server.id);
+ if (!jwt && server.managed) {
+ jwt = await reauthenticateManagedServer(server);
+ }
+
+ // A persistent per-server partition isolates the gateway session from other
+ // servers and from the app's own web content, and keeps it across opens.
+ const partition = `persist:switch-gateway:${server.id}`;
+ const ses = electronSession.fromPartition(partition);
+
+ if (jwt) {
+ try {
+ await ses.cookies.set({
+ url: gatewayOrigin,
+ name: SWITCH_AUTH_COOKIE,
+ value: jwt,
+ httpOnly: true,
+ sameSite: 'lax',
+ secure: gatewayOrigin.startsWith('https'),
+ });
+ } catch (cause) {
+ // Non-fatal: the page still opens, just unauthenticated (its own sign-in).
+ log.warn('Could not inject Switch session cookie into gateway window', {
+ server: server.id,
+ cause: cause instanceof Error ? cause.message : String(cause),
+ });
+ }
+ }
+
+ const win = new BrowserWindow({
+ width: 1280,
+ height: 860,
+ title: server.name,
+ autoHideMenuBar: true,
+ webPreferences: { partition, nodeIntegration: false, contextIsolation: true },
+ });
+ await win.loadURL(url);
+}
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx
index e3f285d9b..d3342dd8f 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/sidebar/location-item.tsx
@@ -141,7 +141,9 @@ export const SidebarLocationItem = observer(function SidebarLocationItem({
? switchRoomsStore.gatewayAgentUrl(agent.serverId, agent.switchAgentId)
: null;
const openInGateway = () => {
- if (gatewayUrl) void rpc.app.openExternal(gatewayUrl);
+ if (gatewayUrl && agent?.serverId) {
+ void rpc.switchServers.openGatewayPage({ serverId: agent.serverId, url: gatewayUrl });
+ }
};
const renderSpinnerWithTooltip = () => {
diff --git a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
index c2816c67f..01869a04e 100644
--- a/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
+++ b/dash/apps/switchdash-desktop/src/renderer/features/switch-servers/view.tsx
@@ -150,7 +150,12 @@ const ServerMainPanel = observer(function ServerMainPanel() {
<Button
variant="outline"
size="sm"
- onClick={() => void rpc.app.openExternal(server.gatewayUrl)}
+ onClick={() =>
+ void rpc.switchServers.openGatewayPage({
+ serverId: server.id,
+ url: server.gatewayUrl,
+ })
+ }
>
<ExternalLink className="size-4" />
Open web app