Skip to content

Commit 9c1c63c

Browse files
fix(mosaic): hold contact verify and MFA actions under one section lock
Sending a verification code for an email or phone now holds the section, so set-primary, Remove and Add wait until the code is sent. Changing the default SMS method, regenerating backup codes and removing an MFA method now exclude each other, and the method menus and Add are disabled while one runs. Adds waitFor to the machine runtime so a pending action can wait for a machine-driven step.
1 parent ee99bc2 commit 9c1c63c

18 files changed

Lines changed: 199 additions & 42 deletions

‎packages/mosaic/AGENTS.md‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,7 @@ Most problems a feature hits already have a shared answer. Find the row for your
3535
| ------------------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------- |
3636
| An async action from a button or row: pending, an error, one lock | `usePendingAction` (`src/hooks/`) |
3737
| Direct actions and confirmation dialogs that must exclude each other | `usePendingAction.guard` on the confirmation (`src/hooks/`, `src/blocks/confirm/`) |
38+
| A machine-driven step that a lock or caller must await | `waitFor` (`src/machine/wait-for.ts`), inside `usePendingAction.run` |
3839
| A form: values, validation, submit, field errors | `useForm` (`src/components/form/`), with `validateAsync` for a server-side check |
3940
| A `<form>` element, without the browser's validation popup | `Form` (`src/primitives/form/`) |
4041
| A model save whose Clerk errors should land on form fields | `save` (`src/utils/errors.ts`) in the model, or reject with `FormSubmitError` |

‎packages/mosaic/docs/controllers.md‎

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -85,9 +85,12 @@ so views render it without comparing pending keys.
8585

8686
`run` resolves `true` on success, so the caller can close a dialog or move
8787
focus. To hold pending through an OAuth redirect, await a delay inside the
88-
action (`user-profile-connected-accounts-section.controller.ts`). When the user
89-
cancels a reverification challenge, `run` resolves `false` without showing an
90-
error and releases the lock. It is not for:
88+
action (`user-profile-connected-accounts-section.controller.ts`). To hold it
89+
through a step a machine drives, run an action that awaits `waitFor`
90+
(`machine/wait-for.ts`) until the machine leaves that state
91+
(`user-profile-add-email.controller.ts`). When the user cancels a
92+
reverification challenge, `run` resolves `false` without showing an error and
93+
releases the lock. It is not for:
9194

9295
- a form → `useForm`
9396
- a confirm step → `useConfirmController` with `Confirmation` / `Destructive`

‎packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-add-email.controller.test.ts‎

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -200,7 +200,7 @@ describe('useUserProfileAddEmailController', () => {
200200
useUserProfileAddEmailController({ reverification: idleReverification, onCreate }),
201201
);
202202

203-
act(() => result.current.onVerifyEmail(other, email));
203+
act(() => void result.current.onVerifyEmail(other, email));
204204
expect(email.start).toHaveBeenCalledOnce();
205205
expect(result.current.open).toBe(false);
206206
expect(result.current.pendingVerifyId).toBe('email_2');
@@ -227,11 +227,11 @@ describe('useUserProfileAddEmailController', () => {
227227
);
228228
expect(result.current.verifyingId).toBeUndefined();
229229

230-
act(() => result.current.onVerifyEmail(other, email));
230+
act(() => void result.current.onVerifyEmail(other, email));
231231
expect(result.current.verifyingId).toBe('email_2');
232232
await waitFor(() => expect(result.current.step).toBe('verify'));
233233

234-
act(() => result.current.onVerifyEmail({ id: 'email_3', value: 'person@acme.co' }, email));
234+
act(() => void result.current.onVerifyEmail({ id: 'email_3', value: 'person@acme.co' }, email));
235235
expect(result.current.verifyingId).toBe('email_2');
236236
expect(result.current.emailAddress).toBe('other@example.com');
237237

@@ -253,7 +253,7 @@ describe('useUserProfileAddEmailController', () => {
253253
useUserProfileAddEmailController({ reverification: idleReverification, onCreate: created }),
254254
);
255255

256-
act(() => result.current.onVerifyEmail(other, email));
256+
act(() => void result.current.onVerifyEmail(other, email));
257257
await waitFor(() => expect(result.current.errorMessage).toBe('Too many requests'));
258258
expect(result.current.step).toBe('verify');
259259
expect(result.current.resendSeconds).toBe(0);
@@ -279,7 +279,7 @@ describe('useUserProfileAddEmailController', () => {
279279
const verified = createDeferredPromise();
280280
const { result } = renderHook(() => useUserProfileAddEmailController({ reverification: idleReverification }));
281281

282-
act(() => result.current.onVerifyEmail(other, verifier(sentLink(verified.promise.then(() => undefined)))));
282+
act(() => void result.current.onVerifyEmail(other, verifier(sentLink(verified.promise.then(() => undefined)))));
283283
expect(result.current.step).toBe('link');
284284
expect(result.current.resendSeconds).toBe(60);
285285

@@ -297,12 +297,12 @@ describe('useUserProfileAddEmailController', () => {
297297
useUserProfileAddEmailController({ reverification: idleReverification }),
298298
);
299299

300-
act(() => result.current.onVerifyEmail(other, email));
300+
act(() => void result.current.onVerifyEmail(other, email));
301301
await waitFor(() => expect(result.current.step).toBe('link'));
302302
act(() => result.current.onOpenChange(false));
303303
expect(cancel).toHaveBeenCalledOnce();
304304

305-
act(() => result.current.onVerifyEmail(other, email));
305+
act(() => void result.current.onVerifyEmail(other, email));
306306
await waitFor(() => expect(result.current.step).toBe('link'));
307307
unmount();
308308
expect(cancel).toHaveBeenCalledTimes(2);
@@ -312,7 +312,7 @@ describe('useUserProfileAddEmailController', () => {
312312
const email = verifier(sentLink(Promise.reject(saveError('Link expired'))));
313313
const { result } = renderHook(() => useUserProfileAddEmailController({ reverification: idleReverification }));
314314

315-
act(() => result.current.onVerifyEmail(other, email));
315+
act(() => void result.current.onVerifyEmail(other, email));
316316
await waitFor(() => expect(result.current.errorMessage).toBe('Link expired'));
317317
expect(result.current.step).toBe('link');
318318
expect(result.current.open).toBe(true);
@@ -323,7 +323,7 @@ describe('useUserProfileAddEmailController', () => {
323323
const email = verifier(() => ({ method: 'sso', connect }));
324324
const { result } = renderHook(() => useUserProfileAddEmailController({ reverification: idleReverification }));
325325

326-
act(() => result.current.onVerifyEmail({ id: 'email_3', value: 'person@acme.co' }, email));
326+
act(() => void result.current.onVerifyEmail({ id: 'email_3', value: 'person@acme.co' }, email));
327327
expect(result.current.step).toBe('sso');
328328
expect(result.current.resendSeconds).toBe(0);
329329

‎packages/mosaic/src/features/user-profile/user-profile-email-section/__tests__/user-profile-email-section.feature.test.tsx‎

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -156,12 +156,18 @@ describe('the user profile email section', () => {
156156
expect(screen.getByRole('menuitem', { name: 'Verify' })).toHaveAttribute('aria-busy', 'true');
157157
expect(await screen.findByRole('progressbar', { name: 'Verify' })).toBeVisible();
158158
expect(screen.queryByRole('dialog')).toBeNull();
159+
expect(screen.getByRole('button', { name: 'Manage alice@example.com' })).toHaveAttribute('aria-disabled', 'true');
160+
expect(screen.getByRole('button', { name: 'Add email' })).toBeDisabled();
159161
} finally {
160162
prepare.release();
161163
}
162164

163165
await enterCode(actor, VERIFICATION_CODE);
164166
expect(screen.queryByRole('menu')).toBeNull();
167+
expect(screen.getByRole('button', { name: 'Manage alice@example.com' })).not.toHaveAttribute(
168+
'aria-disabled',
169+
'true',
170+
);
165171
await waitFor(() => expect(screen.queryByRole('dialog')).not.toBeInTheDocument());
166172
});
167173

‎packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-add-email.controller.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ import { useErrorText } from '../../../localization';
77
import { setup } from '../../../machine/setup';
88
import type { ErrorInvokeEvent } from '../../../machine/types';
99
import { useMachine } from '../../../machine/use-machine';
10+
import { waitFor } from '../../../machine/wait-for';
1011
import type { FormError } from '../../../utils/errors';
1112
import { toFormError } from '../../../utils/errors';
1213
import type { ReverificationController } from '../../reverification';
@@ -30,7 +31,7 @@ export interface UserProfileAddEmailController extends UserProfileAddEmailDialog
3031
handle: DialogHandle<unknown>;
3132
verifyingId: string | undefined;
3233
pendingVerifyId: string | undefined;
33-
onVerifyEmail: (email: Pick<UserProfileEmail, 'id' | 'value'>, verifier: UserProfileEmailVerifier) => void;
34+
onVerifyEmail: (email: Pick<UserProfileEmail, 'id' | 'value'>, verifier: UserProfileEmailVerifier) => Promise<void>;
3435
}
3536

3637
interface Context {
@@ -268,9 +269,10 @@ export function useUserProfileAddEmailController({
268269
onConnect: () => send({ type: 'CONNECT' }),
269270
verifyingId: snapshot.context.verifyingId,
270271
pendingVerifyId: state === 'preparing' ? snapshot.context.verifyingId : undefined,
271-
onVerifyEmail: (email, verifier) => {
272+
onVerifyEmail: async (email, verifier) => {
272273
codeForm.reset();
273274
send({ type: 'START', id: email.id, emailAddress: email.value, verifier });
275+
await waitFor(actor, current => current.value !== 'preparing');
274276
},
275277
};
276278
}

‎packages/mosaic/src/features/user-profile/user-profile-email-section/user-profile-email-section.controller.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,7 +58,7 @@ export function useUserProfileEmailSectionController({
5858
onVerify: id => {
5959
const email = emails.find(email => email.id === id);
6060
if (email) {
61-
verification.onVerifyEmail(email, getEmailVerifier(id));
61+
void actions.run(id, () => verification.onVerifyEmail(email, getEmailVerifier(id)));
6262
}
6363
},
6464
onSetPrimary: id => void actions.run(id, () => onSetPrimaryEmail(id)),

‎packages/mosaic/src/features/user-profile/user-profile-mfa-section/__tests__/user-profile-mfa-management.feature.test.tsx‎

Lines changed: 62 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -367,6 +367,41 @@ describe('User profile MFA management', () => {
367367
}
368368
});
369369

370+
it('blocks backup-code regeneration while the default SMS method is changing', async () => {
371+
const first = fapiPhoneNumber({ ...phone, reserved_for_second_factor: true, default_second_factor: true });
372+
const second = fapiPhoneNumber({
373+
...phone,
374+
id: 'phone_2',
375+
phone_number: '+15555550202',
376+
reserved_for_second_factor: true,
377+
});
378+
const fapi = await renderMfa(
379+
fapiUser({ id: 'user_1', phone_numbers: [first, second], backup_code_enabled: true, two_factor_enabled: true }),
380+
);
381+
const held = holdRequests('post', '/v1/me/phone_numbers/phone_2');
382+
const user = userEvent.setup();
383+
try {
384+
await openMenu(user, screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0202' }));
385+
await user.click(screen.getByRole('menuitem', { name: 'Set as default' }));
386+
await waitFor(() => expect(held.requests).toHaveLength(1));
387+
await waitFor(() => expect(screen.queryByRole('menu')).toBeNull());
388+
const manage = screen.getByRole('button', { name: 'Manage Backup codes' });
389+
expect(manage).toHaveAttribute('aria-disabled', 'true');
390+
await user.click(manage);
391+
expect(screen.queryByRole('menu')).toBeNull();
392+
expect(fapi.mfa.backupCodeCreations).toBe(0);
393+
expect(screen.getByRole('button', { name: 'Add verification method' })).toBeDisabled();
394+
} finally {
395+
held.release();
396+
}
397+
const manage = screen.getByRole('button', { name: 'Manage Backup codes' });
398+
await waitFor(() => expect(manage).not.toHaveAttribute('aria-disabled', 'true'));
399+
await openMenu(user, manage);
400+
await user.click(screen.getByRole('menuitem', { name: 'Regenerate' }));
401+
await waitFor(() => expect(screen.getByText('CODE0100')).toBeVisible());
402+
expect(fapi.mfa.backupCodeCreations).toBe(1);
403+
});
404+
370405
it('returns failed regeneration to the section and retries from the menu', async () => {
371406
const fapi = await renderMfa(
372407
fapiUser({ id: 'user_1', totp_enabled: true, backup_code_enabled: true, two_factor_enabled: true }),
@@ -421,13 +456,18 @@ describe('User profile MFA management', () => {
421456
expect(screen.getByRole('menuitem', { name: 'Regenerate' })).toHaveAttribute('aria-busy', 'true');
422457
expect(await screen.findByRole('progressbar', { name: 'Regenerate' })).toBeVisible();
423458
expect(screen.queryByRole('dialog')).toBeNull();
459+
expect(screen.getByRole('button', { name: 'Manage Authenticator app' })).toHaveAttribute('aria-disabled', 'true');
424460
} finally {
425461
generate.release();
426462
}
427463

428464
const list = await screen.findByRole('list', { name: 'Backup codes' });
429465
expect(within(list).getAllByRole('listitem')).toHaveLength(10);
430466
await waitFor(() => expect(screen.queryByRole('menu')).toBeNull());
467+
expect(screen.getByRole('button', { name: 'Manage Authenticator app', hidden: true })).not.toHaveAttribute(
468+
'aria-disabled',
469+
'true',
470+
);
431471
});
432472

433473
it('holds the Regenerate menu item until session verification opens', async () => {
@@ -865,6 +905,12 @@ describe('User profile MFA management', () => {
865905
expect(screen.getAllByText('SMS verification')[0]?.closest('li')).toHaveTextContent('+1 (555) 555-0202'),
866906
);
867907
expect(screen.getAllByText('SMS verification')[0]?.closest('li')).toHaveTextContent('Default');
908+
await waitFor(() =>
909+
expect(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' })).not.toHaveAttribute(
910+
'aria-disabled',
911+
'true',
912+
),
913+
);
868914
await user.click(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' }));
869915
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Set as default' })).toBeVisible());
870916
});
@@ -908,6 +954,12 @@ describe('User profile MFA management', () => {
908954
expect(fapi.mfa.phoneUpdates).toContainEqual({ id: 'phone_2', default: true, reserved: undefined }),
909955
);
910956
expect(attempts).toBe(2);
957+
await waitFor(() =>
958+
expect(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' })).not.toHaveAttribute(
959+
'aria-disabled',
960+
'true',
961+
),
962+
);
911963
await user.click(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' }));
912964
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Set as default' })).toBeVisible());
913965
});
@@ -916,7 +968,7 @@ describe('User profile MFA management', () => {
916968
{ phase: 'mutation', method: 'post', path: '/v1/me/phone_numbers/phone_2', pendingPhone: '+1 (555) 555-0202' },
917969
{ phase: 'refresh', method: 'get', path: '/v1/me', pendingPhone: '+1 (555) 555-0101' },
918970
] as const)(
919-
'keeps method menus available but hides default changes during $phase',
971+
'disables method menus while changing the default during $phase',
920972
async ({ method, path, pendingPhone }) => {
921973
const first = fapiPhoneNumber({ ...phone, reserved_for_second_factor: true, default_second_factor: true });
922974
const second = fapiPhoneNumber({
@@ -934,16 +986,21 @@ describe('User profile MFA management', () => {
934986
await waitFor(() => expect(held.requests).toHaveLength(1));
935987
try {
936988
const pendingAction = screen.getByRole('button', { name: `Manage SMS verification ${pendingPhone}` });
937-
await openMenu(user, pendingAction);
938-
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Remove method' })).toBeVisible());
939-
expect(screen.queryByRole('menuitem', { name: 'Set as default' })).toBeNull();
940-
await user.click(await screen.findByRole('menuitem', { name: 'Remove method' }));
989+
expect(pendingAction).toHaveAttribute('aria-disabled', 'true');
990+
await user.click(pendingAction);
991+
expect(screen.queryByRole('menu')).toBeNull();
941992
expect(screen.queryByRole('alertdialog')).toBeNull();
942993
} finally {
943994
held.release();
944995
}
945996
await waitFor(() => expect(screen.getByText('+1 (555) 555-0202').closest('li')).toHaveTextContent('Default'));
946997
await user.keyboard('{Escape}');
998+
await waitFor(() =>
999+
expect(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' })).not.toHaveAttribute(
1000+
'aria-disabled',
1001+
'true',
1002+
),
1003+
);
9471004
await user.click(screen.getByRole('button', { name: 'Manage SMS verification +1 (555) 555-0101' }));
9481005
await waitFor(() => expect(screen.getByRole('menuitem', { name: 'Set as default' })).toBeVisible());
9491006
},

‎packages/mosaic/src/features/user-profile/user-profile-mfa-section/user-profile-mfa-row.view.tsx‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,12 +11,14 @@ import type { UserProfileMfaMethod, UserProfileMfaSectionViewProps } from './use
1111

1212
export function UserProfileMfaRowView({
1313
method,
14+
isDisabled,
1415
triggerRef,
1516
onRemove,
1617
onSetDefault,
1718
regenerate,
1819
}: Pick<UserProfileMfaSectionViewProps, 'regenerate'> & {
1920
method: UserProfileMfaMethod;
21+
isDisabled?: boolean;
2022
triggerRef?: Ref<HTMLButtonElement>;
2123
onRemove?: () => void;
2224
onSetDefault?: (id: string) => void;
@@ -56,6 +58,8 @@ export function UserProfileMfaRowView({
5658
{actions.length > 0 ? (
5759
<Section.Actions>
5860
<ActionMenu
61+
disabled={isDisabled}
62+
focusableWhenDisabled
5963
triggerRef={triggerRef}
6064
actions={actions}
6165
label={manageLabel}

‎packages/mosaic/src/features/user-profile/user-profile-mfa-section/user-profile-mfa-section-leaf.controller.ts‎

Lines changed: 10 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@ import type { UserProfileMfaSectionViewProps } from './user-profile-mfa-section.
99

1010
export function useUserProfileMfaSectionLeafController({
1111
methods,
12+
pendingAction,
1213
onAdd,
1314
onRemove,
1415
onSetDefault,
@@ -22,23 +23,25 @@ export function useUserProfileMfaSectionLeafController({
2223
fallback: () =>
2324
sectionRef.current?.querySelector<HTMLButtonElement>('button:not([disabled])') ?? sectionRef.current,
2425
});
26+
const localPendingAction = usePendingAction();
27+
const actions = pendingAction ?? localPendingAction;
2528
const remove = useConfirmController<UserProfileMfaMethod>({
2629
onConfirm: method => removalFocus.remove(method.id),
2730
reverification: removeReverification,
2831
});
2932
const [pickerOpen, setPickerOpen] = useState(false);
30-
const defaultAction = usePendingAction({ errorFallback: m.setDefaultError });
3133

3234
const setDefault = (id: string) => {
3335
const method = methods.find(method => method.id === id);
3436
if (!onSetDefault || method?.type !== 'sms' || !method.canSetDefault || method.isDefault) {
3537
return;
3638
}
37-
void defaultAction.run(id, () => onSetDefault(id));
39+
void actions.run(id, () => onSetDefault(id), { errorFallback: m.setDefaultError });
3840
};
3941

4042
return {
4143
sectionRef,
44+
isDisabled: actions.isPending,
4245
pickerOpen,
4346
onPickerOpenChange: setPickerOpen,
4447
addMethod: onAdd
@@ -49,16 +52,13 @@ export function useUserProfileMfaSectionLeafController({
4952
: undefined,
5053
registerTrigger: removalFocus.registerTrigger,
5154
openRemoval: (method: UserProfileMfaMethod) => {
52-
if (defaultAction.isPending) {
53-
return;
54-
}
55-
defaultAction.reset();
55+
actions.reset();
5656
remove.open(method);
5757
},
58-
remove: onRemove ? remove : undefined,
58+
remove: onRemove ? actions.guard(remove) : undefined,
5959
finalRemovalFocus: removalFocus.finalFocus,
60-
setDefaultFinalFocus: () => (defaultAction.lastKey ? removalFocus.trigger(defaultAction.lastKey) : null),
61-
defaultError: defaultAction.error,
62-
setDefault: onSetDefault && !defaultAction.isPending ? setDefault : undefined,
60+
setDefaultFinalFocus: () => (actions.lastKey ? removalFocus.trigger(actions.lastKey) : null),
61+
defaultError: actions.error,
62+
setDefault: onSetDefault ? setDefault : undefined,
6363
};
6464
}

0 commit comments

Comments
 (0)