diff --git a/web/src/App.tsx b/web/src/App.tsx
index ed88fdf..9530940 100644
--- a/web/src/App.tsx
+++ b/web/src/App.tsx
@@ -1,3 +1,9 @@
+import AuthGate from './auth/AuthGate'
+
export default function App() {
- return
Sonda
+ return (
+
+ Sonda
+
+ )
}
diff --git a/web/src/api/client.test.ts b/web/src/api/client.test.ts
new file mode 100644
index 0000000..0db4a0f
--- /dev/null
+++ b/web/src/api/client.test.ts
@@ -0,0 +1,101 @@
+import { beforeEach, expect, test, vi } from 'vitest'
+import { apiError, mockFetch } from '@/test/mockFetch'
+import { api, ApiError, setAuthHooks } from './client'
+
+const hooks = {
+ getAccessToken: vi.fn(async () => 't1' as string | null),
+ refresh: vi.fn(async () => 't2' as string | null),
+ signOut: vi.fn(),
+}
+
+beforeEach(() => {
+ hooks.getAccessToken.mockClear().mockResolvedValue('t1')
+ hooks.refresh.mockClear().mockResolvedValue('t2')
+ hooks.signOut.mockClear()
+ setAuthHooks(hooks)
+})
+
+function authorization(call: { init: RequestInit }): string | undefined {
+ return (call.init.headers as Record).Authorization
+}
+
+test('sends the access token as a bearer token', async () => {
+ const { calls } = mockFetch({ 'GET /api/v1/artists': () => ({ items: [] }) })
+ await api.get('/artists')
+ expect(authorization(calls[0])).toBe('Bearer t1')
+})
+
+test('an error response becomes an ApiError with the server code', async () => {
+ mockFetch({ 'GET /api/v1/artists': () => apiError(400, 'invalid_input', 'bad limit') })
+ const failure = await api.get('/artists').catch((e: unknown) => e)
+ expect(failure).toBeInstanceOf(ApiError)
+ expect(failure).toMatchObject({ status: 400, code: 'invalid_input', message: 'bad limit' })
+})
+
+test('a 401 renews the session and retries once', async () => {
+ let n = 0
+ const { calls } = mockFetch({
+ 'GET /api/v1/artists': () => (++n === 1 ? apiError(401, 'unauthorized') : { items: ['ok'] }),
+ })
+ await expect(api.get('/artists')).resolves.toEqual({ items: ['ok'] })
+ expect(calls).toHaveLength(2)
+ expect(hooks.refresh).toHaveBeenCalledTimes(1)
+ expect(authorization(calls[1])).toBe('Bearer t2')
+ expect(hooks.signOut).not.toHaveBeenCalled()
+})
+
+test('a second 401 signs the user out and the error reaches the caller', async () => {
+ const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') })
+ await expect(api.get('/artists')).rejects.toMatchObject({ status: 401, code: 'unauthorized' })
+ expect(calls).toHaveLength(2)
+ expect(hooks.signOut).toHaveBeenCalledTimes(1)
+})
+
+test('a 401 with nothing to renew signs out without a retry', async () => {
+ hooks.refresh.mockResolvedValue(null)
+ const { calls } = mockFetch({ 'GET /api/v1/artists': () => apiError(401, 'unauthorized') })
+ await expect(api.get('/artists')).rejects.toMatchObject({ status: 401 })
+ expect(calls).toHaveLength(1)
+ expect(hooks.signOut).toHaveBeenCalledTimes(1)
+})
+
+test('a call that does not need a session sends no token and never renews', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') })
+ await expect(api.post('/auth/login', { username: 'a', password: 'b' }, { auth: false })).rejects.toMatchObject({
+ code: 'invalid_credentials',
+ })
+ expect(hooks.getAccessToken).not.toHaveBeenCalled()
+ expect(hooks.refresh).not.toHaveBeenCalled()
+ expect(authorization(calls[0])).toBeUndefined()
+})
+
+test('query values are sent, undefined ones are left out', async () => {
+ const { calls } = mockFetch({ 'GET /api/v1/albums': () => ({ items: [] }) })
+ await api.get('/albums', { q: 'björk', limit: 50, artist_id: undefined, counted: true })
+ expect(calls[0].url.searchParams.get('q')).toBe('björk')
+ expect(calls[0].url.searchParams.get('limit')).toBe('50')
+ expect(calls[0].url.searchParams.has('artist_id')).toBe(false)
+ expect(calls[0].url.searchParams.get('counted')).toBe('true')
+})
+
+test('a JSON body is sent with its content type', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded' }) })
+ await api.post('/listens', { track_id: 3 })
+ expect((calls[0].init.headers as Record)['Content-Type']).toBe('application/json')
+ expect(JSON.parse(calls[0].init.body as string)).toEqual({ track_id: 3 })
+})
+
+test('a 204 answer gives undefined', async () => {
+ mockFetch({ 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }) })
+ await expect(api.post('/auth/logout', { refresh_token: 'r' }, { auth: false })).resolves.toBeUndefined()
+})
+
+test('a network failure becomes an ApiError with the code network', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch')
+ }),
+ )
+ await expect(api.get('/artists')).rejects.toMatchObject({ status: 0, code: 'network' })
+})
diff --git a/web/src/api/client.ts b/web/src/api/client.ts
new file mode 100644
index 0000000..4c84ad1
--- /dev/null
+++ b/web/src/api/client.ts
@@ -0,0 +1,92 @@
+/** What the server answers when a call fails: `{"error": {"code", "message"}}`. */
+export class ApiError extends Error {
+ status: number
+ code: string
+
+ constructor(status: number, code: string, message: string) {
+ super(message)
+ this.name = 'ApiError'
+ this.status = status
+ this.code = code
+ }
+}
+
+/** The session side of a call, injected so that this file never imports the session (which imports this). */
+export interface AuthHooks {
+ getAccessToken(): Promise
+ /** Renews the session; resolves to the new access token, or null when there is nothing to renew. */
+ refresh(): Promise
+ signOut(): void
+}
+
+let hooks: AuthHooks = {
+ getAccessToken: async () => null,
+ refresh: async () => null,
+ signOut: () => {},
+}
+
+export function setAuthHooks(next: AuthHooks): void {
+ hooks = next
+}
+
+type Query = Record
+
+export interface CallOptions {
+ /** Default true. Login, register, refresh and logout say false: they carry no token and never renew. */
+ auth?: boolean
+}
+
+const BASE = '/api/v1'
+
+function buildUrl(path: string, params?: Query): string {
+ const query = new URLSearchParams()
+ for (const [key, value] of Object.entries(params ?? {})) {
+ if (value !== undefined) query.set(key, String(value))
+ }
+ const text = query.toString()
+ return `${BASE}${path}${text ? `?${text}` : ''}`
+}
+
+async function toApiError(res: Response): Promise {
+ try {
+ const body = (await res.json()) as { error?: { code?: string; message?: string } }
+ return new ApiError(res.status, body.error?.code ?? 'unknown', body.error?.message ?? res.statusText)
+ } catch {
+ return new ApiError(res.status, 'unknown', res.statusText)
+ }
+}
+
+async function send(method: string, url: string, body: unknown, token: string | null): Promise {
+ const headers: Record = { Accept: 'application/json' }
+ if (body !== undefined) headers['Content-Type'] = 'application/json'
+ if (token) headers.Authorization = `Bearer ${token}`
+ try {
+ return await fetch(url, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) })
+ } catch {
+ throw new ApiError(0, 'network', 'The server cannot be reached')
+ }
+}
+
+async function request(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise {
+ const auth = opts.auth ?? true
+ const url = buildUrl(path, params)
+ let res = await send(method, url, body, auth ? await hooks.getAccessToken() : null)
+
+ if (res.status === 401 && auth) {
+ const fresh = await hooks.refresh()
+ if (fresh) res = await send(method, url, body, fresh)
+ if (res.status === 401) hooks.signOut()
+ }
+
+ if (!res.ok) throw await toApiError(res)
+ if (res.status === 204) return undefined as T
+ return (await res.json()) as T
+}
+
+export const api = {
+ get: (path: string, params?: Query, opts: CallOptions = {}) => request('GET', path, params, undefined, opts),
+ post: (path: string, body?: unknown, opts: CallOptions = {}) => request('POST', path, undefined, body ?? {}, opts),
+ patch: (path: string, body?: unknown, opts: CallOptions = {}) => request('PATCH', path, undefined, body ?? {}, opts),
+ put: (path: string, body?: unknown, opts: CallOptions = {}) => request('PUT', path, undefined, body ?? {}, opts),
+ del: (path: string, opts: CallOptions = {}) => request('DELETE', path, undefined, undefined, opts),
+}
diff --git a/web/src/auth/AuthGate.tsx b/web/src/auth/AuthGate.tsx
new file mode 100644
index 0000000..7f5fe51
--- /dev/null
+++ b/web/src/auth/AuthGate.tsx
@@ -0,0 +1,16 @@
+import type { ReactNode } from 'react'
+import { useTranslation } from 'react-i18next'
+import LoginPage from './LoginPage'
+import { useSession } from './session'
+
+/** Shows the app to a signed-in user and the sign-in form to everyone else. */
+export default function AuthGate({ children }: { children: ReactNode }) {
+ const { status } = useSession()
+ const { t } = useTranslation()
+
+ if (status === 'loading') {
+ return
+ }
+ if (status === 'anonymous') return
+ return <>{children}>
+}
diff --git a/web/src/auth/LoginPage.test.tsx b/web/src/auth/LoginPage.test.tsx
new file mode 100644
index 0000000..4af1071
--- /dev/null
+++ b/web/src/auth/LoginPage.test.tsx
@@ -0,0 +1,94 @@
+import { render, screen } from '@testing-library/react'
+import userEvent from '@testing-library/user-event'
+import { beforeEach, expect, test, vi } from 'vitest'
+import { initI18n } from '@/i18n'
+import { apiError, mockFetch } from '@/test/mockFetch'
+import AuthGate from './AuthGate'
+import LoginPage from './LoginPage'
+import { sessionStore } from './session'
+
+const user = { id: 1, username: 'tom', is_admin: true }
+const session = {
+ access_token: 'a1',
+ access_expires_at: new Date(Date.now() + 900_000).toISOString(),
+ refresh_token: 'r1',
+ refresh_expires_at: new Date(Date.now() + 86_400_000).toISOString(),
+ user,
+}
+
+beforeEach(async () => {
+ vi.spyOn(navigator, 'language', 'get').mockReturnValue('en-US')
+ await initI18n()
+ sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null })
+})
+
+async function fill(username: string, password: string) {
+ await userEvent.type(screen.getByLabelText('Username'), username)
+ await userEvent.type(screen.getByLabelText('Password'), password)
+}
+
+test('a wrong password shows the translated message', async () => {
+ mockFetch({ 'POST /api/v1/auth/login': () => apiError(401, 'invalid_credentials') })
+ render()
+ await fill('tom', 'wrong-password')
+ await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('Wrong username or password.')
+})
+
+test('signing in sends what was typed', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session })
+ render()
+ await fill('tom', 'secret123')
+ await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
+ await vi.waitFor(() => expect(sessionStore.getState().status).toBe('authenticated'))
+ expect(JSON.parse(calls[0].init.body as string)).toEqual({ username: 'tom', password: 'secret123' })
+})
+
+test('the first-account link switches to registration and says when one already exists', async () => {
+ mockFetch({ 'POST /api/v1/auth/register': () => apiError(403, 'registration_closed') })
+ render()
+ await userEvent.click(screen.getByRole('button', { name: 'This is a new server: create the first account' }))
+ await fill('tom', 'secret123')
+ await userEvent.click(screen.getByRole('button', { name: 'Create account' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('An account already exists.')
+})
+
+test('an unreachable server is reported as such', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => {
+ throw new TypeError('Failed to fetch')
+ }),
+ )
+ render()
+ await fill('tom', 'secret123')
+ await userEvent.click(screen.getByRole('button', { name: 'Sign in' }))
+ expect(await screen.findByRole('alert')).toHaveTextContent('Cannot reach the server.')
+})
+
+test('AuthGate shows nothing while loading, the form when signed out, the app when signed in', () => {
+ sessionStore.setState({ status: 'loading' })
+ const { rerender } = render(
+
+ the app
+ ,
+ )
+ expect(screen.queryByText('the app')).not.toBeInTheDocument()
+ expect(screen.queryByLabelText('Username')).not.toBeInTheDocument()
+
+ sessionStore.setState({ status: 'anonymous' })
+ rerender(
+
+ the app
+ ,
+ )
+ expect(screen.getByLabelText('Username')).toBeInTheDocument()
+
+ sessionStore.setState({ status: 'authenticated', user })
+ rerender(
+
+ the app
+ ,
+ )
+ expect(screen.getByText('the app')).toBeInTheDocument()
+})
diff --git a/web/src/auth/LoginPage.tsx b/web/src/auth/LoginPage.tsx
new file mode 100644
index 0000000..cf24bc6
--- /dev/null
+++ b/web/src/auth/LoginPage.tsx
@@ -0,0 +1,89 @@
+import { useState, type FormEvent } from 'react'
+import { useTranslation } from 'react-i18next'
+import { ApiError } from '@/api/client'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { Label } from '@/components/ui/label'
+import { errorMessageKey } from '@/i18n'
+import { login, register } from './session'
+
+/** Sign in, or (on a new server) create the first account, which becomes the admin. */
+export default function LoginPage() {
+ const { t } = useTranslation()
+ const [creating, setCreating] = useState(false)
+ const [username, setUsername] = useState('')
+ const [password, setPassword] = useState('')
+ const [error, setError] = useState(null)
+ const [busy, setBusy] = useState(false)
+
+ async function submit(event: FormEvent) {
+ event.preventDefault()
+ setBusy(true)
+ setError(null)
+ try {
+ await (creating ? register : login)(username, password)
+ } catch (e) {
+ setError(t(errorMessageKey(e instanceof ApiError ? e.code : 'unknown')))
+ } finally {
+ setBusy(false)
+ }
+ }
+
+ return (
+
+
+
+
+ {t('app.name')}
+
+
{creating ? t('auth.registerTitle') : t('auth.signInTitle')}
+
+
+
+
+ )
+}
diff --git a/web/src/auth/session.test.ts b/web/src/auth/session.test.ts
new file mode 100644
index 0000000..8842986
--- /dev/null
+++ b/web/src/auth/session.test.ts
@@ -0,0 +1,237 @@
+import { afterEach, beforeEach, expect, test, vi } from 'vitest'
+import { apiError, mockFetch } from '@/test/mockFetch'
+import {
+ getAccessToken,
+ login,
+ logout,
+ mediaUrl,
+ onTokenChange,
+ register,
+ restoreSession,
+ sessionStore,
+} from './session'
+
+const user = { id: 1, username: 'tom', is_admin: true }
+
+function session(opts: { access?: string; refresh?: string; expiresInSeconds?: number } = {}) {
+ const { access = 'a1', refresh = 'r1', expiresInSeconds = 900 } = opts
+ return {
+ access_token: access,
+ access_expires_at: new Date(Date.now() + expiresInSeconds * 1000).toISOString(),
+ refresh_token: refresh,
+ refresh_expires_at: new Date(Date.now() + 86_400_000).toISOString(),
+ user,
+ }
+}
+
+function stored() {
+ const raw = localStorage.getItem('sonda.session')
+ return raw ? JSON.parse(raw) : null
+}
+
+function storeSession(s: ReturnType) {
+ localStorage.setItem('sonda.session', JSON.stringify(s))
+}
+
+beforeEach(() => {
+ sessionStore.setState({
+ status: 'loading',
+ user: null,
+ accessToken: null,
+ accessExpiresAt: 0,
+ refreshToken: null,
+ })
+})
+
+afterEach(() => {
+ vi.restoreAllMocks()
+ delete (navigator as unknown as Record).locks
+})
+
+test('login keeps the session and opens it', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session() })
+ await login('tom', 'secret123')
+ expect(sessionStore.getState().status).toBe('authenticated')
+ expect(sessionStore.getState().user).toEqual(user)
+ expect(stored().access_token).toBe('a1')
+ expect(stored().refresh_token).toBe('r1')
+ expect(JSON.parse(calls[0].init.body as string)).toEqual({ username: 'tom', password: 'secret123' })
+ expect((calls[0].init.headers as Record).Authorization).toBeUndefined()
+})
+
+test('register creates the account and then signs in', async () => {
+ const { calls } = mockFetch({
+ 'POST /api/v1/auth/register': () => new Response(JSON.stringify(user), { status: 201 }),
+ 'POST /api/v1/auth/login': () => session(),
+ })
+ await register('tom', 'secret123')
+ expect(calls.map((c) => c.key)).toEqual(['POST /api/v1/auth/register', 'POST /api/v1/auth/login'])
+ expect(sessionStore.getState().status).toBe('authenticated')
+})
+
+test('a token with time left is returned without any request', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 600 }) })
+ await login('tom', 'secret123')
+ await expect(getAccessToken()).resolves.toBe('a1')
+ expect(calls).toHaveLength(1)
+})
+
+test('five calls at once with 30 seconds left send a single refresh', async () => {
+ mockFetch({
+ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }),
+ 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }),
+ })
+ await login('tom', 'secret123')
+ const tokens = await Promise.all([1, 2, 3, 4, 5].map(() => getAccessToken()))
+ expect(tokens).toEqual(['a2', 'a2', 'a2', 'a2', 'a2'])
+ const calls = (fetch as ReturnType).mock.calls.filter(([url]) => String(url).endsWith('/auth/refresh'))
+ expect(calls).toHaveLength(1)
+ expect(stored().refresh_token).toBe('r2')
+})
+
+test('a refresh sends the stored refresh token', async () => {
+ const { calls } = mockFetch({
+ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30, refresh: 'r1' }),
+ 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }),
+ })
+ await login('tom', 'secret123')
+ await getAccessToken()
+ const refresh = calls.find((c) => c.key === 'POST /api/v1/auth/refresh')!
+ expect(JSON.parse(refresh.init.body as string)).toEqual({ refresh_token: 'r1' })
+})
+
+test('a second tab that already renewed the session is adopted, not renewed again', async () => {
+ const { calls } = mockFetch({ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }) })
+ await login('tom', 'secret123')
+ // The lock is where tab B gets in first: by the time this tab holds it, B has written a fresh session.
+ Object.defineProperty(navigator, 'locks', {
+ configurable: true,
+ value: {
+ request: async (_name: string, fn: () => Promise) => {
+ storeSession(session({ access: 'from-tab-b', refresh: 'r-b' }))
+ return fn()
+ },
+ },
+ })
+ await expect(getAccessToken()).resolves.toBe('from-tab-b')
+ expect(calls.filter((c) => c.key === 'POST /api/v1/auth/refresh')).toHaveLength(0)
+ expect(sessionStore.getState().refreshToken).toBe('r-b')
+})
+
+test('a refresh token the server refuses signs out once and stops asking', async () => {
+ const { calls } = mockFetch({
+ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }),
+ 'POST /api/v1/auth/refresh': () => apiError(401, 'invalid_refresh_token'),
+ })
+ await login('tom', 'secret123')
+ await expect(getAccessToken()).resolves.toBeNull()
+ expect(sessionStore.getState().status).toBe('anonymous')
+ expect(localStorage.getItem('sonda.session')).toBeNull()
+ const before = calls.length
+ await expect(getAccessToken()).resolves.toBeNull()
+ expect(calls).toHaveLength(before)
+})
+
+test('a network failure while renewing keeps the session', async () => {
+ mockFetch({
+ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }),
+ 'POST /api/v1/auth/refresh': () => {
+ throw new TypeError('Failed to fetch')
+ },
+ })
+ await login('tom', 'secret123')
+ await expect(getAccessToken()).resolves.toBe('a1')
+ expect(sessionStore.getState().status).toBe('authenticated')
+ expect(stored()).not.toBeNull()
+})
+
+test('login works for the page lifetime when storage is blocked', async () => {
+ vi.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {
+ throw new Error('blocked')
+ })
+ mockFetch({ 'POST /api/v1/auth/login': () => session() })
+ await login('tom', 'secret123')
+ expect(sessionStore.getState().status).toBe('authenticated')
+ await expect(getAccessToken()).resolves.toBe('a1')
+})
+
+test('mediaUrl adds the token to a path of the API', async () => {
+ mockFetch({ 'POST /api/v1/auth/login': () => session({ access: 'tok' }) })
+ await login('tom', 'secret123')
+ expect(mediaUrl('/tracks/3/stream')).toBe('/api/v1/tracks/3/stream?access_token=tok')
+})
+
+test('mediaUrl without a session gives the bare URL', () => {
+ expect(mediaUrl('/albums/2/cover')).toBe('/api/v1/albums/2/cover')
+})
+
+test('listeners hear about a new token until they unsubscribe', async () => {
+ mockFetch({
+ 'POST /api/v1/auth/login': () => session({ expiresInSeconds: 30 }),
+ 'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }),
+ })
+ const heard: string[] = []
+ const off = onTokenChange((t) => heard.push(t))
+ await login('tom', 'secret123')
+ await getAccessToken()
+ off()
+ sessionStore.setState({ accessExpiresAt: Date.now() + 10_000 })
+ mockFetch({ 'POST /api/v1/auth/refresh': () => session({ access: 'a3', refresh: 'r3' }) })
+ await getAccessToken()
+ expect(heard).toEqual(['a1', 'a2'])
+})
+
+test('logout revokes the refresh token and forgets the session', async () => {
+ const { calls } = mockFetch({
+ 'POST /api/v1/auth/login': () => session(),
+ 'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }),
+ })
+ await login('tom', 'secret123')
+ await logout()
+ const call = calls.find((c) => c.key === 'POST /api/v1/auth/logout')!
+ expect(JSON.parse(call.init.body as string)).toEqual({ refresh_token: 'r1' })
+ expect(sessionStore.getState().status).toBe('anonymous')
+ expect(localStorage.getItem('sonda.session')).toBeNull()
+})
+
+test('logout forgets the session even when the server cannot be reached', async () => {
+ mockFetch({
+ 'POST /api/v1/auth/login': () => session(),
+ 'POST /api/v1/auth/logout': () => {
+ throw new TypeError('Failed to fetch')
+ },
+ })
+ await login('tom', 'secret123')
+ await logout()
+ expect(sessionStore.getState().status).toBe('anonymous')
+})
+
+test('restoring with nothing stored leaves you signed out', async () => {
+ await restoreSession()
+ expect(sessionStore.getState().status).toBe('anonymous')
+})
+
+test('restoring a fresh stored session signs in without a request', async () => {
+ const { calls } = mockFetch({})
+ storeSession(session({ access: 'kept' }))
+ await restoreSession()
+ expect(sessionStore.getState().status).toBe('authenticated')
+ expect(sessionStore.getState().user).toEqual(user)
+ expect(calls).toHaveLength(0)
+ await expect(getAccessToken()).resolves.toBe('kept')
+})
+
+test('restoring a session whose access token ran out renews it', async () => {
+ mockFetch({ 'POST /api/v1/auth/refresh': () => session({ access: 'renewed', refresh: 'r2' }) })
+ storeSession(session({ expiresInSeconds: -60 }))
+ await restoreSession()
+ expect(sessionStore.getState().status).toBe('authenticated')
+ expect(sessionStore.getState().accessToken).toBe('renewed')
+})
+
+test('restoring a session the server no longer accepts signs out', async () => {
+ mockFetch({ 'POST /api/v1/auth/refresh': () => apiError(401, 'invalid_refresh_token') })
+ storeSession(session({ expiresInSeconds: -60 }))
+ await restoreSession()
+ expect(sessionStore.getState().status).toBe('anonymous')
+})
diff --git a/web/src/auth/session.ts b/web/src/auth/session.ts
new file mode 100644
index 0000000..76ac066
--- /dev/null
+++ b/web/src/auth/session.ts
@@ -0,0 +1,199 @@
+import { create } from 'zustand'
+import { useShallow } from 'zustand/react/shallow'
+import { api, ApiError, setAuthHooks } from '@/api/client'
+import type { components } from '@/api/schema'
+
+type Session = components['schemas']['Session']
+type User = components['schemas']['User']
+
+type Status = 'loading' | 'anonymous' | 'authenticated'
+
+interface SessionState {
+ status: Status
+ user: User | null
+ accessToken: string | null
+ /** Milliseconds since the epoch. */
+ accessExpiresAt: number
+ refreshToken: string | null
+}
+
+const STORAGE_KEY = 'sonda.session'
+/** An access token with less than this left is renewed before it is used. */
+const SKEW_MS = 60_000
+
+export const sessionStore = create()(() => ({
+ status: 'loading',
+ user: null,
+ accessToken: null,
+ accessExpiresAt: 0,
+ refreshToken: null,
+}))
+
+export function useSession(): { status: Status; user: User | null } {
+ return sessionStore(useShallow((s) => ({ status: s.status, user: s.user })))
+}
+
+// --- storage -------------------------------------------------------------------------------------
+// The whole session lives in localStorage so that a second tab can adopt a session the first one
+// already renewed (a refresh token works once). When storage is blocked the memory copy is enough.
+
+type Stored = Pick
+
+function readStored(): Stored | null {
+ try {
+ const raw = localStorage.getItem(STORAGE_KEY)
+ if (!raw) return null
+ const s = JSON.parse(raw) as Partial
+ if (typeof s.access_token !== 'string' || typeof s.refresh_token !== 'string') return null
+ if (typeof s.access_expires_at !== 'string' || !s.user) return null
+ return s as Stored
+ } catch {
+ return null
+ }
+}
+
+function writeStored(s: SessionState) {
+ try {
+ if (!s.accessToken || !s.refreshToken || !s.user) {
+ localStorage.removeItem(STORAGE_KEY)
+ return
+ }
+ const stored: Stored = {
+ access_token: s.accessToken,
+ access_expires_at: new Date(s.accessExpiresAt).toISOString(),
+ refresh_token: s.refreshToken,
+ user: s.user,
+ }
+ localStorage.setItem(STORAGE_KEY, JSON.stringify(stored))
+ } catch {
+ // The session still works for this page view.
+ }
+}
+
+// --- token listeners -----------------------------------------------------------------------------
+
+const listeners = new Set<(token: string) => void>()
+
+/** Calls `cb` whenever the access token changes (sign-in, renewal). Returns the function that stops it. */
+export function onTokenChange(cb: (token: string) => void): () => void {
+ listeners.add(cb)
+ return () => listeners.delete(cb)
+}
+
+// --- state changes -------------------------------------------------------------------------------
+
+function open(s: Stored, persist: boolean) {
+ const previous = sessionStore.getState().accessToken
+ sessionStore.setState({
+ status: 'authenticated',
+ user: s.user,
+ accessToken: s.access_token,
+ accessExpiresAt: Date.parse(s.access_expires_at),
+ refreshToken: s.refresh_token,
+ })
+ if (persist) writeStored(sessionStore.getState())
+ if (previous !== s.access_token) listeners.forEach((fn) => fn(s.access_token))
+}
+
+export function signOut(): void {
+ sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null })
+ try {
+ localStorage.removeItem(STORAGE_KEY)
+ } catch {
+ // nothing stored that we could remove
+ }
+}
+
+// --- public operations ---------------------------------------------------------------------------
+
+export async function login(username: string, password: string): Promise {
+ const session = await api.post('/auth/login', { username, password }, { auth: false })
+ open(session, true)
+}
+
+export async function register(username: string, password: string): Promise {
+ await api.post('/auth/register', { username, password }, { auth: false })
+ await login(username, password)
+}
+
+export async function logout(): Promise {
+ const { refreshToken } = sessionStore.getState()
+ try {
+ if (refreshToken) await api.post('/auth/logout', { refresh_token: refreshToken }, { auth: false })
+ } catch {
+ // The server could not be reached: the session is forgotten here all the same.
+ }
+ signOut()
+}
+
+/** Opens the session kept in storage, renewing it first if its access token has run out. */
+export async function restoreSession(): Promise {
+ const stored = readStored()
+ if (!stored) {
+ sessionStore.setState({ status: 'anonymous' })
+ return
+ }
+ open(stored, false)
+ if (Date.parse(stored.access_expires_at) - Date.now() <= SKEW_MS) await refresh()
+}
+
+export async function getAccessToken(): Promise {
+ const s = sessionStore.getState()
+ if (!s.accessToken && !s.refreshToken) return null
+ if (s.accessToken && s.accessExpiresAt - Date.now() > SKEW_MS) return s.accessToken
+ return refresh()
+}
+
+/** A path of the API that an