Skip to content

Commit b792ea2

Browse files
fix(mosaic): preserve field and global reverification errors
1 parent edb9bab commit b792ea2

14 files changed

Lines changed: 402 additions & 105 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: 26 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -31,32 +31,32 @@ A flow lives in `src/features/<feature>/`. The **model** (`*.model.ts(x)`) is th
3131

3232
Most problems a feature hits already have a shared answer. Find the row for your problem and use it. Do not write a local version, even a small one.
3333

34-
| Problem | Use |
35-
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
36-
| An async action from a button or row: pending, an error, one lock | `usePendingAction` (`src/hooks/`) |
37-
| A form: values, validation, submit, field errors | `useForm` (`src/components/form/`), with `validateAsync` for a server-side check |
38-
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
39-
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |
40-
| A confirm step before an action | `useConfirmController` (`src/blocks/confirm/`) with `Confirmation` (`src/blocks/confirmation/`) |
41-
| A delete that needs the user to type a phrase | `useConfirmController` (`src/blocks/confirm/`) with `Destructive` (`src/blocks/destructive/`) |
42-
| An action that may need step-up verification | `useReverificationFlow` (`src/features/reverification/`) in the model, passed to `useConfirmController` |
43-
| A direct action that needs step-up verification | `useReverificationFlow` in the model, with `ReverificationDialog` (`src/blocks/reverification/`) in the view |
44-
| Showing any error to the user | One of the owners above. They call `toLocalizableError` and resolve copy with `useErrorText` |
45-
| Moving focus after a list row is removed | `useListRemovalFocus` (`src/hooks/`) |
46-
| A debounced, abortable async check as the user types | `useDebouncedAsync` (`src/hooks/`) |
47-
| A spinner that should not flash or flicker | `useSpinDelay` (`src/hooks/`) |
48-
| A placeholder for content that is still loading | `Skeleton` (`src/components/skeleton/`), see [Skeletons](docs/skeletons.md) |
49-
| A date shown to the user | `formatDate` (`src/utils/format-date.ts`) |
50-
| A value turned into kebab case, e.g. for a `data-*` attribute | `kebabCase` (`src/utils/kebab-case.ts`) |
51-
| Current time for display labels | `useNow` (`src/hooks/`) |
52-
| Whether enterprise SSO permits adding another identification | `allowsIdentificationCreation` (`src/utils/allows-identification-creation.ts`) |
53-
| An inline message row; height is undefined until measured | `useHeldMessage`, `useMessageHeight`, `FeedbackBody` (`src/utils/feedback.tsx`) + `src/styles/feedback.styles.ts` |
54-
| Data read from a Clerk resource that should be cached across mounts | A query hook in `src/queries/`, called from the model (`src/queries/use-user-sessions-query.ts`) |
55-
| An item changed in place in an infinite list, kept until the next reload | `replaceInPages` (`src/utils/infinite-pages.ts`), passed to the list's `setData` |
56-
| Siblings that slide when an item is added or removed | `useLayoutAnimation` (`src/primitives/hooks/`) |
57-
| An input that reformats as the user types without moving the caret | `useFormattedInput` (`src/primitives/hooks/`) |
58-
| An interaction with an async lifecycle or two values that move together | A machine in the controller file, via `setup()` (`src/machine/`) |
59-
| Styles several components share | `src/styles/*.styles.ts` |
34+
| Problem | Use |
35+
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------- |
36+
| An async action from a button or row: pending, an error, one lock | `usePendingAction` (`src/hooks/`) |
37+
| A form: values, validation, submit, field errors | `useForm` (`src/components/form/`), with `validateAsync` for a server-side check |
38+
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
39+
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |
40+
| A confirm step before an action | `useConfirmController` (`src/blocks/confirm/`) with `Confirmation` (`src/blocks/confirmation/`) |
41+
| A delete that needs the user to type a phrase | `useConfirmController` (`src/blocks/confirm/`) with `Destructive` (`src/blocks/destructive/`) |
42+
| An action that may need step-up verification | `useReverificationFlow` (`src/features/reverification/`) in the model, passed to `useConfirmController` |
43+
| A direct action that needs step-up verification | `useReverificationFlow` in the model, with `ReverificationDialog` (`src/blocks/reverification/`) in the view |
44+
| Showing any error to the user | One of the owners above. They call `toLocalizableError` (or `toLocalizableErrors` for all errors) and resolve copy with `useErrorText` |
45+
| Moving focus after a list row is removed | `useListRemovalFocus` (`src/hooks/`) |
46+
| A debounced, abortable async check as the user types | `useDebouncedAsync` (`src/hooks/`) |
47+
| A spinner that should not flash or flicker | `useSpinDelay` (`src/hooks/`) |
48+
| A placeholder for content that is still loading | `Skeleton` (`src/components/skeleton/`), see [Skeletons](docs/skeletons.md) |
49+
| A date shown to the user | `formatDate` (`src/utils/format-date.ts`) |
50+
| A value turned into kebab case, e.g. for a `data-*` attribute | `kebabCase` (`src/utils/kebab-case.ts`) |
51+
| Current time for display labels | `useNow` (`src/hooks/`) |
52+
| Whether enterprise SSO permits adding another identification | `allowsIdentificationCreation` (`src/utils/allows-identification-creation.ts`) |
53+
| An inline message row; height is undefined until measured | `useHeldMessage`, `useMessageHeight`, `FeedbackBody` (`src/utils/feedback.tsx`) + `src/styles/feedback.styles.ts` |
54+
| Data read from a Clerk resource that should be cached across mounts | A query hook in `src/queries/`, called from the model (`src/queries/use-user-sessions-query.ts`) |
55+
| An item changed in place in an infinite list, kept until the next reload | `replaceInPages` (`src/utils/infinite-pages.ts`), passed to the list's `setData` |
56+
| Siblings that slide when an item is added or removed | `useLayoutAnimation` (`src/primitives/hooks/`) |
57+
| An input that reformats as the user types without moving the caret | `useFormattedInput` (`src/primitives/hooks/`) |
58+
| An interaction with an async lifecycle or two values that move together | A machine in the controller file, via `setup()` (`src/machine/`) |
59+
| Styles several components share | `src/styles/*.styles.ts` |
6060

6161
## Signs you are about to invent a pattern
6262

‎packages/mosaic/docs/controllers.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -320,6 +320,11 @@ One path, so every error a user sees goes through the `errors.*` catalog:
320320
`toLocalizableError(cause)` from `utils/errors.ts`. Use one of them instead of
321321
catching in a feature. A controller with its own machine maps in the machine's
322322
`onError` (`user-profile-rename-passkey.controller.ts`).
323+
- **Machines that display all errors use `toLocalizableErrors(cause)`.** It
324+
preserves each error and its parameter name. Reverification stores this array,
325+
routes matching parameters to the active field and everything else to the
326+
global banner, then localizes each message at render. Single-error owners keep
327+
using `toLocalizableError`, including its global-first `SaveError` behavior.
323328
- **Forms map through `save`.** A model wraps a form's Clerk call in
324329
`save(run, fields, params)` from `utils/errors.ts`, which rethrows a Clerk
325330
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+
});

0 commit comments

Comments
 (0)