Files
Moonbase/src/lib/auth.ts
tonym 0904790dca Security: force first-login password change, gate admin tools, validate restore
Fixes from the code review:
- #1 Wire mustChangePassword: dashboard layout redirects to a new /change-password
  page + /api/account/change-password (verifies current pw, re-hashes, clears the
  flag, refreshes the session). Provisioned admins can no longer keep the default.
- #2 Assert NEXTAUTH_SECRET in production (not during build); set it on authOptions.
- #3 Backup page now server-gated to admins (split into server page + client panel),
  matching the Updates page.
- #4 Restore validates input: strict zod schema for the users table (known fields,
  role enum) + array checks for the rest; returns generic errors instead of String(err).

No version bump/changelog — left for you to fold into the next release (you're
editing those live). Not pushed, not deployed.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 23:59:39 -05:00

126 lines
3.5 KiB
TypeScript

import { NextAuthOptions, getServerSession } from "next-auth";
import CredentialsProvider from "next-auth/providers/credentials";
import { compare } from "bcryptjs";
import { db } from "@/lib/db";
import { UserRole } from "@prisma/client";
declare module "next-auth" {
interface Session {
user: {
id: string;
email: string;
name: string;
role: UserRole;
mustChangePassword: boolean;
};
}
interface User {
id: string;
role: UserRole;
mustChangePassword: boolean;
}
}
declare module "next-auth/jwt" {
interface JWT {
id: string;
role: UserRole;
mustChangePassword: boolean;
}
}
// Fail loudly in production if the JWT secret is missing or left at the
// placeholder — otherwise sessions are forgeable. Skipped during `next build`
// (no runtime env) and in development.
const NEXTAUTH_SECRET = process.env.NEXTAUTH_SECRET;
if (
process.env.NODE_ENV === "production" &&
process.env.NEXT_PHASE !== "phase-production-build" &&
(!NEXTAUTH_SECRET || NEXTAUTH_SECRET.length < 16 || NEXTAUTH_SECRET.includes("change-me"))
) {
throw new Error(
"NEXTAUTH_SECRET is missing or insecure — generate one with `openssl rand -base64 32` and set it in the environment."
);
}
export const authOptions: NextAuthOptions = {
secret: NEXTAUTH_SECRET,
session: { strategy: "jwt" },
pages: { signIn: "/login", error: "/login" },
providers: [
CredentialsProvider({
name: "credentials",
credentials: {
email: { label: "Username or email", type: "text" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) return null;
const id = credentials.email.trim();
const user = await db.user.findFirst({
where: {
active: true,
OR: [
{ email: id.toLowerCase() },
{ username: { equals: id, mode: "insensitive" } },
],
},
select: {
id: true,
name: true,
email: true,
passwordHash: true,
role: true,
mustChangePassword: true,
},
});
if (!user) return null;
const ok = await compare(credentials.password, user.passwordHash);
if (!ok) return null;
return {
id: user.id,
email: user.email,
name: user.name,
role: user.role,
mustChangePassword: user.mustChangePassword,
};
},
}),
],
callbacks: {
async jwt({ token, user, trigger }) {
if (user) {
token.id = user.id;
token.role = user.role;
token.mustChangePassword = user.mustChangePassword;
}
if (trigger === "update") {
const fresh = await db.user.findUnique({
where: { id: token.id },
select: { mustChangePassword: true },
});
if (fresh) token.mustChangePassword = fresh.mustChangePassword;
}
return token;
},
async session({ session, token }) {
session.user.id = token.id;
session.user.role = token.role;
session.user.mustChangePassword = token.mustChangePassword;
return session;
},
},
};
export const getSession = () => getServerSession(authOptions);
export async function requireAuth() {
const session = await getSession();
if (!session) throw new Error("Unauthorized");
return session;
}
export function isAdmin(role: UserRole): boolean {
return role === "ADMIN";
}