Skip to content

Commit 4fa1675

Browse files
fix(mosaic): preserve field and global reverification errors
1 parent aa9a6a3 commit 4fa1675

14 files changed

Lines changed: 377 additions & 80 deletions

‎.changeset/tidy-errors-reverify.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"@clerk/mosaic": patch
3+
---
4+
5+
Preserve all errors during UserProfile reverification. Show errors for the active password or code beside that field, and unrelated errors in a banner without marking the field invalid.

‎packages/mosaic/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,7 @@ Most problems a feature hits already have a shared answer. Find the row for your
4242
| A delete that needs the user to type a phrase | `useConfirmController` (`src/blocks/confirm/`) with `Destructive` (`src/blocks/destructive/`) |
4343
| An action that may need step-up verification | `useReverificationFlow` (`src/features/reverification/`) in the model, passed to `useConfirmController` |
4444
| A direct action that needs step-up verification | `useReverificationFlow` in the model, with `ReverificationDialog` (`src/blocks/reverification/`) in the view |
45-
| Showing any error to the user | One of the owners above. They call `toLocalizableError` and resolve copy with `useErrorText` |
45+
| Showing any error to the user | One of the owners above. They call `toLocalizableError` (or `toLocalizableErrors` for all errors) and resolve copy with `useErrorText` |
4646
| Moving focus after a list row is removed | `useListRemovalFocus` (`src/hooks/`) |
4747
| A debounced, abortable async check as the user types | `useDebouncedAsync` (`src/hooks/`) |
4848
| A spinner that should not flash or flicker | `useSpinDelay` (`src/hooks/`) |

‎packages/mosaic/docs/controllers.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -333,6 +333,11 @@ One path, so every error a user sees goes through the `errors.*` catalog:
333333
`toLocalizableError(cause)` from `utils/errors.ts`. Use one of them instead of
334334
catching in a feature. A controller with its own machine maps in the machine's
335335
`onError` (`user-profile-rename-passkey.controller.ts`).
336+
- **Machines that display all errors use `toLocalizableErrors(cause)`.** It
337+
preserves each error and its parameter name. Reverification stores this array,
338+
routes matching parameters to the active field and everything else to the
339+
global banner, then localizes each message at render. Single-error owners keep
340+
using `toLocalizableError`, including its global-first `SaveError` behavior.
336341
- **Forms map through `save`.** A model wraps a form's Clerk call in
337342
`save(run, fields, params)` from `utils/errors.ts`, which rethrows a Clerk
338343
error as a `SaveError` with each error routed to the field it names. The form
Lines changed: 166 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,166 @@
1+
import { reverificationError } from '@clerk/shared/authorization-errors';
2+
import { screen, waitFor } from '@testing-library/react';
3+
import userEvent from '@testing-library/user-event';
4+
import { http, HttpResponse } from 'msw';
5+
import { describe, expect, it, vi } from 'vitest';
6+
7+
import { fapiUrl, serveFapi, worker } from '../../../__tests__/feature/fake-fapi';
8+
import { fapiClient, fapiEnvironment, fapiSession, fapiUser } from '../../../__tests__/feature/fapi';
9+
import { renderWithClerk } from '../../../__tests__/feature/render';
10+
import { MosaicProvider } from '../../../mosaic-provider';
11+
import { Host } from './reverification-test-host';
12+
13+
const factors = [
14+
{
15+
strategy: 'password',
16+
label: 'Password',
17+
paramName: 'password',
18+
level: 'first_factor',
19+
endpoint: 'attempt_first_factor',
20+
},
21+
{
22+
strategy: 'backup_code',
23+
label: 'Backup code',
24+
paramName: 'code',
25+
level: 'second_factor',
26+
endpoint: 'attempt_second_factor',
27+
},
28+
] as const;
29+
30+
for (const factor of factors) {
31+
describe(`${factor.strategy} error routing`, () => {
32+
for (const kind of ['matching', 'unrelated', 'global', 'mixed'] as const) {
33+
it(`renders ${kind} errors in their proper places and clears them on edit`, async () => {
34+
serveFapi({
35+
client: fapiClient([fapiSession({ id: 'sess_1', user: fapiUser({ id: 'user_1' }) })]),
36+
verification: {
37+
firstFactors: [{ strategy: 'password' }],
38+
secondFactors: [{ strategy: 'backup_code' }],
39+
secrets: { password: 'correct', backup_code: 'correct' },
40+
},
41+
});
42+
const action = vi
43+
.fn()
44+
.mockResolvedValueOnce(reverificationError({ level: factor.level, afterMinutes: 10 }))
45+
.mockResolvedValue({ done: true });
46+
await renderWithClerk(
47+
<MosaicProvider
48+
localization={{ messages: { 'errors.form_param_nil__password': 'Localized password required.' } }}
49+
>
50+
<Host action={action} />
51+
</MosaicProvider>,
52+
);
53+
const fieldMessages =
54+
factor.strategy === 'password'
55+
? 'Localized password required. Another field error.'
56+
: 'Field error. Another field error.';
57+
const fieldErrors = [
58+
{
59+
code: factor.strategy === 'password' ? 'form_param_nil' : 'custom_field',
60+
message: 'Field error.',
61+
meta: { param_name: factor.paramName },
62+
},
63+
{ code: 'custom_field', message: 'Another field error.', meta: { param_name: factor.paramName } },
64+
];
65+
const globalErrors = [
66+
{ code: 'custom_global', message: 'Global error.' },
67+
{ code: 'custom_other', message: 'Unrelated error.', meta: { param_name: 'session_id' } },
68+
];
69+
const errors =
70+
kind === 'matching'
71+
? fieldErrors
72+
: kind === 'unrelated'
73+
? globalErrors.slice(1)
74+
: kind === 'global'
75+
? globalErrors.slice(0, 1)
76+
: [globalErrors[0], ...fieldErrors, globalErrors[1]];
77+
worker.use(
78+
http.post(
79+
fapiUrl(`/v1/client/sessions/sess_1/verify/${factor.endpoint}`),
80+
() => HttpResponse.json({ errors }, { status: 422 }),
81+
{ once: true },
82+
),
83+
);
84+
const user = userEvent.setup();
85+
await user.click(screen.getByRole('button', { name: 'Run action' }));
86+
const field = await screen.findByLabelText(factor.label);
87+
await user.type(field, 'wrong{Enter}');
88+
const hasField = kind === 'matching' || kind === 'mixed';
89+
if (hasField) {
90+
expect(await screen.findByText(fieldMessages)).toBeVisible();
91+
expect(field).toHaveAttribute('aria-invalid', 'true');
92+
expect(field).toHaveAccessibleDescription(fieldMessages);
93+
}
94+
if (kind !== 'matching') {
95+
const globalMessage =
96+
kind === 'mixed'
97+
? 'Global error. Unrelated error.'
98+
: kind === 'global'
99+
? 'Global error.'
100+
: 'Unrelated error.';
101+
await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(globalMessage));
102+
if (!hasField) {
103+
expect(field).not.toHaveAttribute('aria-invalid', 'true');
104+
}
105+
}
106+
await user.clear(field);
107+
await user.type(field, 'correct');
108+
await waitFor(() => expect(screen.queryByText(fieldMessages)).toBeNull());
109+
await waitFor(() => expect(screen.getByRole('alert')).not.toHaveTextContent(/Global error|Unrelated error/));
110+
expect(field).not.toHaveAttribute('aria-invalid', 'true');
111+
await user.type(field, '{Enter}');
112+
await waitFor(() => expect(screen.getByLabelText('Outcome')).toHaveTextContent('resolved'));
113+
expect(action).toHaveBeenCalledTimes(2);
114+
});
115+
}
116+
});
117+
}
118+
119+
it('clears mixed errors when switching factors and does not restore them on return', async () => {
120+
serveFapi({
121+
client: fapiClient([fapiSession({ id: 'sess_1', user: fapiUser({ id: 'user_1' }) })]),
122+
environment: fapiEnvironment({ display_config: { preferred_sign_in_strategy: 'password' } }),
123+
verification: {
124+
firstFactors: [
125+
{ strategy: 'password' },
126+
{ strategy: 'email_code', email_address_id: 'idn_email', safe_identifier: 'alice@example.com' },
127+
],
128+
secrets: { password: 'correct', email_code: '123456' },
129+
},
130+
});
131+
const action = vi.fn().mockResolvedValueOnce(reverificationError()).mockResolvedValue({ done: true });
132+
await renderWithClerk(<Host action={action} />);
133+
worker.use(
134+
http.post(
135+
fapiUrl('/v1/client/sessions/sess_1/verify/attempt_first_factor'),
136+
() =>
137+
HttpResponse.json(
138+
{
139+
errors: [
140+
{ code: 'custom_field', message: 'Field error.', meta: { param_name: 'password' } },
141+
{ code: 'custom_global', message: 'Global error.' },
142+
],
143+
},
144+
{ status: 422 },
145+
),
146+
{ once: true },
147+
),
148+
);
149+
const user = userEvent.setup();
150+
await user.click(screen.getByRole('button', { name: 'Run action' }));
151+
await user.type(await screen.findByLabelText('Password'), 'wrong{Enter}');
152+
expect(await screen.findByText('Field error.')).toBeVisible();
153+
expect(screen.getByRole('alert')).toHaveTextContent('Global error.');
154+
await user.click(screen.getByRole('button', { name: 'Use another method' }));
155+
await user.click(await screen.findByRole('button', { name: /Email code to/ }));
156+
expect(await screen.findByRole('group', { name: 'Verification code' })).toBeVisible();
157+
await waitFor(() => expect(screen.queryByText('Field error.')).toBeNull());
158+
await waitFor(() => expect(screen.queryByText('Global error.')).toBeNull());
159+
await user.click(screen.getByRole('button', { name: 'Use another method' }));
160+
await user.click(await screen.findByRole('button', { name: 'Continue with your password' }));
161+
const field = await screen.findByLabelText('Password');
162+
expect(field).toHaveValue('');
163+
expect(field).not.toHaveAttribute('aria-invalid', 'true');
164+
expect(screen.queryByText('Field error.')).toBeNull();
165+
expect(screen.queryByText('Global error.')).toBeNull();
166+
});
Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
import { useRef, useState } from 'react';
2+
3+
import { Card } from '../../../components/card';
4+
import { Reverification, useReverificationFlow } from '../reverification';
5+
6+
export function errorCode(error: unknown) {
7+
if (error instanceof Error) {
8+
return 'code' in error && typeof error.code === 'string' ? error.code : error.message;
9+
}
10+
return 'unknown';
11+
}
12+
13+
export function Host({ action, onOutcome }: { action: () => Promise<unknown>; onOutcome?: (outcome: string) => void }) {
14+
const [run, reverification] = useReverificationFlow(action);
15+
const [outcome, setOutcome] = useState('');
16+
const [running, setRunning] = useState(false);
17+
const inFlight = useRef(false);
18+
const report = (value: string) => {
19+
setOutcome(value);
20+
onOutcome?.(value);
21+
};
22+
23+
return (
24+
<>
25+
<button
26+
type='button'
27+
onClick={() => {
28+
const owner = !inFlight.current;
29+
if (owner) {
30+
inFlight.current = true;
31+
setRunning(true);
32+
}
33+
void run()
34+
.then(
35+
() => report('resolved'),
36+
(error: unknown) => report(`rejected: ${errorCode(error)}`),
37+
)
38+
.finally(() => {
39+
if (owner) {
40+
inFlight.current = false;
41+
setRunning(false);
42+
}
43+
});
44+
}}
45+
>
46+
Run action
47+
</button>
48+
<output aria-label='Outcome'>{outcome}</output>
49+
{running ? (
50+
<Card.Root renderBranding={false}>
51+
<Reverification controller={reverification} />
52+
{reverification.onCancel ? (
53+
<button
54+
type='button'
55+
onClick={reverification.onCancel}
56+
>
57+
Dismiss
58+
</button>
59+
) : null}
60+
</Card.Root>
61+
) : null}
62+
</>
63+
);
64+
}

‎packages/mosaic/src/features/reverification/__tests__/reverification.feature.test.tsx‎

Lines changed: 25 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,7 @@ import type {
99
import { act, screen, waitFor, within } from '@testing-library/react';
1010
import userEvent from '@testing-library/user-event';
1111
import { http, HttpResponse } from 'msw';
12-
import { useRef, useState } from 'react';
12+
import { useState } from 'react';
1313
import { describe, expect, it, vi } from 'vitest';
1414

1515
import { deferred } from '../../../__tests__/async';
@@ -21,6 +21,7 @@ import { Card } from '../../../components/card';
2121
import type { MosaicLocalization } from '../../../localization';
2222
import { MosaicProvider } from '../../../mosaic-provider';
2323
import { Reverification, useReverificationFlow } from '../reverification';
24+
import { errorCode, Host } from './reverification-test-host';
2425

2526
const alice = fapiUser({
2627
id: 'user_1',
@@ -111,66 +112,6 @@ function guardedAction(config?: ReverificationConfig) {
111112
return vi.fn().mockResolvedValueOnce(reverificationError(config)).mockResolvedValue({ done: true });
112113
}
113114

114-
function errorCode(error: unknown) {
115-
if (error instanceof Error) {
116-
return 'code' in error && typeof error.code === 'string' ? error.code : error.message;
117-
}
118-
return 'unknown';
119-
}
120-
121-
function Host({ action, onOutcome }: { action: () => Promise<unknown>; onOutcome?: (outcome: string) => void }) {
122-
const [run, reverification] = useReverificationFlow(action);
123-
const [outcome, setOutcome] = useState('');
124-
const [running, setRunning] = useState(false);
125-
const inFlight = useRef(false);
126-
const report = (value: string) => {
127-
setOutcome(value);
128-
onOutcome?.(value);
129-
};
130-
131-
return (
132-
<>
133-
<button
134-
type='button'
135-
onClick={() => {
136-
const owner = !inFlight.current;
137-
if (owner) {
138-
inFlight.current = true;
139-
setRunning(true);
140-
}
141-
void run()
142-
.then(
143-
() => report('resolved'),
144-
(error: unknown) => report(`rejected: ${errorCode(error)}`),
145-
)
146-
.finally(() => {
147-
if (owner) {
148-
inFlight.current = false;
149-
setRunning(false);
150-
}
151-
});
152-
}}
153-
>
154-
Run action
155-
</button>
156-
<output aria-label='Outcome'>{outcome}</output>
157-
{running ? (
158-
<Card.Root renderBranding={false}>
159-
<Reverification controller={reverification} />
160-
{reverification.onCancel ? (
161-
<button
162-
type='button'
163-
onClick={reverification.onCancel}
164-
>
165-
Dismiss
166-
</button>
167-
) : null}
168-
</Card.Root>
169-
) : null}
170-
</>
171-
);
172-
}
173-
174115
function HoldingHost({ action }: { action: () => Promise<unknown> }) {
175116
const [run, reverification] = useReverificationFlow(action);
176117
const [outcome, setOutcome] = useState('');
@@ -504,6 +445,21 @@ describe('Reverification', () => {
504445
});
505446

506447
describe('password', () => {
448+
it('shows unrelated attempt errors globally without marking the password invalid', async () => {
449+
await renderReverification(guardedAction(), verificationSeed({ firstFactors: [passwordFactor] }));
450+
const user = await startVerification();
451+
expect(await screen.findByText(STEP.password)).toBeVisible();
452+
const attempt = holdRequests('post', ATTEMPT_FIRST);
453+
454+
await user.type(passwordField(), `${PASSWORD}{Enter}`);
455+
await waitFor(() => expect(attempt.requests).toHaveLength(1));
456+
attempt.fail('unrelated_parameter', 'This session cannot be verified.', 'session_id');
457+
458+
expect(await screen.findByText('This session cannot be verified.')).toBeVisible();
459+
expect(passwordField()).not.toHaveAttribute('aria-invalid', 'true');
460+
expect(screen.getByRole('alert')).toHaveTextContent('This session cannot be verified.');
461+
});
462+
507463
it('recovers from a wrong password and completes the challenge', async () => {
508464
const { action } = await renderReverification(
509465
guardedAction(),
@@ -1770,7 +1726,10 @@ describe('Reverification', () => {
17701726

17711727
await user.type(await screen.findByLabelText('Password'), `${PASSWORD}{Enter}`);
17721728

1773-
await waitFor(() => expect(passwordField()).toBeInvalid());
1729+
await waitFor(() =>
1730+
expect(screen.getByRole('alert')).toHaveTextContent('Something went wrong. Please try again.'),
1731+
);
1732+
expect(passwordField()).not.toHaveAttribute('aria-invalid', 'true');
17741733
expect(screen.getByText('Something went wrong. Please try again.')).toBeInTheDocument();
17751734
expect(document.body).not.toHaveTextContent(/https?:\/\//);
17761735
} finally {
@@ -1788,7 +1747,10 @@ describe('Reverification', () => {
17881747

17891748
// The step stays open with an error
17901749
await user.type(await screen.findByLabelText('Password'), `${PASSWORD}{Enter}`);
1791-
await waitFor(() => expect(passwordField()).toBeInvalid());
1750+
await waitFor(() =>
1751+
expect(screen.getByRole('alert')).toHaveTextContent('Something went wrong. Please try again.'),
1752+
);
1753+
expect(passwordField()).not.toHaveAttribute('aria-invalid', 'true');
17921754
expect(screen.getByText(STEP.password)).toBeVisible();
17931755
expect(passwordField()).toBeEnabled();
17941756
expect(passwordField()).toHaveValue(PASSWORD);

0 commit comments

Comments
 (0)