// Modified in the independent hardening fork; see docs/hardening/README.md. // Modified for AgentDeskFixes: prevent a late logout from redirecting a newer login. "use client" import { createContext, startTransition, useContext, useCallback, useEffect, type ReactNode, } from "react" import { usePathname, useRouter } from "next/navigation" import { SessionProvider, useSession } from "@/components/session-provider" import { readSession, type AuthSession } from "@/lib/auth" type AuthContextValue = { session: AuthSession | null ready: boolean refreshProfile: () => Promise signOut: () => Promise } const AuthContext = createContext(null) export function AuthProvider({ children }: { children: ReactNode }) { return ( {children} ) } function DashboardAuthProvider({ children }: { children: ReactNode }) { const pathname = usePathname() const router = useRouter() const { session, ready, refreshSession, signOut: endSession } = useSession() const isDashboardLoginRoute = pathname?.startsWith("/dashboard/login") ?? false const requiresAuth = ((pathname?.startsWith("/dashboard") ?? false) || (pathname?.startsWith("/workbench") ?? false)) && !isDashboardLoginRoute const refreshProfile = useCallback(() => refreshSession(), [refreshSession]) async function signOut() { try { await endSession() } finally { // A different tab or login flow may have established a new session meanwhile. if (!readSession()) { startTransition(() => { router.replace("/dashboard/login") }) } } } useEffect(() => { if (ready && !session && requiresAuth) { // A different tab or login flow may have established a new session meanwhile. if (!readSession()) { startTransition(() => { router.replace("/dashboard/login") }) } } }, [ready, requiresAuth, router, session]) return ( {children} ) } export function useAuth() { const ctx = useContext(AuthContext) if (!ctx) { throw new Error("useAuth must be used within AuthProvider") } return ctx }