Files
Todo/auth.ts
Paul Bailey 534796edd7 feat: implement security enhancements (task 17)
- Add rate limiting for login, registration, and invitations
- Implement CSRF protection with SameSite cookies and security headers
- Configure secure session cookies with httpOnly and secure flags
- Enhance input sanitization for XSS and injection prevention
- Add comprehensive security tests (41 tests passing)
- Document security enhancements in SECURITY_ENHANCEMENTS.md

Requirements: 9.3, 9.4, 9.5
2025-12-02 01:29:35 +00:00

103 lines
2.9 KiB
TypeScript

import NextAuth from "next-auth"
import Credentials from "next-auth/providers/credentials"
import { prisma } from "@/lib/db"
import bcrypt from "bcryptjs"
import { z } from "zod"
// Validation schemas
const loginSchema = z.object({
email: z.string().email(),
password: z.string().min(1),
})
export const { handlers, signIn, signOut, auth } = NextAuth({
session: {
strategy: "jwt",
maxAge: 30 * 24 * 60 * 60, // 30 days in seconds
updateAge: 24 * 60 * 60, // Update session every 24 hours
},
cookies: {
sessionToken: {
name: `${process.env.NODE_ENV === 'production' ? '__Secure-' : ''}next-auth.session-token`,
options: {
httpOnly: true, // Prevent JavaScript access to cookies (XSS protection)
sameSite: 'lax', // CSRF protection - prevents cookie from being sent in cross-site requests
path: '/',
secure: process.env.NODE_ENV === 'production', // Only send cookie over HTTPS in production
},
},
},
providers: [
Credentials({
name: "credentials",
credentials: {
email: { label: "Email", type: "email" },
password: { label: "Password", type: "password" },
},
async authorize(credentials) {
try {
// Validate credentials format
const { email, password } = loginSchema.parse(credentials)
// Query user from database
const user = await prisma.user.findUnique({
where: { email },
})
// Check if user exists
if (!user || !user.passwordHash) {
return null
}
// Verify password with bcrypt
const isPasswordValid = await bcrypt.compare(password, user.passwordHash)
if (!isPasswordValid) {
return null
}
// Return user object (without password hash)
return {
id: user.id,
email: user.email,
name: user.name,
}
} catch (error) {
console.error("Authorization error:", error)
return null
}
},
}),
],
callbacks: {
async jwt({ token, user, trigger }) {
// Add user ID to token on sign in
if (user) {
token.id = user.id
}
// Handle session expiration
// Token will be automatically invalidated by NextAuth when it expires
// based on the maxAge setting in session config
return token
},
async session({ session, token }) {
// Add user ID to session from token
if (session.user && token.id) {
session.user.id = token.id as string
}
// Session validation happens automatically via JWT expiration
// If token is expired, this callback won't be called and user will be redirected
return session
},
},
pages: {
signIn: "/auth/login",
signOut: "/auth/logout",
error: "/auth/error",
},
})