All files / src/lib/auth account-lockout.ts

90.54% Statements 182/201
75% Branches 30/40
100% Functions 5/5
90.54% Lines 182/201

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 2021x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 9x 9x 9x 9x 9x 3x 3x 6x 6x 9x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 6x 6x 6x 6x 6x 6x 6x 2x 2x 4x 4x 6x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 1x 4x 4x 4x 4x 4x 5x 1x 1x 4x 4x 4x 5x 5x 5x 5x 5x 5x 5x 5x 4x 5x 1x 1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x             1x 4x 4x 4x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 3x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 2x 2x 2x 2x 2x 2x 2x 2x 4x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                       4x 4x 4x 4x 4x 4x 4x 4x  
import { prisma } from '@/lib/prisma';
import { logger } from '@/lib/logging';
import { sendAccountLockedEmail } from '@/lib/integrations';
import { logAccountLocked } from '@/lib/audit-logger';
 
/**
 * Account lockout configuration
 */
export const LOCKOUT_CONFIG = {
  maxFailedAttempts: 5,
  lockoutDurationMs: 15 * 60 * 1000, // 15 minutes
  resetAttemptsAfterMs: 60 * 60 * 1000, // 1 hour
} as const;
 
/**
 * Check if an account is currently locked
 */
export async function isAccountLocked(userId: number): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { lockedUntil: true }});
 
  if (!user?.lockedUntil) {
    return false;
  }
 
  // Check if lockout period has expired
  if (new Date() > user.lockedUntil) {
    // Unlock the account
    await prisma.user.update({
      where: { id: userId },
      data: {
        lockedUntil: null,
        failedLoginAttempts: 0}});
    return false;
  }
 
  return true;
}
 
/**
 * Get remaining lockout time in seconds
 */
export async function getRemainingLockoutTime(
  userId: number
): Promise<number | null> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { lockedUntil: true }});
 
  if (!user?.lockedUntil) {
    return null;
  }
 
  const remainingMs = user.lockedUntil.getTime() - Date.now();
  if (remainingMs <= 0) {
    return null;
  }
 
  return Math.ceil(remainingMs / 1000);
}
 
/**
 * Record a failed login attempt
 * Returns true if account is now locked
 */
export async function recordFailedLoginAttempt(
  userId: number,
  request?: Request
): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: {
      id: true,
      email: true,
      failedLoginAttempts: true,
      updatedAt: true}});
 
  if (!user) {
    return false;
  }
 
  // Check if we should reset the counter (if enough time has passed)
  const timeSinceLastAttempt = Date.now() - user.updatedAt.getTime();
  let newAttemptCount = user.failedLoginAttempts + 1;
 
  if (timeSinceLastAttempt > LOCKOUT_CONFIG.resetAttemptsAfterMs) {
    newAttemptCount = 1;
  }
 
  const shouldLock = newAttemptCount >= LOCKOUT_CONFIG.maxFailedAttempts;
  const lockedUntil = shouldLock
    ? new Date(Date.now() + LOCKOUT_CONFIG.lockoutDurationMs)
    : null;
 
  await prisma.user.update({
    where: { id: userId },
    data: {
      failedLoginAttempts: newAttemptCount,
      lockedUntil}});
 
  if (shouldLock) {
    logger.warn(`Account locked for user ${userId}`, {
      category: "AUTH",
      failedAttempts: newAttemptCount,
      lockedUntil});
 
    // Log the lockout event
    if (request) {
      await logAccountLocked(request, userId, newAttemptCount);
    }
 
    // Send notification email
    try {
      await sendAccountLockedEmail(user.email, lockedUntil!);
    } catch (error) {
      logger.error(
        "Failed to send account locked email",
        error instanceof Error ? error : new Error(String(error)),
        { category: "AUTH" }
      );
    }
  }
 
  return shouldLock;
}
 
/**
 * Reset failed login attempts on successful login
 */
export async function resetFailedLoginAttempts(userId: number): Promise<void> {
  await prisma.user.update({
    where: { id: userId },
    data: {
      failedLoginAttempts: 0,
      lockedUntil: null}});
}
 
/**
 * Handle login attempt - call this during authentication
 * Returns an object with the result
 */
export async function handleLoginAttempt(
  email: string,
  success: boolean,
  request?: Request
): Promise<{
  locked: boolean;
  remainingAttempts: number;
  lockedUntil: Date | null;
}> {
  const user = await prisma.user.findUnique({
    where: { email: email.toLowerCase() },
    select: {
      id: true,
      failedLoginAttempts: true,
      lockedUntil: true}});
 
  if (!user) {
    // User doesn't exist, return neutral response
    return {
      locked: false,
      remainingAttempts: LOCKOUT_CONFIG.maxFailedAttempts,
      lockedUntil: null};
  }
 
  // Check if already locked
  if (await isAccountLocked(user.id)) {
    return {
      locked: true,
      remainingAttempts: 0,
      lockedUntil: user.lockedUntil};
  }
 
  if (success) {
    // Reset on successful login
    await resetFailedLoginAttempts(user.id);
    return {
      locked: false,
      remainingAttempts: LOCKOUT_CONFIG.maxFailedAttempts,
      lockedUntil: null};
  }

  // Record failed attempt
  const nowLocked = await recordFailedLoginAttempt(user.id, request);

  // Get updated user data
  const updatedUser = await prisma.user.findUnique({
    where: { id: user.id },
    select: { failedLoginAttempts: true, lockedUntil: true }});

  const remainingAttempts = Math.max(
    0,
    LOCKOUT_CONFIG.maxFailedAttempts - (updatedUser?.failedLoginAttempts || 0)
  );
 
  return {
    locked: nowLocked,
    remainingAttempts,
    lockedUntil: updatedUser?.lockedUntil || null};
}