feat(web): API client, session with cross-tab refresh, login screen
- fetch client with bearer token, one retry after a renewal, ApiError with the server code - session kept in localStorage; renewal is single-flight in a tab and under a Web Lock across tabs, and a tab adopts a session another tab already renewed - a refused refresh token signs out once; an unreachable server keeps the session - mediaUrl and onTokenChange for audio and image URLs that carry the token - sign-in and first-account screen, and a gate that shows the app only when signed in
This commit is contained in:
parent
7363b80ebd
commit
1c5b4a4fa0
12 changed files with 876 additions and 2 deletions
|
|
@ -1,3 +1,9 @@
|
|||
import AuthGate from './auth/AuthGate'
|
||||
|
||||
export default function App() {
|
||||
return <h1>Sonda</h1>
|
||||
return (
|
||||
<AuthGate>
|
||||
<h1>Sonda</h1>
|
||||
</AuthGate>
|
||||
)
|
||||
}
|
||||
|
|
|
|||
101
web/src/api/client.test.ts
Normal file
101
web/src/api/client.test.ts
Normal file
|
|
@ -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<string, string>).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<string, string>)['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' })
|
||||
})
|
||||
92
web/src/api/client.ts
Normal file
92
web/src/api/client.ts
Normal file
|
|
@ -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<string | null>
|
||||
/** Renews the session; resolves to the new access token, or null when there is nothing to renew. */
|
||||
refresh(): Promise<string | null>
|
||||
signOut(): void
|
||||
}
|
||||
|
||||
let hooks: AuthHooks = {
|
||||
getAccessToken: async () => null,
|
||||
refresh: async () => null,
|
||||
signOut: () => {},
|
||||
}
|
||||
|
||||
export function setAuthHooks(next: AuthHooks): void {
|
||||
hooks = next
|
||||
}
|
||||
|
||||
type Query = Record<string, string | number | boolean | undefined>
|
||||
|
||||
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<ApiError> {
|
||||
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<Response> {
|
||||
const headers: Record<string, string> = { 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<T>(method: string, path: string, params: Query | undefined, body: unknown, opts: CallOptions): Promise<T> {
|
||||
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: <T>(path: string, params?: Query, opts: CallOptions = {}) => request<T>('GET', path, params, undefined, opts),
|
||||
post: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('POST', path, undefined, body ?? {}, opts),
|
||||
patch: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PATCH', path, undefined, body ?? {}, opts),
|
||||
put: <T>(path: string, body?: unknown, opts: CallOptions = {}) => request<T>('PUT', path, undefined, body ?? {}, opts),
|
||||
del: <T>(path: string, opts: CallOptions = {}) => request<T>('DELETE', path, undefined, undefined, opts),
|
||||
}
|
||||
16
web/src/auth/AuthGate.tsx
Normal file
16
web/src/auth/AuthGate.tsx
Normal file
|
|
@ -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 <div role="status" aria-label={t('common.loading')} className="min-h-screen bg-background" />
|
||||
}
|
||||
if (status === 'anonymous') return <LoginPage />
|
||||
return <>{children}</>
|
||||
}
|
||||
94
web/src/auth/LoginPage.test.tsx
Normal file
94
web/src/auth/LoginPage.test.tsx
Normal file
|
|
@ -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(<LoginPage />)
|
||||
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(<LoginPage />)
|
||||
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(<LoginPage />)
|
||||
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(<LoginPage />)
|
||||
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(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.queryByText('the app')).not.toBeInTheDocument()
|
||||
expect(screen.queryByLabelText('Username')).not.toBeInTheDocument()
|
||||
|
||||
sessionStore.setState({ status: 'anonymous' })
|
||||
rerender(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.getByLabelText('Username')).toBeInTheDocument()
|
||||
|
||||
sessionStore.setState({ status: 'authenticated', user })
|
||||
rerender(
|
||||
<AuthGate>
|
||||
<p>the app</p>
|
||||
</AuthGate>,
|
||||
)
|
||||
expect(screen.getByText('the app')).toBeInTheDocument()
|
||||
})
|
||||
89
web/src/auth/LoginPage.tsx
Normal file
89
web/src/auth/LoginPage.tsx
Normal file
|
|
@ -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<string | null>(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 (
|
||||
<main className="flex min-h-screen items-center justify-center bg-background p-4">
|
||||
<div className="flex w-full max-w-sm flex-col gap-6 rounded-xl bg-card p-8 text-card-foreground">
|
||||
<div className="flex items-center gap-3">
|
||||
<svg width="32" height="32" viewBox="0 0 28 28" fill="none" aria-hidden="true">
|
||||
<circle cx="14" cy="14" r="3" fill="var(--primary)" />
|
||||
<circle cx="14" cy="14" r="8" stroke="var(--primary)" strokeWidth="2" opacity="0.75" />
|
||||
<circle cx="14" cy="14" r="12.5" stroke="var(--primary)" strokeWidth="1.5" opacity="0.35" />
|
||||
</svg>
|
||||
<span className="text-2xl font-extrabold tracking-tight">{t('app.name')}</span>
|
||||
</div>
|
||||
<h1 className="text-xl font-bold">{creating ? t('auth.registerTitle') : t('auth.signInTitle')}</h1>
|
||||
<form onSubmit={submit} className="flex flex-col gap-4">
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="username">{t('auth.username')}</Label>
|
||||
<Input
|
||||
id="username"
|
||||
value={username}
|
||||
onChange={(e) => setUsername(e.target.value)}
|
||||
autoComplete="username"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label htmlFor="password">{t('auth.password')}</Label>
|
||||
<Input
|
||||
id="password"
|
||||
type="password"
|
||||
value={password}
|
||||
onChange={(e) => setPassword(e.target.value)}
|
||||
autoComplete={creating ? 'new-password' : 'current-password'}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
{error && (
|
||||
<p role="alert" className="text-sm text-destructive">
|
||||
{error}
|
||||
</p>
|
||||
)}
|
||||
<Button type="submit" disabled={busy}>
|
||||
{creating ? t('auth.createAccount') : t('auth.signIn')}
|
||||
</Button>
|
||||
</form>
|
||||
<Button
|
||||
type="button"
|
||||
variant="link"
|
||||
className="h-auto self-start p-0"
|
||||
onClick={() => {
|
||||
setCreating(!creating)
|
||||
setError(null)
|
||||
}}
|
||||
>
|
||||
{creating ? t('auth.haveAccount') : t('auth.firstUser')}
|
||||
</Button>
|
||||
</div>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
237
web/src/auth/session.test.ts
Normal file
237
web/src/auth/session.test.ts
Normal file
|
|
@ -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<typeof session>) {
|
||||
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<string, unknown>).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<string, string>).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<typeof vi.fn>).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<unknown>) => {
|
||||
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')
|
||||
})
|
||||
199
web/src/auth/session.ts
Normal file
199
web/src/auth/session.ts
Normal file
|
|
@ -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<SessionState>()(() => ({
|
||||
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<Session, 'access_token' | 'access_expires_at' | 'refresh_token' | 'user'>
|
||||
|
||||
function readStored(): Stored | null {
|
||||
try {
|
||||
const raw = localStorage.getItem(STORAGE_KEY)
|
||||
if (!raw) return null
|
||||
const s = JSON.parse(raw) as Partial<Stored>
|
||||
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<void> {
|
||||
const session = await api.post<Session>('/auth/login', { username, password }, { auth: false })
|
||||
open(session, true)
|
||||
}
|
||||
|
||||
export async function register(username: string, password: string): Promise<void> {
|
||||
await api.post('/auth/register', { username, password }, { auth: false })
|
||||
await login(username, password)
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
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<void> {
|
||||
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<string | null> {
|
||||
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 <audio> or <img> can load: the token goes in the query. */
|
||||
export function mediaUrl(path: string): string {
|
||||
const base = `/api/v1${path}`
|
||||
const token = sessionStore.getState().accessToken
|
||||
if (!token) return base
|
||||
return `${base}${base.includes('?') ? '&' : '?'}access_token=${encodeURIComponent(token)}`
|
||||
}
|
||||
|
||||
// --- renewal -------------------------------------------------------------------------------------
|
||||
|
||||
let inflight: Promise<string | null> | null = null
|
||||
|
||||
/** Renews the session. Callers in this tab share one request; tabs share one request through a lock. */
|
||||
function refresh(): Promise<string | null> {
|
||||
inflight ??= withLock(renew).finally(() => {
|
||||
inflight = null
|
||||
})
|
||||
return inflight
|
||||
}
|
||||
|
||||
function withLock<T>(fn: () => Promise<T>): Promise<T> {
|
||||
const locks = navigator.locks as LockManager | undefined
|
||||
return locks ? locks.request('sonda-refresh', fn) : fn()
|
||||
}
|
||||
|
||||
async function renew(): Promise<string | null> {
|
||||
// Another tab may have renewed while this one waited for the lock: use its session.
|
||||
const stored = readStored()
|
||||
if (stored && Date.parse(stored.access_expires_at) - Date.now() > SKEW_MS) {
|
||||
open(stored, false)
|
||||
return stored.access_token
|
||||
}
|
||||
|
||||
const refreshToken = stored?.refresh_token ?? sessionStore.getState().refreshToken
|
||||
if (!refreshToken) {
|
||||
signOut()
|
||||
return null
|
||||
}
|
||||
try {
|
||||
const session = await api.post<Session>('/auth/refresh', { refresh_token: refreshToken }, { auth: false })
|
||||
open(session, true)
|
||||
return session.access_token
|
||||
} catch (e) {
|
||||
// The server refused the token (4xx): the session is over. Unreachable or failing (0, 5xx): keep it.
|
||||
if (e instanceof ApiError && e.status >= 400 && e.status < 500) {
|
||||
signOut()
|
||||
return null
|
||||
}
|
||||
return sessionStore.getState().accessToken
|
||||
}
|
||||
}
|
||||
|
||||
setAuthHooks({ getAccessToken, refresh, signOut })
|
||||
19
web/src/components/ui/input.tsx
Normal file
19
web/src/components/ui/input.tsx
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
import * as React from "react"
|
||||
import { Input as InputPrimitive } from "@base-ui/react/input"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Input({ className, type, ...props }: React.ComponentProps<"input">) {
|
||||
return (
|
||||
<InputPrimitive
|
||||
type={type}
|
||||
data-slot="input"
|
||||
className={cn(
|
||||
"h-8 w-full min-w-0 rounded-lg border border-input bg-transparent px-2.5 py-1 text-base transition-colors outline-none file:inline-flex file:h-6 file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-3 focus-visible:ring-ring/50 disabled:pointer-events-none disabled:cursor-not-allowed disabled:bg-input/50 disabled:opacity-50 aria-invalid:border-destructive aria-invalid:ring-3 aria-invalid:ring-destructive/20 md:text-sm dark:bg-input/30 dark:disabled:bg-input/80 dark:aria-invalid:border-destructive/50 dark:aria-invalid:ring-destructive/40",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Input }
|
||||
17
web/src/components/ui/label.tsx
Normal file
17
web/src/components/ui/label.tsx
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import * as React from "react"
|
||||
import { cn } from "cn"
|
||||
|
||||
function Label({ className, ...props }: React.ComponentProps<"label">) {
|
||||
return (
|
||||
<label
|
||||
data-slot="label"
|
||||
className={cn(
|
||||
"flex items-center gap-2 text-sm leading-none font-medium select-none group-data-[disabled=true]:pointer-events-none group-data-[disabled=true]:opacity-50 peer-disabled:cursor-not-allowed peer-disabled:opacity-50",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
export { Label }
|
||||
|
|
@ -2,10 +2,12 @@ import { StrictMode } from 'react'
|
|||
import { createRoot } from 'react-dom/client'
|
||||
import './index.css'
|
||||
import App from './App.tsx'
|
||||
import { restoreSession } from './auth/session'
|
||||
import { initI18n } from './i18n'
|
||||
import { initTheme } from './theme/theme'
|
||||
|
||||
initTheme()
|
||||
void restoreSession()
|
||||
|
||||
void initI18n().then(() => {
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
|
|
|
|||
|
|
@ -1,8 +1,10 @@
|
|||
import { render, screen } from '@testing-library/react'
|
||||
import { expect, test } from 'vitest'
|
||||
import App from './App'
|
||||
import { sessionStore } from './auth/session'
|
||||
|
||||
test('the app shows its name', () => {
|
||||
test('a signed-in user sees the app', () => {
|
||||
sessionStore.setState({ status: 'authenticated', user: { id: 1, username: 'tom', is_admin: true } })
|
||||
render(<App />)
|
||||
expect(screen.getByText('Sonda')).toBeInTheDocument()
|
||||
})
|
||||
|
|
|
|||
Loading…
Reference in a new issue