All files / src/lib/auth two-factor.ts

0% Statements 0/321
100% Branches 0/0
0% Functions 0/1
0% Lines 0/321

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 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
/**
 * Two-Factor Authentication Service
 *
 * Implements TOTP-based 2FA using the otplib library.
 * Provides setup, verification, and backup code management.
 */

import { authenticator } from 'otplib';
import QRCode from 'qrcode';
import crypto from 'crypto';
import { prisma } from '@/lib/prisma';

// ============================================================================
// Configuration
// ============================================================================

const ISSUER = process.env.NEXT_PUBLIC_APP_NAME || 'Elite Events';
const ENCRYPTION_KEY = process.env.ENCRYPTION_KEY || process.env.NEXTAUTH_SECRET || '';
const BACKUP_CODE_COUNT = 10;

// Configure authenticator
authenticator.options = {
  window: 1, // Allow 1 step before/after for clock drift
};

// ============================================================================
// Encryption Helpers
// ============================================================================

function getEncryptionKey(): Buffer {
  // Use first 32 bytes of hashed secret as key
  return crypto.createHash('sha256').update(ENCRYPTION_KEY).digest();
}

/**
 * Encrypt a secret for storage
 */
function encryptSecret(secret: string): string {
  const key = getEncryptionKey();
  const iv = crypto.randomBytes(16);
  const cipher = crypto.createCipheriv('aes-256-gcm', key, iv);

  let encrypted = cipher.update(secret, 'utf8', 'hex');
  encrypted += cipher.final('hex');
  const authTag = cipher.getAuthTag();

  return `${iv.toString('hex')}:${authTag.toString('hex')}:${encrypted}`;
}

/**
 * Decrypt a stored secret
 */
function decryptSecret(encryptedSecret: string): string {
  const parts = encryptedSecret.split(':');
  if (parts.length !== 3) {
    throw new Error('Invalid encrypted secret format');
  }

  const [ivHex, authTagHex, encrypted] = parts;
  const key = getEncryptionKey();
  const iv = Buffer.from(ivHex, 'hex');
  const authTag = Buffer.from(authTagHex, 'hex');

  const decipher = crypto.createDecipheriv('aes-256-gcm', key, iv);
  decipher.setAuthTag(authTag);

  let decrypted = decipher.update(encrypted, 'hex', 'utf8');
  decrypted += decipher.final('utf8');

  return decrypted;
}

// ============================================================================
// Two-Factor Setup
// ============================================================================

/**
 * Generate a new 2FA secret for a user
 */
export async function generateTwoFactorSecret(userId: number): Promise<string> {
  const secret = authenticator.generateSecret();

  // Store encrypted secret (not yet enabled)
  const encryptedSecret = encryptSecret(secret);

  await prisma.user.update({
    where: { id: userId },
    data: {
      twoFactorSecret: encryptedSecret,
      twoFactorEnabled: false,
    },
  });

  return secret;
}

/**
 * Get QR code for authenticator app setup
 */
export async function getTwoFactorQRCode(
  email: string,
  secret: string
): Promise<string> {
  const otpauth = authenticator.keyuri(email, ISSUER, secret);
  return QRCode.toDataURL(otpauth);
}

/**
 * Get the manual entry code for authenticator apps
 */
export function getManualEntryCode(secret: string): string {
  // Format secret in groups of 4 for easier manual entry
  return secret.match(/.{1,4}/g)?.join(' ') || secret;
}

// ============================================================================
// Verification
// ============================================================================

/**
 * Verify a TOTP token
 */
export async function verifyTwoFactorToken(
  userId: number,
  token: string
): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { twoFactorSecret: true, twoFactorEnabled: true },
  });

  if (!user?.twoFactorSecret) {
    return false;
  }

  try {
    const secret = decryptSecret(user.twoFactorSecret);
    return authenticator.verify({ token, secret });
  } catch {
    return false;
  }
}

/**
 * Enable 2FA after verifying initial token
 */
export async function enableTwoFactor(
  userId: number,
  token: string
): Promise<{ success: boolean; backupCodes?: string[] }> {
  const isValid = await verifyTwoFactorToken(userId, token);

  if (!isValid) {
    return { success: false };
  }

  // Generate backup codes
  const backupCodes = generateBackupCodes(BACKUP_CODE_COUNT);
  const hashedCodes = backupCodes.map((code) =>
    crypto.createHash('sha256').update(code).digest('hex')
  );

  await prisma.user.update({
    where: { id: userId },
    data: {
      twoFactorEnabled: true,
      twoFactorBackupCodes: hashedCodes,
    },
  });

  return { success: true, backupCodes };
}

/**
 * Disable 2FA for a user
 */
export async function disableTwoFactor(userId: number): Promise<void> {
  await prisma.user.update({
    where: { id: userId },
    data: {
      twoFactorEnabled: false,
      twoFactorSecret: null,
      twoFactorBackupCodes: [],
    },
  });
}

// ============================================================================
// Backup Codes
// ============================================================================

/**
 * Generate random backup codes
 */
function generateBackupCodes(count: number = BACKUP_CODE_COUNT): string[] {
  return Array.from({ length: count }, () =>
    crypto.randomBytes(4).toString('hex').toUpperCase()
  );
}

/**
 * Verify and consume a backup code
 */
export async function verifyBackupCode(
  userId: number,
  code: string
): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { twoFactorBackupCodes: true },
  });

  if (!user?.twoFactorBackupCodes || !Array.isArray(user.twoFactorBackupCodes)) {
    return false;
  }

  const hashedCode = crypto.createHash('sha256').update(code.toUpperCase()).digest('hex');
  const codeIndex = (user.twoFactorBackupCodes as string[]).indexOf(hashedCode);

  if (codeIndex === -1) {
    return false;
  }

  // Remove used backup code
  const updatedCodes = [...(user.twoFactorBackupCodes as string[])];
  updatedCodes.splice(codeIndex, 1);

  await prisma.user.update({
    where: { id: userId },
    data: { twoFactorBackupCodes: updatedCodes },
  });

  return true;
}

/**
 * Get the count of remaining backup codes
 */
export async function getRemainingBackupCodeCount(userId: number): Promise<number> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { twoFactorBackupCodes: true },
  });

  if (!user?.twoFactorBackupCodes || !Array.isArray(user.twoFactorBackupCodes)) {
    return 0;
  }

  return user.twoFactorBackupCodes.length;
}

/**
 * Regenerate backup codes (invalidates all existing codes)
 */
export async function regenerateBackupCodes(userId: number): Promise<string[]> {
  const backupCodes = generateBackupCodes(BACKUP_CODE_COUNT);
  const hashedCodes = backupCodes.map((code) =>
    crypto.createHash('sha256').update(code).digest('hex')
  );

  await prisma.user.update({
    where: { id: userId },
    data: { twoFactorBackupCodes: hashedCodes },
  });

  return backupCodes;
}

// ============================================================================
// Status Helpers
// ============================================================================

/**
 * Check if 2FA is enabled for a user
 */
export async function isTwoFactorEnabled(userId: number): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { twoFactorEnabled: true },
  });

  return user?.twoFactorEnabled || false;
}

/**
 * Check if user has 2FA setup in progress (secret generated but not enabled)
 */
export async function hasPendingTwoFactorSetup(userId: number): Promise<boolean> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: { twoFactorSecret: true, twoFactorEnabled: true },
  });

  return !!user?.twoFactorSecret && !user?.twoFactorEnabled;
}

/**
 * Get 2FA status for a user
 */
export async function getTwoFactorStatus(userId: number): Promise<{
  enabled: boolean;
  pendingSetup: boolean;
  backupCodesRemaining: number;
}> {
  const user = await prisma.user.findUnique({
    where: { id: userId },
    select: {
      twoFactorEnabled: true,
      twoFactorSecret: true,
      twoFactorBackupCodes: true,
    },
  });

  return {
    enabled: user?.twoFactorEnabled || false,
    pendingSetup: !!user?.twoFactorSecret && !user?.twoFactorEnabled,
    backupCodesRemaining: Array.isArray(user?.twoFactorBackupCodes)
      ? user.twoFactorBackupCodes.length
      : 0,
  };
}