* Begin enrollment. Requires the user's current password as step-up * auth so a stolen session cannot silently enrol a new device. The * generated secret is encrypted at rest in Valkey; the route forwards * the otpauth URI + plaintext recovery codes to the SPA for display. * * Calling
(userId: string, password: string)
| 56 | * Calling `setup` twice replaces the prior staged secret. |
| 57 | */ |
| 58 | async setup(userId: string, password: string): Promise<IMfaSetupResult> { |
| 59 | const user = await this.assertPasswordValid(userId, password); |
| 60 | |
| 61 | if (user.mfaEnabledAt !== null) { |
| 62 | throw ApiErrors.conflict( |
| 63 | "MFA is already enabled. Disable it before enrolling a new device." |
| 64 | ); |
| 65 | } |
| 66 | |
| 67 | const secret = new Secret({ size: 32 }); |
| 68 | const totp = buildTotp(secret.base32, user.email); |
| 69 | const recoveryCodes = generateRecoveryCodes(); |
| 70 | const recoveryCodeHashes = await Promise.all( |
| 71 | recoveryCodes.map((code) => passwordService.hash(code)) |
| 72 | ); |
| 73 | const cachePayload: IMfaSetupCachePayload = { |
| 74 | secretEncrypted: encryptString(secret.base32), |
| 75 | recoveryCodeHashes, |
| 76 | }; |
| 77 | |
| 78 | await cacheService.set(MFA_CACHE_KEYS.setup(userId), cachePayload, { |
| 79 | ttlSeconds: MFA_SETUP_TTL_SECONDS, |
| 80 | }); |
| 81 | |
| 82 | void auditLogService.record({ |
| 83 | userId, |
| 84 | action: AUDIT_ACTIONS.AUTH_MFA_SETUP_INITIATED, |
| 85 | }); |
| 86 | |
| 87 | logger.info("MFA setup initiated", { |
| 88 | event: "auth.mfa.setup_initiated", |
| 89 | userId, |
| 90 | }); |
| 91 | |
| 92 | return { |
| 93 | otpauthUri: totp.toString(), |
| 94 | secretBase32: secret.base32, |
| 95 | recoveryCodes, |
| 96 | }; |
| 97 | } |
| 98 | |
| 99 | /** |
| 100 | * Complete enrollment. Validates the first TOTP code against the |