Skip to content
Merged
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
5 changes: 5 additions & 0 deletions .changeset/mfa-totp-verify-back-button.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/ui': patch
---

Add a "Back" action to the authenticator-app verification step in `<UserProfile />`, so a user who needs to re-scan can return to the QR code instead of cancelling the whole setup. Going back now reuses the TOTP secret already issued rather than generating a new one, keeping any code the user has already scanned valid.
17 changes: 14 additions & 3 deletions packages/ui/src/components/UserProfile/AddAuthenticatorApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,18 @@ import { useActionContext } from '../../elements/Action/ActionRoot';

type AddAuthenticatorAppProps = FormProps & {
title: LocalizationKey;
pendingTotpRef: React.MutableRefObject<TOTPResource | undefined>;
};

type DisplayFormat = 'qr' | 'uri';

export const AddAuthenticatorApp = withCardStateProvider((props: AddAuthenticatorAppProps) => {
const { title, onSuccess, onReset } = props;
const { title, onSuccess, onReset, pendingTotpRef } = props;
const { user } = useUser();
const card = useCardState();
const createTOTP = useReverification(() => user?.createTOTP());
const { close } = useActionContext();
const [totp, setTOTP] = React.useState<TOTPResource | undefined>(undefined);
const [totp, setTOTP] = React.useState<TOTPResource | undefined>(pendingTotpRef.current);
const [displayFormat, setDisplayFormat] = React.useState<DisplayFormat>('qr');

// TODO: React18
Expand All @@ -38,8 +39,18 @@ export const AddAuthenticatorApp = withCardStateProvider((props: AddAuthenticato
return;
}

// Each createTOTP() mints a new secret server-side, so reuse the one already
// issued this session — otherwise navigating back here invalidates the QR the
// user has scanned.
if (pendingTotpRef.current) {
return;
}

void createTOTP()
.then(totp => setTOTP(totp))
.then(totp => {
pendingTotpRef.current = totp;
setTOTP(totp);
})
.catch(err => {
if (isClerkRuntimeError(err) && err.code === 'reverification_cancelled') {
return close();
Expand Down
9 changes: 6 additions & 3 deletions packages/ui/src/components/UserProfile/MfaTOTPScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,20 +15,23 @@ type MfaTOTPFormProps = FormProps;
export const MfaTOTPScreen = withCardStateProvider((props: MfaTOTPFormProps) => {
const { onReset } = props;
const wizard = useWizard();
const ref = React.useRef<TOTPResource>();
const pendingTotpRef = React.useRef<TOTPResource>();
const verifiedTotpRef = React.useRef<TOTPResource>();

return (
<Wizard {...wizard.props}>
<AddAuthenticatorApp
title={localizationKeys('userProfile.mfaTOTPPage.title')}
onSuccess={wizard.nextStep}
onReset={onReset}
pendingTotpRef={pendingTotpRef}
/>

<VerifyTOTP
onSuccess={wizard.nextStep}
onReset={onReset}
resourceRef={ref}
onBack={wizard.prevStep}
verifiedTotpRef={verifiedTotpRef}
/>

<SuccessPage
Expand All @@ -38,7 +41,7 @@ export const MfaTOTPScreen = withCardStateProvider((props: MfaTOTPFormProps) =>
contents={
<MfaBackupCodeList
subtitle={localizationKeys('userProfile.backupCodePage.successSubtitle')}
backupCodes={ref.current?.backupCodes}
backupCodes={verifiedTotpRef.current?.backupCodes}
/>
}
/>
Expand Down
15 changes: 12 additions & 3 deletions packages/ui/src/components/UserProfile/VerifyTOTP.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,12 @@ import { FormContainer } from '@/ui/elements/FormContainer';
import { Button, Col, descriptors, localizationKeys } from '../../customizables';

type VerifyTOTPProps = FormProps & {
resourceRef: React.MutableRefObject<TOTPResource | undefined>;
verifiedTotpRef: React.MutableRefObject<TOTPResource | undefined>;
onBack: () => void;
};

export const VerifyTOTP = withCardStateProvider((props: VerifyTOTPProps) => {
const { onSuccess, onReset, resourceRef } = props;
const { onSuccess, onReset, onBack, verifiedTotpRef } = props;
const { user } = useUser();

const otp = useFieldOTP<TOTPResource>({
Expand All @@ -27,7 +28,7 @@ export const VerifyTOTP = withCardStateProvider((props: VerifyTOTPProps) => {
.catch(reject);
},
onResolve: a => {
resourceRef.current = a;
verifiedTotpRef.current = a;
onSuccess();
},
});
Expand All @@ -50,6 +51,14 @@ export const VerifyTOTP = withCardStateProvider((props: VerifyTOTPProps) => {
localizationKey={localizationKeys('userProfile.formButtonReset')}
elementDescriptor={descriptors.formButtonReset}
/>

<Button
onClick={onBack}
variant='ghost'
isDisabled={otp.isLoading}
localizationKey={localizationKeys('backButton')}
elementDescriptor={descriptors.backLink}
/>
</FormButtonContainer>
</FormContainer>
);
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
import type { TOTPResource } from '@clerk/shared/types';
import { act } from '@testing-library/react';
import { afterEach, describe, expect, it, vi } from 'vitest';

import { bindCreateFixtures } from '@/test/create-fixtures';
import { render } from '@/test/utils';
import { ActionRoot } from '@/ui/elements/Action/ActionRoot';

import { MfaTOTPScreen } from '../MfaTOTPScreen';

const { createFixtures } = bindCreateFixtures('UserProfile');

const totp = {
uri: 'otpauth://totp/Test:test@clerk.com?secret=TESTSECRET&issuer=Test',
secret: 'TESTSECRET',
} as TOTPResource;

describe('MfaTOTPScreen', () => {
afterEach(() => {
vi.clearAllMocks();
});

it('keeps the same TOTP secret when navigating back from the verification step', async () => {
const { wrapper, fixtures } = await createFixtures(f => {
f.withAuthenticatorApp();
f.withUser({ two_factor_enabled: true });
});

fixtures.clerk.user?.createTOTP.mockResolvedValue(totp);

const { findByText, findByRole, getByRole, userEvent } = render(
<ActionRoot>
<MfaTOTPScreen
onSuccess={vi.fn()}
onReset={vi.fn()}
/>
</ActionRoot>,
{ wrapper },
);

await findByText(/scan the following QR code/i);
expect(fixtures.clerk.user?.createTOTP).toHaveBeenCalledTimes(1);

await act(async () => {
await userEvent.click(getByRole('button', { name: /continue/i }));
});

await act(async () => {
await userEvent.click(await findByRole('button', { name: /^back$/i }));
});

// Back returns to the QR step without minting a new secret, so the code the
// user already scanned stays valid.
await findByText(/scan the following QR code/i);
expect(fixtures.clerk.user?.createTOTP).toHaveBeenCalledTimes(1);
});
});
Loading