diff --git a/.changeset/mosaic-sign-up-whatsapp-codes.md b/.changeset/mosaic-sign-up-whatsapp-codes.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-sign-up-whatsapp-codes.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md index b2f0fa40a5c..fa144305070 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -38,7 +38,8 @@ Sign-up renders one component per screen, so the route decides what is mounted ( - A screen with work to do on arrival owns its controller. `SignUpVerify` holds the code machine and sends the code when it mounts on a step with `sent: false`. A submit, a reload and a redirect all arrive that way. A screen that runs a controller reaches the view as a slot the wrapper builds, as the profile section's `nameAction` does, so `SignUpView` renders plain props only. - `SignUpVerify` takes the sign-up's id as its `key`, so a new sign-up never reuses the last one's screen. - A screen another feature owns arrives as a slot. The wrapper runs the task's model once, passes it to `TaskChooseOrganizationContent` (the task without its card), and tells the controller whether the task has loaded. The view mounts the slot on the task route. -- A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. A route whose screen is not built yet (`enterpriseConnections`) shows `startOver`. +- A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `alternativePhone` replaces `start` while the user has picked a phone channel such as WhatsApp there, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. A route whose screen is not built yet (`enterpriseConnections`) shows `startOver`. +- The channel `alternativePhone` shows is state in `useSignUpDetailsController`, not a route. The user picks it on the start form before any sign-up exists, the screen edits that same form, and no step `getSignUpNextStep` returns leads to it, so there is nothing for a route to restore. Use another method on that screen and Edit on the code screen both clear it. ## Move on after a submit diff --git a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts index 1223bdf7df9..be7e7d3a806 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -1,4 +1,11 @@ -import type { ClientJSON, SessionJSON, SignUpField, SignUpIdentificationField, SignUpJSON } from '@clerk/shared/types'; +import type { + ClientJSON, + PhoneCodeChannel, + SessionJSON, + SignUpField, + SignUpIdentificationField, + SignUpJSON, +} from '@clerk/shared/types'; import { http, HttpResponse } from 'msw'; import { @@ -27,6 +34,8 @@ export interface FakeSignUpSeed { protectCheckResolvedElsewhere?: boolean; protectCheckBlocked?: Record; protectCheckScript?: string; + whatsAppEnabled?: boolean; + whatsAppQuotaExceeded?: boolean; } export interface FakeSignUpState { @@ -41,6 +50,8 @@ export interface FakeSignUpState { protectCheckResolvedElsewhere?: boolean; protectCheckBlocked?: Record; protectCheckScript?: string; + whatsAppEnabled: boolean; + whatsAppQuotaExceeded: boolean; issuedProtectChecks: number; reloads: number; proofTokens: string[]; @@ -56,6 +67,8 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState { sessionTasks: null, weakPasswords: {}, protectChecks: 0, + whatsAppEnabled: true, + whatsAppQuotaExceeded: false, issuedProtectChecks: 0, reloads: 0, proofTokens: [], @@ -326,6 +339,47 @@ export function signUpHandlers( return next; }; + const prepare = (signUp: SignUpJSON, body: URLSearchParams): SignUpJSON | ReturnType => { + const strategy = body.get('strategy') ?? ''; + const channel = body.get('channel'); + const field = STRATEGIES[strategy]; + const attribute = field ? settings().attributes[field] : undefined; + if (!field || !attribute?.verifications.some(supported => supported === strategy)) { + return rejected('form_param_value_invalid', `${strategy} does not match one of the allowed values.`, 'strategy'); + } + if (!signUp[field]) { + return rejected('form_param_missing', `${field} must be set before it can be verified.`, field); + } + if (signUp.verifications?.[field].status === 'verified') { + return rejected('verification_already_verified', 'This verification has already been verified.', undefined, 400); + } + const isPhone = field === 'phone_number'; + if (isPhone && channel && channel !== 'sms' && channel !== 'whatsapp') { + return rejected('form_param_value_invalid', `${channel} does not match one of the allowed values.`, 'channel'); + } + if (isPhone && channel === 'whatsapp' && !state.signUp.whatsAppEnabled) { + return rejected( + 'whatsapp_channel_not_enabled', + "The 'whatsapp' channel is not available for this instance.", + 'channel', + ); + } + const sentOver = channel === 'whatsapp' && state.signUp.whatsAppQuotaExceeded ? 'sms' : (channel ?? 'sms'); + state.signUp.preparations.push(isPhone && channel ? `${strategy}:${channel}` : strategy); + return { + ...signUp, + verifications: { + ...signUp.verifications!, + [field]: { + ...signUp.verifications![field], + ...fapiVerification(strategy), + next_action: 'needs_attempt', + channel: isPhone ? (sentOver as PhoneCodeChannel) : undefined, + }, + }, + }; + }; + if (state.client.sign_up) { state.client = { ...state.client, sign_up: settle(state.client.sign_up) }; } @@ -342,7 +396,16 @@ export function signUpHandlers( } const blank = fapiSignUp({ id: `sua_${state.signUp.creations.length}` }); const applied = apply(blank, body); - return applied instanceof HttpResponse ? applied : store(settle(issueProtectCheck(applied))); + if (applied instanceof HttpResponse) { + return applied; + } + const created = issueProtectCheck(applied); + const prepared = body.get('strategy') === 'phone_code' ? prepare(created, body) : created; + if (prepared instanceof HttpResponse) { + store(settle(created)); + return clientError(prepared); + } + return store(settle(prepared)); }), http.get(fapiUrl('/protect-check/challenge.js'), () => HttpResponse.text(state.signUp.protectCheckScript ?? PROTECT_CHECK_SCRIPT, { @@ -410,35 +473,8 @@ export function signUpHandlers( if (!signUp?.verifications) { return missing(); } - const strategy = new URLSearchParams(await request.text()).get('strategy') ?? ''; - const field = STRATEGIES[strategy]; - const attribute = field ? settings().attributes[field] : undefined; - if (!field || !attribute?.verifications.some(supported => supported === strategy)) { - return rejected( - 'form_param_value_invalid', - `${strategy} does not match one of the allowed values.`, - 'strategy', - ); - } - if (!signUp[field]) { - return rejected('form_param_missing', `${field} must be set before it can be verified.`, field); - } - if (signUp.verifications[field].status === 'verified') { - return rejected( - 'verification_already_verified', - 'This verification has already been verified.', - undefined, - 400, - ); - } - state.signUp.preparations.push(strategy); - return store({ - ...signUp, - verifications: { - ...signUp.verifications, - [field]: { ...signUp.verifications[field], ...fapiVerification(strategy), next_action: 'needs_attempt' }, - }, - }); + const prepared = prepare(signUp, new URLSearchParams(await request.text())); + return prepared instanceof HttpResponse ? prepared : store(prepared); }), http.post(fapiUrl('/v1/client/sign_ups/:id/attempt_verification'), async ({ params, request }) => { const signUp = current(params.id); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.phone-channel.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.phone-channel.feature.test.tsx new file mode 100644 index 00000000000..bc57534744d --- /dev/null +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.phone-channel.feature.test.tsx @@ -0,0 +1,368 @@ +import { act, screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { holdRequests, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; +import { + fapiClient, + fapiEnvironment, + type FapiEnvironmentOverrides, + fapiSignUp, +} from '../../../__tests__/feature/fapi'; +import { codeSent, continueButton, enterCode, renderSignUp, renderSignUpWithRouteProbe } from './sign-up.fixtures'; + +function phoneEnvironment(authConfig: FapiEnvironmentOverrides['auth_config'] = {}) { + return fapiEnvironment({ + attributes: { + email_address: { enabled: false }, + password: { enabled: false }, + phone_number: { + enabled: true, + required: true, + verifications: ['phone_code'], + used_for_first_factor: true, + first_factors: ['phone_code'], + verify_at_sign_up: true, + channels: ['sms', 'whatsapp'], + }, + }, + auth_config: authConfig, + }); +} + +describe('choosing SMS or WhatsApp for the phone code', () => { + it('sends the phone code by SMS by default', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + + await user.type(await screen.findByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await codeSent(); + expect(fapi.signUp.creations[0].get('strategy')).toBeNull(); + expect(fapi.signUp.preparations).toEqual(['phone_code:sms']); + }); + + it('sends the phone code over WhatsApp when the user picks it, then signs them up', async () => { + const { fapi, user, navigate } = await renderSignUp({ environment: phoneEnvironment() }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + expect(await screen.findByRole('heading', { name: /with WhatsApp/ })).toBeInTheDocument(); + await user.type(screen.getByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your WhatsApp' })).toBeInTheDocument(); + expect(fapi.signUp.creations).toHaveLength(1); + expect(fapi.signUp.creations[0].get('strategy')).toBe('phone_code'); + expect(fapi.signUp.creations[0].get('channel')).toBe('whatsapp'); + expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp']); + + await user.click(screen.getByRole('textbox', { name: 'Verification code' })); + await user.keyboard(VERIFICATION_CODE); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.client.sessions).toHaveLength(1); + }); + + it("sends the phone code over the channel the instance prefers for the number's country", async () => { + const { fapi, user } = await renderSignUp({ + environment: phoneEnvironment({ preferred_channels: { US: 'whatsapp' } }), + }); + + await user.type(await screen.findByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your WhatsApp' })).toBeInTheDocument(); + await waitFor(() => expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp'])); + expect(fapi.signUp.creations[0].get('channel')).toBe('whatsapp'); + }); + + it('shows the SMS code screen when FAPI sends the code by SMS instead of WhatsApp', async () => { + const { user } = await renderSignUp({ + environment: phoneEnvironment(), + signUp: { whatsAppQuotaExceeded: true }, + }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'Send code via SMS instead' })).toBeNull(); + await codeSent(); + }); + + it('offers no WhatsApp on the continue screen and sends a code entered there by SMS', async () => { + const { fapi, user } = await renderSignUpWithRouteProbe({ + environment: phoneEnvironment({ preferred_channels: { US: 'whatsapp' } }), + client: { ...fapiClient(), sign_up: fapiSignUp({}) }, + }); + + await user.click(screen.getByRole('button', { name: 'Open the continue route' })); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /WhatsApp/ })).toBeNull(); + await user.type(screen.getByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + + await codeSent(); + expect(fapi.signUp.preparations).toEqual(['phone_code:sms']); + }); + + it('keeps Continue disabled on the WhatsApp phone screen until the phone number is filled', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await screen.findByRole('heading', { name: /with WhatsApp/ }); + await user.click(continueButton()); + + expect(continueButton()).toHaveAttribute('aria-disabled', 'true'); + expect(fapi.signUp.creations).toHaveLength(0); + await user.type(screen.getByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + expect(continueButton()).not.toHaveAttribute('aria-disabled'); + }); + + it('sends a prefilled value the WhatsApp phone screen does not show', async () => { + const { fapi, user } = await renderSignUp( + { + environment: fapiEnvironment({ + attributes: { + email_address: { enabled: false }, + password: { enabled: false }, + first_name: { enabled: true, required: false }, + phone_number: { + enabled: true, + required: true, + verifications: ['phone_code'], + used_for_first_factor: true, + first_factors: ['phone_code'], + verify_at_sign_up: true, + channels: ['sms', 'whatsapp'], + }, + }, + }), + }, + { initialValues: { firstName: 'Ada' } }, + ); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + + await codeSent(); + expect(fapi.signUp.creations[0].get('first_name')).toBe('Ada'); + }); +}); + +describe('changing the channel or the number from the WhatsApp code screen', () => { + it('locks the code screen while switching the code to SMS', async () => { + const { user } = await renderSignUp({ environment: phoneEnvironment() }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await codeSent(); + const hold = holdRequests('post', '/v1/client/sign_ups/:id/prepare_verification'); + await user.click(screen.getByRole('button', { name: 'Send code via SMS instead' })); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + + expect(screen.getByRole('button', { name: 'Send code via SMS instead' })).toBeDisabled(); + hold.release(); + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await codeSent(); + }); + + it('leaves a wrong WhatsApp code error behind when the code is sent by SMS instead', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await enterCode(user, '111111'); + expect(await screen.findByText('Incorrect code')).toBeInTheDocument(); + + await user.click(screen.getByRole('button', { name: 'Send code via SMS instead' })); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await waitFor(() => expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp', 'phone_code:sms'])); + await waitFor(() => expect(screen.queryByText('Incorrect code')).toBeNull()); + expect(screen.getByRole('textbox', { name: 'Verification code' })).toHaveValue(''); + }); + + it('returns to the main form when the phone number is edited from the WhatsApp code screen', async () => { + const { user } = await renderSignUp({ environment: phoneEnvironment() }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await codeSent(); + await user.click(screen.getByRole('button', { name: 'Edit phone number' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: /with WhatsApp/ })).toBeNull(); + }); +}); + +describe('resending the phone code', () => { + it('resends the phone code over WhatsApp from the WhatsApp code screen', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await codeSent(); + vi.useFakeTimers({ shouldAdvanceTime: true }); + + try { + await user.click(screen.getByRole('textbox', { name: 'Verification code' })); + await user.keyboard('12'); + await act(() => vi.advanceTimersByTimeAsync(30_000)); + await user.click(await screen.findByRole('button', { name: 'Resend' })); + + await waitFor(() => expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp', 'phone_code:whatsapp'])); + expect(screen.getByRole('textbox', { name: 'Verification code' })).toHaveValue(''); + expect(screen.getByRole('heading', { name: 'Verify your WhatsApp' })).toBeInTheDocument(); + await codeSent(); + } finally { + vi.useRealTimers(); + } + }); + + it('resends the phone code by SMS after switching to SMS from the WhatsApp code screen', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await codeSent(); + await user.click(screen.getByRole('button', { name: 'Send code via SMS instead' })); + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await codeSent(); + vi.useFakeTimers({ shouldAdvanceTime: true }); + + try { + await act(() => vi.advanceTimersByTimeAsync(30_000)); + await user.click(await screen.findByRole('button', { name: 'Resend' })); + + await waitFor(() => + expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp', 'phone_code:sms', 'phone_code:sms']), + ); + expect(screen.getByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await codeSent(); + } finally { + vi.useRealTimers(); + } + }); + + it('starts the resend countdown after a code fails to send', async () => { + const { user } = await renderSignUp({ environment: phoneEnvironment() }); + const hold = holdRequests('post', '/v1/client/sign_ups/:id/prepare_verification'); + + await user.type(await screen.findByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + hold.fail('verification_code_too_many_requests', 'Too many requests. Please wait before trying again.'); + + expect(await screen.findByText('Too many requests. Please wait before trying again.')).toBeInTheDocument(); + await codeSent(); + }); +}); + +describe('when the phone number or the WhatsApp send is rejected', () => { + it('leaves a field or global phone error behind when moving between the form and the WhatsApp phone screen', async () => { + const { fapi, user } = await renderSignUp({ environment: phoneEnvironment() }); + const onForm = holdRequests('post', '/v1/client/sign_ups'); + + await user.type(await screen.findByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + await waitFor(() => expect(onForm.requests).toHaveLength(1)); + onForm.fail('form_identifier_exists', 'That phone number is taken. Please try another.', 'phone_number'); + await screen.findByText('That phone number is taken. Please try another.'); + await user.click(screen.getByRole('button', { name: /WhatsApp/ })); + + expect(await screen.findByRole('heading', { name: /with WhatsApp/ })).toBeInTheDocument(); + expect(screen.queryByText('That phone number is taken. Please try another.')).toBeNull(); + + const rejected = holdRequests('post', '/v1/client/sign_ups'); + await user.click(continueButton()); + await waitFor(() => expect(rejected.requests).toHaveLength(1)); + rejected.fail('form_identifier_exists', 'That phone number is taken. Please try another.', 'phone_number'); + + expect(await screen.findByText('That phone number is taken. Please try another.')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: /with WhatsApp/ })).toBeInTheDocument(); + expect(fapi.signUp.preparations).toEqual([]); + await user.click(screen.getByRole('button', { name: 'Use another method' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(screen.queryByText('That phone number is taken. Please try another.')).toBeNull(); + + const limited = holdRequests('post', '/v1/client/sign_ups'); + await user.click(screen.getByRole('button', { name: /WhatsApp/ })); + await screen.findByRole('heading', { name: /with WhatsApp/ }); + await user.click(continueButton()); + await waitFor(() => expect(limited.requests).toHaveLength(1)); + limited.fail('too_many_requests', 'Too many requests. Please try again later.'); + + await waitFor(() => + expect(screen.getByRole('alert')).toHaveTextContent('Too many requests. Please try again later.'), + ); + await user.click(screen.getByRole('button', { name: 'Use another method' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + await waitFor(() => expect(screen.queryByText('Too many requests. Please try again later.')).toBeNull()); + }); + + it('replaces the WhatsApp phone screen with the blocked notice when the request is blocked', async () => { + const { user } = await renderSignUp({ + environment: phoneEnvironment(), + signUp: { blocked: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' } }, + }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); + expect(screen.getByText('Contact support.')).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: /with WhatsApp/ })).toBeNull(); + }); + + it('keeps the WhatsApp screen and its error after a failed send, then sends the code on retry', async () => { + const { fapi, user } = await renderSignUp({ + environment: phoneEnvironment(), + signUp: { whatsAppEnabled: false }, + }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByText("The 'whatsapp' channel is not available for this instance.")).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: /with WhatsApp/ })).toBeInTheDocument(); + expect(fapi.client.sign_up).toMatchObject({ id: 'sua_1', phone_number: '+15555550123' }); + fapi.signUp.whatsAppEnabled = true; + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your WhatsApp' })).toBeInTheDocument(); + await codeSent(); + expect(fapi.signUp.preparations).toEqual(['phone_code:whatsapp']); + }); + + it('signs up over SMS from the form after a failed WhatsApp send left a sign-up', async () => { + const { fapi, user } = await renderSignUp({ + environment: phoneEnvironment(), + signUp: { whatsAppEnabled: false }, + }); + + await user.click(await screen.findByRole('button', { name: /WhatsApp/ })); + await user.type(await screen.findByRole('textbox', { name: 'WhatsApp phone number' }), '5555550123'); + await user.click(continueButton()); + await screen.findByText("The 'whatsapp' channel is not available for this instance."); + await user.click(screen.getByRole('button', { name: 'Use another method' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + await user.clear(screen.getByRole('textbox', { name: 'Phone number' })); + await user.type(screen.getByRole('textbox', { name: 'Phone number' }), '5555550123'); + await user.click(continueButton()); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + await codeSent(); + expect(fapi.signUp.preparations).toEqual(['phone_code:sms']); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index 558c321256b..f7dec5ea616 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -1,4 +1,5 @@ import { DEBOUNCE_MS } from '@clerk/shared/internal/clerk-js/constants'; +import type { PhoneCodeChannel } from '@clerk/shared/types'; import { useState } from 'react'; import type { FieldFeedback, FieldsConfig } from '../../../components/form'; @@ -7,9 +8,18 @@ import { useDebouncedAsync } from '../../../hooks/use-debounced-async'; import type { MosaicMessages } from '../../../localization'; import { useMessages } from '../../../localization'; import type { SignUpCreateResult, SignUpDetailsModel, SignUpDetailsValues, SignUpIdentifier } from '../sign-up.model'; -import type { SignUpDetails, SignUpDetailsScreen, SignUpFieldName, SignUpFields, SignUpValues } from '../sign-up.types'; +import type { + SignUpAlternativePhoneScreen, + SignUpDetails, + SignUpDetailsScreen, + SignUpFieldName, + SignUpFields, + SignUpValues, +} from '../sign-up.types'; import { signUpFieldNames } from '../sign-up.utils'; +const ALTERNATIVE_PHONE_FIELDS: SignUpFields = { phoneNumber: { required: true } }; + const emptyValues: SignUpValues = { firstName: '', lastName: '', @@ -95,12 +105,15 @@ export function useSignUpDetailsController( { purpose, isBusy, globalErrorMessage, onNext, onSignIn }: SignUpDetailsOptions, ) { const [chosenIdentifier, setChosenIdentifier] = useState(undefined); + const [chosenChannel, setChosenChannel] = useState(undefined); const genericError = useMessages('errors').generic; const m = useMessages('signUp'); const identifier = chosenIdentifier ?? details.initialIdentifier; const startFields = details.startFieldsFor(identifier); const continueFields = details.continueFieldsFor(identifier); - const fields = purpose === 'continue' ? continueFields : startFields; + const channel = purpose === 'start' ? chosenChannel : undefined; + const alternativeChannel = details.alternativeChannels.find(provider => provider.id === channel); + const fields = alternativeChannel ? ALTERNATIVE_PHONE_FIELDS : purpose === 'continue' ? continueFields : startFields; const consentRequired = Boolean(purpose === 'continue' ? details.continueLegalConsent : details.legalConsent); @@ -109,9 +122,13 @@ export function useSignUpDetailsController( fields: requiredFields(fields, consentRequired, m), onSubmit: values => { const submitted = detailsValues(values, fields); - return purpose === 'continue' - ? details.update(submitted) - : details.create({ ...submitted, ...details.startHiddenValuesFor(identifier) }); + if (purpose === 'continue') { + return details.update(submitted); + } + return details.create( + { ...submitted, ...details.startHiddenValuesFor(identifier) }, + { channel: alternativeChannel?.id }, + ); }, onSuccess: result => { if (result) { @@ -130,9 +147,7 @@ export function useSignUpDetailsController( : strength.data; const isPending = form.isSubmitting || isBusy; - const screen: Omit = { - socialProviders: [], - onSelectProvider: () => undefined, + const screen: Omit = { form, onSubmit: form.handleSubmit, isPending, @@ -142,21 +157,49 @@ export function useSignUpDetailsController( onSignIn, }; + const switchChannel = (next: PhoneCodeChannel | undefined) => { + setChosenChannel(next); + form.reset(form.values); + }; + + const alternativePhone: SignUpAlternativePhoneScreen | undefined = alternativeChannel + ? { + channel: alternativeChannel, + legalConsent: details.legalConsent, + form, + onSubmit: form.handleSubmit, + isPending, + isDisabled: isPending, + globalErrorMessage: form.error ?? globalErrorMessage, + onCancel: () => switchChannel(undefined), + } + : undefined; + const switchField = (purpose: 'start' | 'continue') => canSwitch(purpose, details) ? () => setChosenIdentifier(otherIdentifier(identifier)) : undefined; return { + alternativePhone, start: { ...screen, step: detailsStep('start', startFields, details, identifier), onSwitchField: switchField('start'), + socialProviders: details.alternativeChannels, + onSelectProvider: (id: string) => + switchChannel(details.alternativeChannels.find(provider => provider.id === id)?.id), }, continue: { ...screen, step: detailsStep('continue', continueFields, details, identifier), onSwitchField: switchField('continue'), + socialProviders: [], + onSelectProvider: () => undefined, }, error: form.error, - reset: form.reset, + leaveChannel: () => switchChannel(undefined), + reset: () => { + form.reset(); + setChosenChannel(undefined); + }, }; } diff --git a/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.controller.ts index 6c78cbd6c18..43aab9ce26f 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.controller.ts @@ -9,22 +9,36 @@ import type { ErrorInvokeEvent } from '../../../machine/types'; import { useMachine } from '../../../machine/use-machine'; import { toLocalizableError } from '../../../utils/errors'; import { CODE_RESEND_SECONDS, isResendUnlocked, resendUnlockTime } from '../../../utils/verification'; +import type { SignUpVerificationModel } from '../sign-up.model'; import type { SignUpVerifyScreen } from '../sign-up.types'; interface CodeContext { - sendCode: () => Promise; + sendCode: SignUpVerificationModel['send']; resendAvailableAt: number | undefined; error: ErrorDescription | undefined; } -type CodeEvent = { type: 'SEND' } | { type: 'RESEND' } | { type: 'ALREADY_SENT' }; +type CodeEvent = { type: 'SEND' } | { type: 'RESEND' } | { type: 'SEND_SMS' } | { type: 'ALREADY_SENT' }; const code = setup(); const clearError = code.assign(() => ({ error: undefined })); +const sendBySms = { target: 'sendingSms' as const, actions: clearError }; + const startCooldown = code.assign(() => ({ resendAvailableAt: resendUnlockTime(CODE_RESEND_SECONDS) })); +const settleSend = { + onDone: { target: 'sent' as const, actions: startCooldown }, + onError: { + target: 'sent' as const, + actions: code.assign((_, event) => ({ + error: toLocalizableError(event.error), + resendAvailableAt: resendUnlockTime(CODE_RESEND_SECONDS), + })), + }, +}; + const codeMachine = code.createMachine({ id: 'signUpCode', initial: 'idle', @@ -35,20 +49,19 @@ const codeMachine = code.createMachine({ }, states: { idle: { - on: { SEND: 'sending', RESEND: 'sending', ALREADY_SENT: { target: 'sent', actions: startCooldown } }, - }, - sending: { - invoke: code.fromPromise(context => context.sendCode(), { - onDone: { target: 'sent', actions: startCooldown }, - onError: { - target: 'sent', - actions: code.assign((_, event) => ({ error: toLocalizableError(event.error) })), - }, - }), + on: { + SEND: 'sending', + RESEND: 'sending', + SEND_SMS: sendBySms, + ALREADY_SENT: { target: 'sent', actions: startCooldown }, + }, }, + sending: { invoke: code.fromPromise(context => context.sendCode(), settleSend) }, + sendingSms: { invoke: code.fromPromise(context => context.sendCode({ channel: 'sms' }), settleSend) }, sent: { on: { SEND: { target: 'sending', actions: clearError }, + SEND_SMS: sendBySms, RESEND: { target: 'sending', guard: context => isResendUnlocked(context.resendAvailableAt), @@ -78,7 +91,8 @@ export function useSignUpVerifyController({ send({ type: needsCode ? 'SEND' : 'ALREADY_SENT' }); }, [needsCode, send]); - const isPending = actions.isPending || isFlowPending; + const isSwitchingToSms = snapshot.value === 'sendingSms'; + const isPending = actions.isPending || isFlowPending || isSwitchingToSms; const submit = (submitted: string) => void actions.run('code', async () => onNext(await verification.verify(submitted))); @@ -91,7 +105,17 @@ export function useSignUpVerifyController({ canEditIdentifier: !isPending && snapshot.value !== 'sending', errorMessage: actions.error, globalErrorMessage: snapshot.context.error ? errorText(snapshot.context.error) : globalErrorMessage, - onResend: () => send({ type: 'RESEND' }), + onResend: () => { + setValue(''); + send({ type: 'RESEND' }); + }, + onSendSms: verification.provider + ? () => { + setValue(''); + actions.reset(); + send({ type: 'SEND_SMS' }); + } + : undefined, canResend: snapshot.value === 'sent' && resendSeconds === 0 && !isPending, resendRemainingSeconds: resendSeconds || undefined, }; diff --git a/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.tsx b/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.tsx index f499f2cad48..ef6e5c98533 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up-verify/sign-up-verify.tsx @@ -9,7 +9,7 @@ interface SignUpVerifyProps extends SignUpVerifyScreen { channel: 'email' | 'phone'; } -export function SignUpVerify({ channel, provider, onEditIdentifier, onCancel, ...options }: SignUpVerifyProps) { +export function SignUpVerify({ channel, onEditIdentifier, onCancel, ...options }: SignUpVerifyProps) { const m = useMessages('signUp'); const { value, @@ -21,15 +21,16 @@ export function SignUpVerify({ channel, provider, onEditIdentifier, onCancel, .. onSubmit, onComplete, onResend, + onSendSms, canResend, resendRemainingSeconds, } = useSignUpVerifyController(options); const step: SignUpCode = { purpose: channel === 'email' ? 'verify-email' : 'verify-phone', identifier: options.verification.target, - provider, + provider: options.verification.provider, }; - const secondary = signUpCodeSecondaryAction(step, m, onCancel); + const secondary = signUpCodeSecondaryAction(step, m, onSendSms ?? onCancel); const identity = signUpCodeIdentity(step, m); return ( diff --git a/packages/mosaic/src/features/sign-up/sign-up.controller.ts b/packages/mosaic/src/features/sign-up/sign-up.controller.ts index c85dca749e3..a4b09465aa0 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -161,6 +161,7 @@ export function useSignUpController( globalErrorMessage: finishError, onEditIdentifier: () => { sendFinish({ type: 'DISMISS' }); + details.leaveChannel(); go(detailsRouteFor(route)); }, }; @@ -171,8 +172,9 @@ export function useSignUpController( return { status: 'ready', - screen, + screen: screen === 'start' && details.alternativePhone ? 'alternativePhone' : screen, attempt: flow.signUpId, + alternativePhone: details.alternativePhone, start: details.start, continue: details.continue, verifyEmail: { ...verify, verification: verification.email }, diff --git a/packages/mosaic/src/features/sign-up/sign-up.model.ts b/packages/mosaic/src/features/sign-up/sign-up.model.ts index 37978201ab2..e50b522115a 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -1,3 +1,5 @@ +import { getAlternativePhoneCodeProviderData } from '@clerk/shared/alternativePhoneCode'; +import { iconImageUrl } from '@clerk/shared/constants'; import type { ClerkError } from '@clerk/shared/error'; import { isClerkAPIResponseError } from '@clerk/shared/error'; import { actionBlockedDetailsFrom } from '@clerk/shared/internal/clerk-js/actionBlocked'; @@ -14,11 +16,18 @@ import { emailOrPhone, getInitialActiveIdentifier, } from '@clerk/shared/internal/clerk-js/signUpFormFields'; +import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; import { __internal_useClerkSignal, useClerk, useSession } from '@clerk/shared/react'; -import type { ClerkAPIError, SessionTask, SignUpFutureResource, SignUpInitialValues } from '@clerk/shared/types'; +import type { + ClerkAPIError, + PhoneCodeChannel, + SessionTask, + SignUpFutureResource, + SignUpInitialValues, +} from '@clerk/shared/types'; import { useMemo } from 'react'; -import type { AuthActionBlockedDetails } from '../../blocks/auth'; +import type { AuthActionBlockedDetails, AuthProvider } from '../../blocks/auth'; import type { FieldFeedback, FormFieldErrors } from '../../components/form'; import { FormSubmitError } from '../../components/form'; import { useMosaicEnvironment } from '../../hooks/use-mosaic-environment'; @@ -92,14 +101,16 @@ export interface SignUpDetailsModel { legalConsent?: SignUpLegalConsent; continueLegalConsent?: SignUpLegalConsent; validatePassword: (password: string) => Promise; - create: (values: SignUpDetailsValues) => Promise; + alternativeChannels: Array; + create: (values: SignUpDetailsValues, options?: { channel?: PhoneCodeChannel }) => Promise; update: (values: SignUpDetailsValues) => Promise; } export interface SignUpVerificationModel { target: string; needsCode: boolean; - send: () => Promise; + provider?: string; + send: (options?: { channel?: PhoneCodeChannel }) => Promise; verify: (code: string) => Promise; } @@ -320,6 +331,13 @@ export function useSignUpModel({ : undefined; const step = next(signUp); + const phoneChannel = signUp.verifications.phoneNumber.channel; + const preferredPhoneChannel = (phoneNumber: string | undefined): PhoneCodeChannel | undefined => { + const { preferredChannels } = environment.authConfig; + const preferred = + phoneNumber && preferredChannels ? getPreferredPhoneCodeChannelByCountry(phoneNumber, preferredChannels) : null; + return preferred && preferred !== 'sms' ? preferred : undefined; + }; return { status: 'ready', @@ -399,8 +417,16 @@ export function useSignUpModel({ legalConsent, continueLegalConsent: signUp.missingFields.includes('legal_accepted') ? legalConsent : undefined, validatePassword, - create: async values => { - const result = await signUp.create(details(values)); + alternativeChannels: userSettings.alternativePhoneCodeChannels.flatMap(channel => { + const provider = getAlternativePhoneCodeProviderData(channel); + return provider ? [{ id: channel, name: provider.name, iconUrl: iconImageUrl(channel) }] : []; + }), + create: async (values, { channel } = {}) => { + const sendOver = channel ?? preferredPhoneChannel(values.phoneNumber); + const result = await signUp.create({ + ...details(values), + ...(sendOver ? { strategy: 'phone_code' as const, channel: sendOver } : {}), + }); const blocked = blockedBy(result.error); if (blocked) { return { type: 'blocked', details: blocked }; @@ -459,7 +485,8 @@ export function useSignUpModel({ phone: { target: signUp.phoneNumber ?? '', needsCode: step.type === 'verify_phone' && !step.sent, - send: () => run(() => signUp.verifications.sendPhoneCode()), + provider: getAlternativePhoneCodeProviderData(phoneChannel)?.name, + send: ({ channel } = {}) => run(() => signUp.verifications.sendPhoneCode({ channel: channel ?? phoneChannel })), verify: code => verify(() => signUp.verifications.verifyPhoneCode({ code })), }, }, diff --git a/packages/mosaic/src/features/sign-up/sign-up.types.ts b/packages/mosaic/src/features/sign-up/sign-up.types.ts index 859328e3ca6..90c11711a03 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.types.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.types.ts @@ -63,7 +63,6 @@ export interface SignUpDetailsScreen { export interface SignUpVerifyScreen { verification: SignUpVerificationModel; onNext: (step: SignUpNextStep) => void; - provider?: string; isPending: boolean; globalErrorMessage?: string; onEditIdentifier: () => void; diff --git a/packages/swingset/src/stories/sign-up.stories.tsx b/packages/swingset/src/stories/sign-up.stories.tsx index 119da2043e0..a4c55e7c0fd 100644 --- a/packages/swingset/src/stories/sign-up.stories.tsx +++ b/packages/swingset/src/stories/sign-up.stories.tsx @@ -341,8 +341,7 @@ export function VerifyPhoneAlternativeChannel() { } />