Commit 4957eaf3 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix permanently-blank admin panel and a real-network-call leak in tests

Two compounding bugs, both traced from live "Token expired on Library" /
"blank Admin panel" reports:

1. AuthContext never recovered from a failed token refresh. isAuthenticated
   only ever got set to true (on mount or dev auto-login); nothing set it
   back to false when apiFetch's own refresh-and-retry also failed and
   silently cleared localStorage out from under it. role stayed null
   forever in that state, and RequireRole renders nothing while role is
   null (to avoid flashing "access denied" during the real initial
   fetch) - so a stale/expired token produced a permanently blank page
   instead of a "not authenticated" message. Now a 401 from /auth/me
   (meaning the retry already failed) flips isAuthenticated back to
   false so the UI recovers on its own.

2. AuthContext captured VITE_DEV_ACCESS_TOKEN/VITE_DEV_REFRESH_TOKEN as
   module-level constants at import time, so every test file's
   vi.stubEnv() calls in beforeEach (all of them except AuthContext's
   own tests, which knew to work around this with vi.resetModules())
   were silent no-ops. With genuinely valid dev tokens now in .env, this
   started making real network calls to the live backend during `npm
   test` and made Nearby.test.tsx flaky (real role resolved to
   super_admin, so the real "Business" nav link collided with a
   soundmark's own tier badge text). Reading the env vars fresh inside
   the effect instead of as frozen constants fixes it for every test
   file at once, not just the ones edited here.

Also regenerated .env's dev tokens via the real auth issuance path
(_issue_tokens) so they're backed by an actual refresh_tokens DB row,
not just a bare unregistered JWT.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 162b63ec
Pipeline #1068 canceled with stage
......@@ -14,13 +14,17 @@ import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/
async function loadFreshAuthContext() {
vi.resetModules()
// AuthContext.tsx's own `import * as authApi from '../api/auth'` gets re-evaluated as part
// of this fresh import too (resetModules cleared that module instance as well) - so a spy
// has to target *this* freshly-imported reference, not one imported statically at the top
// of this file before resetModules() ran, which would bind to a stale, disconnected copy.
// AuthContext.tsx's own `import * as authApi from '../api/auth'` (and, transitively,
// '../api/client' for ApiError) gets re-evaluated as part of this fresh import too
// (resetModules cleared those module instances as well) - so a spy, and any ApiError
// instance a test constructs to be caught by AuthContext's `instanceof ApiError` check, has
// to come from *these* freshly-imported references, not ones imported statically at the top
// of this file before resetModules() ran, which would be a different class identity entirely
// and silently fail every `instanceof` check against it.
const authModule = await import('./AuthContext')
const authApi = await import('../api/auth')
return { ...authModule, authApi }
const client = await import('../api/client')
return { ...authModule, authApi, client }
}
function Probe({ useAuth }: { useAuth: typeof import('./AuthContext').useAuth }) {
......@@ -138,6 +142,54 @@ describe('AuthProvider dev auto-login', () => {
expect(screen.getByTestId('is-business-admin')).toHaveTextContent('false')
expect(screen.getByTestId('is-super-admin')).toHaveTextContent('false')
})
it('recovers to "not authenticated" instead of hanging on role=null forever when the stored token is expired/invalid', async () => {
// Regression test: a stale token (e.g. an expired dev token) makes isAuthenticated start
// true, but if apiFetch's own refresh-and-retry inside getMe() also fails, tokens get
// cleared out from under this component (client.ts's tryRefresh does that on a failed
// refresh) with no way for React state to find out - role stayed null forever, and
// RequireRole renders nothing while role is null, which is exactly what produced a
// permanently blank admin panel instead of a "please log in again" message.
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('expired-access-token', 'expired-refresh-token')
const { AuthProvider, useAuth, authApi, client } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockRejectedValue(new client.ApiError(401, 'Token expired', null))
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
await waitFor(() => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('not-authenticated')
})
expect(screen.getByTestId('role')).toHaveTextContent('none')
})
it('does not flip to "not authenticated" on a non-auth failure (e.g. a 500)', async () => {
// A server error fetching /auth/me isn't proof the session is invalid - only a 401 is
// (meaning even the refresh retry inside apiFetch failed), so anything else should leave
// isAuthenticated alone rather than bouncing a legitimately logged-in user out.
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
setTokens('some-access-token', 'some-refresh-token')
const { AuthProvider, useAuth, authApi, client } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockRejectedValue(new client.ApiError(500, 'Server exploded', null))
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
// Give the rejected promise a tick to settle, then confirm it's still authenticated.
await new Promise((r) => setTimeout(r, 0))
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
})
})
describe('logout', () => {
......
import { createContext, useContext, useEffect, useState, type ReactNode } from 'react'
import * as authApi from '../api/auth'
import type { UserRole } from '../api/auth'
import { clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
import { ApiError, clearTokens, getAccessToken, getRefreshToken, setTokens } from '../api/client'
interface AuthContextValue {
isAuthenticated: boolean
......@@ -16,22 +16,28 @@ interface AuthContextValue {
const AuthContext = createContext<AuthContextValue | null>(null)
// Real Telegram phone/code login is gone from this app for now - dev doesn't need it at all.
// import.meta.env.DEV is Vite's own flag (true for `npm run dev`, false in a production
// build), so this bootstrap never runs outside local development no matter what. The tokens
// are for a real, DB-backed dev-test-user row and refresh_tokens entry on the dev server
// (not a fake/forged pair) - the existing auto-refresh-on-401 in client.ts keeps working
// against them indefinitely, same as a real login would.
const DEV_ACCESS_TOKEN = import.meta.env.VITE_DEV_ACCESS_TOKEN as string | undefined
const DEV_REFRESH_TOKEN = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | undefined
export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(() => Boolean(getAccessToken()))
const [role, setRole] = useState<UserRole | null>(null)
useEffect(() => {
if (import.meta.env.DEV && !getAccessToken() && DEV_ACCESS_TOKEN && DEV_REFRESH_TOKEN) {
setTokens(DEV_ACCESS_TOKEN, DEV_REFRESH_TOKEN)
// Real Telegram phone/code login is gone from this app for now - dev doesn't need it at
// all. import.meta.env.DEV is Vite's own flag (true for `npm run dev`, false in a
// production build), so this bootstrap never runs outside local development no matter
// what. The tokens are for a real, DB-backed dev-test-user row and refresh_tokens entry on
// the dev server (not a fake/forged pair) - the existing auto-refresh-on-401 in client.ts
// keeps working against them indefinitely, same as a real login would.
//
// Read fresh here on every mount rather than as module-level constants: import.meta.env is
// captured once at module-evaluation time otherwise, which a test's vi.stubEnv() (run in
// its own beforeEach, after this module has already loaded) can never retroactively
// change - every test file rendering AuthProvider without vi.resetModules() gymnastics
// would otherwise silently pick up .env's real dev tokens and, if those happen to be
// currently valid, make a genuine network call to the live backend during `npm test`.
const devAccessToken = import.meta.env.VITE_DEV_ACCESS_TOKEN as string | undefined
const devRefreshToken = import.meta.env.VITE_DEV_REFRESH_TOKEN as string | undefined
if (import.meta.env.DEV && !getAccessToken() && devAccessToken && devRefreshToken) {
setTokens(devAccessToken, devRefreshToken)
setIsAuthenticated(true)
}
}, [])
......@@ -47,8 +53,17 @@ export function AuthProvider({ children }: { children: ReactNode }) {
.then((res) => {
if (!cancelled) setRole(res.user.role)
})
.catch(() => {
// Role-gated UI just stays hidden if this fails - not worth surfacing an error for.
.catch((err) => {
if (cancelled) return
// A 401 here means apiFetch's own refresh-and-retry already failed too, so the tokens
// are gone from localStorage (client.ts's tryRefresh clears them) even though this
// component's isAuthenticated state doesn't know that yet - without this, `role` would
// stay null forever and RequireRole (which renders nothing while role is null, to avoid
// flashing "access denied" during the real initial fetch) would show a blank page
// permanently instead of falling back to "not authenticated".
if (err instanceof ApiError && err.status === 401) {
setIsAuthenticated(false)
}
})
return () => {
cancelled = true
......
......@@ -7,6 +7,7 @@ import { AuthProvider } from '../context/AuthContext'
import { PlayerProvider } from '../context/PlayerContext'
import * as soundmarksApi from '../api/soundmarks'
import * as libraryApi from '../api/library'
import { clearTokens } from '../api/client'
const FOUND_MARK: soundmarksApi.NearbySoundmark = {
id: 1,
......@@ -82,6 +83,11 @@ function renderNearby() {
describe('Nearby', () => {
beforeEach(() => {
// Vitest's jsdom environment is shared across every `it()` in this file (isolation is at
// the file level, not the test level) - without this, a token left behind by one test
// (real or via stray state) makes isAuthenticated start true in a later one, silently
// pulling in the authenticated nav links this suite doesn't otherwise account for.
clearTokens()
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
// jsdom's default test origin doesn't count as a secure context, unlike the real
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment