From 5f67289943bbc8188a7f4b00ef080f5be49ab078 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Mon, 9 Nov 2026 15:31:51 +0100 Subject: [PATCH] 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 --- admin/src/App.test.tsx | 80 +++++++++++++++++ admin/src/App.tsx | 22 +++++ admin/src/components/Shell.tsx | 27 ++++++ admin/src/lib/auth.tsx | 52 +++++++++++ admin/src/main.tsx | 20 ++++- admin/src/pages/ListsPage.tsx | 45 ++++++++++ admin/src/pages/LoginPage.tsx | 63 +++++++++++++ admin/src/pages/NotFoundPage.tsx | 12 +++ admin/src/test/fakeApi.ts | 148 +++++++++++++++++++++++++++++++ admin/src/test/render.tsx | 24 +++++ admin/src/test/setup.ts | 25 +++++- 11 files changed, 516 insertions(+), 2 deletions(-) create mode 100644 admin/src/App.test.tsx create mode 100644 admin/src/App.tsx create mode 100644 admin/src/components/Shell.tsx create mode 100644 admin/src/lib/auth.tsx create mode 100644 admin/src/pages/ListsPage.tsx create mode 100644 admin/src/pages/LoginPage.tsx create mode 100644 admin/src/pages/NotFoundPage.tsx create mode 100644 admin/src/test/fakeApi.ts create mode 100644 admin/src/test/render.tsx diff --git a/admin/src/App.test.tsx b/admin/src/App.test.tsx new file mode 100644 index 0000000..3f0b236 --- /dev/null +++ b/admin/src/App.test.tsx @@ -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', '/') + }) +}) diff --git a/admin/src/App.tsx b/admin/src/App.tsx new file mode 100644 index 0000000..b27a6b9 --- /dev/null +++ b/admin/src/App.tsx @@ -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 ( + <> + + } /> + }> + } /> + } /> + + + + + ) +} diff --git a/admin/src/components/Shell.tsx b/admin/src/components/Shell.tsx new file mode 100644 index 0000000..d594b00 --- /dev/null +++ b/admin/src/components/Shell.tsx @@ -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 + return ( +
+
+
+ + Parsimony + + +
+
+
+ +
+
+ ) +} diff --git a/admin/src/lib/auth.tsx b/admin/src/lib/auth.tsx new file mode 100644 index 0000000..9202167 --- /dev/null +++ b/admin/src/lib/auth.tsx @@ -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 + logout: () => void +} + +const AuthContext = createContext(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 {children} +} + +export function useAuth(): AuthState { + const ctx = useContext(AuthContext) + if (!ctx) throw new Error('useAuth must be used inside AuthProvider') + return ctx +} diff --git a/admin/src/main.tsx b/admin/src/main.tsx index 96e207c..e1f8a89 100644 --- a/admin/src/main.tsx +++ b/admin/src/main.tsx @@ -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(
) +const queryClient = new QueryClient({ + defaultOptions: { queries: { retry: false, refetchOnWindowFocus: false } }, +}) + +createRoot(document.getElementById('root')!).render( + + + + + + + + + , +) diff --git a/admin/src/pages/ListsPage.tsx b/admin/src/pages/ListsPage.tsx new file mode 100644 index 0000000..6666331 --- /dev/null +++ b/admin/src/pages/ListsPage.tsx @@ -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 ( +
+

Lists

+ {lists.isPending &&

Loading…

} + {lists.isError &&

{lists.error.message}

} + {lists.data && lists.data.length === 0 &&

No lists yet.

} + {lists.data && lists.data.length > 0 && ( + + + + Address + Title + Posting + Joining + Archive + + + + {lists.data.map((l) => ( + + + + {l.address} + + + {l.title} + {l.post_policy} + {l.join_policy} + {l.archive_policy} + + ))} + +
+ )} +
+ ) +} diff --git a/admin/src/pages/LoginPage.tsx b/admin/src/pages/LoginPage.tsx new file mode 100644 index 0000000..6b1c4c1 --- /dev/null +++ b/admin/src/pages/LoginPage.tsx @@ -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(null) + const [busy, setBusy] = useState(false) + + if (authed) return + + 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 ( +
+ + + +

Sign in

+
+ Use the bearer token of this Parsimony server. +
+ +
+
+ + setToken(e.target.value)} /> +
+ {error && ( +

+ {error} +

+ )} + +
+
+
+
+ ) +} diff --git a/admin/src/pages/NotFoundPage.tsx b/admin/src/pages/NotFoundPage.tsx new file mode 100644 index 0000000..8dd0660 --- /dev/null +++ b/admin/src/pages/NotFoundPage.tsx @@ -0,0 +1,12 @@ +import { Link } from 'react-router' + +export function NotFoundPage() { + return ( +
+

Not found

+ + Back to lists + +
+ ) +} diff --git a/admin/src/test/fakeApi.ts b/admin/src/test/fakeApi.ts new file mode 100644 index 0000000..7fdd8f8 --- /dev/null +++ b/admin/src/test/fakeApi.ts @@ -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 + held: Record + archive: Record + nextId: number + /** Every request seen, as "METHOD /path". */ + calls: string[] + /** Force the next matching request ("METHOD /path") to fail with this status. */ + fail: Record +} + +export function newState(overrides: Partial = {}): FakeState { + return { token: 'good', lists: [], members: {}, held: {}, archive: {}, nextId: 100, calls: [], fail: {}, ...overrides } +} + +export function aList(over: Partial = {}): 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 => { + 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 | 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 +} diff --git a/admin/src/test/render.tsx b/admin/src/test/render.tsx new file mode 100644 index 0000000..103c765 --- /dev/null +++ b/admin/src/test/render.tsx @@ -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( + + + + + + + , + ) + return { user, client, ...utils } +} diff --git a/admin/src/test/setup.ts b/admin/src/test/setup.ts index f79e1fc..cb3d737 100644 --- a/admin/src/test/setup.ts +++ b/admin/src/test/setup.ts @@ -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() })