sonda/web/src/auth/session.ts
tgiachi 1c5b4a4fa0 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
2026-11-12 11:21:06 +01:00

199 lines
6.6 KiB
TypeScript

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 })