Files
linumiq_net-web_app/middleware.ts
T
Gerhard Scheikl 6e8724c9a4 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.
2026-06-01 22:01:51 +02:00

169 lines
5.6 KiB
TypeScript

import { createServerClient } from '@supabase/ssr';
import { NextResponse, type NextRequest } from 'next/server';
// Path prefixes that are reachable without a completed MFA step-up. These are
// the auth flow itself, the MFA enrollment/challenge surface, their supporting
// APIs, and public email templates. Everything else (including the root path)
// requires aal2 once the user is authenticated.
const MFA_ALLOWLIST = [
'/login',
'/signup',
'/auth',
'/security',
'/api/auth',
'/api/security',
'/email-templates',
];
function isMfaAllowlisted(path: string): boolean {
return MFA_ALLOWLIST.some(
(prefix) => path === prefix || path.startsWith(`${prefix}/`),
);
}
export async function middleware(request: NextRequest) {
let response = NextResponse.next({ request });
const supabase = createServerClient(
process.env.NEXT_PUBLIC_SUPABASE_URL!,
process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!,
{
cookies: {
getAll() {
return request.cookies.getAll();
},
setAll(toSet) {
toSet.forEach(({ name, value }) => request.cookies.set(name, value));
response = NextResponse.next({ request });
toSet.forEach(({ name, value, options }) =>
response.cookies.set(name, value, options),
);
},
},
},
);
const {
data: { user },
error: userError,
} = await supabase.auth.getUser();
const path = request.nextUrl.pathname;
// Carry any cookies Supabase rotated onto the working `response` over to a
// deny/redirect response, so a refreshed session/refresh token is always
// persisted — otherwise a fresh NextResponse would drop them and a
// concurrent request could spuriously 401. Also stamp `no-store` so these
// short-circuit responses are never cached by intermediaries or the browser.
const withCookies = (res: NextResponse): NextResponse => {
response.cookies.getAll().forEach((cookie) => res.cookies.set(cookie));
res.headers.set('Cache-Control', 'no-store');
return res;
};
const redirectTo = (pathname: string, search = ''): NextResponse => {
const url = request.nextUrl.clone();
url.pathname = pathname;
url.search = search;
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')) {
if (!user) {
if (path.startsWith('/api/admin')) {
return withCookies(
NextResponse.json({ error: 'unauthorized' }, { status: 401 }),
);
}
return redirectTo('/login');
}
if (user.app_metadata?.role !== 'admin') {
if (path.startsWith('/api/admin')) {
return withCookies(
NextResponse.json({ error: 'forbidden' }, { status: 403 }),
);
}
return redirectTo('/dashboard');
}
}
// Mandatory MFA gate for every authenticated request outside the allowlist.
if (user && !isMfaAllowlisted(path)) {
const [{ data: aal }, { data: factors }] = await Promise.all([
supabase.auth.mfa.getAuthenticatorAssuranceLevel(),
supabase.auth.mfa.listFactors(),
]);
const verifiedCount =
factors?.all.filter((f) => f.status === 'verified').length ?? 0;
if (verifiedCount === 0) {
// No second factor at all → force enrollment.
return redirectTo('/security/enroll');
}
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
// Has a factor but session is only aal1 → force step-up, preserving the
// originally requested destination.
const next = encodeURIComponent(`${path}${request.nextUrl.search}`);
return redirectTo('/security/challenge', `?next=${next}`);
}
}
return response;
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim|api/device).*)',
'/admin/:path*',
'/api/admin/:path*',
],
};