Skip to content
Closed
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
2 changes: 2 additions & 0 deletions .changeset/mosaic-reverification-passkey-cancel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
Original file line number Diff line number Diff line change
Expand Up @@ -842,7 +842,6 @@ describe('Reverification', () => {
});

describe('passkey', () => {
// Currently wrong: the banner shows the browser or clerk-js error message as is, which is not localized.
it('completes the challenge with the passkey', async () => {
const { clerk } = await renderReverification(
guardedAction(),
Expand All @@ -853,7 +852,9 @@ describe('Reverification', () => {
.fn()
.mockResolvedValueOnce({
publicKeyCredential: null,
error: new ClerkWebAuthnError('The operation was refused', { code: 'passkey_retrieval_failed' }),
error: new ClerkWebAuthnError('The operation either timed out or was not allowed.', {
code: 'passkey_retrieval_cancelled',
}),
})
.mockImplementationOnce(
() =>
Expand All @@ -869,9 +870,12 @@ describe('Reverification', () => {
const user = await startVerification();
expect(await screen.findByText(STEP.passkey)).toBeVisible();

// A refused credential shows an error banner and stays on the step
// A cancelled prompt shows the localized error and stays on the step
await user.click(screen.getByRole('button', { name: 'Continue' }));
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('The operation was refused'));
await waitFor(() =>
expect(screen.getByRole('alert')).toHaveTextContent('Passkey verification was cancelled or timed out.'),
);
expect(screen.getByRole('alert')).not.toHaveTextContent('The operation either timed out or was not allowed.');
expect(screen.getByText(STEP.passkey)).toBeVisible();

// The button is disabled and shows the verifying label while the credential is being verified
Expand All @@ -888,6 +892,34 @@ describe('Reverification', () => {
}
});

it('explains when the device returns no passkey', async () => {
const { clerk } = await renderReverification(
guardedAction(),
verificationSeed({ firstFactors: [passwordFactor, passkeyFactor] }),
);
clerk.__internal_getPublicCredentials = vi.fn().mockResolvedValue({
publicKeyCredential: null,
error: new ClerkWebAuthnError('Browser failed to get credential', { code: 'passkey_retrieval_failed' }),
});
const restore = pretendToBeARealBrowser();

try {
const user = await startVerification();
expect(await screen.findByText(STEP.passkey)).toBeVisible();

await user.click(screen.getByRole('button', { name: 'Continue' }));

await waitFor(() =>
expect(screen.getByRole('alert')).toHaveTextContent(
"Your device couldn't verify your passkey. Please try again.",
),
);
expect(screen.getByText(STEP.passkey)).toBeVisible();
} finally {
restore();
}
});

it('offers the passkey from the picker when another method is showing', async () => {
await renderReverification(guardedAction(), verificationSeed({ firstFactors: [passwordFactor, passkeyFactor] }));
const restore = pretendToBeARealBrowser();
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { useEffect, useMemo, useState } from 'react';

import type { FlowDirection } from '../../components/flow';
import { useMessages } from '../../localization';
import type { ErrorDescription } from '../../localization';
import { useErrorText, useMessages } from '../../localization';
import { setup } from '../../machine/setup';
import type { DoneInvokeEvent, StateConfig } from '../../machine/types';
import { useMachine } from '../../machine/use-machine';
Expand All @@ -13,7 +14,7 @@ import type {
ReverificationStep,
ReverificationViewProps,
} from './reverification.types';
import { errorDetail, needsPrepare, otpChannelFor } from './reverification.utils';
import { errorDescription, needsPrepare, otpChannelFor, serverErrorDetail } from './reverification.utils';

type ReverificationControllerState =
| { status: 'idle'; onCancel?: undefined }
Expand All @@ -35,9 +36,7 @@ type OverlayFrom = 'factor' | 'method-picker';

export type ReverificationDeps = Pick<ReverificationActiveModel, 'start' | 'prepare' | 'attempt' | 'finish'>;

interface FactorError {
detail: string | undefined;
}
type FactorError = { serverDetail: string } | { description: ErrorDescription };

interface ReverificationContext {
inputValue: string;
Expand Down Expand Up @@ -88,7 +87,8 @@ function unlockResend(): Pick<ReverificationContext, 'resendAvailableAt'> {
}

function factorError(error: unknown): FactorError {
return { detail: errorDetail(error) };
const serverDetail = serverErrorDetail(error);
return serverDetail ? { serverDetail } : { description: errorDescription(error) };
}

function selectMethod(ctx: ReverificationContext, id: string): Partial<ReverificationContext> {
Expand Down Expand Up @@ -415,6 +415,7 @@ export function useReverificationController(model: ReverificationModel): Reverif

function useReverificationState(model: ReverificationModel): ReverificationControllerState {
const m = useMessages('reverification');
const errorText = useErrorText();
const active = model.status === 'active' ? model : null;

const [snapshot, send] = useMachine(
Expand Down Expand Up @@ -495,7 +496,11 @@ function useReverificationState(model: ReverificationModel): ReverificationContr
direction: context.direction,
value: context.inputValue,
onValueChange: (value: string) => send({ type: 'TYPE', value }),
errorMessage: context.error ? (context.error.detail ?? m.unstable__errors__generic) : undefined,
errorMessage: context.error
? 'serverDetail' in context.error
? context.error.serverDetail
: errorText(context.error.description, m.unstable__errors__generic)
: undefined,
isPending: pendingStates.has(state),
onSubmit: () => send({ type: 'SUBMIT' }),
onShowMethods: () => send({ type: 'SHOW_METHODS' }),
Expand Down Expand Up @@ -525,5 +530,5 @@ function useReverificationState(model: ReverificationModel): ReverificationContr
};

return state === 'retrying' ? { status: 'retrying', ...view } : { status: 'ready', onCancel, ...view };
}, [inactive, snapshot, onCancel, send, m, canResend, countingDown, resendAvailableAt, now]);
}, [inactive, snapshot, onCancel, send, m, errorText, canResend, countingDown, resendAvailableAt, now]);
}
Original file line number Diff line number Diff line change
@@ -1,23 +1,28 @@
import { isClerkAPIResponseError, isClerkRuntimeError } from '@clerk/shared/error';
import type { PreferredSignInStrategy } from '@clerk/shared/types';

import type { ErrorDescription } from '../../localization';
import { toLocalizableError } from '../../utils/errors';
import type {
ReverificationMethod,
ReverificationOtpChannel,
ReverificationPreparableMethod,
ReverificationStrategy,
} from './reverification.types';

// TODO: Return toLocalizableError(error) and render with errorText so Clerk errors are localized by code instead of shown raw.
export function errorDetail(error: unknown): string | undefined {
if (isClerkAPIResponseError(error)) {
const first = error.errors[0];
return first?.longMessage || first?.message || error.message;
}
export function errorDescription(error: unknown): ErrorDescription {
if (isClerkRuntimeError(error) && error.code !== 'network_error') {
return error.message;
return toLocalizableError(error);
}
return undefined;
return { cause: error };
}

export function serverErrorDetail(error: unknown): string | undefined {
if (!isClerkAPIResponseError(error)) {
return undefined;
}
const first = error.errors[0];
return first?.longMessage || first?.message || error.message;
}

export function otpChannelFor(strategy: ReverificationStrategy): ReverificationOtpChannel | undefined {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -368,6 +368,16 @@ describe('Adding a passkey', () => {
await user.click(screen.getByRole('button', { name: 'Add passkey' }));
expect(await screen.findByText('Chrome on macOS')).toBeVisible();
});
it('explains when the device returns no passkey', async () => {
servePasskeys([]);
fakeAuthenticator().mockResolvedValueOnce(null);
await renderWithClerk(<UserProfilePasskeysSection />);
await userEvent.setup().click(screen.getByRole('button', { name: 'Add passkey' }));
await waitFor(() =>
expect(screen.getByRole('alert')).toHaveTextContent("Your device couldn't create a passkey. Please try again."),
);
expect(screen.getByRole('button', { name: 'Add passkey' })).toBeEnabled();
});
});

describe('Renaming a passkey', () => {
Expand Down
2 changes: 2 additions & 0 deletions packages/mosaic/src/localization/errors.messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,9 @@ export const errorMessages: { readonly generic: string } & Readonly<Record<strin
passkey_not_supported: 'Passkeys are not supported on this device.',
passkey_pa_not_supported: 'Registration requires a platform authenticator but the device does not support it.',
passkey_registration_cancelled: 'Passkey registration was cancelled or timed out.',
passkey_registration_failed: "Your device couldn't create a passkey. Please try again.",
passkey_retrieval_cancelled: 'Passkey verification was cancelled or timed out.',
passkey_retrieval_failed: "Your device couldn't verify your passkey. Please try again.",
protect_check_execution_failed: "Verification didn't complete. Please try again.",
protect_check_invalid_script: "Couldn't load verification. Please contact support if this persists.",
protect_check_invalid_sdk_url: "Verification couldn't start. Please contact support.",
Expand Down
Loading