From 6e8724c9a46598ee0a746c718bbbaf90e9005588 Mon Sep 17 00:00:00 2001 From: Gerhard Scheikl Date: Mon, 1 Jun 2026 22:01:51 +0200 Subject: [PATCH] fix(auth): clear stale Supabase auth cookies on invalid session When getUser() rejects a present session cookie with user_not_found / session_not_found / bad_jwt (e.g. a deleted account or a cookie that outlived its session), the middleware now clears the sb-*-auth-token cookies and redirects to /login instead of leaving the browser wedged in a logged-out page that still renders a Sign out button. --- middleware.ts | 47 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/middleware.ts b/middleware.ts index 70057cb..752bf63 100644 --- a/middleware.ts +++ b/middleware.ts @@ -45,6 +45,7 @@ export async function middleware(request: NextRequest) { const { data: { user }, + error: userError, } = await supabase.auth.getUser(); const path = request.nextUrl.pathname; @@ -67,6 +68,52 @@ export async function middleware(request: NextRequest) { return withCookies(NextResponse.redirect(url)); }; + // If a session cookie is present but the auth server rejects it because the + // underlying user or session no longer exists (a deleted account, or a stale + // cookie that outlived its session), proactively clear the Supabase auth + // cookies. Otherwise the browser keeps a token whose `sub` is gone, every + // `getUser()` 403s with `user_not_found`, and the UI gets wedged in a + // confusing "logged-out page that still shows a Sign out button" state. + const INVALID_SESSION_CODES = new Set([ + 'user_not_found', + 'session_not_found', + 'session_expired', + 'refresh_token_not_found', + 'bad_jwt', + ]); + const isAuthCookie = (name: string): boolean => + name.startsWith('sb-') && name.includes('-auth-token'); + if ( + !user && + userError && + INVALID_SESSION_CODES.has(userError.code ?? '') && + request.cookies.getAll().some((c) => isAuthCookie(c.name)) + ) { + const clearStale = (res: NextResponse): NextResponse => { + request.cookies.getAll().forEach((c) => { + if (isAuthCookie(c.name)) { + res.cookies.set(c.name, '', { maxAge: 0, path: '/' }); + } + }); + res.headers.set('Cache-Control', 'no-store'); + return res; + }; + if (path.startsWith('/api/')) { + return clearStale( + NextResponse.json({ error: 'unauthorized' }, { status: 401 }), + ); + } + if (!isMfaAllowlisted(path)) { + const url = request.nextUrl.clone(); + url.pathname = '/login'; + url.search = ''; + return clearStale(NextResponse.redirect(url)); + } + // Allowlisted pages (e.g. /login itself) render fine logged-out — just drop + // the dead cookies so the nav is consistent on the next request. + return clearStale(NextResponse.next({ request })); + } + // Defense-in-depth: guard the admin surface here in addition to the // per-route requireAdmin()/requireAdminApi() checks. if (path.startsWith('/admin') || path.startsWith('/api/admin')) {