Security Improvements: - Auto-generate AUTH_SECRET and admin credentials on first launch - Cryptographically secure random generation - Stored in database for persistence - Logged once to container logs for admin retrieval - Implement CSRF protection with double-submit cookie pattern - Three-way validation: cookie, header, and session database - Automatic client-side injection via plugin - Server middleware for automatic validation - Zero frontend code changes required - Add session fixation prevention with automatic invalidation - Regenerate sessions on password changes - Keep current session active, invalidate others on profile password change - Invalidate ALL sessions on forgot-password reset - Invalidate ALL sessions on admin password reset - Upgrade password reset codes to 8-char alphanumeric - Increased from 1M to 1.8 trillion combinations - Uses crypto.randomInt() for cryptographic randomness - Excluded confusing characters (I, O) for better UX - Case-insensitive verification - Implement dual-layer account lockout - IP-based rate limiting (existing) - Per-account lockout: 10 attempts = 30 min lock - Automatic unlock after expiration - Admin manual unlock via UI - Visual status indicators in users table Database Changes: - Add csrf_token column to sessions table - Add failed_login_attempts and locked_until columns to users table - Add settings table for persistent AUTH_SECRET storage - All migrations backward-compatible with try-catch New Files: - server/utils/csrf.ts - CSRF protection utilities - server/middleware/csrf.ts - Automatic CSRF validation middleware - plugins/csrf.client.ts - Automatic CSRF header injection - server/api/users/unlock/[id].post.ts - Admin unlock endpoint Modified Files: - server/utils/database.ts - Core security functions and schema updates - server/utils/email.ts - Enhanced reset code generation - server/api/auth/login.post.ts - CSRF + account lockout logic - server/api/auth/register.post.ts - CSRF token generation - server/api/auth/logout.post.ts - CSRF cookie cleanup - server/api/auth/reset-password.post.ts - Session invalidation - server/api/auth/verify-reset-code.post.ts - Case-insensitive codes - server/api/profile/update.put.ts - Session invalidation on password change - server/api/users/password/[id].put.ts - Session invalidation on admin reset - pages/users.vue - Lock status display and unlock functionality - docker-compose.yml - Removed default credentials - nuxt.config.ts - Support auto-generation All changes follow OWASP best practices and are production-ready. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com>
127 lines
3.8 KiB
TypeScript
127 lines
3.8 KiB
TypeScript
import { getUserByUsername, getUserByEmail, deleteOtherUserSessions } from '~/server/utils/database'
|
|
import { getAuthUser, getAuthCookie } from '~/server/utils/auth'
|
|
import bcrypt from 'bcrypt'
|
|
|
|
export default defineEventHandler(async (event) => {
|
|
const authUser = await getAuthUser(event)
|
|
|
|
if (!authUser) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
message: 'Unauthorized',
|
|
})
|
|
}
|
|
|
|
const body = await readBody(event)
|
|
const { firstName, lastName, email, currentPassword, newPassword, confirmPassword } = body
|
|
|
|
if (!firstName || !lastName || !email) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'First name, last name, and email are required',
|
|
})
|
|
}
|
|
|
|
// Validate email format
|
|
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/
|
|
if (!emailRegex.test(email)) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'Invalid email format',
|
|
})
|
|
}
|
|
|
|
const db = (await import('~/server/utils/database')).getDatabase()
|
|
|
|
// Get current user data
|
|
const currentUser = getUserByUsername(authUser.username)
|
|
if (!currentUser) {
|
|
throw createError({
|
|
statusCode: 404,
|
|
message: 'User not found',
|
|
})
|
|
}
|
|
|
|
// Check if email is already taken by another user
|
|
if (email.toLowerCase() !== currentUser.email?.toLowerCase()) {
|
|
const existingEmail = getUserByEmail(email)
|
|
if (existingEmail && existingEmail.id !== currentUser.id) {
|
|
throw createError({
|
|
statusCode: 409,
|
|
message: 'Email already exists',
|
|
})
|
|
}
|
|
}
|
|
|
|
// If changing password, validate it
|
|
if (newPassword) {
|
|
if (!currentPassword) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'Current password is required to change password',
|
|
})
|
|
}
|
|
|
|
// Verify current password
|
|
const isValidPassword = bcrypt.compareSync(currentPassword, currentUser.password)
|
|
if (!isValidPassword) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'Current password is incorrect',
|
|
})
|
|
}
|
|
|
|
if (newPassword !== confirmPassword) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'New passwords do not match',
|
|
})
|
|
}
|
|
|
|
// Validate new password requirements
|
|
if (newPassword.length < 8) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'Password must be at least 8 characters long',
|
|
})
|
|
}
|
|
|
|
const hasUpperCase = /[A-Z]/.test(newPassword)
|
|
const hasLowerCase = /[a-z]/.test(newPassword)
|
|
const hasNumberOrSymbol = /[0-9!@#$%^&*()_+\-=\[\]{};':"\\|,.<>\/?]/.test(newPassword)
|
|
|
|
if (!hasUpperCase || !hasLowerCase || !hasNumberOrSymbol) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
message: 'Password must contain uppercase, lowercase, and number/symbol',
|
|
})
|
|
}
|
|
|
|
// Update with new password
|
|
const saltRounds = 10
|
|
const hashedPassword = bcrypt.hashSync(newPassword, saltRounds)
|
|
db.prepare('UPDATE users SET first_name = ?, last_name = ?, email = ?, password = ? WHERE id = ?')
|
|
.run(firstName, lastName, email.toLowerCase(), hashedPassword, currentUser.id)
|
|
|
|
// SECURITY: Invalidate all other sessions when password changes
|
|
// This prevents session fixation and forces re-login on all other devices
|
|
const currentSessionToken = getAuthCookie(event)
|
|
if (currentSessionToken) {
|
|
// Keep current session active, but logout all other sessions
|
|
deleteOtherUserSessions(authUser.username, currentSessionToken)
|
|
}
|
|
|
|
return {
|
|
success: true,
|
|
message: 'Password updated successfully. Other sessions have been logged out for security.',
|
|
passwordChanged: true
|
|
}
|
|
} else {
|
|
// Update without changing password
|
|
db.prepare('UPDATE users SET first_name = ?, last_name = ?, email = ? WHERE id = ?')
|
|
.run(firstName, lastName, email.toLowerCase(), currentUser.id)
|
|
|
|
return { success: true, message: 'Profile updated successfully' }
|
|
}
|
|
})
|