Commit a631b91b authored by Aryan Noshirvnai's avatar Aryan Noshirvnai

Fix mixed-content-blocked API calls in the production build + harden auth-failure recovery

Two compounding bugs behind "cannot sign in" / protected pages showing a
blank page instead of prompting to log in:

1. The production build (vite build, mode=production) doesn't read
   .env.development.local - only .env - so it baked in the raw
   http://144.76.210.145:8000 absolute URL instead of the /api proxy path.
   Since the page is served over https:// (via vite preview, see
   stax_dev_mode_is_the_real_slowness in project memory), the browser
   silently blocked every single fetch as mixed content - no server-side
   error, just every API call failing client-side. Added
   .env.production.local (gitignored, documented in .env.example so a
   fresh checkout doesn't regress) with the same /api override
   .env.development.local already used for dev mode.

2. AuthContext's role-fetch effect only recognized a clean 401 ApiError as
   "not authenticated" - a mixed-content-blocked fetch throws a raw
   TypeError instead, which the old check didn't recognize, so `role`
   stayed null forever and RequireRole rendered a blank page indefinitely
   instead of ever redirecting to /login. Now only a 5xx (a transient
   server hiccup) is treated as "stay logged in, don't overreact" -
   everything else, including a network-level failure, is treated as "not
   authenticated" so the user always gets a login prompt instead of
   silence.
Co-Authored-By: 's avatarClaude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_019i3NAUkLkHNbsPg5vKfzF9
parent 9d69f811
Pipeline #1088 failed with stage
......@@ -14,7 +14,24 @@ BACKEND_PROXY_TARGET=http://127.0.0.1:8000
# *.local, not committed) with:
# VITE_API_BASE_URL=/api
# Leave this file's VITE_API_BASE_URL above as the real absolute URL - it's what
# BACKEND_PROXY_TARGET/production builds use.
# BACKEND_PROXY_TARGET/production builds use *in general*.
#
# IMPORTANT if `vite preview` is what's actually serving the production build on this same
# box (see stax_dev_mode_is_the_real_slowness in project memory - as of 2026-08-15 that's how
# this app is deployed, port 5173 runs `vite preview` against `dist/`, not a separate
# reverse-proxied host): `vite preview` reuses this same vite.config.ts proxy, but env
# resolution happens at BUILD time (`vite build`, mode=production), not at preview/serve time.
# Without an override, the absolute http:// URL above gets baked directly into the built JS
# bundle - mixed content blocks every single fetch from a browser once the page is https://,
# which is silent (no server-side error to see) and looks exactly like "nothing works" or
# "can't sign in." Create .env.production.local (gitignored, not committed - a fresh checkout
# needs this recreated) with the same override:
# VITE_API_BASE_URL=/api
# then `npm run build` again and restart `vite preview` before assuming the fix landed - the
# env value is baked in at build time, not read fresh by the already-running preview server.
# This override is NOT needed for a real deployment where the backend itself is served over
# HTTPS and/or a separate reverse proxy/CDN sits in front - only for this same-box
# vite-preview-as-prod-server setup.
# 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
......
......@@ -146,10 +146,10 @@ describe('AuthProvider bootstrap from stored tokens', () => {
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.
it('does not flip to "not authenticated" on a transient server failure (e.g. a 500)', async () => {
// A server error fetching /auth/me isn't proof the session is invalid - only a genuine
// auth failure is - so a 5xx should leave isAuthenticated alone rather than bouncing a
// legitimately logged-in user out over a backend blip.
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))
......@@ -165,6 +165,29 @@ describe('AuthProvider bootstrap from stored tokens', () => {
await new Promise((r) => setTimeout(r, 0))
expect(screen.getByTestId('auth-state')).toHaveTextContent('authenticated')
})
it('flips to "not authenticated" on a raw network failure (e.g. a mixed-content-blocked fetch), not just a 401', async () => {
// Regression test (2026-08-15): a fetch() that never gets a response at all - blocked as
// mixed content, CORS, offline - throws a plain TypeError, not an ApiError with status
// 401. The old check only recognized `err instanceof ApiError && err.status === 401`, so
// this exact failure mode left `role` null forever and RequireRole stuck rendering a
// blank page instead of ever redirecting to /login.
setTokens('some-access-token', 'some-refresh-token')
const { AuthProvider, useAuth, authApi } = await loadFreshAuthContext()
vi.spyOn(authApi, 'getMe').mockRejectedValue(new TypeError('Failed to fetch'))
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')
})
})
describe('completeLogin', () => {
......
......@@ -50,13 +50,21 @@ export function AuthProvider({ children }: { children: ReactNode }) {
})
.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) {
// 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" -
// this happened for real (2026-08-15) when a mixed-content-blocked fetch threw a raw
// network error instead of a clean 401 response, which the old `status === 401`-only
// check didn't recognize.
//
// A 5xx is the one case treated as "server had a hiccup, stay logged in" rather than
// "not authenticated" - a transient backend error isn't proof the session is invalid,
// and bouncing a legitimately logged-in user out over a blip would be worse than a
// stale blank moment. Everything else (401, any other status, or a fetch that never
// got a response at all - network error, CORS, mixed content) is treated as "assume
// not authenticated and let them log in again" rather than staying blank indefinitely.
const isTransientServerError = err instanceof ApiError && err.status >= 500
if (!isTransientServerError) {
setIsAuthenticated(false)
}
})
......
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