From d9a39dda22d2b90265820f45e123a617bd3ffefa Mon Sep 17 00:00:00 2001 From: lobo Date: Fri, 25 Sep 2026 13:45:08 +0200 Subject: [PATCH] feat(auth): use the cookie session and refresh on 401 The token is no longer stored; a tbp_session flag remembers the login. apiFetch renews the session once on a 401 and sends the request again. Parallel requests and other tabs share one refresh, because Auth revokes the session when a refresh token is used twice. Only a 401 from the refresh ends the session; a 502 or no network shows the normal error. --- README.md | 5 +- src/App.jsx | 11 +- src/App.test.jsx | 11 +- src/components/BacklogCard.jsx | 4 +- src/components/BacklogCard.test.jsx | 2 +- src/components/CompletedHint.test.jsx | 2 +- src/components/PlayingHint.test.jsx | 2 +- src/hooks/useForceSync.js | 4 +- src/hooks/useLibrarySync.js | 4 +- src/hooks/useSaveAppearance.test.jsx | 2 +- src/hooks/useSessionExpired.js | 4 +- src/hooks/useSteamProfile.js | 12 +- src/hooks/useSteamProfile.test.jsx | 16 +-- src/pages/Dashboard.jsx | 4 +- src/pages/Dashboard.test.jsx | 2 +- src/pages/GameDetail.jsx | 4 +- src/pages/GameDetail.test.jsx | 2 +- src/pages/GameLibrary.jsx | 4 +- src/pages/GameLibrary.test.jsx | 2 +- src/pages/LandingPage.jsx | 4 +- src/pages/LoginPage.jsx | 9 +- src/pages/LoginPage.test.jsx | 11 +- src/pages/PlayNextPage.jsx | 4 +- src/pages/PlayNextPage.language.test.jsx | 2 +- src/pages/PlayNextPage.test.jsx | 2 +- src/pages/RegistrationPage.jsx | 3 +- src/pages/SettingsPage.jsx | 10 +- src/pages/SettingsPage.test.jsx | 7 +- src/pages/WishlistPage.jsx | 4 +- src/pages/WishlistPage.test.jsx | 6 +- src/utils/api.js | 60 +++++++++- src/utils/api.test.js | 138 +++++++++++++++++++---- src/utils/auth.js | 44 +++----- src/utils/auth.test.js | 43 ++++--- 34 files changed, 297 insertions(+), 147 deletions(-) diff --git a/README.md b/README.md index 547c4b8..d70e0ce 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ To Be Played is split into three repositories: - **Appearance**: accent color, corner style, wide layout, page background and banner from your own game art. Saved in Auth, so it follows you to every device. - German and English, dark mode, mobile layout, session-expired message instead of a silent logout. +- **Session**: the tokens are HttpOnly cookies that no script can read. `apiFetch` renews an expired access token + once and sends the request again; parallel requests and other tabs share one refresh. ## Tech stack @@ -85,8 +87,7 @@ npm run build ## Roadmap - Mood filter for "What to play next". -- Move the JWT from `localStorage` to an httpOnly cookie (needs Auth changes) and add a Content Security Policy in - `nginx.conf`. +- A Content Security Policy in `nginx.conf`. - Installable PWA. ## License diff --git a/src/App.jsx b/src/App.jsx index 0a1a4b0..53a94eb 100644 --- a/src/App.jsx +++ b/src/App.jsx @@ -18,7 +18,8 @@ import {Toaster} from '@/components/ui/sonner'; import {TooltipProvider} from '@/components/ui/tooltip'; import PageBackground from './components/PageBackground.jsx'; import {usePreferences} from './context/PreferencesContext.jsx'; -import {clearToken, getToken} from './utils/auth.js'; +import {clearSession, hasSession} from './utils/auth.js'; +import {logout} from './utils/api.js'; function App() { const {t} = useTranslation(); @@ -32,7 +33,7 @@ function App() { useEffect(() => { // No local expiry check here: a 401 from the backend ends the session (useSessionExpired), and a browser // clock that runs ahead would otherwise end it silently. - setIsAuthenticated(!!getToken()); + setIsAuthenticated(hasSession()); }, [location]); // On login and on page load; the cached look shows until Auth answers. @@ -40,8 +41,10 @@ function App() { if (isAuthenticated) syncAppearance(); }, [isAuthenticated, syncAppearance]); - const handleLogout = () => { - clearToken(); + // Waits for Auth: a late logout answer would clear the cookies of a login that came after it. + const handleLogout = async () => { + await logout(); + clearSession(); resetAppearance(); setIsAuthenticated(false); navigate('/login'); diff --git a/src/App.test.jsx b/src/App.test.jsx index 691eebe..f349197 100644 --- a/src/App.test.jsx +++ b/src/App.test.jsx @@ -10,9 +10,6 @@ vi.mock('./hooks/useLibrarySync.js', () => ({default: () => ({status: 'OK', last vi.mock('./hooks/useForceSync.js', () => ({default: () => ({trigger: vi.fn(), busy: false})})); const DEBOUNCE_WAIT_MS = 700; -const b64 = (o) => btoa(JSON.stringify(o)).replace(/=+$/, ''); -// Expired by the browser clock. A clock that runs ahead of the server makes the backend still accept it. -const EXPIRED_BY_LOCAL_CLOCK = `${b64({alg: 'EdDSA'})}.${b64({exp: Math.floor(Date.now() / 1000) - 60})}.sig`; const page = {content: [{appid: 220, name: 'Half-Life 2', playtimeMinutes: 0, status: 'BACKLOG'}], page: 0, size: 20, totalElements: 1, totalPages: 1}; const wait = (ms) => act(() => new Promise((resolve) => setTimeout(resolve, ms))); @@ -25,7 +22,7 @@ function Spy() { } beforeEach(() => { - localStorage.setItem('tbp_jwt', EXPIRED_BY_LOCAL_CLOCK); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => page})); }); @@ -35,14 +32,13 @@ afterEach(() => { }); describe('App', () => { - it('keeps a token that only the browser clock calls expired; a 401 from the backend ends the session', async () => { + it('ends the session on a 401 that the refresh cannot fix', async () => { render( , ); await waitFor(() => expect(screen.getByText('Half-Life 2')).toBeTruthy()); - expect(localStorage.getItem('tbp_jwt')).toBe(EXPIRED_BY_LOCAL_CLOCK); fetch.mockImplementation(async () => ({ok: false, status: 401, json: async () => ({})})); fireEvent.change(screen.getByRole('searchbox'), {target: {value: 'half'}}); @@ -50,6 +46,7 @@ describe('App', () => { await waitFor(() => expect(current.location.pathname).toBe('/login')); expect(current.location.state).toEqual({sessionExpired: true, from: '/library?q=half&page=0'}); - expect(localStorage.getItem('tbp_jwt')).toBeNull(); + expect(localStorage.getItem('tbp_session')).toBeNull(); + expect(fetch).toHaveBeenCalledWith(expect.stringContaining('/api/auth/refresh'), expect.objectContaining({method: 'POST'})); }); }); diff --git a/src/components/BacklogCard.jsx b/src/components/BacklogCard.jsx index 6424c78..4ae42fd 100644 --- a/src/components/BacklogCard.jsx +++ b/src/components/BacklogCard.jsx @@ -13,7 +13,7 @@ import {cn} from '@/lib/utils'; import {STATUS_META} from './GameStatusBadge.jsx'; import {GAME_PRIORITIES, GAME_STATUSES, NO_PRIORITY, saveBacklogEntry, toBacklogRequest} from '../utils/backlog.js'; import useSessionExpired from '../hooks/useSessionExpired.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const NOTES_MAX = 2000; @@ -42,7 +42,7 @@ export default function BacklogCard({game, onSaved}) { const set = (field) => (value) => setForm((f) => ({...f, [field]: value})); const save = async () => { - if (!getToken()) { + if (!hasSession()) { navigate('/login'); return; } diff --git a/src/components/BacklogCard.test.jsx b/src/components/BacklogCard.test.jsx index e0f742d..41bb156 100644 --- a/src/components/BacklogCard.test.jsx +++ b/src/components/BacklogCard.test.jsx @@ -12,7 +12,7 @@ const saveButton = () => screen.getByRole('button', {name: 'BACKLOG.SAVE'}); describe('BacklogCard', () => { beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async (url, init) => ({ok: true, status: 200, json: async () => JSON.parse(init.body)})); }); diff --git a/src/components/CompletedHint.test.jsx b/src/components/CompletedHint.test.jsx index 3acc9e1..f9040b8 100644 --- a/src/components/CompletedHint.test.jsx +++ b/src/components/CompletedHint.test.jsx @@ -12,7 +12,7 @@ const renderHint = (props) => render( { beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async (url, init) => ({ ok: true, status: 200, json: async () => ({...JSON.parse(init.body), rating: 5, notes: 'keep', priority: null}), })); diff --git a/src/components/PlayingHint.test.jsx b/src/components/PlayingHint.test.jsx index d0ce2d5..1227f2e 100644 --- a/src/components/PlayingHint.test.jsx +++ b/src/components/PlayingHint.test.jsx @@ -12,7 +12,7 @@ const renderHint = (props) => render( { beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async (url, init) => ({ok: true, status: 200, json: async () => JSON.parse(init.body)})); }); diff --git a/src/hooks/useForceSync.js b/src/hooks/useForceSync.js index 257484b..32445e8 100644 --- a/src/hooks/useForceSync.js +++ b/src/hooks/useForceSync.js @@ -4,7 +4,7 @@ import {useTranslation} from 'react-i18next'; import {toast} from 'sonner'; import useSessionExpired from './useSessionExpired.js'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const RELOAD_DELAY_MS = 4000; @@ -19,7 +19,7 @@ export default function useForceSync(onStarted) { const [busy, setBusy] = useState(false); const trigger = async () => { - if (!getToken()) { + if (!hasSession()) { navigate('/login'); return; } diff --git a/src/hooks/useLibrarySync.js b/src/hooks/useLibrarySync.js index 11069eb..e4c2d8e 100644 --- a/src/hooks/useLibrarySync.js +++ b/src/hooks/useLibrarySync.js @@ -1,6 +1,6 @@ import {useEffect, useRef, useState} from 'react'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const POLL_INTERVAL_MS = 3000; const MAX_POLL_DURATION_MS = 120_000; @@ -34,7 +34,7 @@ export default function useLibrarySync({enabled, expectInitialSync = false, onCo const startedAt = Date.now(); const fetchOnce = async () => { - if (!getToken()) return; + if (!hasSession()) return; try { const response = await apiFetch( diff --git a/src/hooks/useSaveAppearance.test.jsx b/src/hooks/useSaveAppearance.test.jsx index 75c8e11..e14a61c 100644 --- a/src/hooks/useSaveAppearance.test.jsx +++ b/src/hooks/useSaveAppearance.test.jsx @@ -17,7 +17,7 @@ const wrapper = ({children}) => ( const renderSave = () => renderHook(() => ({save: useSaveAppearance(), preferences: usePreferences()}), {wrapper}); beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); }); afterEach(() => { diff --git a/src/hooks/useSessionExpired.js b/src/hooks/useSessionExpired.js index 4a55e36..dbe52bf 100644 --- a/src/hooks/useSessionExpired.js +++ b/src/hooks/useSessionExpired.js @@ -1,7 +1,7 @@ import {useCallback, useRef} from 'react'; import {useLocation, useNavigate} from 'react-router-dom'; import {useResetAppearance} from '../context/PreferencesContext.jsx'; -import {clearToken} from '../utils/auth.js'; +import {clearSession} from '../utils/auth.js'; /** * Returns a function for a 401 answer: it removes the token and the user's look and opens the login page, which @@ -17,7 +17,7 @@ export default function useSessionExpired() { return useCallback(() => { const {pathname, search} = locationRef.current; - clearToken(); + clearSession(); resetAppearance(); navigate('/login', {replace: true, state: {sessionExpired: true, from: pathname + search}}); }, [navigate, resetAppearance]); diff --git a/src/hooks/useSteamProfile.js b/src/hooks/useSteamProfile.js index aad9943..d9157e4 100644 --- a/src/hooks/useSteamProfile.js +++ b/src/hooks/useSteamProfile.js @@ -1,18 +1,18 @@ import {useEffect, useState} from 'react'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {sessionStamp} from '../utils/auth.js'; /** * The user's Steam name and avatar from Core, or null while loading, without a Steam ID or on any error. Only - * decoration, so a failed call shows the default icon and never ends the session. Loads again for a new token - * (new Steam ID or another login) on the next render, e.g. the next navigation. + * decoration, so a failed call shows the default icon and never ends the session. Loads again after a new login + * or a settings save (see sessionStamp) on the next render, e.g. the next navigation. */ export default function useSteamProfile(enabled) { const [profile, setProfile] = useState(null); - const token = getToken(); + const stamp = sessionStamp(); useEffect(() => { - if (!enabled || !token) { + if (!enabled || !stamp) { setProfile(null); return undefined; } @@ -29,7 +29,7 @@ export default function useSteamProfile(enabled) { return () => { cancelled = true; }; - }, [enabled, token]); + }, [enabled, stamp]); return profile; } diff --git a/src/hooks/useSteamProfile.test.jsx b/src/hooks/useSteamProfile.test.jsx index d4beb8a..cd7d761 100644 --- a/src/hooks/useSteamProfile.test.jsx +++ b/src/hooks/useSteamProfile.test.jsx @@ -6,7 +6,7 @@ import useSteamProfile from './useSteamProfile.js'; const ok = (body) => ({ok: true, status: 200, json: async () => body}); beforeEach(() => { - localStorage.setItem('tbp_jwt', 'old-token'); + localStorage.setItem('tbp_session', 'first-login'); }); afterEach(() => { @@ -15,21 +15,21 @@ afterEach(() => { }); describe('useSteamProfile', () => { - it('loads again after a new token was stored, e.g. with a new Steam ID', async () => { - globalThis.fetch = vi.fn(async (url, init) => ok(init.headers.Authorization === 'Bearer new-token' - ? {personaName: 'New', avatarUrl: 'https://avatars.steamstatic.com/new_full.jpg'} - : {personaName: 'Old', avatarUrl: 'https://avatars.steamstatic.com/old_full.jpg'})); + it('loads again after the session stamp changed, e.g. with a new Steam ID', async () => { + let steamName = 'old'; + globalThis.fetch = vi.fn(async () => ok({personaName: steamName, avatarUrl: `https://avatars.steamstatic.com/${steamName}_full.jpg`})); const {result, rerender} = renderHook(() => useSteamProfile(true)); await waitFor(() => expect(result.current?.avatarUrl).toContain('old_full')); - localStorage.setItem('tbp_jwt', 'new-token'); + steamName = 'new'; + localStorage.setItem('tbp_session', 'settings-saved'); rerender(); await waitFor(() => expect(result.current?.avatarUrl).toContain('new_full')); }); - it('sends nothing without a token, e.g. right after the session expired', async () => { - localStorage.removeItem('tbp_jwt'); + it('sends nothing without a session, e.g. right after it expired', async () => { + localStorage.removeItem('tbp_session'); globalThis.fetch = vi.fn(async () => ({ok: false, status: 401, json: async () => ({})})); renderHook(() => useSteamProfile(true)); diff --git a/src/pages/Dashboard.jsx b/src/pages/Dashboard.jsx index 736622c..3293aa2 100644 --- a/src/pages/Dashboard.jsx +++ b/src/pages/Dashboard.jsx @@ -26,7 +26,7 @@ import useSteamProfile from '../hooks/useSteamProfile.js'; import {cn} from '@/lib/utils'; import {usePreferences} from '../context/PreferencesContext.jsx'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const TOP_GAMES = 5; // The games endpoint accepts only the page sizes 20, 40 and 80. @@ -172,7 +172,7 @@ const Dashboard = () => { useEffect(() => { const fetchUserData = async () => { - if (!getToken()) { + if (!hasSession()) { navigate('/login'); return; } diff --git a/src/pages/Dashboard.test.jsx b/src/pages/Dashboard.test.jsx index c8ab0e6..af9469d 100644 --- a/src/pages/Dashboard.test.jsx +++ b/src/pages/Dashboard.test.jsx @@ -20,7 +20,7 @@ const ok = (body) => ({ok: true, status: 200, json: async () => body}); const unauthorized = () => ({ok: false, status: 401, json: async () => ({})}); beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); }); afterEach(() => { diff --git a/src/pages/GameDetail.jsx b/src/pages/GameDetail.jsx index 6d0d4c0..61da600 100644 --- a/src/pages/GameDetail.jsx +++ b/src/pages/GameDetail.jsx @@ -20,7 +20,7 @@ import useSaveAppearance from '../hooks/useSaveAppearance.js'; import {usePreferences} from '../context/PreferencesContext.jsx'; import PageContainer from '../components/PageContainer.jsx'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const formatUnlockedAt = (instant, locale) => { if (!instant) return ''; @@ -45,7 +45,7 @@ export default function GameDetail() { useEffect(() => { let cancelled = false; - if (!getToken()) { + if (!hasSession()) { navigate('/login'); return; } diff --git a/src/pages/GameDetail.test.jsx b/src/pages/GameDetail.test.jsx index 0ac50c2..ef67b33 100644 --- a/src/pages/GameDetail.test.jsx +++ b/src/pages/GameDetail.test.jsx @@ -20,7 +20,7 @@ const renderDetail = () => render( ); beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async (url, init) => init?.method === 'PUT' ? {ok: true, status: 200, json: async () => JSON.parse(init.body)} : {ok: true, status: 200, json: async () => game}); diff --git a/src/pages/GameLibrary.jsx b/src/pages/GameLibrary.jsx index f72136f..231c55e 100644 --- a/src/pages/GameLibrary.jsx +++ b/src/pages/GameLibrary.jsx @@ -20,7 +20,7 @@ import LibraryTabs from '../components/LibraryTabs.jsx'; import GameStatusBadge from '../components/GameStatusBadge.jsx'; import PageContainer from '../components/PageContainer.jsx'; import {apiFetch} from '../utils/api.js'; -import {getToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; const PAGE_SIZES = [20, 40, 80]; const DEFAULT_SIZE = 20; @@ -60,7 +60,7 @@ export default function GameLibrary() { const [error, setError] = useState(null); const load = useCallback(async () => { - if (!getToken()) { + if (!hasSession()) { navigate('/login'); return; } diff --git a/src/pages/GameLibrary.test.jsx b/src/pages/GameLibrary.test.jsx index 45088c5..4667b3b 100644 --- a/src/pages/GameLibrary.test.jsx +++ b/src/pages/GameLibrary.test.jsx @@ -41,7 +41,7 @@ function renderLibrary(initialEntry = '/library') { const typeInto = (value) => fireEvent.change(screen.getByRole('searchbox'), {target: {value}}); beforeEach(() => { - localStorage.setItem('tbp_jwt', 'token'); + localStorage.setItem('tbp_session', '1'); globalThis.fetch = vi.fn(async () => ({ok: true, status: 200, json: async () => page})); }); diff --git a/src/pages/LandingPage.jsx b/src/pages/LandingPage.jsx index 2819907..3259d2c 100644 --- a/src/pages/LandingPage.jsx +++ b/src/pages/LandingPage.jsx @@ -10,7 +10,7 @@ import {Card} from '@/components/ui/card'; import {Skeleton} from '@/components/ui/skeleton'; import GameCover from '../components/GameCover.jsx'; import StatCard from '../components/StatCard.jsx'; -import {getValidToken} from '../utils/auth.js'; +import {hasSession} from '../utils/auth.js'; import usePublicStats from '../hooks/usePublicStats.js'; @@ -64,7 +64,7 @@ export default function LandingPage() {

{t('MAIN.WELCOME')}

{t('MAIN.DESCRIPTION')}