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
1 change: 1 addition & 0 deletions packages/experience/src/apis/experience/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ export * from './social';
export * from './one-time-token';
export * from './passkey-sign-in';
export * from './step-up';
export * from './subject-verification-code';

/**
* For sign-in flow user identity not found error handling use.
Expand Down
67 changes: 65 additions & 2 deletions packages/experience/src/apis/experience/mfa.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import {
InteractionEvent,
MfaFactor,
type SignInIdentifier,
SignInIdentifier,
type VerificationType,
type WebAuthnRegistrationOptions,
type WebAuthnAuthenticationOptions,
type BindMfaPayload,
Expand All @@ -11,15 +13,57 @@ import api from '../api';

import { experienceApiRoutes } from './const';
import { submitInteraction } from './interaction';
import { verifySubjectVerificationCode } from './subject-verification-code';

const addMfa = async (type: MfaFactor, verificationId: string) =>
export const addMfa = async (type: MfaFactor, verificationId: string) =>
api.post(`${experienceApiRoutes.mfa}`, {
json: {
type,
verificationId,
},
});

type SanitizedVerificationRecord = {
id?: unknown;
type?: unknown;
verified?: unknown;
};

type InteractionStateResponse = {
interactionEvent?: unknown;
verificationRecords?: unknown;
};

/**
* Return the verified email/phone verification record ID from the current `Register`
* interaction, if one exists, so enrolling that same identifier for MFA needs no second code.
*/
export const getVerifiedRegisterCodeRecordId = async (
verificationType: VerificationType.EmailVerificationCode | VerificationType.PhoneVerificationCode
): Promise<string | undefined> => {
const { interactionEvent, verificationRecords } = await api
.get(experienceApiRoutes.interaction)
.json<InteractionStateResponse>();

if (interactionEvent !== InteractionEvent.Register || !Array.isArray(verificationRecords)) {
return;
}

const matched = verificationRecords.find(
(record): record is SanitizedVerificationRecord =>
typeof record === 'object' &&
record !== null &&
'type' in record &&
record.type === verificationType &&
'verified' in record &&
record.verified === true &&
'id' in record &&
typeof record.id === 'string'
);

return typeof matched?.id === 'string' ? matched.id : undefined;
};

type TotpSecretResponse = {
verificationId: string;
secret: string;
Expand Down Expand Up @@ -162,3 +206,22 @@ export const verifyMfaByVerificationCode = async (
});
return submitInteraction();
};

export const bindMfaByVerificationCode = async (
verificationId: string,
code: string,
identifierType: SignInIdentifier.Email | SignInIdentifier.Phone
) => {
const { verificationId: verifiedId } = await verifySubjectVerificationCode({
type: identifierType,
code,
verificationId,
});

const factor =
identifierType === SignInIdentifier.Email
? MfaFactor.EmailVerificationCode
: MfaFactor.PhoneVerificationCode;

return bindMfa(factor, verifiedId);
};
Comment thread
wangsijie marked this conversation as resolved.
Resolved
32 changes: 8 additions & 24 deletions packages/experience/src/apis/experience/step-up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@ import {
interactionAuthenticationContextGuard,
} from '@logto/schemas';

import { type VerificationCodeIdentifier } from '@/types';

import api from '../api';

import { experienceApiRoutes, type VerificationResponse } from './const';
import { identifyAndSubmitInteraction } from './interaction';
import {
verifySubjectVerificationCode,
type SubjectVerificationCodePayload,
} from './subject-verification-code';

type StepUpInitResult = {
/**
Expand Down Expand Up @@ -60,12 +62,6 @@ export const getStepUpContext = async (): Promise<InteractionAuthenticationConte
* type is sent: Core resolves the value from the subject, and the raw identifier never reaches
* the browser.
*/
export const sendStepUpVerificationCode = async (type: VerificationCodeIdentifier) =>
api
.post(`${experienceApiRoutes.verification}/verification-code`, {
json: { interactionEvent: InteractionEvent.SignIn, identifier: { type } },
})
.json<VerificationResponse>();

/**
* Verify the pinned subject's password and complete the interaction.
Expand All @@ -82,27 +78,15 @@ export const verifyStepUpPassword = async (password: string) => {
return identifyAndSubmitInteraction({ verificationId });
};

type StepUpVerificationCodePayload = {
type: VerificationCodeIdentifier;
code: string;
verificationId: string;
};

/**
* Verify a code sent to the pinned subject's primary email or phone, and complete the
* interaction. As when sending it, only the identifier type travels; Core reads the value it
* challenged from the verification record.
*/
export const verifyStepUpVerificationCode = async ({
type,
code,
verificationId,
}: StepUpVerificationCodePayload) => {
const { verificationId: verifiedVerificationId } = await api
.post(`${experienceApiRoutes.verification}/verification-code/verify`, {
json: { identifier: { type }, code, verificationId },
})
.json<VerificationResponse>();
export const verifyStepUpVerificationCode = async (payload: SubjectVerificationCodePayload) => {
const { verificationId: verifiedVerificationId } = await verifySubjectVerificationCode(payload);

return identifyAndSubmitInteraction({ verificationId: verifiedVerificationId });
};

export { sendSubjectVerificationCode as sendStepUpVerificationCode } from './subject-verification-code';
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import { InteractionEvent } from '@logto/schemas';

import { type VerificationCodeIdentifier } from '@/types';

import api from '../api';

import { experienceApiRoutes, type VerificationResponse } from './const';

export type SubjectVerificationCodePayload = {
type: VerificationCodeIdentifier;
code: string;
verificationId: string;
};

/**
* Send a verification code to the subject's primary email or phone without transmitting the
* raw identifier from the browser.
*/
export const sendSubjectVerificationCode = async (type: VerificationCodeIdentifier) =>
api
.post(`${experienceApiRoutes.verification}/verification-code`, {
json: {
interactionEvent: InteractionEvent.SignIn,
identifier: { type },
},
})
.json<VerificationResponse>();

/**
* Verify a subject-bound primary verification code and return the verified `verificationId`.
*/
export const verifySubjectVerificationCode = async ({
type,
code,
verificationId,
}: SubjectVerificationCodePayload) =>
api
.post(`${experienceApiRoutes.verification}/verification-code/verify`, {
json: {
identifier: { type },
code,
verificationId,
},
})
.json<VerificationResponse>();
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,11 @@ const mockedUseResendMfaVerificationCode = jest.mocked(useResendMfaVerificationC

const renderVerification = () => {
const onSubmit = jest.fn().mockResolvedValue(undefined);
mockedUseMfaCodeVerification.mockReturnValue({ errorMessage: undefined, onSubmit });
mockedUseMfaCodeVerification.mockReturnValue({
errorMessage: undefined,
clearErrorMessage: jest.fn(),
onSubmit,
});
mockedUseResendMfaVerificationCode.mockReturnValue({
seconds: 30,
isRunning: true,
Expand Down
31 changes: 21 additions & 10 deletions packages/experience/src/containers/MfaCodeVerification/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import type { SignInIdentifier } from '@logto/schemas';
import { useCallback, useEffect, useState } from 'react';
import { Trans, useTranslation } from 'react-i18next';

import { type sendMfaVerificationCode, type verifyMfaByVerificationCode } from '@/apis/experience';
import TextLink from '@/components/TextLink';
import Button from '@/shared/components/Button';
import VerificationCodeInput from '@/shared/components/VerificationCode';
Expand All @@ -19,9 +20,11 @@ const isCodeReady = (code: string[]) => {
type Props = {
readonly identifierType: SignInIdentifier.Email | SignInIdentifier.Phone;
readonly verificationId: string;
readonly verifyCode?: typeof verifyMfaByVerificationCode;
readonly resendCode?: typeof sendMfaVerificationCode;
};

const MfaCodeVerification = ({ identifierType, verificationId }: Props) => {
const MfaCodeVerification = ({ identifierType, verificationId, verifyCode, resendCode }: Props) => {
const { t } = useTranslation();
const [codeInput, setCodeInput] = useState<string[]>([]);
const [inputErrorMessage, setInputErrorMessage] = useState<string>();
Expand All @@ -36,18 +39,20 @@ const MfaCodeVerification = ({ identifierType, verificationId }: Props) => {
setInputErrorMessage(undefined);
}, []);

const { errorMessage: submitErrorMessage, onSubmit } = useMfaCodeVerification(
identifierType,
currentVerificationId,
errorCallback
);
const {
errorMessage: submitErrorMessage,
clearErrorMessage,
onSubmit,
} = useMfaCodeVerification(identifierType, currentVerificationId, errorCallback, verifyCode);

const [isSubmitting, setIsSubmitting] = useState(false);

const errorMessage = inputErrorMessage ?? submitErrorMessage;

const { seconds, isRunning, onResendVerificationCode } =
useResendMfaVerificationCode(identifierType);
const { seconds, isRunning, onResendVerificationCode } = useResendMfaVerificationCode(
identifierType,
resendCode
);

const handleSubmit = useCallback(
async (code: string[]) => {
Expand All @@ -58,8 +63,11 @@ const MfaCodeVerification = ({ identifierType, verificationId }: Props) => {
setInputErrorMessage(undefined);
setIsSubmitting(true);

await onSubmit(code.join(''));
setIsSubmitting(false);
try {
await onSubmit(code.join(''));
} finally {
setIsSubmitting(false);
}
},
[onSubmit, isSubmitting]
);
Expand All @@ -72,6 +80,8 @@ const MfaCodeVerification = ({ identifierType, verificationId }: Props) => {
className={styles.codeInput}
error={errorMessage}
onChange={(code) => {
setInputErrorMessage(undefined);
clearErrorMessage?.();
setCodeInput(code);
if (isCodeReady(code)) {
void handleSubmit(code);
Expand All @@ -90,6 +100,7 @@ const MfaCodeVerification = ({ identifierType, verificationId }: Props) => {
<TextLink
className={styles.link}
onClick={async () => {
clearErrorMessage?.();
setInputErrorMessage(undefined);
setCodeInput([]);
const newId = await onResendVerificationCode();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,18 +10,28 @@ import useMfaSubmitErrorHandler from '@/hooks/use-mfa-submit-error-handler';

import useGeneralVerificationCodeErrorHandler from '../VerificationCode/use-general-verification-code-error-handler';

type UseMfaCodeVerificationResult = {
errorMessage?: string;
clearErrorMessage?: () => void;
onSubmit: (code: string) => Promise<void>;
};

const useMfaCodeVerification = (
identifierType: SignInIdentifier.Email | SignInIdentifier.Phone,
verificationId: string,
errorCallback?: () => void
) => {
errorCallback?: () => void,
verifyCode: typeof verifyMfaByVerificationCode = verifyMfaByVerificationCode
): UseMfaCodeVerificationResult => {
const [errorMessage, setErrorMessage] = useState<string>();
const asyncVerify = useApi(verifyMfaByVerificationCode);
const asyncVerify = useApi(verifyCode);
const handleError = useErrorHandler();
const redirectTo = useGlobalRedirectTo();

const { generalVerificationCodeErrorHandlers, errorMessage: generalErrorMessage } =
useGeneralVerificationCodeErrorHandler();
const {
generalVerificationCodeErrorHandlers,
errorMessage: generalErrorMessage,
clearErrorMessage,
} = useGeneralVerificationCodeErrorHandler();

const submitInteractionErrorHandler = useMfaSubmitErrorHandler();

Expand Down Expand Up @@ -60,8 +70,14 @@ const useMfaCodeVerification = (
]
);

const clearAllErrorMessages = () => {
setErrorMessage(undefined);
clearErrorMessage();
};

return {
errorMessage: errorMessage ?? generalErrorMessage,
clearErrorMessage: clearAllErrorMessages,
onSubmit,
};
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,12 +20,13 @@ const getTimeout = () => {
};

const useResendMfaVerificationCode = (
identifierType: SignInIdentifier.Email | SignInIdentifier.Phone
identifierType: SignInIdentifier.Email | SignInIdentifier.Phone,
sendCode: typeof sendMfaVerificationCode = sendMfaVerificationCode
) => {
const { setToast } = useToast();
const handleError = useErrorHandler();
const stepUpErrorHandlers = usePureStepUpErrorHandler();
const resend = useApi(sendMfaVerificationCode);
const resend = useApi(sendCode);
const { setVerificationId } = useContext(UserInteractionContext);

const { seconds, isRunning, restart } = useTimer({
Expand Down
Loading
Loading