Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 20 additions & 0 deletions packages/core/src/libraries/mfa.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,26 @@ describe('getAllUserEnabledMfaVerifications', () => {
{ primaryPhone: '+123456789' }
)
).not.toContain(MfaFactor.PhoneVerificationCode);
// Staging the phone MFA slot makes a newly provided phone active in explicit mode.
expect(
getAllUserEnabledMfaVerifications(
mfaSettings,
{ ...user, primaryPhone: null },
{ primaryPhone: '+123456789' },
[MfaFactor.PhoneVerificationCode]
)
).toEqual([
MfaFactor.TOTP,
MfaFactor.PhoneVerificationCode,
MfaFactor.EmailVerificationCode,
MfaFactor.BackupCode,
]);
// Staging only an email/phone MFA slot without the corresponding primary identifier is ignored.
expect(
getAllUserEnabledMfaVerifications(mfaSettings, { ...user, primaryPhone: null }, undefined, [
MfaFactor.PhoneVerificationCode,
])
).not.toContain(MfaFactor.PhoneVerificationCode);
expect(
getAllUserEnabledMfaVerifications(
{ ...mfaSettings, verificationCodeEnrollment: MfaVerificationCodeEnrollment.Implicit },
Expand Down
6 changes: 4 additions & 2 deletions packages/core/src/libraries/mfa.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,12 +33,14 @@ const filterOutEmptyBackupCodes = (
* @param mfaSettings - MFA settings from sign-in experience
* @param user - User object with mfaVerifications and profile data
* @param currentProfile - Optional profile override (for current interaction contexts), in cases of MFA verification, this is not needed
* @param stagedMfaFactors - Optional MFA factors bound in the current interaction before submission
* @returns Array of all enabled MFA verifications
*/
export const getAllUserEnabledMfaVerifications = (
mfaSettings: Mfa,
user: Pick<User, 'mfaVerifications' | 'primaryEmail' | 'primaryPhone'>,
currentProfile?: MfaProfile
currentProfile?: MfaProfile,
stagedMfaFactors: readonly MfaFactor[] = []
): MfaFactor[] => {
const storedVerifications = filterOutEmptyBackupCodes(user.mfaVerifications)
.filter((verification) => mfaSettings.factors.includes(verification.type))
Expand Down Expand Up @@ -83,7 +85,7 @@ export const getAllUserEnabledMfaVerifications = (

return resolveUserMfaFactors({
mfaSettings,
storedFactors: storedVerifications,
storedFactors: [...storedVerifications, ...stagedMfaFactors],
hasPrimaryEmail: Boolean(currentProfile?.primaryEmail ?? user.primaryEmail),
hasPrimaryPhone: Boolean(currentProfile?.primaryPhone ?? user.primaryPhone),
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1624,7 +1624,8 @@ export default class ExperienceInteraction {
const mfaValidator = new MfaValidator(mfaSettings, user);
const hasEligibleVerification = mfaValidator.hasEligibleTrustedDeviceVerification(
this.verificationRecordsArray,
this.profile.data
this.profile.data,
this.mfa.stagedVerificationCodeFactors
);

const hasEligibleBinding = this.mfa.bindMfaFactorsArray.some(
Expand Down
56 changes: 54 additions & 2 deletions packages/core/src/routes/experience/classes/helpers.test.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,10 @@
import { InteractionEvent, MfaFactor, userMfaDataKey } from '@logto/schemas';
import { InteractionEvent, MfaFactor, userMfaDataKey, type User } from '@logto/schemas';

import { parseMfaPropertiesToUserConfig, sortMfaFactors } from './helpers.js';
import {
mergeUserMfaVerifications,
parseMfaPropertiesToUserConfig,
sortMfaFactors,
} from './helpers.js';

describe('sortMfaFactors', () => {
it('sorts factors by priority order', () => {
Expand Down Expand Up @@ -64,3 +68,51 @@ describe('parseMfaPropertiesToUserConfig', () => {
});
});
});

describe('mergeUserMfaVerifications', () => {
it('replaces existing backup code, email, and phone records while preserving others', () => {
const existingVerifications: User['mfaVerifications'] = [
{
id: 'totp-1',
type: MfaFactor.TOTP,
key: 'secret',
createdAt: '2025-01-01T00:00:00.000Z',
},
{
id: 'backup-1',
type: MfaFactor.BackupCode,
codes: [{ code: 'old' }],
createdAt: '2025-01-01T00:00:00.000Z',
},
{
id: 'email-1',
type: MfaFactor.EmailVerificationCode,
createdAt: '2025-01-01T00:00:00.000Z',
},
{
id: 'phone-1',
type: MfaFactor.PhoneVerificationCode,
createdAt: '2025-01-01T00:00:00.000Z',
},
];
const newVerifications: User['mfaVerifications'] = [
{
id: 'email-2',
type: MfaFactor.EmailVerificationCode,
createdAt: '2026-01-01T00:00:00.000Z',
},
{
id: 'backup-2',
type: MfaFactor.BackupCode,
codes: [{ code: 'new' }],
createdAt: '2026-01-01T00:00:00.000Z',
},
];

expect(mergeUserMfaVerifications(existingVerifications, newVerifications)).toEqual([
existingVerifications[0],
existingVerifications[3],
...newVerifications,
]);
});
});
21 changes: 16 additions & 5 deletions packages/core/src/routes/experience/classes/helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,17 +185,28 @@ export const identifyUserByVerificationRecord = async (
}
};

const singletonMfaFactors = new Set<MfaFactor>([
MfaFactor.BackupCode,
MfaFactor.EmailVerificationCode,
MfaFactor.PhoneVerificationCode,
]);

/**
* Should remove the old backup codes verification if the user is binding a new one
* Replace existing singleton MFA factor records (backup codes, email/phone verification codes)
* when binding a new verification of the same type.
*/
export const mergeUserMfaVerifications = (
userMfaVerifications: User['mfaVerifications'],
newMfaVerifications: User['mfaVerifications']
): User['mfaVerifications'] => {
if (newMfaVerifications.some((verification) => verification.type === MfaFactor.BackupCode)) {
const filteredMfaVerifications = userMfaVerifications.filter(({ type }) => {
return type !== MfaFactor.BackupCode;
});
const typesToReplace = new Set(
newMfaVerifications.map(({ type }) => type).filter((type) => singletonMfaFactors.has(type))
);

if (typesToReplace.size > 0) {
const filteredMfaVerifications = userMfaVerifications.filter(
({ type }) => !typesToReplace.has(type)
);
return [...filteredMfaVerifications, ...newMfaVerifications];
}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,4 +1,10 @@
import { MfaFactor, MfaPolicy, type User, VerificationType } from '@logto/schemas';
import {
MfaFactor,
MfaPolicy,
MfaVerificationCodeEnrollment,
type User,
VerificationType,
} from '@logto/schemas';

import { mockUserWithMfaVerifications } from '#src/__mocks__/user.js';

Expand Down Expand Up @@ -63,3 +69,42 @@ describe('MfaValidator enforced requirements', () => {
}
);
});

const mfaCodeRecord = (type: VerificationType, userId: string) =>
({
type,
userId,
isVerified: true,
isNewBindMfaVerification: false,
}) as unknown as VerificationRecord;

describe('MfaValidator.hasEligibleTrustedDeviceVerification', () => {
it('requires a stored or staged email/phone MFA factor in explicit enrollment mode', () => {
const settings = {
policy: MfaPolicy.Mandatory,
factors: [MfaFactor.EmailVerificationCode, MfaFactor.PhoneVerificationCode],
verificationCodeEnrollment: MfaVerificationCodeEnrollment.Explicit,
};
const user: User = {
...mockUserWithMfaVerifications,
primaryEmail: 'user@example.com',
primaryPhone: '16502530000',
mfaVerifications: [],
};
const validator = new MfaValidator(settings, user);
const emailRecord = mfaCodeRecord(VerificationType.MfaEmailVerificationCode, user.id);
const phoneRecord = mfaCodeRecord(VerificationType.MfaPhoneVerificationCode, user.id);

expect(validator.hasEligibleTrustedDeviceVerification([emailRecord])).toBe(false);
expect(
validator.hasEligibleTrustedDeviceVerification([emailRecord], undefined, [
MfaFactor.EmailVerificationCode,
])
).toBe(true);
expect(
validator.hasEligibleTrustedDeviceVerification([phoneRecord], undefined, [
MfaFactor.PhoneVerificationCode,
])
).toBe(true);
});
});
Original file line number Diff line number Diff line change
Expand Up @@ -147,21 +147,26 @@ export class MfaValidator {

hasEligibleTrustedDeviceVerification(
verificationRecords: VerificationRecord[],
currentProfile?: InteractionProfile
currentProfile?: InteractionProfile,
stagedMfaFactors?: readonly MfaFactor[]
) {
return this.getVerifiedMfaVerificationRecords(verificationRecords, currentProfile).some(
({ type }) => type !== VerificationType.BackupCode
);
return this.getVerifiedMfaVerificationRecords(
verificationRecords,
currentProfile,
stagedMfaFactors
).some(({ type }) => type !== VerificationType.BackupCode);
}

private getVerifiedMfaVerificationRecords(
verificationRecords: VerificationRecord[],
currentProfile?: InteractionProfile
currentProfile?: InteractionProfile,
stagedMfaFactors?: readonly MfaFactor[]
) {
const userEnabledMfaVerifications = getAllUserEnabledMfaVerifications(
this.mfaSettings,
this.user,
currentProfile
currentProfile,
stagedMfaFactors
);

return verificationRecords.filter(
Expand Down
Loading
Loading