/** * Auth.js (v5) configuration: the magic-link credentials provider plus a JWT * session that carries `systemRole` so `requirePermission()` can read it from * `session.user` without another DB hit. * * No database adapter is needed — JWT sessions are self-contained. The * credentials provider's `authorize` verifies the one-time magic-link token and * returns the active user. */ import NextAuth from "next-auth"; import Credentials from "next-auth/providers/credentials"; import { getUser, verifyMagicToken } from "./magic-link"; import type { SystemRole } from "./roles"; export const authConfig = { providers: [ Credentials({ id: "magic-link", name: "Magic Link", credentials: { token: { label: "Token", type: "text" }, }, async authorize(credentials) { const token = credentials?.token as string | undefined; const payload = await verifyMagicToken(token); if (!payload) return null; const user = await getUser(payload.email); if (!user || user.status !== "active" || user.deactivatedAt) return null; return { id: user.id, email: user.email, name: user.displayName ?? user.email, systemRole: user.systemRole, }; }, }), ], session: { strategy: "jwt" }, secret: process.env.AUTH_SECRET ?? process.env.NEXTAUTH_SECRET, // Auth.js v5 gates the callback on the request `Host` header and throws // `UntrustedHost` unless `trustHost` is true. In `pnpm start` (production) // the env-based default is false, which silently drops the session cookie // on the magic-link callback (the A4 blocker). This is a localhost app behind // a reverse proxy, so trusting the Host header is the documented fix. trustHost: true, pages: { signIn: "/login" }, callbacks: { async jwt({ token, user }) { if (user) { (token as { systemRole?: SystemRole }).systemRole = (user as { systemRole?: SystemRole }).systemRole ?? "volunteer"; } return token; }, async session({ session, token }) { (session.user as { systemRole?: SystemRole }).systemRole = (token as { systemRole?: SystemRole }).systemRole ?? "volunteer"; return session; }, }, } satisfies Parameters[0]; export const { handlers, auth, signIn, signOut } = NextAuth(authConfig);