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 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 | import { Injectable, Logger, BadRequestException, ForbiddenException, NotFoundException, } from '@nestjs/common'; import { InjectModel } from '@nestjs/mongoose'; import { Model } from 'mongoose'; import * as crypto from 'crypto'; import * as bcrypt from 'bcrypt'; import { MfaMethod, MfaChallenge, MfaRecoveryCode, MfaEnforcementPolicy, MfaAuditLog, } from '../schemas/mfa.schema'; import { EventBusService } from '../../events/event-bus.service'; /** * MFA Service — Multi-Factor Authentication management. * * Supports: * - TOTP (Time-Based One-Time Password) via RFC 6238 * - Email OTP (6-digit codes sent via notification service) * - Backup/Recovery codes (one-time use) * * Security: * - TOTP secrets are stored encrypted * - OTP codes are hashed (bcrypt) before storage * - Recovery codes are hashed, single-use, batched * - Challenge attempts are rate-limited * - All events are audit-logged */ @Injectable() export class MfaService { private readonly logger = new Logger(MfaService.name); private readonly TOTP_PERIOD = 30; // seconds private readonly TOTP_DIGITS = 6; private readonly OTP_LENGTH = 6; private readonly OTP_TTL_SECONDS = 300; // 5 minutes private readonly CHALLENGE_MAX_ATTEMPTS = 5; private readonly DEFAULT_BACKUP_CODE_COUNT = 10; constructor( @InjectModel(MfaMethod.name) private readonly methodModel: Model<MfaMethod>, @InjectModel(MfaChallenge.name) private readonly challengeModel: Model<MfaChallenge>, @InjectModel(MfaRecoveryCode.name) private readonly recoveryCodeModel: Model<MfaRecoveryCode>, @InjectModel(MfaEnforcementPolicy.name) private readonly policyModel: Model<MfaEnforcementPolicy>, @InjectModel(MfaAuditLog.name) private readonly auditModel: Model<MfaAuditLog>, private readonly eventBus: EventBusService, ) {} // ============================================================ // TOTP ENROLLMENT // ============================================================ /** * Generates a TOTP secret for the user and returns it as a provisioning URI. * The user must verify the TOTP before it is activated. */ async enrollTotp( userId: string, tenantId: string, userEmail: string, ): Promise<{ secret: string; otpauthUri: string; qrData: string; }> { // Check if user already has an active TOTP method const existing = await this.methodModel .findOne({ userId, tenantId, type: 'totp', isActive: true, isVerified: true, }) .exec(); if (existing) { throw new BadRequestException( 'TOTP is already enrolled for this account', ); } // Generate a 20-byte secret (160 bits, per RFC 4226 recommendation) const secretBuffer = crypto.randomBytes(20); const secret = this.base32Encode(secretBuffer); // Create or update the unverified TOTP method await this.methodModel .findOneAndUpdate( { userId, tenantId, type: 'totp' }, { userId, tenantId, type: 'totp', secret: this.encryptSecret(secret), label: 'Authenticator App', isVerified: false, isPrimary: false, isActive: true, enrolledAt: new Date(), }, { upsert: true, new: true }, ) .exec(); const issuer = 'Be-Vision'; const otpauthUri = `otpauth://totp/${issuer}:${encodeURIComponent(userEmail)}?secret=${secret}&issuer=${issuer}&algorithm=SHA1&digits=${this.TOTP_DIGITS}&period=${this.TOTP_PERIOD}`; await this.writeAuditLog(userId, tenantId, 'mfa_enrolled', 'totp'); return { secret, otpauthUri, qrData: otpauthUri, // Client renders QR from this URI }; } /** * Verifies the user's first TOTP code to confirm enrollment. */ async verifyTotpEnrollment( userId: string, tenantId: string, code: string, ): Promise<{ verified: boolean }> { const method = await this.methodModel .findOne({ userId, tenantId, type: 'totp', isActive: true, }) .exec(); if (!method) throw new NotFoundException('No TOTP enrollment found'); if (method.isVerified) throw new BadRequestException('TOTP is already verified'); const secret = this.decryptSecret(method.secret); const isValid = this.verifyTotpCode(secret, code); if (!isValid) { throw new BadRequestException('Invalid TOTP code. Please try again.'); } method.isVerified = true; method.isPrimary = true; method.lastUsedAt = new Date(); await method.save(); await this.writeAuditLog(userId, tenantId, 'mfa_verified', 'totp'); await this.eventBus.publish( 'platform.identity.mfa.enrolled.v1', { userId, tenantId, method: 'totp', }, tenantId, ); return { verified: true }; } // ============================================================ // EMAIL OTP // ============================================================ /** * Enrolls email OTP as an MFA method. */ async enrollEmailOtp( userId: string, tenantId: string, ): Promise<{ enrolled: boolean }> { await this.methodModel .findOneAndUpdate( { userId, tenantId, type: 'email_otp' }, { userId, tenantId, type: 'email_otp', label: 'Email OTP', isVerified: true, // Email is already verified at registration isPrimary: false, isActive: true, enrolledAt: new Date(), }, { upsert: true, new: true }, ) .exec(); await this.writeAuditLog(userId, tenantId, 'mfa_enrolled', 'email_otp'); return { enrolled: true }; } // ============================================================ // CHALLENGE CREATION & VERIFICATION // ============================================================ /** * Creates an MFA challenge for the user (called after primary auth succeeds). * Returns a challengeId that the client uses to submit the code. */ async createChallenge( userId: string, tenantId: string, method: 'totp' | 'email_otp' | 'backup_code', context?: { ipAddress?: string; userAgent?: string }, ): Promise<{ challengeId: string; method: string; expiresAt: Date }> { const enrolledMethod = await this.methodModel .findOne({ userId, tenantId, type: method === 'backup_code' ? 'backup_codes' : method, isActive: true, isVerified: true, }) .exec(); if (!enrolledMethod && method !== 'backup_code') { throw new BadRequestException(`MFA method '${method}' is not enrolled`); } const challengeId = crypto.randomUUID(); const expiresAt = new Date(Date.now() + this.OTP_TTL_SECONDS * 1000); const challengeData: any = { userId, tenantId, challengeId, method, expiresAt, isCompleted: false, attempts: 0, maxAttempts: this.CHALLENGE_MAX_ATTEMPTS, ipAddress: context?.ipAddress, userAgent: context?.userAgent, }; // For email OTP, generate and store a hashed OTP code if (method === 'email_otp') { const otp = this.generateNumericOtp(this.OTP_LENGTH); challengeData.otpCode = await bcrypt.hash(otp, 10); // Dispatch OTP via notification system (the actual email sending // is delegated to the notification queue) await this.eventBus.publish( 'platform.identity.mfa.otp.requested.v1', { userId, tenantId, otp, method: 'email_otp', }, tenantId, ); } await this.challengeModel.create(challengeData); await this.writeAuditLog(userId, tenantId, 'mfa_challenge_created', method); return { challengeId, method, expiresAt }; } /** * Verifies the MFA challenge with the provided code. */ async verifyChallenge( userId: string, tenantId: string, challengeId: string, code: string, context?: { ipAddress?: string; userAgent?: string }, ): Promise<{ verified: boolean; token?: string }> { const challenge = await this.challengeModel .findOne({ userId, tenantId, challengeId, isCompleted: false, }) .exec(); if (!challenge) { throw new NotFoundException( 'MFA challenge not found or already completed', ); } // Check expiration if (challenge.expiresAt < new Date()) { throw new BadRequestException('MFA challenge has expired'); } // Check attempt limit if (challenge.attempts >= challenge.maxAttempts) { await this.writeAuditLog( userId, tenantId, 'mfa_challenge_failed', challenge.method, { reason: 'max_attempts_exceeded', challengeId, }, ); throw new ForbiddenException( 'Too many failed attempts. Please request a new challenge.', ); } challenge.attempts += 1; let isValid = false; switch (challenge.method) { case 'totp': isValid = await this.verifyTotpChallenge(userId, tenantId, code); break; case 'email_otp': isValid = await bcrypt.compare(code, challenge.otpCode || ''); break; case 'backup_code': isValid = await this.verifyBackupCode(userId, tenantId, code, context); break; default: throw new BadRequestException( `Unsupported MFA method: ${challenge.method}`, ); } if (!isValid) { await challenge.save(); await this.writeAuditLog( userId, tenantId, 'mfa_challenge_failed', challenge.method, { challengeId, attempts: challenge.attempts, }, ); throw new BadRequestException('Invalid MFA code'); } challenge.isCompleted = true; challenge.completedAt = new Date(); await challenge.save(); // Update method's last used timestamp if (challenge.method !== 'backup_code') { await this.methodModel .findOneAndUpdate( { userId, tenantId, type: challenge.method, isActive: true }, { lastUsedAt: new Date() }, ) .exec(); } await this.writeAuditLog( userId, tenantId, 'mfa_challenge_passed', challenge.method, { challengeId }, ); await this.eventBus.publish( 'platform.identity.mfa.verified.v1', { userId, tenantId, method: challenge.method, challengeId, }, tenantId, ); // Generate a short-lived MFA verification token that the auth flow can exchange for a JWT const mfaToken = crypto.randomBytes(32).toString('hex'); return { verified: true, token: mfaToken }; } // ============================================================ // BACKUP / RECOVERY CODES // ============================================================ /** * Generates a new set of recovery codes for the user. * Previous unused codes are invalidated. */ async generateRecoveryCodes( userId: string, tenantId: string, ): Promise<{ codes: string[] }> { const policy = await this.getPolicy(tenantId); const count = policy?.backupCodeCount || this.DEFAULT_BACKUP_CODE_COUNT; const batchId = crypto.randomUUID(); // Invalidate previous unused codes await this.recoveryCodeModel .updateMany( { userId, tenantId, isUsed: false }, { isUsed: true, usedAt: new Date() }, ) .exec(); // Generate new codes const codes: string[] = []; const docs: any[] = []; for (let i = 0; i < count; i++) { const code = this.generateRecoveryCode(); codes.push(code); docs.push({ userId, tenantId, codeHash: await bcrypt.hash(code, 10), isUsed: false, batchId, }); } await this.recoveryCodeModel.insertMany(docs); // Ensure backup_codes method is enrolled await this.methodModel .findOneAndUpdate( { userId, tenantId, type: 'backup_codes' }, { userId, tenantId, type: 'backup_codes', label: 'Recovery Codes', isVerified: true, isActive: true, enrolledAt: new Date(), }, { upsert: true, new: true }, ) .exec(); await this.writeAuditLog( userId, tenantId, 'backup_codes_generated', 'backup_codes', { count, batchId }, ); return { codes }; } /** * Gets the count of remaining (unused) recovery codes. */ async getRemainingRecoveryCodeCount( userId: string, tenantId: string, ): Promise<number> { return this.recoveryCodeModel .countDocuments({ userId, tenantId, isUsed: false }) .exec(); } // ============================================================ // MFA STATUS & MANAGEMENT // ============================================================ /** * Gets the user's enrolled MFA methods. */ async getEnrolledMethods(userId: string, tenantId: string): Promise<any[]> { const methods = await this.methodModel .find({ userId, tenantId, isActive: true, isVerified: true, }) .lean() .exec(); return methods.map((m) => ({ id: (m as any)._id.toString(), type: m.type, label: m.label, isPrimary: m.isPrimary, lastUsedAt: m.lastUsedAt, enrolledAt: m.enrolledAt, })); } /** * Checks if a user has MFA enabled (at least one verified method). */ async isMfaEnabled(userId: string, tenantId: string): Promise<boolean> { const count = await this.methodModel .countDocuments({ userId, tenantId, isActive: true, isVerified: true, type: { $in: ['totp', 'email_otp'] }, }) .exec(); return count > 0; } /** * Checks if MFA is required for the user based on tenant policy. */ async isMfaRequired(tenantId: string, userRoles: string[]): Promise<boolean> { const policy = await this.getPolicy(tenantId); if (!policy || !policy.isEnabled) return false; if (policy.isEnforcedForAll) return true; return policy.enforcedRoles.some((r) => userRoles.includes(r)); } /** * Disables a specific MFA method for the user. */ async disableMethod( userId: string, tenantId: string, methodType: string, ): Promise<void> { const method = await this.methodModel .findOne({ userId, tenantId, type: methodType, isActive: true, }) .exec(); if (!method) throw new NotFoundException(`MFA method '${methodType}' not found`); method.isActive = false; await method.save(); await this.writeAuditLog( userId, tenantId, 'mfa_method_removed', methodType, ); await this.eventBus.publish( 'platform.identity.mfa.disabled.v1', { userId, tenantId, method: methodType, }, tenantId, ); } // ============================================================ // POLICY MANAGEMENT // ============================================================ /** * Gets or creates the MFA enforcement policy for a tenant. */ async getPolicy(tenantId: string): Promise<MfaEnforcementPolicy> { let policy = await this.policyModel.findOne({ tenantId }).exec(); if (!policy) { policy = await this.policyModel.create({ tenantId }); } return policy; } /** * Updates the MFA enforcement policy for a tenant. */ async updatePolicy( tenantId: string, updates: Partial<MfaEnforcementPolicy>, updatedBy: string, ): Promise<MfaEnforcementPolicy> { const policy = await this.getPolicy(tenantId); if (updates.isEnabled !== undefined) policy.isEnabled = updates.isEnabled; if (updates.isEnforcedForAll !== undefined) policy.isEnforcedForAll = updates.isEnforcedForAll; if (updates.enforcedRoles) policy.enforcedRoles = updates.enforcedRoles; if (updates.allowedMethods) policy.allowedMethods = updates.allowedMethods; if (updates.gracePeriodDays !== undefined) policy.gracePeriodDays = updates.gracePeriodDays; if (updates.backupCodeCount !== undefined) policy.backupCodeCount = updates.backupCodeCount; policy.updatedBy = updatedBy; if (updates.isEnabled && !policy.enforcedAt) { policy.enforcedAt = new Date(); } await policy.save(); await this.writeAuditLog( updatedBy, tenantId, 'mfa_policy_updated', null, updates, ); return policy; } // ============================================================ // PRIVATE HELPERS // ============================================================ /** * Verifies a TOTP code against the user's secret. */ private async verifyTotpChallenge( userId: string, tenantId: string, code: string, ): Promise<boolean> { const method = await this.methodModel .findOne({ userId, tenantId, type: 'totp', isActive: true, isVerified: true, }) .exec(); if (!method) return false; const secret = this.decryptSecret(method.secret); return this.verifyTotpCode(secret, code); } /** * RFC 6238 TOTP verification with ±1 window for clock skew. */ private verifyTotpCode(secret: string, code: string): boolean { const now = Math.floor(Date.now() / 1000); // Check current, previous, and next time steps for (const offset of [-1, 0, 1]) { const timeStep = Math.floor( (now + offset * this.TOTP_PERIOD) / this.TOTP_PERIOD, ); const generated = this.generateHotp(secret, timeStep); if (generated === code) return true; } return false; } /** * Generates an HOTP code per RFC 4226. */ private generateHotp(secret: string, counter: number): string { const secretBuffer = this.base32Decode(secret); const counterBuffer = Buffer.alloc(8); counterBuffer.writeBigInt64BE(BigInt(counter)); const hmac = crypto.createHmac('sha1', secretBuffer); hmac.update(counterBuffer); const hmacResult = hmac.digest(); const offset = hmacResult[hmacResult.length - 1] & 0x0f; const code = ((hmacResult[offset] & 0x7f) << 24) | ((hmacResult[offset + 1] & 0xff) << 16) | ((hmacResult[offset + 2] & 0xff) << 8) | (hmacResult[offset + 3] & 0xff); return (code % Math.pow(10, this.TOTP_DIGITS)) .toString() .padStart(this.TOTP_DIGITS, '0'); } /** * Verifies a backup code and marks it as used. */ private async verifyBackupCode( userId: string, tenantId: string, code: string, context?: { ipAddress?: string }, ): Promise<boolean> { const unusedCodes = await this.recoveryCodeModel .find({ userId, tenantId, isUsed: false, }) .exec(); for (const doc of unusedCodes) { const matches = await bcrypt.compare(code, doc.codeHash); if (matches) { doc.isUsed = true; doc.usedAt = new Date(); doc.usedIpAddress = context?.ipAddress ?? ''; await doc.save(); await this.writeAuditLog( userId, tenantId, 'backup_code_used', 'backup_code', ); return true; } } return false; } /** * Generates a numeric OTP of specified length. */ private generateNumericOtp(length: number): string { const digits = '0123456789'; const buffer = crypto.randomBytes(length); return Array.from(buffer) .map((b) => digits[b % 10]) .join(''); } /** * Generates a human-readable recovery code (e.g., "ABCD-1234-EFGH"). */ private generateRecoveryCode(): string { const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789'; // No confusable chars const segments = 3; const segmentLength = 4; const parts: string[] = []; for (let s = 0; s < segments; s++) { const bytes = crypto.randomBytes(segmentLength); let segment = ''; for (let i = 0; i < segmentLength; i++) { segment += chars[bytes[i] % chars.length]; } parts.push(segment); } return parts.join('-'); } /** * Base32 encode (RFC 4648). */ private base32Encode(buffer: Buffer): string { const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; let bits = ''; for (const byte of buffer) { bits += byte.toString(2).padStart(8, '0'); } let result = ''; for (let i = 0; i < bits.length; i += 5) { const chunk = bits.substring(i, i + 5).padEnd(5, '0'); result += alphabet[parseInt(chunk, 2)]; } return result; } /** * Base32 decode (RFC 4648). */ private base32Decode(encoded: string): Buffer { const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'; let bits = ''; for (const char of encoded.toUpperCase()) { const index = alphabet.indexOf(char); if (index === -1) continue; bits += index.toString(2).padStart(5, '0'); } const bytes: number[] = []; for (let i = 0; i + 8 <= bits.length; i += 8) { bytes.push(parseInt(bits.substring(i, i + 8), 2)); } return Buffer.from(bytes); } /** * Encrypts a TOTP secret for storage. * Uses AES-256-GCM with a key derived from the MFA_ENCRYPTION_KEY env var. */ private encryptSecret(plaintext: string): string { const key = this.getEncryptionKey(); const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-gcm', key, iv); let encrypted = cipher.update(plaintext, 'utf8', 'hex'); encrypted += cipher.final('hex'); const authTag = cipher.getAuthTag().toString('hex'); return `${iv.toString('hex')}:${authTag}:${encrypted}`; } /** * Decrypts a stored TOTP secret. */ private decryptSecret(ciphertext: string): string { const key = this.getEncryptionKey(); const parts = ciphertext.split(':'); if (parts.length !== 3) { throw new Error('Invalid encrypted secret format'); } const [ivHex, authTagHex, encrypted] = parts; 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; } /** * Derives the 32-byte encryption key from the MFA_ENCRYPTION_KEY env var. */ private getEncryptionKey(): Buffer { const envKey = process.env.MFA_ENCRYPTION_KEY || process.env.JWT_SECRET || 'default-mfa-key-change-in-production'; return crypto.createHash('sha256').update(envKey).digest(); } /** * Writes an MFA audit log entry. */ private async writeAuditLog( userId: string, tenantId: string, event: string, method: string | null, metadata: Record<string, any> = {}, ): Promise<void> { try { await this.auditModel.create({ userId, tenantId, event, method, metadata, }); } catch (err) { this.logger.error(`Failed to write MFA audit log: ${err.message}`); } } } |