import type { ActionFunctionArgs, LoaderFunctionArgs } from "react-router"; import { redirect } from "react-router"; import { AdminSsoConfigError, getAdminSsoClient, readAdminSsoEnv, } from "~/modules/admin-sso"; import { clearIdTokenCookie, readIdTokenFromRequest } from "~/modules/admin-sso/logout.server"; import { writeAdminSsoAuditEvent } from "~/modules/admin-sso/audit.server"; import { commitSession, getUserInfo, getUserSession } from "~/utils/session.server"; /** * Phase 09 Task #82 — POST /auth/admin/logout * * Always tears down the local App-Session and clears the id-token cookie. * If an id_token is present AND Authentik is reachable, additionally * redirects to Authentik's end_session_endpoint for RP-initiated logout. * Otherwise falls back to /admin/login?logged_out=1 directly so a stale * IdP doesn't trap users inside the panel. */ // React-Router session storage is owned by ~/utils/session.server.ts; pull // in destroySession via getUserSession round-trip. async function destroyAppSession(request: Request): Promise { const session = await getUserSession(request); // session.destroy() is not exposed; we explicitly clear every known key // through the storage adapter via a fresh response with `Set-Cookie: // =; Max-Age=0`. The simplest path that respects the existing // cookie config is to call `commitSession` on a session with no userId. for (const key of [ "userId", "lightOrDarkMode", "lng", "csrf", "metrics", "cookies", "impersonatingFromUserId", "impersonatingStartedAt", "theme", ]) { session.unset(key); } // commitSession returns a Set-Cookie header serializing the (now empty) // session. With Max-Age preserved this effectively logs the user out for // any handler that looks up `userId`. return commitSession(session); } async function buildLogoutRedirect(request: Request): Promise { const userInfo = await getUserInfo(request); const idToken = readIdTokenFromRequest(request); await writeAdminSsoAuditEvent({ action: "admin.logout.sso", actorAdminUserId: userInfo.userId ?? null, request, meta: { hadIdToken: Boolean(idToken) }, }); let target = "/admin/login?logged_out=1"; if (idToken) { try { const env = readAdminSsoEnv(); const client = await getAdminSsoClient(env); target = client.endSessionUrl({ id_token_hint: idToken, post_logout_redirect_uri: env.postLogoutRedirectUri ?? target, }); } catch (err) { // If Authentik is unreachable we still want to terminate the local // session; just skip the IdP redirect. if (!(err instanceof AdminSsoConfigError)) { // swallow - logger absent here, audit already written } } } const headers = new Headers(); headers.append("Set-Cookie", await destroyAppSession(request)); headers.append("Set-Cookie", clearIdTokenCookie()); return redirect(target, { headers }); } export async function action({ request }: ActionFunctionArgs): Promise { return buildLogoutRedirect(request); } // GET also works (e.g. browser back-button). React Router allows logout-via-GET // when CSRF for logout isn't required; we keep both to maximise compatibility. export async function loader({ request }: LoaderFunctionArgs): Promise { return buildLogoutRedirect(request); } export default function AuthAdminLogout() { return null; }