Commit 9d69f811 authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Remove the dev auto-login shortcut - it kept going stale and presenting as "site is slow"

VITE_DEV_ACCESS_TOKEN/VITE_DEV_REFRESH_TOKEN was a single refresh token
baked into .env and shared across every consumer (every dev session, every
test run, every stray curl). Refresh tokens are single-use/rotating by
design - the instant any one consumer used it, the backend rotated it and
the file's copy went dead for everyone else, with no way to keep a static
file in sync with a rotating secret. Confirmed live in the backend log:
the real browser session was stuck looping GET /auth/me -> 401 -> POST
/auth/refresh -> 401 on every page load, which is what "still very slow"
actually was - not a performance bug, an auth bug that looked like one.

Regenerating the pair (done twice already this session) only delays the
same failure. Removed the mechanism entirely: isAuthenticated's initial
value now comes straight from whatever's already in localStorage, exactly
like a real logged-in user. Real username/password login (shipped earlier
today) replaces the dev shortcut with no such failure mode - log in with
dev-test-user / StaxDev2026! instead.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 27f06c50
Pipeline #1087 canceled with stage
......@@ -16,18 +16,10 @@ BACKEND_PROXY_TARGET=http://127.0.0.1:8000
# Leave this file's VITE_API_BASE_URL above as the real absolute URL - it's what
# BACKEND_PROXY_TARGET/production builds use.
# Dev-only auto-login (see AuthContext.tsx) - only takes effect under `npm run dev`
# (import.meta.env.DEV), never in a production build, regardless of whether these are set.
# Real, DB-backed tokens for a dedicated dev-test-user row (username "dev-test-user",
# super_admin), not forged. These WILL go stale on their own - refresh tokens are
# single-use/rotating by design, so the pair below stops working the moment it's ever used
# once (e.g. an open dev tab silently refreshing after the access token's 30-min TTL), and a
# subsequent fresh page load (cleared storage, new tab/device) does two dead round trips
# before bouncing to /login, which reads as "pages take forever to load" - that happened for
# real on 2026-08-15. When it does: don't debug it, just log in through the real UI (real
# username/password login exists now) instead of depending on this shortcut, or mint a fresh
# pair with a normal login call:
# curl -X POST <backend>/auth/login -H "Content-Type: application/json" \
# -d '{"username":"dev-test-user","password":"<the password>"}'
VITE_DEV_ACCESS_TOKEN=
VITE_DEV_REFRESH_TOKEN=
# There is no dev-only auto-login token pair anymore (removed 2026-08-15) - it was a
# single-use, rotating refresh token baked into a static file and shared across every
# consumer (every dev session, every test run, every curl); the instant any one of them used
# it, the backend rotated it and the file's copy went dead for everyone else, with no way to
# keep a static file in sync with a rotating secret. That repeatedly presented as "the site is
# slow/broken." Just log in through the real UI instead - real username/password login
# (AuthContext.tsx/Login.tsx) is just as fast for local dev and has no such failure mode.
......@@ -39,20 +39,21 @@ function Probe({ useAuth }: { useAuth: typeof import('./AuthContext').useAuth })
)
}
describe('AuthProvider dev auto-login', () => {
describe('AuthProvider bootstrap from stored tokens', () => {
// No more dev-only .env auto-login (removed 2026-08-15 - a shared rotating refresh token in
// a static file goes dead the instant any one consumer uses it, with no way to keep the file
// in sync). isAuthenticated's initial value now comes straight from whatever's already in
// localStorage, same as a real logged-in user reloading the page.
beforeEach(() => {
clearTokens()
})
afterEach(() => {
vi.unstubAllEnvs()
clearTokens()
vi.restoreAllMocks()
})
it('does not auto-authenticate when no dev tokens are configured', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', '')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', '')
it('is not authenticated when no tokens are stored', async () => {
const { AuthProvider, useAuth } = await loadFreshAuthContext()
render(
......@@ -65,9 +66,8 @@ describe('AuthProvider dev auto-login', () => {
expect(getAccessToken()).toBeNull()
})
it('auto-authenticates using the configured dev tokens', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
it('is authenticated immediately when a token is already stored (e.g. a prior real login)', async () => {
setTokens('stored-access-token', 'stored-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
......@@ -77,33 +77,13 @@ describe('AuthProvider dev auto-login', () => {
</AuthProvider>,
)
await waitFor(() => {
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
})
expect(getAccessToken()).toBe('dev-access-token')
expect(getRefreshToken()).toBe('dev-refresh-token')
})
it('does not overwrite an already-present access token (e.g. from a real login)', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
setTokens('already-logged-in-token', 'already-logged-in-refresh')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
render(
<AuthProvider>
<Probe useAuth={useAuth} />
</AuthProvider>,
)
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
expect(getAccessToken()).toBe('already-logged-in-token')
expect(getAccessToken()).toBe('stored-access-token')
expect(getRefreshToken()).toBe('stored-refresh-token')
})
it('fetches and exposes the current user role once authenticated', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
setTokens('stored-access-token', 'stored-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({
status: 'success',
......@@ -125,8 +105,7 @@ describe('AuthProvider dev auto-login', () => {
})
it('leaves role null (not "user") until the fetch resolves, and plain "user" role gates out admin UI', async () => {
vi.stubEnv('VITE_DEV_ACCESS_TOKEN', 'dev-access-token')
vi.stubEnv('VITE_DEV_REFRESH_TOKEN', 'dev-refresh-token')
setTokens('stored-access-token', 'stored-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockResolvedValue({ status: 'success', user: { id: 1, username: 'x', role: 'user' } })
......@@ -144,14 +123,12 @@ describe('AuthProvider dev auto-login', () => {
})
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', '')
// Regression test: a stale stored 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.
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))
......@@ -173,8 +150,6 @@ describe('AuthProvider dev auto-login', () => {
// 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))
......
......@@ -12,43 +12,29 @@ interface AuthContextValue {
isBusinessAdmin: boolean
isSuperAdmin: boolean
logout: () => Promise<void>
/** Called by Login.tsx once /auth/login returns a real token pair - stores them and flips
* isAuthenticated, same effect a page reload after the old dev-only bootstrap used to have. */
/** Called by Login.tsx once /auth/login (or /auth/register) returns a real token pair -
* stores them and flips isAuthenticated. */
completeLogin: (tokens: TokenPair) => void
}
const AuthContext = createContext<AuthContextValue | null>(null)
function bootstrapAuth(): boolean {
if (getAccessToken()) return true
// This dev-only bootstrap is separate from (and skipped entirely for) the real login flow in
// Login.tsx/completeLogin below - it exists purely so `npm run dev` doesn't require clicking
// through a real Telegram code every time. import.meta.env.DEV is Vite's own flag (true for
// `npm run dev`, false in a production build), so this 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.
//
// Runs synchronously as the isAuthenticated state's lazy initializer, not a useEffect: an
// effect only fires *after* the first render, so ProtectedRoute/RequireRole's very first
// render would still see isAuthenticated as false and redirect to /login via <Navigate>
// before this ever got a chance to run - stranding a dev session on the login page even
// though it was about to auto-authenticate a moment later. Reading import.meta.env here
// (rather than as a module-level constant) still lets a test's vi.stubEnv() control it,
// since stubEnv always runs in beforeEach - before render() - regardless of whether this is
// an effect or an initializer.
if (!import.meta.env.DEV) return false
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 (devAccessToken && devRefreshToken) {
setTokens(devAccessToken, devRefreshToken)
return true
}
return false
}
// isAuthenticated's initial value comes straight from whatever's already in localStorage
// (a real prior login, real credentials) - resolved synchronously via useState's lazy
// initializer, not a useEffect, since an effect only fires *after* the first render and
// ProtectedRoute/RequireRole's very first render already needs the real answer to decide
// whether to <Navigate> to /login.
//
// This used to also auto-inject a dev-only token pair from .env (VITE_DEV_ACCESS_TOKEN/
// VITE_DEV_REFRESH_TOKEN) so `npm run dev` didn't require logging in by hand. Removed
// 2026-08-15: that pair is a *rotating* refresh token shared across every consumer (every dev
// session, every test run, every stray curl) - the instant any one of them used it, the
// backend rotated it and the value baked into .env went dead for everyone else, with no way
// to keep a static file in sync with a single-use secret. It kept silently reappearing as
// "the site is broken/slow" days apart. Real username/password login (see Login.tsx) is just
// as fast and has no such failure mode - log in for real instead.
export function AuthProvider({ children }: { children: ReactNode }) {
const [isAuthenticated, setIsAuthenticated] = useState(bootstrapAuth)
const [isAuthenticated, setIsAuthenticated] = useState(() => !!getAccessToken())
const [role, setRole] = useState<UserRole | null>(null)
useEffect(() => {
......
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