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.
This commit is contained in:
@@ -45,6 +45,7 @@ export async function middleware(request: NextRequest) {
|
|||||||
|
|
||||||
const {
|
const {
|
||||||
data: { user },
|
data: { user },
|
||||||
|
error: userError,
|
||||||
} = await supabase.auth.getUser();
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
const path = request.nextUrl.pathname;
|
const path = request.nextUrl.pathname;
|
||||||
@@ -67,6 +68,52 @@ export async function middleware(request: NextRequest) {
|
|||||||
return withCookies(NextResponse.redirect(url));
|
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
|
// Defense-in-depth: guard the admin surface here in addition to the
|
||||||
// per-route requireAdmin()/requireAdminApi() checks.
|
// per-route requireAdmin()/requireAdminApi() checks.
|
||||||
if (path.startsWith('/admin') || path.startsWith('/api/admin')) {
|
if (path.startsWith('/admin') || path.startsWith('/api/admin')) {
|
||||||
|
|||||||
Reference in New Issue
Block a user