feat(admin): login, session guard and lists overview

- Add AuthProvider that verifies the token and ends the session on any 401
- Add login page, shell with sign out, not-found page
- Add lists table with policy badges
- Add fake API and render helpers for component tests
This commit is contained in:
tgiachi 2026-11-09 15:31:51 +01:00
commit 5f67289943
11 changed files with 516 additions and 2 deletions

80
admin/src/App.test.tsx Normal file
View file

@ -0,0 +1,80 @@
import { screen, waitFor } from '@testing-library/react'
import { describe, expect, it } from 'vitest'
import { aList, installFakeApi, newState } from '@/test/fakeApi'
import { renderApp } from '@/test/render'
describe('authentication', () => {
it('sends anonymous visitors to the login page', async () => {
installFakeApi(newState())
renderApp('/')
expect(await screen.findByRole('heading', { name: /sign in/i })).toBeInTheDocument()
expect(screen.getByLabelText(/api token/i)).toHaveAttribute('type', 'password')
})
it('also protects deep links', async () => {
installFakeApi(newState({ lists: [aList()] }))
renderApp('/lists/1/members')
expect(await screen.findByRole('heading', { name: /sign in/i })).toBeInTheDocument()
})
it('shows the server error for a wrong token and stays on the login page', async () => {
const state = installFakeApi(newState())
const { user } = renderApp('/login')
await user.type(await screen.findByLabelText(/api token/i), 'wrong')
await user.click(screen.getByRole('button', { name: /sign in/i }))
expect(await screen.findByText('invalid or missing token')).toBeInTheDocument()
expect(screen.getByRole('heading', { name: /sign in/i })).toBeInTheDocument()
expect(sessionStorage.getItem('parsimony.token')).toBeNull()
expect(state.calls).toEqual(['GET /lists'])
})
it('does not call the API with an empty token', async () => {
const state = installFakeApi(newState())
const { user } = renderApp('/login')
await user.click(await screen.findByRole('button', { name: /sign in/i }))
expect(await screen.findByText(/enter the api token/i)).toBeInTheDocument()
expect(state.calls).toEqual([])
})
it('signs in with a good token and shows the lists', async () => {
installFakeApi(newState({ lists: [aList()] }))
const { user } = renderApp('/login')
await user.type(await screen.findByLabelText(/api token/i), 'good')
await user.click(screen.getByRole('button', { name: /sign in/i }))
expect(await screen.findByRole('heading', { name: /^lists$/i })).toBeInTheDocument()
expect(await screen.findByText('dev@example.org')).toBeInTheDocument()
expect(sessionStorage.getItem('parsimony.token')).toBe('good')
})
it('goes straight to the lists when a token is already stored', async () => {
installFakeApi(newState({ lists: [aList()] }))
renderApp('/', { token: 'good' })
expect(await screen.findByText('dev@example.org')).toBeInTheDocument()
})
it('signs out', async () => {
installFakeApi(newState())
const { user } = renderApp('/', { token: 'good' })
await user.click(await screen.findByRole('button', { name: /sign out/i }))
expect(await screen.findByRole('heading', { name: /sign in/i })).toBeInTheDocument()
expect(sessionStorage.getItem('parsimony.token')).toBeNull()
})
it('falls back to the login page when the token stops working', async () => {
const state = installFakeApi(newState({ lists: [aList()] }))
renderApp('/', { token: 'good' })
await screen.findByText('dev@example.org')
state.token = 'rotated' // the server no longer accepts the stored token
const { api } = await import('@/lib/api')
await api.lists.list().catch(() => undefined)
await waitFor(() => expect(screen.getByRole('heading', { name: /sign in/i })).toBeInTheDocument())
expect(sessionStorage.getItem('parsimony.token')).toBeNull()
})
it('unknown paths show a not-found page with a way back', async () => {
installFakeApi(newState())
renderApp('/nowhere', { token: 'good' })
expect(await screen.findByRole('heading', { name: /not found/i })).toBeInTheDocument()
expect(screen.getByRole('link', { name: /back to lists/i })).toHaveAttribute('href', '/')
})
})

22
admin/src/App.tsx Normal file
View file

@ -0,0 +1,22 @@
import { Route, Routes } from 'react-router'
import { Shell } from '@/components/Shell'
import { ListsPage } from '@/pages/ListsPage'
import { LoginPage } from '@/pages/LoginPage'
import { NotFoundPage } from '@/pages/NotFoundPage'
import { Toaster } from '@/components/ui/sonner'
/** Routes only: providers (query client, router, auth) are set up by the caller. */
export function App() {
return (
<>
<Routes>
<Route path="/login" element={<LoginPage />} />
<Route element={<Shell />}>
<Route index element={<ListsPage />} />
<Route path="*" element={<NotFoundPage />} />
</Route>
</Routes>
<Toaster />
</>
)
}

View file

@ -0,0 +1,27 @@
import { Link, Navigate, Outlet, useLocation } from 'react-router'
import { Button } from '@/components/ui/button'
import { useAuth } from '@/lib/auth'
/** Layout for every page that needs a session. */
export function Shell() {
const { authed, logout } = useAuth()
const location = useLocation()
if (!authed) return <Navigate to="/login" replace state={{ from: location.pathname }} />
return (
<div className="min-h-screen">
<header className="border-b">
<div className="mx-auto flex max-w-5xl items-center justify-between p-4">
<Link to="/" className="text-lg font-semibold">
Parsimony
</Link>
<Button variant="outline" size="sm" onClick={logout}>
Sign out
</Button>
</div>
</header>
<main className="mx-auto max-w-5xl p-4">
<Outlet />
</main>
</div>
)
}

52
admin/src/lib/auth.tsx Normal file
View file

@ -0,0 +1,52 @@
import { useQueryClient } from '@tanstack/react-query'
import { createContext, useCallback, useContext, useEffect, useMemo, useState, type ReactNode } from 'react'
import { api, session } from '@/lib/api'
interface AuthState {
authed: boolean
/** Verifies the token against the API and keeps it for this tab. Throws ApiError on failure. */
login: (token: string) => Promise<void>
logout: () => void
}
const AuthContext = createContext<AuthState | null>(null)
export function AuthProvider({ children }: { children: ReactNode }) {
const queryClient = useQueryClient()
const [authed, setAuthed] = useState(() => session.get() !== null)
// Any 401 from the API ends the session.
useEffect(() => {
session.onUnauthorized(() => {
setAuthed(false)
queryClient.clear()
})
return () => session.onUnauthorized(null)
}, [queryClient])
const login = useCallback(async (token: string) => {
session.set(token)
try {
await api.lists.list()
} catch (e) {
session.clear()
throw e
}
setAuthed(true)
}, [])
const logout = useCallback(() => {
session.clear()
queryClient.clear()
setAuthed(false)
}, [queryClient])
const value = useMemo(() => ({ authed, login, logout }), [authed, login, logout])
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>
}
export function useAuth(): AuthState {
const ctx = useContext(AuthContext)
if (!ctx) throw new Error('useAuth must be used inside AuthProvider')
return ctx
}

View file

@ -1,5 +1,23 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { StrictMode } from 'react'
import { createRoot } from 'react-dom/client'
import { BrowserRouter } from 'react-router'
import { App } from './App'
import { AuthProvider } from './lib/auth'
import './index.css'
createRoot(document.getElementById('root')!).render(<StrictMode><div /></StrictMode>)
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } },
})
createRoot(document.getElementById('root')!).render(
<StrictMode>
<QueryClientProvider client={queryClient}>
<BrowserRouter>
<AuthProvider>
<App />
</AuthProvider>
</BrowserRouter>
</QueryClientProvider>
</StrictMode>,
)

View file

@ -0,0 +1,45 @@
import { useQuery } from '@tanstack/react-query'
import { Link } from 'react-router'
import { Badge } from '@/components/ui/badge'
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from '@/components/ui/table'
import { api } from '@/lib/api'
export function ListsPage() {
const lists = useQuery({ queryKey: ['lists'], queryFn: api.lists.list })
return (
<div className="space-y-4">
<h1 className="text-2xl font-semibold">Lists</h1>
{lists.isPending && <p className="text-muted-foreground">Loading…</p>}
{lists.isError && <p role="alert" className="text-destructive">{lists.error.message}</p>}
{lists.data && lists.data.length === 0 && <p className="text-muted-foreground">No lists yet.</p>}
{lists.data && lists.data.length > 0 && (
<Table>
<TableHeader>
<TableRow>
<TableHead>Address</TableHead>
<TableHead>Title</TableHead>
<TableHead>Posting</TableHead>
<TableHead>Joining</TableHead>
<TableHead>Archive</TableHead>
</TableRow>
</TableHeader>
<TableBody>
{lists.data.map((l) => (
<TableRow key={l.id}>
<TableCell>
<Link to={`/lists/${l.id}`} className="font-medium text-primary underline">
{l.address}
</Link>
</TableCell>
<TableCell>{l.title}</TableCell>
<TableCell><Badge variant="secondary">{l.post_policy}</Badge></TableCell>
<TableCell><Badge variant="secondary">{l.join_policy}</Badge></TableCell>
<TableCell><Badge variant="secondary">{l.archive_policy}</Badge></TableCell>
</TableRow>
))}
</TableBody>
</Table>
)}
</div>
)
}

View file

@ -0,0 +1,63 @@
import { useState, type FormEvent } from 'react'
import { Navigate, useLocation } from 'react-router'
import { Button } from '@/components/ui/button'
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
import { useAuth } from '@/lib/auth'
export function LoginPage() {
const { authed, login } = useAuth()
const location = useLocation()
const [token, setToken] = useState('')
const [error, setError] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
if (authed) return <Navigate to={(location.state as { from?: string } | null)?.from ?? '/'} replace />
async function submit(e: FormEvent) {
e.preventDefault()
if (token.trim() === '') {
setError('Enter the API token')
return
}
setBusy(true)
setError(null)
try {
await login(token.trim())
} catch (err) {
setError(err instanceof Error ? err.message : 'Sign in failed')
} finally {
setBusy(false)
}
}
return (
<div className="flex min-h-screen items-center justify-center p-4">
<Card className="w-full max-w-sm">
<CardHeader>
<CardTitle>
<h1>Sign in</h1>
</CardTitle>
<CardDescription>Use the bearer token of this Parsimony server.</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={submit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="token">API token</Label>
<Input id="token" type="password" autoComplete="off" value={token} onChange={(e) => setToken(e.target.value)} />
</div>
{error && (
<p role="alert" className="text-sm text-destructive">
{error}
</p>
)}
<Button type="submit" className="w-full" disabled={busy}>
Sign in
</Button>
</form>
</CardContent>
</Card>
</div>
)
}

View file

@ -0,0 +1,12 @@
import { Link } from 'react-router'
export function NotFoundPage() {
return (
<div className="space-y-2">
<h1 className="text-2xl font-semibold">Not found</h1>
<Link to="/" className="text-primary underline">
Back to lists
</Link>
</div>
)
}

148
admin/src/test/fakeApi.ts Normal file
View file

@ -0,0 +1,148 @@
// An in-memory stand-in for the Parsimony API, used by component tests.
import { vi } from 'vitest'
import type { Held, List, Member, Message } from '@/lib/api'
export interface FakeState {
token: string
lists: List[]
members: Record<number, Member[]>
held: Record<number, Held[]>
archive: Record<number, Message[]>
nextId: number
/** Every request seen, as "METHOD /path". */
calls: string[]
/** Force the next matching request ("METHOD /path") to fail with this status. */
fail: Record<string, { status: number; error: string }>
}
export function newState(overrides: Partial<FakeState> = {}): FakeState {
return { token: 'good', lists: [], members: {}, held: {}, archive: {}, nextId: 100, calls: [], fail: {}, ...overrides }
}
export function aList(over: Partial<List> = {}): List {
const name = over.name ?? 'dev'
const domain = over.domain ?? 'example.org'
return {
id: 1,
name,
domain,
title: 'Dev list',
address: `${name}@${domain}`,
post_policy: 'members',
join_policy: 'open',
archive_policy: 'private',
...over,
}
}
function json(status: number, body?: unknown) {
return new Response(body === undefined ? null : JSON.stringify(body), {
status,
headers: body === undefined ? {} : { 'Content-Type': 'application/json' },
})
}
const err = (status: number, error: string) => json(status, { error })
export function installFakeApi(state: FakeState) {
const handler = async (input: string, init: RequestInit = {}): Promise<Response> => {
const method = init.method ?? 'GET'
const url = new URL(input, 'http://x')
const path = url.pathname.replace(/^\/api\/v1/, '')
const key = `${method} ${path}`
state.calls.push(key)
const auth = (init.headers as Record<string, string> | undefined)?.Authorization
if (auth !== `Bearer ${state.token}`) return err(401, 'invalid or missing token')
if (state.fail[key]) {
const f = state.fail[key]
delete state.fail[key]
return err(f.status, f.error)
}
const body = init.body ? JSON.parse(init.body as string) : {}
let m: RegExpMatchArray | null
if (path === '/lists' && method === 'GET') return json(200, state.lists)
if (path === '/lists' && method === 'POST') {
if (state.lists.some((l) => l.name === body.name && l.domain === body.domain)) return err(409, 'already exists')
if (!body.name || !body.domain) return err(400, 'name and domain are required')
const l = aList({ id: state.nextId++, name: body.name, domain: body.domain, title: body.title || body.name })
state.lists.push(l)
return json(201, l)
}
if ((m = path.match(/^\/lists\/(\d+)$/))) {
const id = Number(m[1])
const l = state.lists.find((x) => x.id === id)
if (!l) return err(404, 'not found')
if (method === 'GET') return json(200, l)
if (method === 'PATCH') {
Object.assign(l, body)
return json(200, l)
}
if (method === 'DELETE') {
state.lists = state.lists.filter((x) => x.id !== id)
return json(204)
}
}
if ((m = path.match(/^\/lists\/(\d+)\/members$/))) {
const id = Number(m[1])
const ms = (state.members[id] ??= [])
if (method === 'GET') return json(200, ms)
if (method === 'POST') {
if (!/^[^@\s]+@[^@\s]+$/.test(body.address ?? '')) return err(400, 'a valid email address is required')
const mem: Member = { address: body.address.toLowerCase(), display_name: body.display_name ?? '', disabled: false, bounce_count: 0 }
state.members[id] = [...ms.filter((x) => x.address !== mem.address), mem]
return json(201, mem)
}
}
if ((m = path.match(/^\/lists\/(\d+)\/members\/(.+)$/)) && method === 'DELETE') {
const id = Number(m[1])
const addr = decodeURIComponent(m[2])
const before = state.members[id] ?? []
if (!before.some((x) => x.address === addr)) return err(404, 'not found')
state.members[id] = before.filter((x) => x.address !== addr)
return json(204)
}
if ((m = path.match(/^\/lists\/(\d+)\/held$/)) && method === 'GET') return json(200, state.held[Number(m[1])] ?? [])
if ((m = path.match(/^\/held\/(\d+)(\/approve)?$/))) {
const id = Number(m[1])
for (const k of Object.keys(state.held)) {
const list = state.held[Number(k)]
if (list.some((h) => h.id === id)) {
if ((m[2] && method === 'POST') || (!m[2] && method === 'DELETE')) {
state.held[Number(k)] = list.filter((h) => h.id !== id)
return json(204)
}
}
}
return err(404, 'not found')
}
if ((m = path.match(/^\/lists\/(\d+)\/archive$/)) && method === 'GET') {
const id = Number(m[1])
const q = (url.searchParams.get('q') ?? '').toLowerCase()
const limit = Number(url.searchParams.get('limit') ?? 50)
const offset = Number(url.searchParams.get('offset') ?? 0)
const all = (state.archive[id] ?? [])
.filter((x) => !q || x.subject.toLowerCase().includes(q) || (x.body ?? '').toLowerCase().includes(q))
.map((x) => ({ ...x, body: undefined }))
return json(200, { total: all.length, messages: all.slice(offset, offset + limit) })
}
if ((m = path.match(/^\/archive\/(\d+)$/))) {
const id = Number(m[1])
for (const k of Object.keys(state.archive)) {
const msg = state.archive[Number(k)].find((x) => x.id === id)
if (msg) {
if (method === 'GET') return json(200, msg)
if (method === 'DELETE') {
state.archive[Number(k)] = state.archive[Number(k)].filter((x) => x.id !== id)
return json(204)
}
}
}
return err(404, 'not found')
}
return err(404, 'not found')
}
vi.stubGlobal('fetch', vi.fn(handler))
return state
}

24
admin/src/test/render.tsx Normal file
View file

@ -0,0 +1,24 @@
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
import { render } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router'
import { App } from '@/App'
import { AuthProvider } from '@/lib/auth'
import { session } from '@/lib/api'
/** Renders the whole app at `path`. Pass `token` to start logged in. */
export function renderApp(path = '/', opts: { token?: string } = {}) {
if (opts.token) session.set(opts.token)
const client = new QueryClient({ defaultOptions: { queries: { retry: false, gcTime: 0 }, mutations: { retry: false } } })
const user = userEvent.setup()
const utils = render(
<QueryClientProvider client={client}>
<MemoryRouter initialEntries={[path]}>
<AuthProvider>
<App />
</AuthProvider>
</MemoryRouter>
</QueryClientProvider>,
)
return { user, client, ...utils }
}

View file

@ -1,8 +1,31 @@
import '@testing-library/jest-dom/vitest'
import { cleanup } from '@testing-library/react'
import { afterEach } from 'vitest'
import { afterEach, vi } from 'vitest'
// jsdom lacks a few browser APIs that sonner and Base UI use.
if (!window.matchMedia) {
window.matchMedia = (query: string) =>
({
matches: false,
media: query,
onchange: null,
addEventListener: () => {},
removeEventListener: () => {},
addListener: () => {},
removeListener: () => {},
dispatchEvent: () => false,
}) as MediaQueryList
}
class NoopObserver {
observe() {}
unobserve() {}
disconnect() {}
}
window.ResizeObserver ??= NoopObserver as unknown as typeof ResizeObserver
Element.prototype.scrollIntoView ??= () => {}
afterEach(() => {
cleanup()
sessionStorage.clear()
vi.unstubAllGlobals()
})