Skip to content

Self-hosted homelab infrastructure visualizer — interactive network diagram with live status monitoring

feat(auth): add OIDC browser session flow

ypsofd96b7d6ae83
diff --git a/frontend/src/App.tsx b/frontend/src/App.tsx
index c0fda1c..7dcac07 100644
--- a/frontend/src/App.tsx
+++ b/frontend/src/App.tsx
@@ -51,6 +51,7 @@ import { WalkthroughInvite } from '@/walkthrough/WalkthroughInvite'
import { WalkthroughOverlay } from '@/walkthrough/WalkthroughOverlay'
import { DEMO_SCAN_RUNS, DEMO_PENDING_DEVICES } from '@/walkthrough/demoTourData'
import { useStatusPolling } from '@/hooks/useStatusPolling'
+import { bootstrapAuth } from '@/auth/bootstrap'
import type { NodeData, EdgeData, CustomStyleDef, FloorMapConfig, NodeType } from '@/types'
import type { ZigbeeNode, ZigbeeEdge } from '@/components/zigbee/types'
import type { ZwaveNode, ZwaveEdge } from '@/components/zwave/types'
@@ -62,12 +63,19 @@ const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
export default function App() {
const { loadCanvas, applyLayout, markSaved, markUnsaved, hasUnsavedChanges, editSeq, selectedNodeId, selectedNodeIds, addNode, updateNode, deleteNode, onConnect, updateEdge, deleteEdge, setProxmoxContainerMode, setNodeZIndex, editingGroupRectId, setEditingGroupRectId, editingTextId, setEditingTextId, nodes, edges, snapshotHistory, undo, redo, addToGroup, addToContainer, floorMap, setFloorMap } = useCanvasStore()
const canvasRef = useRef<HTMLDivElement>(null)
- const { isAuthenticated } = useAuthStore()
+ const { isAuthenticated, isInitialized } = useAuthStore()
+ const authBootstrapStarted = useRef(false)
const { activeTheme, setTheme, customStyle, setCustomStyle } = useThemeStore()
const { activeDesignId, setDesigns, setActiveDesign } = useDesignStore()
useStatusPolling()
+ useEffect(() => {
+ if (STANDALONE || authBootstrapStarted.current) return
+ authBootstrapStarted.current = true
+ void bootstrapAuth()
+ }, [])
+
const [autosave, setAutosave] = useState<AutosaveSettings>(readAutosaveSettings)
useEffect(() => subscribeAutosaveSettings(setAutosave), [])
@@ -922,6 +930,13 @@ export default function App() {
const editNode = editNodeId ? nodes.find((n) => n.id === editNodeId) : null
const editEdge = editEdgeId ? edges.find((e) => e.id === editEdgeId) : null
+ if (!STANDALONE && !isInitialized) {
+ return (
+ <div className="flex h-screen w-screen items-center justify-center bg-[#0d1117] text-sm text-muted-foreground">
+ Loading authentication…
+ </div>
+ )
+ }
if (!STANDALONE && !isAuthenticated) return <LoginPage />
return (
diff --git a/frontend/src/api/__tests__/client.test.ts b/frontend/src/api/__tests__/client.test.ts
index 5f3bc66..3cda64d 100644
--- a/frontend/src/api/__tests__/client.test.ts
+++ b/frontend/src/api/__tests__/client.test.ts
@@ -6,7 +6,7 @@ type Interceptor<T> = {
}
interface MockInstance {
- defaults: { baseURL?: string }
+ defaults: { baseURL?: string; withCredentials?: boolean }
interceptors: {
request: { use: (f: Interceptor<unknown>['fulfilled'], r?: Interceptor<unknown>['rejected']) => void }
response: { use: (f: Interceptor<unknown>['fulfilled'], r?: Interceptor<unknown>['rejected']) => void }
@@ -25,9 +25,9 @@ const instances = hoisted.instances as MockInstance[]
vi.mock('axios', () => {
return {
default: {
- create: (cfg: { baseURL?: string }) => {
+ create: (cfg: { baseURL?: string; withCredentials?: boolean }) => {
const inst: MockInstance = {
- defaults: { baseURL: cfg?.baseURL },
+ defaults: { baseURL: cfg?.baseURL, withCredentials: cfg?.withCredentials },
interceptors: {
request: { use: (f: unknown, r?: unknown) => { inst.__req = { fulfilled: f as never, rejected: r as never } } },
response: { use: (f: unknown, r?: unknown) => { inst.__res = { fulfilled: f as never, rejected: r as never } } },
@@ -54,7 +54,7 @@ describe('api/client', () => {
const [api, publicApi] = instances
beforeEach(() => {
- useAuthStore.setState({ token: null, isAuthenticated: false })
+ useAuthStore.setState({ token: null, csrfToken: null, isAuthenticated: false })
api.get.mockClear()
api.post.mockClear()
api.patch.mockClear()
@@ -66,6 +66,7 @@ describe('api/client', () => {
it('creates two axios instances with /api/v1 baseURL', () => {
expect(instances).toHaveLength(2)
expect(api.defaults.baseURL).toBe('/api/v1')
+ expect(api.defaults.withCredentials).toBe(true)
expect(publicApi.defaults.baseURL).toBe('/api/v1')
})
@@ -86,6 +87,18 @@ describe('api/client', () => {
expect((out as typeof cfg).headers.Authorization).toBeUndefined()
})
+ it('adds the in-memory OIDC CSRF token only to unsafe requests', () => {
+ useAuthStore.setState({ csrfToken: 'csrf-123' })
+ const post = { method: 'post', headers: {} as Record<string, string> }
+ const get = { method: 'get', headers: {} as Record<string, string> }
+
+ api.__req.fulfilled!(post)
+ api.__req.fulfilled!(get)
+
+ expect(post.headers['X-Homelable-CSRF']).toBe('csrf-123')
+ expect(get.headers['X-Homelable-CSRF']).toBeUndefined()
+ })
+
it('response interceptor passes through 2xx responses', () => {
const r = { status: 200, data: { ok: true } }
expect(api.__res.fulfilled!(r)).toBe(r)
@@ -125,6 +138,15 @@ describe('api/client', () => {
expect(api.post).toHaveBeenCalledWith('/auth/login', { username: 'u', password: 'p' })
})
+ it('authApi discovers auth publicly and manages the current session', () => {
+ mod.authApi.config()
+ expect(publicApi.get).toHaveBeenCalledWith('/auth/config')
+ mod.authApi.me()
+ expect(api.get).toHaveBeenCalledWith('/auth/me')
+ mod.authApi.logout()
+ expect(api.post).toHaveBeenCalledWith('/auth/logout')
+ })
+
it('canvasApi.load GETs /canvas', () => {
mod.canvasApi.load()
expect(api.get).toHaveBeenCalledWith('/canvas', expect.objectContaining({}))
diff --git a/frontend/src/api/client.ts b/frontend/src/api/client.ts
index d792c0d..abacdf6 100644
--- a/frontend/src/api/client.ts
+++ b/frontend/src/api/client.ts
@@ -1,16 +1,22 @@
import axios from 'axios'
import { useAuthStore } from '@/stores/authStore'
+import type { AuthMode, AuthUser } from '@/stores/authStore'
export const api = axios.create({
baseURL: '/api/v1',
+ withCredentials: true,
})
// Unauthenticated axios instance — no JWT, no 401 redirect (used for public endpoints)
const publicApi = axios.create({ baseURL: '/api/v1' })
api.interceptors.request.use((config) => {
- const token = useAuthStore.getState().token
+ const { token, csrfToken } = useAuthStore.getState()
if (token) config.headers.Authorization = `Bearer ${token}`
+ const method = config.method?.toUpperCase() ?? 'GET'
+ if (csrfToken && !['GET', 'HEAD', 'OPTIONS'].includes(method)) {
+ config.headers['X-Homelable-CSRF'] = csrfToken
+ }
return config
})
@@ -23,8 +29,11 @@ api.interceptors.response.use(
)
export const authApi = {
+ config: () => publicApi.get<{ mode: AuthMode; oidc_login_url: string | null }>('/auth/config'),
login: (username: string, password: string) =>
api.post<{ access_token: string }>('/auth/login', { username, password }),
+ me: () => api.get<AuthUser>('/auth/me'),
+ logout: () => api.post('/auth/logout'),
}
export const canvasApi = {
diff --git a/frontend/src/auth/__tests__/bootstrap.test.ts b/frontend/src/auth/__tests__/bootstrap.test.ts
new file mode 100644
index 0000000..36689ec
--- /dev/null
+++ b/frontend/src/auth/__tests__/bootstrap.test.ts
@@ -0,0 +1,121 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { useAuthStore } from '@/stores/authStore'
+
+vi.mock('@/api/client', () => ({
+ authApi: {
+ config: vi.fn(),
+ me: vi.fn(),
+ },
+}))
+
+import { authApi } from '@/api/client'
+import { bootstrapAuth } from '../bootstrap'
+
+describe('bootstrapAuth', () => {
+ beforeEach(() => {
+ sessionStorage.clear()
+ useAuthStore.setState({
+ token: null,
+ isAuthenticated: false,
+ isInitialized: false,
+ authMode: null,
+ authMethod: null,
+ oidcLoginUrl: null,
+ displayName: null,
+ csrfToken: null,
+ })
+ vi.mocked(authApi.config).mockReset()
+ vi.mocked(authApi.me).mockReset()
+ })
+
+ it('restores an OIDC cookie session without storing an IdP token', async () => {
+ vi.mocked(authApi.config).mockResolvedValue({
+ data: { mode: 'oidc', oidc_login_url: '/api/v1/auth/oidc/login' },
+ } as never)
+ vi.mocked(authApi.me).mockResolvedValue({
+ data: {
+ subject: 'user-1',
+ display_name: 'Alice',
+ auth_method: 'oidc',
+ issuer: 'https://id.example/application/o/homelable/',
+ csrf_token: 'csrf-123',
+ },
+ } as never)
+
+ await bootstrapAuth()
+
+ const state = useAuthStore.getState()
+ expect(authApi.me).toHaveBeenCalledOnce()
+ expect(state.isAuthenticated).toBe(true)
+ expect(state.authMethod).toBe('oidc')
+ expect(state.token).toBeNull()
+ expect(state.csrfToken).toBe('csrf-123')
+ })
+
+ it('does not probe /auth/me for local mode without a persisted token', async () => {
+ vi.mocked(authApi.config).mockResolvedValue({
+ data: { mode: 'local', oidc_login_url: null },
+ } as never)
+
+ await bootstrapAuth()
+
+ expect(authApi.me).not.toHaveBeenCalled()
+ expect(useAuthStore.getState()).toMatchObject({
+ authMode: 'local',
+ isAuthenticated: false,
+ isInitialized: true,
+ })
+ })
+
+ it('validates and retains a persisted local bearer token', async () => {
+ useAuthStore.setState({ token: 'local-token' })
+ vi.mocked(authApi.config).mockResolvedValue({
+ data: { mode: 'local', oidc_login_url: null },
+ } as never)
+ vi.mocked(authApi.me).mockResolvedValue({
+ data: {
+ subject: 'admin',
+ display_name: 'admin',
+ auth_method: 'local',
+ issuer: null,
+ csrf_token: null,
+ },
+ } as never)
+
+ await bootstrapAuth()
+
+ expect(useAuthStore.getState()).toMatchObject({
+ token: 'local-token',
+ isAuthenticated: true,
+ authMethod: 'local',
+ })
+ })
+
+ it('fails closed when the backend rejects the session', async () => {
+ useAuthStore.setState({ token: 'expired-token', isAuthenticated: true })
+ vi.mocked(authApi.config).mockResolvedValue({
+ data: { mode: 'local', oidc_login_url: null },
+ } as never)
+ vi.mocked(authApi.me).mockRejectedValue({ response: { status: 401 } })
+
+ await bootstrapAuth()
+
+ expect(useAuthStore.getState()).toMatchObject({
+ token: null,
+ isAuthenticated: false,
+ isInitialized: true,
+ })
+ })
+
+ it('leaves the auth mode unknown when discovery is unavailable', async () => {
+ vi.mocked(authApi.config).mockRejectedValue(new Error('network down'))
+
+ await bootstrapAuth()
+
+ expect(useAuthStore.getState()).toMatchObject({
+ authMode: null,
+ isAuthenticated: false,
+ isInitialized: true,
+ })
+ })
+})
diff --git a/frontend/src/auth/bootstrap.ts b/frontend/src/auth/bootstrap.ts
new file mode 100644
index 0000000..4b7e92b
--- /dev/null
+++ b/frontend/src/auth/bootstrap.ts
@@ -0,0 +1,33 @@
+import { authApi } from '@/api/client'
+import { useAuthStore } from '@/stores/authStore'
+
+/**
+ * Discover the configured authentication mode and restore a valid session.
+ * OIDC sessions are represented only by the backend's HttpOnly cookie; local
+ * sessions retain their existing bearer token until /auth/me validates it.
+ */
+export async function bootstrapAuth(): Promise<void> {
+ const store = useAuthStore.getState()
+
+ try {
+ const { data: config } = await authApi.config()
+ store.setAuthConfig(config.mode, config.oidc_login_url)
+
+ const token = useAuthStore.getState().token
+ if (config.mode === 'oidc' || token) {
+ try {
+ const { data: user } = await authApi.me()
+ useAuthStore.getState().authenticate(user)
+ } catch {
+ // The response interceptor clears invalid credentials on 401. Also
+ // clear them for malformed/unreachable session checks, failing closed.
+ useAuthStore.getState().logout()
+ }
+ }
+ } catch {
+ // Keep authMode unknown when discovery is unreachable. The login screen
+ // reports that state without guessing which authentication mode is active.
+ } finally {
+ useAuthStore.getState().finishInitialization()
+ }
+}
diff --git a/frontend/src/components/LoginPage.tsx b/frontend/src/components/LoginPage.tsx
index 3272798..bdea9f5 100644
--- a/frontend/src/components/LoginPage.tsx
+++ b/frontend/src/components/LoginPage.tsx
@@ -1,17 +1,18 @@
import { useState } from 'react'
import { Network, Loader2 } from 'lucide-react'
-import { Button } from '@/components/ui/button'
+import { Button, buttonVariants } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { authApi } from '@/api/client'
import { useAuthStore } from '@/stores/authStore'
+import { cn } from '@/lib/utils'
export function LoginPage() {
const [username, setUsername] = useState('')
const [password, setPassword] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
- const login = useAuthStore((s) => s.login)
+ const { authMode, oidcLoginUrl, login } = useAuthStore()
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
@@ -51,53 +52,82 @@ export function LoginPage() {
</div>
</div>
- {/* Form */}
- <form
- onSubmit={handleSubmit}
- className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6"
- >
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="username" className="text-xs text-muted-foreground">Username</Label>
- <Input
- id="username"
- autoComplete="username"
- value={username}
- onChange={(e) => setUsername(e.target.value)}
- className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
- placeholder="admin"
- required
- />
- </div>
+ {authMode === 'local' && (
+ <>
+ <form
+ onSubmit={handleSubmit}
+ className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6"
+ >
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="username" className="text-xs text-muted-foreground">Username</Label>
+ <Input
+ id="username"
+ autoComplete="username"
+ value={username}
+ onChange={(e) => setUsername(e.target.value)}
+ className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
+ placeholder="admin"
+ required
+ />
+ </div>
- <div className="flex flex-col gap-1.5">
- <Label htmlFor="password" className="text-xs text-muted-foreground">Password</Label>
- <Input
- id="password"
- type="password"
- autoComplete="current-password"
- value={password}
- onChange={(e) => setPassword(e.target.value)}
- className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
- required
- />
- </div>
+ <div className="flex flex-col gap-1.5">
+ <Label htmlFor="password" className="text-xs text-muted-foreground">Password</Label>
+ <Input
+ id="password"
+ type="password"
+ autoComplete="current-password"
+ value={password}
+ onChange={(e) => setPassword(e.target.value)}
+ className="bg-[#21262d] border-[#30363d] focus-visible:ring-[#00d4ff]/50 text-sm"
+ required
+ />
+ </div>
+
+ {error && (
+ <p className="text-xs text-[#f85149] text-center">{error}</p>
+ )}
- {error && (
- <p className="text-xs text-[#f85149] text-center">{error}</p>
- )}
+ <Button
+ type="submit"
+ disabled={loading}
+ className="mt-1 bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium"
+ >
+ {loading ? <Loader2 size={15} className="animate-spin" /> : 'Sign in'}
+ </Button>
+ </form>
- <Button
- type="submit"
- disabled={loading}
- className="mt-1 bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium"
- >
- {loading ? <Loader2 size={15} className="animate-spin" /> : 'Sign in'}
- </Button>
- </form>
+ <p className="text-center text-[10px] text-muted-foreground/40 mt-4">
+ Credentials configured in <span className="font-mono">.env</span>
+ </p>
+ </>
+ )}
- <p className="text-center text-[10px] text-muted-foreground/40 mt-4">
- Credentials configured in <span className="font-mono">.env</span>
- </p>
+ {authMode === 'oidc' && (
+ <div className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6 text-center">
+ <p className="text-sm text-muted-foreground">
+ Continue through the configured OpenID Connect provider.
+ </p>
+ <a
+ href={oidcLoginUrl ?? '/api/v1/auth/oidc/login'}
+ className={cn(
+ buttonVariants(),
+ 'bg-[#00d4ff] text-[#0d1117] hover:bg-[#00d4ff]/90 font-medium',
+ )}
+ >
+ Sign in with OpenID Connect
+ </a>
+ </div>
+ )}
+
+ {authMode === null && (
+ <div className="flex flex-col gap-4 bg-[#161b22] border border-[#30363d] rounded-xl p-6 text-center">
+ <p className="text-sm text-[#f85149]">Could not load authentication configuration.</p>
+ <Button type="button" variant="outline" onClick={() => window.location.reload()}>
+ Retry
+ </Button>
+ </div>
+ )}
</div>
</div>
)
diff --git a/frontend/src/components/__tests__/LoginPage.test.tsx b/frontend/src/components/__tests__/LoginPage.test.tsx
index 64ca1ab..7df6e52 100644
--- a/frontend/src/components/__tests__/LoginPage.test.tsx
+++ b/frontend/src/components/__tests__/LoginPage.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest'
-import { render, screen, fireEvent, waitFor } from '@testing-library/react'
+import { act, render, screen, fireEvent, waitFor } from '@testing-library/react'
import { LoginPage } from '../LoginPage'
import { useAuthStore } from '@/stores/authStore'
@@ -13,7 +13,12 @@ import { authApi } from '@/api/client'
describe('LoginPage', () => {
beforeEach(() => {
- useAuthStore.setState({ token: null, isAuthenticated: false })
+ useAuthStore.setState({
+ token: null,
+ isAuthenticated: false,
+ authMode: 'local',
+ oidcLoginUrl: null,
+ })
vi.mocked(authApi.login).mockReset()
})
@@ -30,6 +35,30 @@ describe('LoginPage', () => {
expect(screen.getByRole('button', { name: /sign in/i })).toBeDefined()
})
+ it('renders only the provider redirect in OIDC mode', () => {
+ useAuthStore.setState({
+ authMode: 'oidc',
+ oidcLoginUrl: '/api/v1/auth/oidc/login',
+ })
+
+ render(<LoginPage />)
+
+ expect(screen.queryByLabelText('Username')).toBeNull()
+ expect(screen.queryByLabelText('Password')).toBeNull()
+ expect(screen.getByRole('link', { name: 'Sign in with OpenID Connect' }))
+ .toHaveAttribute('href', '/api/v1/auth/oidc/login')
+ })
+
+ it('does not guess an auth mode when discovery failed', () => {
+ useAuthStore.setState({ authMode: null })
+
+ render(<LoginPage />)
+
+ expect(screen.getByText('Could not load authentication configuration.')).toBeDefined()
+ expect(screen.queryByLabelText('Username')).toBeNull()
+ expect(screen.getByRole('button', { name: 'Retry' })).toBeDefined()
+ })
+
// ── Security checks ──────────────────────────────────────────────────────
it('password field type is "password" — not rendered as plain text', () => {
@@ -102,7 +131,9 @@ describe('LoginPage', () => {
await waitFor(() => {
expect((screen.getByRole('button', { name: '' }) as HTMLButtonElement).disabled).toBe(true)
})
- resolve({ data: { access_token: 'tok' } })
+ await act(async () => {
+ resolve({ data: { access_token: 'tok' } })
+ })
})
it('calls authApi.login with credentials via POST body (not URL params)', async () => {
diff --git a/frontend/src/components/panels/Sidebar.tsx b/frontend/src/components/panels/Sidebar.tsx
index 45aa1dc..30f285c 100644
--- a/frontend/src/components/panels/Sidebar.tsx
+++ b/frontend/src/components/panels/Sidebar.tsx
@@ -5,7 +5,7 @@ import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip
import { useCanvasStore } from '@/stores/canvasStore'
import { useDesignStore } from '@/stores/designStore'
import { useAuthStore } from '@/stores/authStore'
-import { designsApi, mediaApi } from '@/api/client'
+import { authApi, designsApi, mediaApi } from '@/api/client'
import * as standaloneStorage from '@/utils/standaloneStorage'
import { resolveDesignIcon, DEFAULT_DESIGN_ICON } from '@/utils/designIcons'
import { DesignModal, type DesignFormData } from '@/components/modals/DesignModal'
@@ -47,6 +47,15 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
const { nodes, hasUnsavedChanges, floorMap, setFloorMap } = useCanvasStore()
const floorMapEditNonce = useCanvasStore((s) => s.floorMapEditNonce)
+ const handleLogout = useCallback(async () => {
+ try {
+ await authApi.logout()
+ logout()
+ } catch {
+ toast.error('Could not end the current session')
+ }
+ }, [logout])
+
const openDesignModal = useCallback((m: { mode: 'create' | 'edit'; design?: Design }) => {
setOpenSeq((s) => s + 1)
setDesignModal(m)
@@ -294,7 +303,7 @@ export function Sidebar({ onAddNode, onAddGroupRect, onAddText, onScan, onZigbee
icon={LogOut}
label="Logout"
collapsed={collapsed}
- onClick={logout}
+ onClick={() => void handleLogout()}
/>
)}
</div>
diff --git a/frontend/src/components/panels/__tests__/Sidebar.test.tsx b/frontend/src/components/panels/__tests__/Sidebar.test.tsx
index c74e73d..45e11b6 100644
--- a/frontend/src/components/panels/__tests__/Sidebar.test.tsx
+++ b/frontend/src/components/panels/__tests__/Sidebar.test.tsx
@@ -1,5 +1,5 @@
import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
-import { render, screen, fireEvent } from '@testing-library/react'
+import { render, screen, fireEvent, waitFor } from '@testing-library/react'
import { Sidebar } from '../Sidebar'
import { useCanvasStore } from '@/stores/canvasStore'
import { useAuthStore } from '@/stores/authStore'
@@ -13,6 +13,9 @@ vi.mock('@/stores/canvasStore')
vi.mock('@/stores/authStore')
vi.mock('@/api/client', () => ({
+ authApi: {
+ logout: vi.fn().mockResolvedValue({}),
+ },
scanApi: {
trigger: vi.fn().mockResolvedValue({}),
runs: vi.fn().mockResolvedValue({ data: [] }),
@@ -272,10 +275,14 @@ describe('Sidebar', () => {
expect(screen.getByText('Logout')).toBeInTheDocument()
})
- it('calls logout when Logout is clicked', () => {
+ it('ends the backend session before clearing local auth state', async () => {
+ const { authApi } = await import('@/api/client')
render(<Sidebar {...defaultProps} />)
fireEvent.click(screen.getByText('Logout'))
- expect(mockLogout).toHaveBeenCalledOnce()
+ await waitFor(() => {
+ expect(authApi.logout).toHaveBeenCalledOnce()
+ expect(mockLogout).toHaveBeenCalledOnce()
+ })
})
})
diff --git a/frontend/src/hooks/__tests__/useStatusPolling.test.ts b/frontend/src/hooks/__tests__/useStatusPolling.test.ts
index 1a89280..a558b42 100644
--- a/frontend/src/hooks/__tests__/useStatusPolling.test.ts
+++ b/frontend/src/hooks/__tests__/useStatusPolling.test.ts
@@ -39,6 +39,7 @@ describe('useStatusPolling', () => {
vi.mocked(useAuthStore).mockReturnValue({
isAuthenticated: true,
+ authMethod: 'local',
token: 'test-token',
} as ReturnType<typeof useAuthStore>)
@@ -58,6 +59,7 @@ describe('useStatusPolling', () => {
it('does not open WebSocket when not authenticated', () => {
vi.mocked(useAuthStore).mockReturnValue({
isAuthenticated: false,
+ authMethod: null,
token: null,
} as ReturnType<typeof useAuthStore>)
renderHook(() => useStatusPolling())
@@ -67,12 +69,28 @@ describe('useStatusPolling', () => {
it('does not open WebSocket when token is missing', () => {
vi.mocked(useAuthStore).mockReturnValue({
isAuthenticated: true,
+ authMethod: 'local',
token: null,
} as ReturnType<typeof useAuthStore>)
renderHook(() => useStatusPolling())
expect(MockWebSocket.instances).toHaveLength(0)
})
+ it('uses the HttpOnly cookie and sends no credential in OIDC mode', () => {
+ vi.mocked(useAuthStore).mockReturnValue({
+ isAuthenticated: true,
+ authMethod: 'oidc',
+ token: null,
+ } as ReturnType<typeof useAuthStore>)
+
+ renderHook(() => useStatusPolling())
+
+ expect(MockWebSocket.instances).toHaveLength(1)
+ const ws = MockWebSocket.instances[0]
+ ws.onopen?.()
+ expect(ws.send).not.toHaveBeenCalled()
+ })
+
it('connects to correct ws:// URL', () => {
renderHook(() => useStatusPolling())
expect(MockWebSocket.instances).toHaveLength(1)
diff --git a/frontend/src/hooks/useStatusPolling.ts b/frontend/src/hooks/useStatusPolling.ts
index b21b340..7b59c39 100644
--- a/frontend/src/hooks/useStatusPolling.ts
+++ b/frontend/src/hooks/useStatusPolling.ts
@@ -25,10 +25,10 @@ const STANDALONE = import.meta.env.VITE_STANDALONE === 'true'
export function useStatusPolling() {
const wsRef = useRef<WebSocket | null>(null)
const { setNodeStatus, notifyScanDeviceFound, setServiceStatuses } = useCanvasStore()
- const { isAuthenticated, token } = useAuthStore()
+ const { isAuthenticated, authMethod, token } = useAuthStore()
useEffect(() => {
- if (STANDALONE || !isAuthenticated || !token) return
+ if (STANDALONE || !isAuthenticated || (authMethod !== 'oidc' && !token)) return
const protocol = window.location.protocol === 'https:' ? 'wss' : 'ws'
const host = window.location.host // includes port when non-standard
@@ -37,9 +37,13 @@ export function useStatusPolling() {
const ws = new WebSocket(url)
wsRef.current = ws
- // Send token as first message (not in URL to avoid log/history exposure)
- ws.onopen = () => {
- ws.send(JSON.stringify({ token }))
+ // Local mode sends the bearer token as the first message (not in the URL
+ // where proxies may log it). OIDC mode is authenticated during the upgrade
+ // with the backend's HttpOnly session cookie, so React sends no credential.
+ if (token) {
+ ws.onopen = () => {
+ ws.send(JSON.stringify({ token }))
+ }
}
ws.onmessage = (event) => {
@@ -71,5 +75,5 @@ export function useStatusPolling() {
ws.close()
wsRef.current = null
}
- }, [isAuthenticated, token, setNodeStatus, notifyScanDeviceFound, setServiceStatuses])
+ }, [isAuthenticated, authMethod, token, setNodeStatus, notifyScanDeviceFound, setServiceStatuses])
}
diff --git a/frontend/src/stores/__tests__/authStore.test.ts b/frontend/src/stores/__tests__/authStore.test.ts
index b44e453..1dde8a6 100644
--- a/frontend/src/stores/__tests__/authStore.test.ts
+++ b/frontend/src/stores/__tests__/authStore.test.ts
@@ -4,7 +4,17 @@ import { useAuthStore } from '@/stores/authStore'
describe('authStore', () => {
beforeEach(() => {
localStorage.clear()
- useAuthStore.setState({ token: null, isAuthenticated: false })
+ sessionStorage.clear()
+ useAuthStore.setState({
+ token: null,
+ isAuthenticated: false,
+ isInitialized: false,
+ authMode: null,
+ authMethod: null,
+ oidcLoginUrl: null,
+ displayName: null,
+ csrfToken: null,
+ })
})
it('starts unauthenticated', () => {
@@ -18,6 +28,8 @@ describe('authStore', () => {
const { token, isAuthenticated } = useAuthStore.getState()
expect(token).toBe('my-jwt-token')
expect(isAuthenticated).toBe(true)
+ expect(useAuthStore.getState().authMethod).toBe('local')
+ expect(useAuthStore.getState().isInitialized).toBe(true)
})
it('logout clears token and isAuthenticated', () => {
@@ -27,4 +39,36 @@ describe('authStore', () => {
expect(token).toBeNull()
expect(isAuthenticated).toBe(false)
})
+
+ it('stores OIDC identity and CSRF state without a browser-readable credential', () => {
+ useAuthStore.getState().setAuthConfig('oidc', '/api/v1/auth/oidc/login')
+ useAuthStore.getState().authenticate({
+ subject: 'user-1',
+ display_name: 'Alice',
+ auth_method: 'oidc',
+ issuer: 'https://id.example/application/o/homelable/',
+ csrf_token: 'csrf-123',
+ })
+
+ const state = useAuthStore.getState()
+ expect(state.token).toBeNull()
+ expect(state.isAuthenticated).toBe(true)
+ expect(state.authMethod).toBe('oidc')
+ expect(state.displayName).toBe('Alice')
+ expect(state.csrfToken).toBe('csrf-123')
+ expect(sessionStorage.getItem('homelable-auth') ?? '').not.toContain('csrf-123')
+ })
+
+ it('keeps a validated local token when applying /auth/me identity', () => {
+ useAuthStore.getState().login('local-token')
+ useAuthStore.getState().authenticate({
+ subject: 'admin',
+ display_name: 'admin',
+ auth_method: 'local',
+ issuer: null,
+ csrf_token: null,
+ })
+
+ expect(useAuthStore.getState().token).toBe('local-token')
+ })
})
diff --git a/frontend/src/stores/authStore.ts b/frontend/src/stores/authStore.ts
index 889ff88..8f44ea5 100644
--- a/frontend/src/stores/authStore.ts
+++ b/frontend/src/stores/authStore.ts
@@ -1,9 +1,29 @@
import { create } from 'zustand'
import { persist, createJSONStorage } from 'zustand/middleware'
+export type AuthMode = 'local' | 'oidc'
+export type AuthMethod = AuthMode
+
+export interface AuthUser {
+ subject: string
+ display_name: string
+ auth_method: AuthMethod
+ issuer: string | null
+ csrf_token: string | null
+}
+
interface AuthState {
token: string | null
isAuthenticated: boolean
+ isInitialized: boolean
+ authMode: AuthMode | null
+ authMethod: AuthMethod | null
+ oidcLoginUrl: string | null
+ displayName: string | null
+ csrfToken: string | null
+ setAuthConfig: (mode: AuthMode, oidcLoginUrl: string | null) => void
+ authenticate: (user: AuthUser) => void
+ finishInitialization: () => void
login: (token: string) => void
logout: () => void
}
@@ -13,14 +33,56 @@ export const useAuthStore = create<AuthState>()(
(set) => ({
token: null,
isAuthenticated: false,
- login: (token) => set({ token, isAuthenticated: true }),
- logout: () => set({ token: null, isAuthenticated: false }),
+ isInitialized: false,
+ authMode: null,
+ authMethod: null,
+ oidcLoginUrl: null,
+ displayName: null,
+ csrfToken: null,
+ setAuthConfig: (authMode, oidcLoginUrl) => set({ authMode, oidcLoginUrl }),
+ authenticate: (user) => set((state) => ({
+ token: user.auth_method === 'oidc' ? null : state.token,
+ isAuthenticated: true,
+ isInitialized: true,
+ authMethod: user.auth_method,
+ displayName: user.display_name,
+ csrfToken: user.csrf_token,
+ })),
+ finishInitialization: () => set({ isInitialized: true }),
+ login: (token) => set({
+ token,
+ isAuthenticated: true,
+ isInitialized: true,
+ authMethod: 'local',
+ displayName: null,
+ csrfToken: null,
+ }),
+ logout: () => set({
+ token: null,
+ isAuthenticated: false,
+ isInitialized: true,
+ authMethod: null,
+ displayName: null,
+ csrfToken: null,
+ }),
}),
{
name: 'homelable-auth',
// sessionStorage: scoped to the tab, cleared on browser close.
// Prevents XSS from other tabs stealing the token via localStorage.
storage: createJSONStorage(() => sessionStorage),
+ // OIDC credentials stay in HttpOnly cookies. Its CSRF token is deliberately
+ // memory-only and is recovered from /auth/me after every page load.
+ partialize: (state) => ({ token: state.token }),
+ // Ignore authentication flags written by older versions of the store. A
+ // persisted local token is revalidated by the bootstrap request instead.
+ merge: (persisted, current) => {
+ const token = (persisted as { token?: unknown } | null)?.token
+ return {
+ ...current,
+ token: typeof token === 'string' ? token : null,
+ }
+ },
}
)
)