fix(web): renew the session in the background, work over plain HTTP, and do not carry a queue to the next sign-in

- the token is renewed in the background when under 3 minutes are left, so the stream URL of the next track is never built from an expired token
- a renewal adopts a session from another tab only when it differs from the one in memory
- listen keys no longer need crypto.randomUUID, which does not exist on pages opened over plain HTTP on a local network
- signing out, or closing the app, stops the music and empties the queue, and the play in progress is reported first
- a provider address that is not an http(s) address is shown as text, never as a link
This commit is contained in:
tgiachi 2026-11-12 11:48:14 +01:00
commit 9eb9341593
10 changed files with 192 additions and 6 deletions

View file

@ -181,6 +181,55 @@ test('listeners hear about a new token until they unsubscribe', async () => {
expect(heard).toEqual(['a1', 'a2'])
})
const refreshRequests = (calls: { key: string }[]) => calls.filter((c) => c.key === 'POST /api/v1/auth/refresh')
test('a session about to run out is renewed in the background, before anyone asks for the token', async () => {
vi.useFakeTimers()
const { calls } = mockFetch({
'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }),
'POST /api/v1/auth/refresh': () => session({ access: 'a2', refresh: 'r2' }),
})
await login('tom', 'secret123')
const heard: string[] = []
onTokenChange((t) => heard.push(t))
await vi.advanceTimersByTimeAsync(11 * 60_000)
expect(refreshRequests(calls)).toHaveLength(0)
await vi.advanceTimersByTimeAsync(2 * 60_000) // 13 minutes in: two left
expect(refreshRequests(calls)).toHaveLength(1)
expect(heard).toEqual(['a2'])
expect(sessionStore.getState().accessToken).toBe('a2')
await vi.advanceTimersByTimeAsync(5 * 60_000) // the new token has plenty of time left
expect(refreshRequests(calls)).toHaveLength(1)
})
test('signing out stops the renewal in the background', async () => {
vi.useFakeTimers()
const { calls } = mockFetch({
'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }),
'POST /api/v1/auth/logout': () => new Response(null, { status: 204 }),
})
await login('tom', 'secret123')
await logout()
await vi.advanceTimersByTimeAsync(20 * 60_000)
expect(refreshRequests(calls)).toHaveLength(0)
})
test('a renewal the server refuses in the background signs out and is not tried again', async () => {
vi.useFakeTimers()
const { calls } = mockFetch({
'POST /api/v1/auth/login': () => session({ expiresInSeconds: 900 }),
'POST /api/v1/auth/refresh': () => apiError(401, 'invalid_refresh_token'),
})
await login('tom', 'secret123')
await vi.advanceTimersByTimeAsync(13 * 60_000)
expect(sessionStore.getState().status).toBe('anonymous')
await vi.advanceTimersByTimeAsync(10 * 60_000)
expect(refreshRequests(calls)).toHaveLength(1)
})
test('logout revokes the refresh token and forgets the session', async () => {
const { calls } = mockFetch({
'POST /api/v1/auth/login': () => session(),

View file

@ -85,6 +85,29 @@ export function onTokenChange(cb: (token: string) => void): () => void {
return () => listeners.delete(cb)
}
// --- renewal in the background -------------------------------------------------------------------
// The player builds the stream URL of the next track from the current token, so the token has to be
// fresh even when nobody is calling the API. Check every 30 seconds and renew when under 3 minutes are
// left (a hidden tab may check only once a minute, so there is room).
const KEEP_FRESH_EVERY_MS = 30_000
const RENEW_AHEAD_MS = 3 * 60_000
let keepFreshTimer: ReturnType<typeof setInterval> | null = null
function stopKeepFresh() {
if (keepFreshTimer !== null) clearInterval(keepFreshTimer)
keepFreshTimer = null
}
function startKeepFresh() {
stopKeepFresh()
keepFreshTimer = setInterval(() => {
const s = sessionStore.getState()
if (s.status === 'authenticated' && s.accessExpiresAt - Date.now() <= RENEW_AHEAD_MS) void refresh()
}, KEEP_FRESH_EVERY_MS)
}
// --- state changes -------------------------------------------------------------------------------
function open(s: Stored, persist: boolean) {
@ -97,10 +120,12 @@ function open(s: Stored, persist: boolean) {
refreshToken: s.refresh_token,
})
if (persist) writeStored(sessionStore.getState())
startKeepFresh()
if (previous !== s.access_token) listeners.forEach((fn) => fn(s.access_token))
}
export function signOut(): void {
stopKeepFresh()
sessionStore.setState({ status: 'anonymous', user: null, accessToken: null, accessExpiresAt: 0, refreshToken: null })
try {
localStorage.removeItem(STORAGE_KEY)
@ -175,9 +200,11 @@ function withLock<T>(fn: () => Promise<T>): Promise<T> {
}
async function renew(): Promise<string | null> {
// Another tab may have renewed while this one waited for the lock: use its session.
// Another tab may have renewed while this one waited for the lock: if storage holds a session other
// than the one in memory, and it is fresh, use it instead of renewing again.
const stored = readStored()
if (stored && Date.parse(stored.access_expires_at) - Date.now() > SKEW_MS) {
const mine = sessionStore.getState().accessToken
if (stored && stored.access_token !== mine && Date.parse(stored.access_expires_at) - Date.now() > SKEW_MS) {
open(stored, false)
return stored.access_token
}

View file

@ -0,0 +1,20 @@
import { render, screen } from '@testing-library/react'
import { expect, test } from 'vitest'
import { ExternalLink } from './Attribution'
test('an address on the web is a link that opens in a new tab and does not hand over the page', () => {
render(<ExternalLink href="https://en.wikipedia.org/wiki/Radiohead">Radiohead</ExternalLink>)
const link = screen.getByRole('link', { name: 'Radiohead' })
expect(link).toHaveAttribute('href', 'https://en.wikipedia.org/wiki/Radiohead')
expect(link).toHaveAttribute('target', '_blank')
expect(link).toHaveAttribute('rel', 'noopener noreferrer')
})
test.each(['javascript:alert(1)', 'data:text/html,<b>x</b>', '/relative/path', 'not an address', ''])(
'the address %j is shown as plain text, never as a link',
(href) => {
render(<ExternalLink href={href}>Credit</ExternalLink>)
expect(screen.queryByRole('link')).not.toBeInTheDocument()
expect(screen.getByText('Credit')).toBeInTheDocument()
},
)

View file

@ -1,7 +1,18 @@
import type { ReactNode } from 'react'
/** A link to another site, opened in a new tab. */
/** Only an absolute address on the web is worth a link: provider text never gets to run a script (`javascript:`). */
function isWebAddress(href: string): boolean {
try {
const { protocol } = new URL(href)
return protocol === 'https:' || protocol === 'http:'
} catch {
return false
}
}
/** A link to another site, opened in a new tab. An address that is not a web address is shown as plain text. */
export function ExternalLink({ href, children }: { href: string; children: ReactNode }) {
if (!isWebAddress(href)) return <>{children}</>
return (
<a href={href} target="_blank" rel="noopener noreferrer" className="underline underline-offset-2 hover:text-foreground">
{children}

20
web/src/lib/uuid.test.ts Normal file
View file

@ -0,0 +1,20 @@
import { afterEach, expect, test, vi } from 'vitest'
import { uuid } from './uuid'
const V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/
afterEach(() => {
vi.unstubAllGlobals()
})
test('a uuid has the shape of a version 4 uuid', () => {
expect(uuid()).toMatch(V4)
})
test('where crypto.randomUUID does not exist (a page opened over plain HTTP) it still makes one', () => {
const real = globalThis.crypto
vi.stubGlobal('crypto', { getRandomValues: (a: Uint8Array<ArrayBuffer>) => real.getRandomValues(a) })
const first = uuid()
expect(first).toMatch(V4)
expect(uuid()).not.toBe(first)
})

13
web/src/lib/uuid.ts Normal file
View file

@ -0,0 +1,13 @@
/**
* A random version 4 uuid. `crypto.randomUUID` only exists on secure pages (HTTPS or localhost), and a
* home server is often opened over plain HTTP on the local network, so fall back to `getRandomValues`,
* which works everywhere.
*/
export function uuid(): string {
if (typeof crypto.randomUUID === 'function') return crypto.randomUUID()
const bytes = crypto.getRandomValues(new Uint8Array(16))
bytes[6] = (bytes[6] & 0x0f) | 0x40 // version 4
bytes[8] = (bytes[8] & 0x3f) | 0x80 // variant 10
const hex = Array.from(bytes, (b) => b.toString(16).padStart(2, '0')).join('')
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`
}

View file

@ -4,6 +4,7 @@ import { MemoryRouter } from 'react-router-dom'
import { beforeEach, expect, test, vi } from 'vitest'
import { sessionStore } from '@/auth/session'
import { initI18n } from '@/i18n'
import { usePlayer } from '@/player/store'
import { apiError, mockFetch } from '@/test/mockFetch'
import { initTheme } from '@/theme/theme'
import SettingsPage from './SettingsPage'
@ -133,6 +134,18 @@ test('a password change that fails for another reason says so', async () => {
expect(await screen.findByRole('alert')).toHaveTextContent('Something went wrong. Try again.')
})
test('signing out also stops the music, so the next person does not inherit the queue', async () => {
mockFetch({ 'POST /api/v1/auth/logout': noContent, 'POST /api/v1/listens': () => ({ status: 'recorded', counted: false }) })
usePlayer.getState().playTracks([
{ id: 1, title: 'Airbag', duration_ms: 1000, track_no: 1, disc_no: 1, album: null, artists: [], format: 'mp3' },
])
renderSettings()
await userEvent.click(screen.getByRole('button', { name: 'Sign out' }))
await vi.waitFor(() => expect(sessionStore.getState().status).toBe('anonymous'))
expect(usePlayer.getState().queue).toEqual([])
expect(usePlayer.getState().playing).toBe(false)
})
test('signing out forgets the session', async () => {
mockFetch({ 'POST /api/v1/auth/logout': noContent })
renderSettings()

View file

@ -8,11 +8,18 @@ import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { errorMessageKey, useLanguage, type Lang } from '@/i18n'
import { usePlayer } from '@/player/store'
import { THEMES, useTheme, type ThemeId } from '@/theme/theme'
const MIN_PASSWORD_BYTES = 8
const MAX_PASSWORD_BYTES = 256
/** Stops the music first, so that the play in progress is reported while the session is still valid. */
async function leave() {
usePlayer.getState().playTracks([])
await logout()
}
/** The colours of a theme in three stripes. The attribute makes the stripes use that theme's variables. */
function ThemePreview({ id }: { id: ThemeId }) {
return (
@ -44,7 +51,7 @@ function ChangePassword() {
try {
await api.post('/auth/password', { current_password: current, new_password: next })
// The server ended every session of this account, this one included: go back to the sign-in screen.
await logout()
await leave()
} catch (e) {
const wrong = e instanceof ApiError && e.status === 403 && e.code === 'invalid_credentials'
setError(wrong ? t('settings.currentPasswordWrong') : t(errorMessageKey(e instanceof ApiError ? e.code : 'unknown')))
@ -105,7 +112,7 @@ export default function SettingsPage() {
{user?.is_admin && (
<span className="rounded-full bg-secondary px-3 py-1 text-sm">{t('settings.admin')}</span>
)}
<Button variant="outline" onClick={() => void logout()}>
<Button variant="outline" onClick={() => void leave()}>
{t('settings.signOut')}
</Button>
</div>

View file

@ -91,6 +91,29 @@ test('closing the page mid-track reports the play as it stands, and lets the req
expect(listenCalls(calls)[0].init.keepalive).toBe(true)
})
test('a play is reported where crypto.randomUUID does not exist, as on a page opened over plain HTTP', async () => {
const real = globalThis.crypto
vi.stubGlobal('crypto', { getRandomValues: (a: Uint8Array<ArrayBuffer>) => real.getRandomValues(a) })
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded', counted: true }) })
renderHook(() => usePlayerEngine())
play(1.5)
act(() => {
audio.dispatchEvent(new Event('ended'))
})
await waitFor(() => expect(listenCalls(calls)).toHaveLength(1))
expect(listenCalls(calls)[0].body.idempotency_key).toMatch(/^[0-9a-f-]{36}$/)
})
test('when the app closes the music stops and the queue is emptied, so nobody inherits it', () => {
const { unmount } = renderHook(() => usePlayerEngine())
play(1.5)
expect(usePlayer.getState().queue).toHaveLength(1)
unmount()
expect(usePlayer.getState().queue).toEqual([])
expect(usePlayer.getState().playing).toBe(false)
expect(audio.paused).toBe(true)
})
test('hiding the tab does not end a play: the music goes on in the background', async () => {
const { calls } = mockFetch({ 'POST /api/v1/listens': () => ({ status: 'recorded', counted: true }) })
renderHook(() => usePlayerEngine())

View file

@ -1,5 +1,6 @@
import { useEffect } from 'react'
import { sendListen } from '@/api/listens'
import { uuid } from '@/lib/uuid'
import { createEngine } from './engine'
import { createListenReporter } from './listens'
import { setMediaSession } from './mediaSession'
@ -14,7 +15,7 @@ export function usePlayerEngine(): void {
const audio = new Audio()
const reporter = createListenReporter({
send: sendListen,
uuid: () => crypto.randomUUID(),
uuid,
now: () => new Date(),
})
const engine = createEngine(audio, {
@ -43,6 +44,8 @@ export function usePlayerEngine(): void {
stopMediaSession()
engine.destroy()
audio.pause()
// The app is closing (signed out): the next person to sign in on this page must not inherit the queue.
usePlayer.getState().playTracks([])
}
}, [])
}