From 0c74feb5bdddc926af2acb0b46a1c76b839b2988 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 14:45:13 -0700 Subject: [PATCH 01/11] test(mosaic): let the fake FAPI send, open and expire a sign-up email link --- .../__tests__/feature/fake-fapi/sign-up.ts | 93 ++++++++++++++++++- 1 file changed, 88 insertions(+), 5 deletions(-) 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 1c3770c292e..1e0143a0f6c 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -45,6 +45,7 @@ export interface FakeSignUpSeed { whatsAppQuotaExceeded?: boolean; tickets?: Record; oauth?: Record; + emailLinkRedirectUrl?: string; } export type FakeOAuthAccount = @@ -85,6 +86,9 @@ export interface FakeSignUpState { transfers: URLSearchParams[]; linkedStrategy?: string; returnFromOAuth: () => void; + emailLinkRedirectUrl?: string; + openEmailLink: (clientId?: string) => string; + expireEmailLink: () => void; issuedProtectChecks: number; reloads: number; proofTokens: string[]; @@ -109,6 +113,12 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState { returnFromOAuth: () => { throw new Error('The fake FAPI has not started'); }, + openEmailLink: () => { + throw new Error('The fake FAPI has not started'); + }, + expireEmailLink: () => { + throw new Error('The fake FAPI has not started'); + }, issuedProtectChecks: 0, reloads: 0, proofTokens: [], @@ -145,7 +155,12 @@ export default (container, { token, setWidgetVisible }) => let scriptIds = 0; -const STRATEGIES: Record = { email_code: 'email_address', phone_code: 'phone_number' }; +const STRATEGIES: Record = { + email_code: 'email_address', + email_link: 'email_address', + phone_code: 'phone_number', +}; +const EMAIL_LINK_LIFETIME_MS = 600_000; const TEXT_FIELDS = ['email_address', 'phone_number', 'username', 'first_name', 'last_name'] as const; const createdAt = Date.UTC(2026, 0, 1); @@ -196,7 +211,12 @@ export function signUpHandlers( return HttpResponse.json({ ...body, meta: { client: state.client } }, { status: response.status }); }; + const completed = new Map(); + const store = (signUp: SignUpJSON) => { + if (signUp.status === 'complete') { + completed.set(signUp.id, signUp); + } state.client = { ...state.client, sign_up: signUp.status === 'complete' ? null : signUp }; return envelope(signUp, state.client); }; @@ -551,6 +571,11 @@ export function signUpHandlers( if (signUp.verifications?.[field].status === 'verified') { return rejected('verification_already_verified', 'This verification has already been verified.', undefined, 400); } + const isLink = strategy === 'email_link'; + const redirectUrl = body.get('redirect_url'); + if (isLink && !redirectUrl) { + return rejected('form_conditional_param_missing', 'redirect_url must be included.', 'redirect_url'); + } 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'); @@ -564,13 +589,26 @@ export function signUpHandlers( } const sentOver = channel === 'whatsapp' && state.signUp.whatsAppQuotaExceeded ? 'sms' : (channel ?? 'sms'); state.signUp.preparations.push(isPhone && channel ? `${strategy}:${channel}` : strategy); + const pending = signUp.verifications![field]; + const linkStillOut = pending.strategy === 'email_link' && pending.status === 'unverified'; + if (isLink && redirectUrl) { + state.signUp.emailLinkRedirectUrl = redirectUrl; + } return { ...signUp, verifications: { ...signUp.verifications!, [field]: { - ...signUp.verifications![field], - ...fapiVerification(strategy), + ...pending, + ...fapiVerification( + strategy, + isLink + ? { + object: 'verification_email_link', + expire_at: linkStillOut ? pending.expire_at : Date.now() + EMAIL_LINK_LIFETIME_MS, + } + : {}, + ), next_action: 'needs_attempt', supported_strategies: [strategy], channel: isPhone ? (sentOver as PhoneCodeChannel) : undefined, @@ -579,6 +617,51 @@ export function signUpHandlers( }; }; + const emailLink = () => { + const signUp = state.client.sign_up; + const pending = signUp?.verifications?.email_address; + const redirectUrl = state.signUp.emailLinkRedirectUrl; + if (!signUp?.verifications || pending?.strategy !== 'email_link' || !redirectUrl) { + throw new Error('No email link has been sent'); + } + return { signUp, verifications: signUp.verifications, pending, landing: new URL(redirectUrl) }; + }; + + state.signUp.openEmailLink = (clientId = state.client.id) => { + const { signUp, verifications, pending, landing } = emailLink(); + if (pending.status === 'expired') { + landing.searchParams.set('__clerk_status', 'expired'); + return landing.toString(); + } + if (pending.status !== 'unverified') { + throw new Error('The email link has already been opened'); + } + const verified = settle({ + ...signUp, + verifications: { + ...verifications, + email_address: { ...pending, status: 'verified', next_action: '', verified_at_client: clientId }, + }, + }); + store(verified); + landing.searchParams.set('__clerk_status', 'verified'); + if (verified.created_session_id) { + landing.searchParams.set('__clerk_created_session', verified.created_session_id); + } + return landing.toString(); + }; + + state.signUp.expireEmailLink = () => { + const { signUp, verifications, pending } = emailLink(); + store({ + ...signUp, + verifications: { + ...verifications, + email_address: { ...pending, status: 'expired', next_action: 'needs_prepare' }, + }, + }); + }; + if (state.client.sign_up) { state.client = { ...state.client, sign_up: settle(state.client.sign_up) }; } @@ -743,7 +826,7 @@ export function signUpHandlers( ); }), http.get(fapiUrl('/v1/client/sign_ups/:id'), ({ params }) => { - const signUp = current(params.id); + const signUp = current(params.id) ?? completed.get(String(params.id)); if (!signUp) { return missing(); } @@ -786,7 +869,7 @@ export function signUpHandlers( const body = new URLSearchParams(await request.text()); const strategy = body.get('strategy') ?? ''; const code = body.get('code') ?? ''; - const field = STRATEGIES[strategy]; + const field = strategy === 'email_link' ? undefined : STRATEGIES[strategy]; if (!field) { return rejected( 'form_param_value_invalid', From efccf81db4916c820c00306c3c4c058eb0f9cf72 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:11:12 -0700 Subject: [PATCH 02/11] feat(mosaic): verify a sign-up email by link --- .../sign-up.email-link.feature.test.tsx | 224 ++++++++++++++++++ .../__tests__/sign-up.feature.test.tsx | 34 --- packages/mosaic/src/features/sign-up/index.ts | 2 + .../sign-up-email-link.controller.test.ts | 45 ++++ .../sign-up-email-link.controller.ts | 132 +++++++++++ .../sign-up-email-link/sign-up-email-link.tsx | 31 +++ .../features/sign-up/sign-up.controller.ts | 23 +- .../src/features/sign-up/sign-up.messages.ts | 1 + .../src/features/sign-up/sign-up.model.ts | 86 ++++++- .../mosaic/src/features/sign-up/sign-up.tsx | 20 +- .../src/features/sign-up/sign-up.types.ts | 15 +- .../src/features/sign-up/sign-up.view.tsx | 25 -- packages/swingset/src/stories/sign-up.mdx | 2 +- .../swingset/src/stories/sign-up.stories.tsx | 25 +- 14 files changed, 570 insertions(+), 95 deletions(-) create mode 100644 packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx create mode 100644 packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts create mode 100644 packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts create mode 100644 packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx new file mode 100644 index 00000000000..36b8c3d8a9b --- /dev/null +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -0,0 +1,224 @@ +import type { SignUpVerificationJSON } from '@clerk/shared/types'; +import { screen, waitFor } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; + +import { holdRequests } from '../../../__tests__/feature/fake-fapi'; +import { fapiClient, fapiSignUp, fapiVerification } from '../../../__tests__/feature/fapi'; +import { + EMAIL, + emailField, + environment, + passwordField, + renderSignUp, + renderSignUpWithRouteProbe, + submitStart, +} from './sign-up.fixtures'; + +const POLL = '/v1/client/sign_ups/:id'; +const SEND = '/v1/client/sign_ups/:id/prepare_verification'; +const LINK_URL = `${window.location.origin}/?__clerk_mosaic_sign_up=verify`; +const EXPIRED = 'The verification link expired. Please request a new link.'; +const POLL_INTERVAL_MS = 1000; + +const byLink = (verifications = ['email_link']) => + environment({ attributes: { email_address: { required: true, verifications } } }); + +function signUpWithLink(emailAddress: Partial, hasPassword = true) { + const signUp = fapiSignUp({ email_address: EMAIL, has_password: hasPassword }); + return { + ...signUp, + verifications: { + ...signUp.verifications!, + email_address: { + ...fapiVerification('email_link'), + next_action: 'needs_attempt', + supported_strategies: ['email_link'], + ...emailAddress, + }, + }, + }; +} + +const linkOut = (hasPassword = true) => ({ + environment: byLink(), + client: { ...fapiClient(), sign_up: signUpWithLink({}, hasPassword) }, + signUp: { emailLinkRedirectUrl: LINK_URL }, +}); + +const linkSent = () => screen.findByRole('button', { name: /^Resend \(\d+\)$/ }); + +describe('SignUp', () => { + describe('verifying the email by link', () => { + it('sends one link that comes back to this page and shows where it went, on an instance that verifies email by link', async () => { + const { fapi, user } = await renderSignUp({ environment: byLink() }); + + await submitStart(user); + + expect(await screen.findByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByText('Use the verification link sent to your email address')).toBeInTheDocument(); + expect(screen.getByText(EMAIL)).toBeInTheDocument(); + expect(screen.queryByRole('textbox', { name: 'Verification code' })).toBeNull(); + expect(await linkSent()).toBeDisabled(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + const redirectUrl = new URL(fapi.signUp.emailLinkRedirectUrl ?? ''); + expect(redirectUrl.origin + redirectUrl.pathname).toBe(window.location.origin + window.location.pathname); + expect(redirectUrl.searchParams.get('__clerk_mosaic_sign_up')).toBe('verify'); + }); + + it('sends a link, not a code, on an instance that verifies email by code or link', async () => { + const { fapi, user } = await renderSignUp({ environment: byLink(['email_code', 'email_link']) }); + + await submitStart(user); + + expect(await linkSent()).toBeDisabled(); + expect(screen.queryByRole('textbox', { name: 'Verification code' })).toBeNull(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + }); + + it('keeps Edit disabled until the link is sent, and shows why when it could not be sent', async () => { + const { user } = await renderSignUp({ environment: byLink() }); + const hold = holdRequests('post', SEND); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + + expect(await screen.findByRole('button', { name: 'Edit email address' })).toBeDisabled(); + + hold.fail('form_param_invalid', 'The email link could not be sent.'); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('The email link could not be sent.')); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + }); + + it('waits without sending again when it opens with a link already out, and finishes once the link is opened', async () => { + const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut()); + const hold = holdRequests('get', POLL); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + + expect(await linkSent()).toBeDisabled(); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + expect(fapi.signUp.preparations).toEqual([]); + + fapi.signUp.openEmailLink('client_other'); + hold.release(); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.client.sessions).toHaveLength(1); + expect(fapi.signUp.preparations).toEqual([]); + }); + + it('signs in and leaves for the after sign-up URL when the link is opened in another browser', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp( + { environment: byLink() }, + {}, + { signUpFallbackRedirectUrl: '/welcome' }, + ); + const hold = holdRequests('get', POLL); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + fapi.signUp.openEmailLink('client_other'); + hold.release(); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/welcome'))); + expect(fapi.client.sessions).toHaveLength(1); + expect(clerk.session?.id).toBe(fapi.client.sessions[0].id); + }); + + it('asks for what is still missing when the link is opened in another browser before the sign-up is complete', async () => { + const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut(false)); + const hold = holdRequests('get', POLL); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + fapi.signUp.openEmailLink('client_other'); + hold.release(); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('tells the user to go to the other tab when the link is opened in this browser, and signs nobody in here', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); + const hold = holdRequests('get', POLL); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + fapi.signUp.openEmailLink(); + hold.release(); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^Resend/ })).toBeNull(); + expect(fapi.client.sessions).toHaveLength(1); + expect(clerk.session).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('says the link expired without sending another, then sends a new one on Resend', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + try { + const { fapi, user } = await renderSignUp({ environment: byLink() }); + const hold = holdRequests('get', POLL); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + fapi.signUp.expireEmailLink(); + hold.release(); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(EXPIRED)); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + + vi.setSystemTime(Date.now() + 61_000); + await user.click(await screen.findByRole('button', { name: 'Resend' })); + + expect(await linkSent()).toBeDisabled(); + expect(screen.getByRole('alert')).not.toHaveTextContent(EXPIRED); + expect(fapi.signUp.preparations).toEqual(['email_link', 'email_link']); + await waitFor(() => expect(hold.requests).toHaveLength(2)); + } finally { + vi.useRealTimers(); + } + }); + + it('returns to the form with the address kept and the password cleared on Edit, and no longer follows the link', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); + const hold = holdRequests('get', POLL); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + await user.click(screen.getByRole('button', { name: 'Edit email address' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(emailField()).toHaveValue(EMAIL); + expect(passwordField()).toHaveValue(''); + + fapi.signUp.openEmailLink('client_other'); + hold.release(); + await waitFor(() => expect(clerk.client?.sessions).toHaveLength(1)); + + expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(hold.requests).toHaveLength(1); + }); + }); + + describe('leaving the link screen', () => { + it('stops asking whether the link was opened once the user leaves the screen', async () => { + const { fapi, user } = await renderSignUp({ environment: byLink() }); + + await submitStart(user); + await waitFor(() => expect(fapi.signUp.reloads).toBe(1)); + await user.click(screen.getByRole('button', { name: 'Edit email address' })); + await screen.findByRole('heading', { name: 'Create your account' }); + await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS / 2)); + const askedBeforeLeaving = fapi.signUp.reloads; + await new Promise(resolve => setTimeout(resolve, 1.5 * POLL_INTERVAL_MS)); + + expect(fapi.signUp.reloads).toBe(askedBeforeLeaving); + }); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx index 0d45d7325ee..40361676987 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx @@ -407,8 +407,6 @@ describe('SignUp', () => { expect(emailField()).toHaveValue(EMAIL); expect(passwordField()).toHaveValue(''); }); - - it.todo('sends an email link instead of a code whenever the instance enables the email link'); }); describe('filling in missing fields', () => { @@ -614,38 +612,6 @@ describe('SignUp', () => { expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Fill in missing fields' })).toBeNull(); }); - - it('offers Start over on an instance that verifies email by link', async () => { - const { fapi, user } = await renderSignUp({ - environment: environment({ attributes: { email_address: { required: true, verifications: ['email_link'] } } }), - }); - - await submitStart(user); - - expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); - expect(screen.getByRole('alert')).toHaveTextContent( - 'We couldn’t continue signing you up. Start over to try again.', - ); - expect(fapi.signUp.preparations).toEqual([]); - - await user.click(screen.getByRole('button', { name: 'Start over' })); - - expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); - expect(emailField()).toHaveValue(''); - }); - - it('offers Start over on an instance that verifies email by code or link', async () => { - const { fapi, user } = await renderSignUp({ - environment: environment({ - attributes: { email_address: { required: true, verifications: ['email_code', 'email_link'] } }, - }), - }); - - await submitStart(user); - - expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); - expect(fapi.signUp.preparations).toEqual([]); - }); }); describe('finishing', () => { diff --git a/packages/mosaic/src/features/sign-up/index.ts b/packages/mosaic/src/features/sign-up/index.ts index 400c31c9e5a..e709e9b2e0f 100644 --- a/packages/mosaic/src/features/sign-up/index.ts +++ b/packages/mosaic/src/features/sign-up/index.ts @@ -1,11 +1,13 @@ export { SignUp } from './sign-up'; export type { SignUpProps } from './sign-up'; +export { SignUpEmailLink } from './sign-up-email-link/sign-up-email-link'; export { SignUpProtect } from './sign-up-protect/sign-up-protect'; export { SignUpVerify } from './sign-up-verify/sign-up-verify'; export { SignUpView } from './sign-up.view'; export type { SignUpDetails, SignUpDetailsScreen, + SignUpEmailLinkScreen, SignUpFieldName, SignUpFields, SignUpLegalConsent, diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts new file mode 100644 index 00000000000..f0f9b62b7cc --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts @@ -0,0 +1,45 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { useSignUpEmailLinkController } from '../sign-up-email-link.controller'; + +describe('useSignUpEmailLinkController', () => { + afterEach(() => vi.useRealTimers()); + + it('locks resend for sixty seconds, then stops the current wait, sends a second link and waits again', async () => { + vi.useFakeTimers(); + const send = vi.fn(() => Promise.resolve()); + const cancel = vi.fn(); + const wait = vi.fn(() => ({ outcome: new Promise(() => {}), cancel })); + const { result } = renderHook(() => + useSignUpEmailLinkController({ + link: { target: 'alice@example.com', needsLink: true, send, wait }, + onNext: () => {}, + isPending: false, + }), + ); + await act(async () => vi.advanceTimersByTimeAsync(0)); + expect(send).toHaveBeenCalledTimes(1); + expect(wait).toHaveBeenCalledTimes(1); + expect(result.current.canResend).toBe(false); + + await act(async () => vi.advanceTimersByTimeAsync(59_000)); + expect(result.current.canResend).toBe(false); + act(() => result.current.onResend()); + expect(send).toHaveBeenCalledTimes(1); + + await act(async () => vi.advanceTimersByTimeAsync(1000)); + expect(result.current.canResend).toBe(true); + expect(cancel).not.toHaveBeenCalled(); + + await act(async () => { + result.current.onResend(); + await vi.advanceTimersByTimeAsync(0); + }); + + expect(cancel).toHaveBeenCalledTimes(1); + expect(send).toHaveBeenCalledTimes(2); + expect(wait).toHaveBeenCalledTimes(2); + expect(result.current.canResend).toBe(false); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts new file mode 100644 index 00000000000..5a356c3cc03 --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts @@ -0,0 +1,132 @@ +import { useEffect, useRef } from 'react'; + +import { useResendSeconds } from '../../../hooks/use-resend-seconds'; +import type { ErrorDescription } from '../../../localization'; +import { useErrorText } from '../../../localization'; +import { setup } from '../../../machine/setup'; +import type { DoneInvokeEvent, ErrorInvokeEvent } from '../../../machine/types'; +import { useMachine } from '../../../machine/use-machine'; +import { toLocalizableError } from '../../../utils/errors'; +import { isResendUnlocked, resendUnlockTime } from '../../../utils/verification'; +import type { SignUpCreateResult, SignUpEmailLinkOutcome } from '../sign-up.model'; +import type { SignUpEmailLinkScreen } from '../sign-up.types'; + +const LINK_RESEND_SECONDS = 60; + +interface LinkContext { + sendLink: () => Promise; + waitForLink: () => Promise; + stopWaiting: () => void; + onVerified: (result: SignUpCreateResult) => void; + resendAvailableAt: number | undefined; + error: ErrorDescription | undefined; +} + +type LinkEvent = { type: 'SEND' } | { type: 'ALREADY_SENT' } | { type: 'RESEND' }; + +const link = setup(); + +const startCooldown = link.assign(() => ({ resendAvailableAt: resendUnlockTime(LINK_RESEND_SECONDS) })); + +const fail = link.assign((_, event) => ({ error: toLocalizableError(event.error) })); + +const resend = { + target: 'sending' as const, + guard: (context: LinkContext) => isResendUnlocked(context.resendAvailableAt), + actions: link.assign(() => ({ error: undefined })), +}; + +const linkMachine = link.createMachine({ + id: 'signUpEmailLink', + initial: 'idle', + context: { + sendLink: () => Promise.resolve(), + waitForLink: () => Promise.resolve({ type: 'expired' }), + stopWaiting: () => {}, + onVerified: () => {}, + resendAvailableAt: undefined, + error: undefined, + }, + states: { + idle: { + on: { + SEND: 'sending', + ALREADY_SENT: { target: 'waiting', actions: startCooldown }, + }, + }, + sending: { + invoke: link.fromPromise(context => context.sendLink(), { + onDone: { target: 'waiting', actions: startCooldown }, + onError: { target: 'failed', actions: [fail, startCooldown] }, + }), + }, + waiting: { + on: { RESEND: resend }, + exit: context => context.stopWaiting(), + invoke: link.fromPromise(context => context.waitForLink(), { + onDone: [ + { target: 'expired', guard: (_, event) => event.output.type === 'expired' }, + { + target: 'verified', + actions: (context: LinkContext, event: DoneInvokeEvent) => { + if (event.output.type === 'verified') { + context.onVerified(event.output.result); + } + }, + }, + ], + onError: { target: 'failed', actions: fail }, + }), + }, + expired: { + on: { RESEND: resend }, + }, + failed: { + on: { RESEND: resend }, + }, + verified: {}, + }, +}); + +type SignUpEmailLinkOptions = Pick; + +export function useSignUpEmailLinkController({ + link: { needsLink, send: sendLink, wait }, + onNext, + isPending: isFlowPending, + globalErrorMessage, +}: SignUpEmailLinkOptions) { + const errorText = useErrorText(); + const cancelWait = useRef<() => void>(undefined); + const [snapshot, send] = useMachine(linkMachine, { + context: { + sendLink, + waitForLink: () => { + const waiting = wait(); + cancelWait.current = waiting.cancel; + return waiting.outcome; + }, + stopWaiting: () => cancelWait.current?.(), + onVerified: onNext, + }, + }); + const resendSeconds = useResendSeconds(snapshot.context.resendAvailableAt, LINK_RESEND_SECONDS); + const arrivedNeedingLink = useRef(needsLink); + + useEffect(() => { + send({ type: arrivedNeedingLink.current ? 'SEND' : 'ALREADY_SENT' }); + }, [send]); + + useEffect(() => () => cancelWait.current?.(), []); + + const isPending = isFlowPending || snapshot.value === 'sending' || snapshot.value === 'verified'; + + return { + isPending, + isExpired: snapshot.value === 'expired', + globalErrorMessage: snapshot.context.error ? errorText(snapshot.context.error) : globalErrorMessage, + onResend: () => send({ type: 'RESEND' }), + canResend: snapshot.value !== 'idle' && resendSeconds === 0 && !isPending, + resendRemainingSeconds: resendSeconds || undefined, + }; +} diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx new file mode 100644 index 00000000000..e4fb3e0106f --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx @@ -0,0 +1,31 @@ +import { AuthEmailLink } from '../../../blocks/auth'; +import { verificationResend } from '../../../blocks/verification'; +import { useMessages } from '../../../localization'; +import type { SignUpEmailLinkScreen } from '../sign-up.types'; +import { useSignUpEmailLinkController } from './sign-up-email-link.controller'; + +export function SignUpEmailLink({ onEditIdentifier, ...options }: SignUpEmailLinkScreen) { + const m = useMessages('signUp'); + const { isPending, isExpired, globalErrorMessage, onResend, canResend, resendRemainingSeconds } = + useSignUpEmailLinkController(options); + + 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 ab9e3a5fbaa..833aac4ad59 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; -import type { AuthActionBlockedDetails, AuthProvider } from '../../blocks/auth'; +import type { AuthActionBlockedDetails, AuthEmailLinkStatusValue, AuthProvider } from '../../blocks/auth'; import { usePendingAction } from '../../hooks/use-pending-action'; import type { ErrorDescription } from '../../localization'; import { useErrorText } from '../../localization'; @@ -18,7 +18,13 @@ import { sessionOverride } from '../auth-flow/auth-flow.utils'; import type { SignUpCreateResult, SignUpReadyModel } from './sign-up.model'; import type { SignUpRoute } from './sign-up.routes'; import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRoutes } from './sign-up.routes'; -import type { SignUpProtectScreen, SignUpScreen, SignUpVerifyScreen, SignUpViewProps } from './sign-up.types'; +import type { + SignUpEmailLinkScreen, + SignUpProtectScreen, + SignUpScreen, + SignUpVerifyScreen, + SignUpViewProps, +} from './sign-up.types'; import { useSignUpDetailsController } from './sign-up-details/sign-up-details.controller'; type SignUpArrivalIntent = 'visit' | 'ticket' | 'return' | 'enterpriseSso'; @@ -265,6 +271,7 @@ type SignUpControllerResult = status: 'ready'; attempt?: string; verifyEmail: SignUpVerifyScreen; + verifyEmailLink?: SignUpEmailLinkScreen; verifyPhone: SignUpVerifyScreen; protectCheck: SignUpProtectScreen; }); @@ -320,6 +327,7 @@ export function useSignUpController( }, }); const [blockedDetails, block] = useBlockedOn(route); + const [emailLinkStatus, setEmailLinkStatus] = useState(); const hasLeft = useRef(false); const connectionActions = usePendingAction(); const expiredProtectReloads = useRef(0); @@ -349,7 +357,10 @@ export function useSignUpController( const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const screen = isLoading ? 'loading' - : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined, connections !== undefined)); + : (heldScreen ?? + (emailLinkStatus + ? 'emailLinkStatus' + : screenFor(correctedRoute, model, blockedDetails !== undefined, connections !== undefined))); useRouteGuard({ route, go }, correctedRoute); @@ -358,6 +369,10 @@ export function useSignUpController( block(result.details); return; } + if (result.type === 'email_link_status') { + setEmailLinkStatus(result.status); + return; + } if (result.type === 'complete') { sendActivity({ type: 'FINALIZE', @@ -428,6 +443,7 @@ export function useSignUpController( start: details.start, continue: details.continue, verifyEmail: { ...verify, verification: verification.email }, + verifyEmailLink: verification.emailLink && { ...verify, link: verification.emailLink }, verifyPhone: { ...verify, verification: verification.phone }, protectCheck: { protect: model.protect, @@ -443,6 +459,7 @@ export function useSignUpController( onSignIn: navigation.goToSignIn, }, actionBlocked: blockedDetails, + emailLinkStatus: emailLinkStatus && { status: emailLinkStatus }, enterpriseConnections: connections && { options: connections, pendingConnectionId: connectionActions.pendingKey, diff --git a/packages/mosaic/src/features/sign-up/sign-up.messages.ts b/packages/mosaic/src/features/sign-up/sign-up.messages.ts index 7a5334717a0..a70051871fd 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.messages.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.messages.ts @@ -87,6 +87,7 @@ export const signUpMessages = { verifyEmailLink: { title: 'Verify your email', description: 'Use the verification link sent to your email address', + expired: 'The verification link expired. Please request a new link.', resendText: 'Didn’t receive a link?', resend: 'Resend', resendCountdown: 'Resend ({seconds})', 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 69bd27b17e6..82369dd088e 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -22,6 +22,7 @@ import { import { buildURL } from '@clerk/shared/internal/clerk-js/url'; import { OAUTH_PROVIDERS } from '@clerk/shared/oauth'; import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; +import { Poller } from '@clerk/shared/poller'; import { __internal_useClerkSignal, useClerk, useSession } from '@clerk/shared/react'; import type { ClerkAPIError, @@ -38,7 +39,7 @@ import type { } from '@clerk/shared/types'; import { useMemo, useRef } from 'react'; -import type { AuthActionBlockedDetails, AuthProvider } from '../../blocks/auth'; +import type { AuthActionBlockedDetails, AuthEmailLinkStatusValue, AuthProvider } from '../../blocks/auth'; import type { FieldFeedback, FormFieldErrors } from '../../components/form'; import { FormSubmitError } from '../../components/form'; import { useMosaicEnvironment } from '../../hooks/use-mosaic-environment'; @@ -111,10 +112,30 @@ export interface SignUpEnterpriseConnectionsResult { connections: readonly AuthProvider[]; } +export interface SignUpEmailLinkStatusResult { + type: 'email_link_status'; + status: Exclude; +} + export type SignUpCreateResult = | SignUpNextStep | { type: 'blocked'; details: AuthActionBlockedDetails } - | SignUpEnterpriseConnectionsResult; + | SignUpEnterpriseConnectionsResult + | SignUpEmailLinkStatusResult; + +export type SignUpEmailLinkOutcome = { type: 'expired' } | { type: 'verified'; result: SignUpCreateResult }; + +export interface SignUpEmailLinkWait { + outcome: Promise; + cancel: () => void; +} + +export interface SignUpEmailLinkModel { + target: string; + needsLink: boolean; + send: () => Promise; + wait: () => SignUpEmailLinkWait; +} export interface SignUpDetailsModel { initialIdentifier: SignUpIdentifier; @@ -164,7 +185,7 @@ export interface SignUpReadyModel { app: SignUpAppModel; navigation: SignUpNavigationModel; details: SignUpDetailsModel; - verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel }; + verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel; emailLink?: SignUpEmailLinkModel }; protect: SignUpProtectModel; } @@ -178,6 +199,7 @@ const ABSOLUTE_URL = /^https?:\/\//; const RETURN_PARAM = '__clerk_mosaic_sign_up'; const ENTERPRISE_CONNECTION_REQUIRED = 'enterprise_connection_id_is_required_with_multiple_connections'; const SSO_RETURN = 'sso-callback'; +const EMAIL_LINK_RETURN = 'verify'; const OAUTH_PREFIX = /^oauth_(custom_)?/; const SHOWN_RETURN_ERRORS: readonly string[] = [ ERROR_CODES.NOT_ALLOWED_TO_SIGN_UP, @@ -210,9 +232,9 @@ function transferRoute(signIn: Pick { const step = getSignUpNextStep(resource); - if (step.type === 'verify_email' && verifiesEmailByLink) { - return { type: 'unknown' }; - } return step.type === 'fields' && !continueCanSatisfy(resource, providerIds) ? { type: 'unknown' } : step; }; @@ -459,6 +478,44 @@ export function useSignUpModel({ return next(signUp); }; + const waitForEmailLink = (): SignUpEmailLinkWait => { + const resource = clerk.client?.signUp; + const { run: poll, stop } = Poller(); + let cancelled = false; + const cancel = () => { + cancelled = true; + stop(); + }; + const outcome = new Promise((resolve, reject) => { + void poll(async () => { + if (cancelled) { + stop(); + return; + } + try { + const reloaded = await resource?.reload(); + const verification = reloaded?.verifications.emailAddress; + if (verification?.status === 'expired') { + cancel(); + resolve({ type: 'expired' }); + } else if (reloaded && verification?.status === 'verified') { + cancel(); + resolve({ + type: 'verified', + result: verification.verifiedFromTheSameClient() + ? { type: 'email_link_status', status: 'signed-in-other-tab' } + : next(reloaded.__internal_future), + }); + } + } catch (cause) { + cancel(); + reject(cause instanceof Error ? cause : new Error(String(cause))); + } + }); + }); + return { outcome, cancel }; + }; + const legalConsent = legalConsentRequired ? { termsUrl: displayConfig.termsUrl || undefined, privacyPolicyUrl: displayConfig.privacyPolicyUrl || undefined } : undefined; @@ -515,7 +572,7 @@ export function useSignUpModel({ const result = await signUp.sso({ strategy: 'enterprise_sso', enterpriseConnectionId: connectionId, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, }); const needsConnection = @@ -653,7 +710,7 @@ export function useSignUpModel({ } const result = await target.sso({ strategy, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, unsafeMetadata, legalAccepted: legalAccepted || undefined, @@ -744,6 +801,15 @@ export function useSignUpModel({ send: ({ channel } = {}) => run(() => signUp.verifications.sendPhoneCode({ channel: channel ?? phoneChannel })), verify: code => verify(() => signUp.verifications.verifyPhoneCode({ code })), }, + emailLink: verifiesEmailByLink + ? { + target: signUp.emailAddress ?? '', + needsLink: step.type === 'verify_email' && !step.sent, + send: () => + run(() => signUp.verifications.sendEmailLink({ verificationUrl: callbackUrl(EMAIL_LINK_RETURN) })), + wait: waitForEmailLink, + } + : undefined, }, }; } diff --git a/packages/mosaic/src/features/sign-up/sign-up.tsx b/packages/mosaic/src/features/sign-up/sign-up.tsx index 730ed1ae7d0..0cb5dfb205d 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.tsx @@ -13,6 +13,7 @@ import { useSignUpController } from './sign-up.controller'; import type { SignUpReadyModel } from './sign-up.model'; import { useSignUpModel } from './sign-up.model'; import { SignUpView } from './sign-up.view'; +import { SignUpEmailLink } from './sign-up-email-link/sign-up-email-link'; import { SignUpProtect } from './sign-up-protect/sign-up-protect'; import { SignUpVerify } from './sign-up-verify/sign-up-verify'; @@ -75,7 +76,7 @@ function SignUpFlow({ return null; } - const { status: _status, attempt, verifyEmail, verifyPhone, protectCheck, ...view } = controller; + const { status: _status, attempt, verifyEmail, verifyEmailLink, verifyPhone, protectCheck, ...view } = controller; const { applicationName, applicationLogoUrl } = model.app; const logo = applicationLogoUrl ? { src: applicationLogoUrl, alt: applicationName } : undefined; @@ -83,11 +84,18 @@ function SignUpFlow({ + verifyEmailLink ? ( + + ) : ( + + ) } verifyPhone={ void; isPending: boolean; globalErrorMessage?: string; onEditIdentifier: () => void; - onResend?: () => void; - canResend: boolean; - resendRemainingSeconds?: number; } export interface SignUpEmailLinkStatusScreen { @@ -146,7 +148,6 @@ export interface SignUpViewProps { actionBlocked?: AuthActionBlockedDetails; startOver: SignUpStartOverScreen; alternativePhone?: SignUpAlternativePhoneScreen; - verifyEmailLink?: SignUpEmailLinkScreen; emailLinkStatus?: SignUpEmailLinkStatusScreen; enterpriseConnections?: SignUpEnterpriseConnectionsScreen; wallets?: SignUpWalletsScreen; diff --git a/packages/mosaic/src/features/sign-up/sign-up.view.tsx b/packages/mosaic/src/features/sign-up/sign-up.view.tsx index b93c2c06f5e..5ff296e5bb4 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.view.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.view.tsx @@ -1,14 +1,12 @@ import { AuthActionBlocked, AuthAlternativeChannel, - AuthEmailLink, AuthEmailLinkStatus, AuthEnterpriseConnections, AuthLoading, AuthStartOver, AuthWallets, } from '../../blocks/auth'; -import { verificationResend } from '../../blocks/verification'; import { Card } from '../../components/card'; import { Flow } from '../../components/flow'; import { useMessages } from '../../localization'; @@ -39,7 +37,6 @@ export function SignUpView(props: SignUpViewProps) { actionBlocked, startOver, alternativePhone, - verifyEmailLink, emailLinkStatus, enterpriseConnections, wallets, @@ -139,28 +136,6 @@ export function SignUpView(props: SignUpViewProps) { ) : null} - - {verifyEmailLink ? ( - - ) : null} - - {emailLinkStatus ? ( Promise.resolve(), + wait: () => ({ outcome: new Promise(noop), cancel: noop }), + }, + onNext: noop, + isPending: false, + onEditIdentifier: noop, +}; + type DetailsOverrides = Partial>; type ScreenOverrides = Partial< @@ -351,14 +364,8 @@ export function VerifyPhoneAlternativeChannel() { export function VerifyEmailLink() { return ( } /> ); } From 7b13c89f30a70d5a21f4e6d17aa12d4c7cd44965 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:19:33 -0700 Subject: [PATCH 03/11] feat(mosaic): handle the page a sign-up email link opens --- .../sign-up.email-link.feature.test.tsx | 123 +++++++++++++++++- .../features/sign-up/sign-up.controller.ts | 52 ++++++-- .../src/features/sign-up/sign-up.model.ts | 48 ++++++- 3 files changed, 203 insertions(+), 20 deletions(-) diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index 36b8c3d8a9b..c3cb02965e1 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -3,7 +3,8 @@ import { screen, waitFor } from '@testing-library/react'; import { describe, expect, it, vi } from 'vitest'; import { holdRequests } from '../../../__tests__/feature/fake-fapi'; -import { fapiClient, fapiSignUp, fapiVerification } from '../../../__tests__/feature/fapi'; +import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from '../../../__tests__/feature/fapi'; +import { SignUp } from '../sign-up'; import { EMAIL, emailField, @@ -11,7 +12,10 @@ import { passwordField, renderSignUp, renderSignUpWithRouteProbe, + signedInSession, submitStart, + visitWithQuery, + watchForHeading, } from './sign-up.fixtures'; const POLL = '/v1/client/sign_ups/:id'; @@ -47,6 +51,11 @@ const linkOut = (hasPassword = true) => ({ const linkSent = () => screen.findByRole('button', { name: /^Resend \(\d+\)$/ }); +const returnParams = () => { + const { searchParams } = new URL(window.location.href); + return ['__clerk_mosaic_sign_up', '__clerk_status', '__clerk_created_session'].filter(name => searchParams.has(name)); +}; + describe('SignUp', () => { describe('verifying the email by link', () => { it('sends one link that comes back to this page and shows where it went, on an instance that verifies email by link', async () => { @@ -221,4 +230,116 @@ describe('SignUp', () => { expect(fapi.signUp.reloads).toBe(askedBeforeLeaving); }); }); + + describe('opening the email link', () => { + const newSession = fapiSession({ id: 'sess_new', user: fapiUser({ id: 'user_new' }) }); + + function openLink(status: string | undefined, createdSession?: string) { + const query = new URLSearchParams({ __clerk_mosaic_sign_up: 'verify', redirect_url: '/after' }); + if (status) { + query.set('__clerk_status', status); + } + if (createdSession) { + query.set('__clerk_created_session', createdSession); + } + visitWithQuery(`?${query.toString()}`); + } + + it('activates the session the link created in this browser, leaves once, and forgets the link', async () => { + openLink('verified', newSession.id); + const { navigate, clerk, rerender } = await renderSignUp({ + environment: byLink(), + client: fapiClient([signedInSession, newSession]), + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/after'))); + rerender(); + + expect(clerk.session?.id).toBe(newSession.id); + expect(navigate).toHaveBeenCalledTimes(1); + expect(returnParams()).toEqual([]); + expect(new URL(window.location.href).searchParams.get('redirect_url')).toBe('/after'); + }); + + it('leaves once for a visitor the link signed in, in single-session mode', async () => { + openLink('verified', newSession.id); + const sawForm = watchForHeading('Create your account'); + const { navigate, clerk, rerender } = await renderSignUp({ + environment: environment({ auth_config: { single_session_mode: true } }), + client: fapiClient([newSession]), + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/after'))); + rerender(); + + expect(clerk.session?.id).toBe(newSession.id); + expect(navigate).toHaveBeenCalledTimes(1); + expect(sawForm()).toBe(false); + }); + + it('says the sign-up is done and points back to the original tab when the session belongs to another browser', async () => { + openLink('verified', 'sess_elsewhere'); + const { navigate } = await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: 'Successfully signed up' })).toBeInTheDocument(); + expect(screen.getByText('Return to original tab to continue')).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(returnParams()).toEqual([]); + }); + + it('asks for what is still missing when the link verified the email but created no session', async () => { + openLink('verified'); + const { navigate } = await renderSignUp({ + environment: byLink(), + client: { + ...fapiClient(), + sign_up: signUpWithLink({ status: 'verified', next_action: '', verified_at_client: 'client_1' }, false), + }, + }); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(returnParams()).toEqual([]); + }); + + it('points back to the other tab when the link verified the email and this browser holds no sign-up', async () => { + openLink('verified'); + await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + }); + + it.each([ + ['expired', 'This verification link has expired'], + ['client_mismatch', 'Verification link is invalid for this device'], + ['transferable', 'Email verified'], + ['failed', 'This verification link is invalid'], + ['bogus', 'This verification link is invalid'], + [undefined, 'This verification link is invalid'], + ])('shows what happened to a link that comes back %s', async (status, title) => { + openLink(status); + const { fapi, rerender } = await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: title })).toBeInTheDocument(); + expect(screen.getByText('You may close this tab')).toBeInTheDocument(); + expect(returnParams()).toEqual([]); + + rerender(); + + expect(screen.getByRole('heading', { name: title })).toBeInTheDocument(); + expect(fapi.signUp.creations).toHaveLength(0); + }); + + it('shows what happened to the link to a visitor who is signed in, without leaving', async () => { + openLink('expired'); + const { navigate } = await renderSignUp({ + environment: environment({ auth_config: { single_session_mode: true } }), + client: fapiClient([signedInSession]), + }); + + expect(await screen.findByRole('heading', { name: 'This verification link has expired' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + }); + }); }); 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 833aac4ad59..331e588b382 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -1,7 +1,7 @@ import { useEffect, useRef, useState } from 'react'; import { flushSync } from 'react-dom'; -import type { AuthActionBlockedDetails, AuthEmailLinkStatusValue, AuthProvider } from '../../blocks/auth'; +import type { AuthActionBlockedDetails, AuthProvider } from '../../blocks/auth'; import { usePendingAction } from '../../hooks/use-pending-action'; import type { ErrorDescription } from '../../localization'; import { useErrorText } from '../../localization'; @@ -20,6 +20,7 @@ import type { SignUpRoute } from './sign-up.routes'; import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRoutes } from './sign-up.routes'; import type { SignUpEmailLinkScreen, + SignUpEmailLinkStatusScreen, SignUpProtectScreen, SignUpScreen, SignUpVerifyScreen, @@ -40,6 +41,7 @@ interface ActivityContext { frozenModel: SignUpReadyModel | null; activate: (() => Promise) | undefined; frozenScreen: 'loading' | undefined; + sessionId: string | undefined; error: ErrorDescription | undefined; onFinalized: (() => void) | undefined; } @@ -48,6 +50,8 @@ type FinalizeStart = { type: 'FINALIZE'; frozenModel: SignUpReadyModel; activate: () => Promise; + frozenScreen?: 'loading'; + sessionId?: string; onFinalized: () => void; }; @@ -70,7 +74,8 @@ const finalizeShowing = (frozenScreen: 'loading' | undefined) => ({ actions: activity.assign((_, event) => ({ frozenModel: event.frozenModel, activate: event.activate, - frozenScreen, + frozenScreen: event.frozenScreen ?? frozenScreen, + sessionId: event.sessionId, onFinalized: event.onFinalized, error: undefined, })), @@ -126,6 +131,7 @@ const activityMachine = activity.createMachine({ frozenModel: null, activate: undefined, frozenScreen: undefined, + sessionId: undefined, error: undefined, onFinalized: undefined, }, @@ -214,9 +220,15 @@ const FINALIZE_STATUS = { function screenFor( route: SignUpRoute | undefined, { attempt, instance }: SignUpReadyModel, - isBlocked: boolean, - hasConnections: boolean, + { + isBlocked, + hasConnections, + hasEmailLinkStatus, + }: { isBlocked: boolean; hasConnections: boolean; hasEmailLinkStatus: boolean }, ): SignUpScreen { + if (hasEmailLinkStatus) { + return 'emailLinkStatus'; + } if (route === undefined || (route === 'enterpriseConnections' && !hasConnections)) { return 'startOver'; } @@ -244,7 +256,7 @@ function arrivalIntentFor( override: AuthSessionOverride, correctedRoute: SignUpRoute | undefined, ): SignUpArrivalIntent { - if (model.attempt.hasPendingReturn) { + if (model.attempt.pendingReturn !== undefined) { return 'return'; } if (override.type === 'none' && correctedRoute === 'enterpriseConnections') { @@ -290,7 +302,7 @@ export function useSignUpController( isSignedOutOnly: isSignedOutOnlyRoute(route), }; const [arrival] = useState(() => { - const session = liveModel.session.type; + const session = liveModel.attempt.pendingReturn === 'email_link' ? 'none' : liveModel.session.type; const override = sessionOverride({ ...facts, sessionOnArrival: session, finalizeStatus: 'idle' }); return { session, @@ -327,7 +339,7 @@ export function useSignUpController( }, }); const [blockedDetails, block] = useBlockedOn(route); - const [emailLinkStatus, setEmailLinkStatus] = useState(); + const [emailLinkStatus, setEmailLinkStatus] = useState(); const hasLeft = useRef(false); const connectionActions = usePendingAction(); const expiredProtectReloads = useRef(0); @@ -358,9 +370,11 @@ export function useSignUpController( const screen = isLoading ? 'loading' : (heldScreen ?? - (emailLinkStatus - ? 'emailLinkStatus' - : screenFor(correctedRoute, model, blockedDetails !== undefined, connections !== undefined))); + screenFor(correctedRoute, model, { + isBlocked: blockedDetails !== undefined, + hasConnections: connections !== undefined, + hasEmailLinkStatus: emailLinkStatus !== undefined, + })); useRouteGuard({ route, go }, correctedRoute); @@ -370,7 +384,7 @@ export function useSignUpController( return; } if (result.type === 'email_link_status') { - setEmailLinkStatus(result.status); + setEmailLinkStatus({ status: result.status }); return; } if (result.type === 'complete') { @@ -382,6 +396,18 @@ export function useSignUpController( }); return; } + if (result.type === 'session') { + const { sessionId } = result; + sendActivity({ + type: 'FINALIZE', + frozenModel: model, + activate: () => model.attempt.finalize(sessionId), + frozenScreen: 'loading', + sessionId, + onFinalized: details.clear, + }); + return; + } if (result.type === 'transfer') { sendActivity({ type: 'COMPLETE_RETURN' }); return; @@ -431,7 +457,7 @@ export function useSignUpController( }, }; - if (isLeaving || override.type === 'done') { + if (isLeaving || (override.type === 'done' && emailLinkStatus === undefined)) { return { status: 'hidden' }; } @@ -459,7 +485,7 @@ export function useSignUpController( onSignIn: navigation.goToSignIn, }, actionBlocked: blockedDetails, - emailLinkStatus: emailLinkStatus && { status: emailLinkStatus }, + emailLinkStatus, enterpriseConnections: connections && { options: connections, pendingConnectionId: connectionActions.pendingKey, 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 82369dd088e..fb988b2abce 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -82,9 +82,9 @@ export interface SignUpAttemptModel { ticket: string | undefined; redeemTicket: () => Promise<{ result: SignUpCreateResult; emailAddress: string }>; startEnterpriseSso: (connectionId?: string) => Promise; - hasPendingReturn: boolean; + pendingReturn: 'sso' | 'email_link' | undefined; completeReturn: () => Promise; - finalize: () => Promise; + finalize: (sessionId?: string) => Promise; reset: () => Promise; } @@ -121,7 +121,8 @@ export type SignUpCreateResult = | SignUpNextStep | { type: 'blocked'; details: AuthActionBlockedDetails } | SignUpEnterpriseConnectionsResult - | SignUpEmailLinkStatusResult; + | SignUpEmailLinkStatusResult + | { type: 'session'; sessionId: string }; export type SignUpEmailLinkOutcome = { type: 'expired' } | { type: 'verified'; result: SignUpCreateResult }; @@ -200,6 +201,15 @@ const RETURN_PARAM = '__clerk_mosaic_sign_up'; const ENTERPRISE_CONNECTION_REQUIRED = 'enterprise_connection_id_is_required_with_multiple_connections'; const SSO_RETURN = 'sso-callback'; const EMAIL_LINK_RETURN = 'verify'; +const RETURNS: Partial> = { + [SSO_RETURN]: 'sso', + [EMAIL_LINK_RETURN]: 'email_link', +}; +const EMAIL_LINK_STATUSES: Partial> = { + expired: 'expired', + client_mismatch: 'client-mismatch', + transferable: 'transferable', +}; const OAUTH_PREFIX = /^oauth_(custom_)?/; const SHOWN_RETURN_ERRORS: readonly string[] = [ ERROR_CODES.NOT_ALLOWED_TO_SIGN_UP, @@ -332,6 +342,7 @@ export function useSignUpModel({ const errorText = useErrorText(); const query = router.getSearchParams(); const returnUrl = query.get('redirect_url') ?? undefined; + const returning = RETURNS[query.get(RETURN_PARAM) ?? '']; const afterSignUpUrl = clerk.buildAfterSignUpUrl({ params: query }); const afterSignInUrl = clerk.buildAfterSignInUrl({ params: query }); const signInUrl = () => clerk.buildSignInUrl(returnUrl ? { redirectUrl: returnUrl } : undefined); @@ -516,6 +527,23 @@ export function useSignUpModel({ return { outcome, cancel }; }; + const completeEmailLinkReturn = (): SignUpCreateResult => { + const status = getClerkQueryParam('__clerk_status'); + const createdSessionId = getClerkQueryParam('__clerk_created_session'); + removeClerkQueryParam('__clerk_status'); + removeClerkQueryParam('__clerk_created_session'); + if (status !== 'verified') { + return { type: 'email_link_status', status: EMAIL_LINK_STATUSES[status ?? ''] ?? 'failed' }; + } + if (createdSessionId) { + return clerk.client?.sessions.some(({ id }) => id === createdSessionId) + ? { type: 'session', sessionId: createdSessionId } + : { type: 'email_link_status', status: 'signed-in' }; + } + const returned = next(signUp); + return returned.type === 'start' ? { type: 'email_link_status', status: 'signed-in-other-tab' } : returned; + }; + const legalConsent = legalConsentRequired ? { termsUrl: displayConfig.termsUrl || undefined, privacyPolicyUrl: displayConfig.privacyPolicyUrl || undefined } : undefined; @@ -597,9 +625,12 @@ export function useSignUpModel({ } return undefined; }, - hasPendingReturn: query.get(RETURN_PARAM) === SSO_RETURN, + pendingReturn: returning, completeReturn: async () => { forgetReturn(); + if (returning === 'email_link') { + return completeEmailLinkReturn(); + } const returned = next(signUp); if (returned.type === 'protect') { return returned; @@ -639,9 +670,14 @@ export function useSignUpModel({ } return returned; }, - finalize: async () => { + finalize: async sessionId => { forgetTicket(); - await run(() => signUp.finalize({ navigate: navigateAfter(afterSignUpUrl, { keepsTaskInFlow: true }) })); + const navigate = navigateAfter(afterSignUpUrl, { keepsTaskInFlow: true }); + if (sessionId) { + await clerk.setActive({ session: sessionId, navigate }); + return; + } + await run(() => signUp.finalize({ navigate })); }, reset: () => { forgetTicket(); From 8b35246df4b18b66c8273ca5583f91dd4fe71cdf Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:20:50 -0700 Subject: [PATCH 04/11] docs(mosaic): describe how sign-up verifies an email by link --- .../docs/internals/sign-in-sign-up-flow.md | 27 ++++++++++++++----- 1 file changed, 20 insertions(+), 7 deletions(-) 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 3d9c19ad2a4..b0067ded035 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -8,7 +8,7 @@ FAPI tracks which requirements are outstanding and whether a code has been sent. Today FAPI sends `status`, `missing_fields` and `unverified_fields`, not a step. Until it sends `nextStep`, `getSignInNextStep` and `getSignUpNextStep` in `shared` compute it from those fields (see [Bridge](#bridge)). -Sign-up's `continue` screen asks for what FAPI lists in `missing_fields`, not for what the instance's settings would require, so the client never re-derives a rule FAPI already applied (`continueFields` in `mosaic/src/features/sign-up/sign-up.utils.ts`). A missing email, phone or username that FAPI also lists in `optional_fields` is a choice, so the form asks for one of them, with the email/phone switch when both are allowed. An email or phone FAPI lists in `unverified_fields` stays on the form, prefilled, so Edit on a verify screen reached from `continue` has an address to change. FAPI drops the old verification whenever an update sends the address, changed or not, so the verify screen sends a new code. Requirements another step owns, such as `enterprise_sso`, don't appear. A missing `oauth_*` provider shows that provider's button, and only the missing ones, since another provider can't satisfy it; the user links the rest from their profile. When FAPI lists a requirement `continue` can't ask for, such as a provider that can't sign the user in, the step is `unknown` and the user sees Start over instead of a form that can't finish. A sign-up that must verify its email on an instance that enables the email link is `unknown` too, until the link screen is built; `ui` shows its link card there (`ui/src/components/SignUp/SignUpVerifyEmail.tsx`). `start` has no sign-up yet, so it reads the instance's settings. +Sign-up's `continue` screen asks for what FAPI lists in `missing_fields`, not for what the instance's settings would require, so the client never re-derives a rule FAPI already applied (`continueFields` in `mosaic/src/features/sign-up/sign-up.utils.ts`). A missing email, phone or username that FAPI also lists in `optional_fields` is a choice, so the form asks for one of them, with the email/phone switch when both are allowed. An email or phone FAPI lists in `unverified_fields` stays on the form, prefilled, so Edit on a verify screen reached from `continue` has an address to change. FAPI drops the old verification whenever an update sends the address, changed or not, so the verify screen sends a new code. Requirements another step owns, such as `enterprise_sso`, don't appear. A missing `oauth_*` provider shows that provider's button, and only the missing ones, since another provider can't satisfy it; the user links the rest from their profile. When FAPI lists a requirement `continue` can't ask for, such as a provider that can't sign the user in, the step is `unknown` and the user sees Start over instead of a form that can't finish. `start` has no sign-up yet, so it reads the instance's settings. There is no step machine and no local copy of the step. What the step can't say lives in the route, such as the factor the user picked in `factorOne`'s `:factor` param, or whether a sign-up verify screen was reached from `continue`. @@ -37,6 +37,10 @@ Sign-up renders one component per screen, so the route decides what is mounted ( - Each screen has a folder that takes its group of the model (`sign-up-details/`, `sign-up-verify/`, `sign-up-restricted/`), as [Features → A flow with several screens](../features.md#a-flow-with-several-screens) describes. - 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. +- On an instance whose email address lists `email_link` in its verifications, the wrapper fills the `verifyEmail` slot with `SignUpEmailLink` (`sign-up-email-link/`) instead of the code screen, with the same `key`. The link wins when the code is enabled too, and there is no way back to the code, as in `ui` (`ui/src/components/SignUp/SignUpVerifyEmail.tsx`). The model returns the `verification.emailLink` group only on such an instance, so its presence picks the screen. +- `SignUpEmailLink` holds the link machine. Its states are `idle`, `sending`, `waiting`, `expired`, `failed` and `verified`. It decides once, when it mounts: a step with `sent: false` sends the link, then waits; a step with `sent: true` only waits, so a reload or a second visit never sends again. FAPI limits how often it sends to one address, so a send the user did not ask for costs them a real one. An expired link turns `sent` back to `false` while the screen is up, and the machine ignores that: it shows the expiry and waits for Resend. Resend unlocks 60 seconds after a send or an arrival, stops the current wait, sends, and waits again. A resend inside the link's ten minutes reuses the link and does not extend it. +- The wait is the model's `emailLink.wait()`, which returns the outcome and a `cancel`. It reloads the client's sign-up once a second through `Poller` (`shared/src/poller.ts`), whose timers run in a worker so a background tab keeps asking. `SignUpFuture.verifications.waitForEmailLinkVerification()` is not used: it cannot be cancelled, and it resolves the same way for a verified and an expired link. The machine cancels the wait when it leaves `waiting`, and the screen cancels it when it unmounts, so Edit, a route change and a remount all stop the requests. `cancel` also marks the wait as cancelled, and the next tick checks that mark before it reloads. `Poller.stop()` alone does not stop a poller that is waiting for its second tick: the first worker timer has id `0`, which `stop()` reads as no timer, and the next `run` clears the stopped flag. +- The wait ends in one of three ways. An expired link moves the machine to `expired`. A link opened in another browser returns the sign-up's next step, read from the sign-up the reload returned, and the screen passes it to `next`: a complete sign-up finishes in this tab, since FAPI creates the session on the client that started the sign-up. A link opened in this browser (`verifiedFromTheSameClient()` on the verification, which compares `verified_at_client` with this client) returns `email_link_status` with `signed-in-other-tab`: the tab the link opened is the one that signs in, so this tab only says so, as `ui`'s `SignUpEmailLinkCard` does. - 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`, `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. `enterpriseConnections` shows its own screen, the connection chooser, only while the controller holds a list of connections. Otherwise an entry that lands on it shows `loading` while the redirect to the IdP starts, and `startOver` once that attempt is over ([Entry actions](#entry-actions)). - 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. @@ -58,6 +62,8 @@ submitPassword: async (password: string) => { - `complete`: the model's `finalize()`, then leave the flow for the after sign-up URL, which honors `redirect_url` and the redirect query params (`clerk.buildAfterSignUpUrl({ params })`). Creating the session clears the sign-up. Sign-up renders the model it left from while `finalize()` runs, and after it until a task that continues in the flow has its data loaded, so the task replaces the screen with no skeleton between them. It keeps the action pending throughout, the way the switcher holds its `frozenModel` ([Controllers → Wrapping actions](../controllers.md#wrapping-actions)). Once the hold ends with the session signed in, the flow is over: if the host keeps the component mounted, it renders nothing. In a modal, don't `close()` when the flow leaves: `finalize()`'s navigation is the last write and takes the modal with it. - `transfer`: sign-up transfers only an OAuth account that already has a user. The OAuth return transfers it before a step reaches `next` ([Entry actions](#entry-actions)), unless a Protect check comes first. Then the Protect screen passes `transfer` to `next`, which runs the return's completion again and shows the loading screen while it does. Sign-in's transfer is planned: the model's `transfer()` will call `signUp.create({ transfer: true, unsafeMetadata })`, then `next` with the sign-up's step; a sign-in with sign-up built in holds the sign-up routes under `create/`, otherwise it leaves for the sign-up page. - `unknown`: nothing. The screen already shows "Start over". +- `email_link_status`: the link screen's wait and the email-link return resolve with it, not a step, when all that is left is to tell the user what happened to the link. The controller keeps the status for this mount and `emailLinkStatus` replaces whatever screen the route would show. It stays up whatever the session is, so a signed-in visitor sees it too, as on `ui`'s `verify` route, which has no signed-in guard. +- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. - `blocked`: sign-up's `create`, the Protect proof's `resolve` and the invitation's `redeemTicket` resolve with it, not a step, when FAPI answers `action_blocked`. The OAuth return's `completeReturn` resolves with it when FAPI stored that error on the external account, and `sso` resolves with it from `start`. From `continue`, `sso` rejects and the error shows inline, as `update`'s does. The controller keeps the details for this mount and shows the notice in place of `start` or the Protect route. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does. - Anything else: `go(routeFor(step))`. - An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. @@ -80,7 +86,7 @@ Sign-up: - `start` → `start` - `protect` → `protectCheck`, or `continueProtectCheck` when reached from `continue`, where `SignUpProtect` runs the challenge through shared `runProtectCheck` when it mounts. It takes the challenge token as its `key`, so a chained or reissued challenge remounts it and runs again. The controller keeps the expired-reload count above it, so the cap holds across those remounts. A blocked proof shows `actionBlocked`. A check that completes the sign-up keeps the screen busy while `finalize()` runs. After a failed `finalize()` no challenge is left, so Try again runs `finalize()` again. The host must not load the legacy Clerk UI (`prefetchUI={false}` on the provider), because clerk-js otherwise opens its own Protect modal for the same check and this screen never renders (`__internal_openProtectCheckModal` in `clerk-js/src/core/clerk.ts`, called from `clerk-js/src/core/protectCheckGate.ts`) - `enterprise_sso` → the IdP. A submit on `start` or `continue` stays on its route and starts the redirect from the form. Every other entry goes to `enterpriseConnections`, which starts it on arrival ([Entry actions](#entry-actions)). When the domain has several connections, both paths end on `enterpriseConnections` with the chooser -- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue` +- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue`. The route shows the code screen, or the link screen on an instance that enables the email link ([Mount the screen](#mount-the-screen)) - `verify_phone` (`target`, `sent`) → `verifyPhone`, or `continueVerifyPhone` when reached from `continue` - `fields` (`fields`) → `continue` @@ -106,12 +112,12 @@ With no `:factor`, `factorOne` starts on the factor `ui`'s `determineStartingSig - FAPI's state changes only on submit. A route the step doesn't allow is replaced with the step's route. - Back to `start` shows the identifier form; submitting it creates a new sign-in. Forward to `factorOne` still works. -- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up verify route sends a code only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. +- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up verify route sends a code or a link only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. `ui`'s link card sends a new link on every mount; sign-up does not. - Virtual routing has no history: a remount starts at `start`, and FAPI's state is kept. ## Entry actions -Sign-up redeems invitation tickets, starts enterprise SSO redirects and completes OAuth returns. The other entries are planned. The controller records why the visitor arrived when sign-up opens (`arrival.intent`), and that intent picks the activity machine's first state. Each entry is that state's `invoke`, which calls the model callback and then `next(step)`, so it runs once. +Sign-up redeems invitation tickets, starts enterprise SSO redirects, and completes OAuth and email-link returns. The other entries are planned. The controller records why the visitor arrived when sign-up opens (`arrival.intent`), and that intent picks the activity machine's first state. Each entry is that state's `invoke`, which calls the model callback and then `next(step)`, so it runs once. - Ticket: - Read and redeem once. Sign-up reads the ticket from `__clerk_ticket` or `__clerk_invitation_token`, as `ui`'s `SignUpStart` does, redeems it with `signUp.ticket({ unsafeMetadata })`, and shows the loading screen while it redeems. Sign-up redeems when it opens on `start`, or when the route guard sends it there. A ticket works only once, and the machine's `redeemingTicket` state runs the redemption once, so StrictMode can't redeem it twice. A failed redemption shows its error on `start` and removes the parameters, so `start` then works as a normal sign-up. A blocked redemption removes them too and shows `actionBlocked`. @@ -123,8 +129,15 @@ Sign-up redeems invitation tickets, starts enterprise SSO redirects and complete - From the `start` and `continue` forms. When the submit returns `enterprise_sso`, `useSignUpDetailsController` starts the redirect inside the form's own submit and keeps it pending for `REDIRECT_HOLD_MS`, as the social buttons do, then resolves without a step so `next` never runs. Both routes are allowed while the step is `enterprise_sso`, so the route stays and the form stays busy, as `ui`'s does. A failed start shows in the form's banner. If the browser is still on the page after the hold, the form is usable again, and Continue starts the redirect again: `start` with a new sign-up, `continue` on the same one. A sign-up that opens on `continue` with the step already `enterprise_sso` shows that form and waits for Continue. - On arrival. A ticket, a code, a Protect check and a return have no form to hold, so `next` sends them to `enterpriseConnections`. `next` also sends `START_ENTERPRISE_SSO`, and a visit that opens on that route starts there, so the activity machine's `startingEnterpriseSso` state shows the loading screen and runs `startEnterpriseSso` once per mount. `startOver` shows when the start failed, with its error, or when the browser is still on the page after the hold. - Several connections. FAPI answers the first start with `enterprise_connection_id_is_required_with_multiple_connections`. The model then lists the connections and resolves with `enterprise_connections` instead of throwing, as `create` resolves with `blocked`. `SignUpFuture` has no list call, so the model reads `__experimental_getEnterpriseConnections()` from the legacy resource. A list that fails, or comes back empty, rejects: the form shows the reason in its banner, and an arrival shows `startOver`. `next` keeps the list in the controller for this mount and goes to `enterpriseConnections`, which shows the chooser while that list is set and does not start a redirect of its own. Picking a connection calls `startEnterpriseSso(id)` under its own pending action, so the picked button is busy and the others are disabled for `REDIRECT_HOLD_MS`, and a failed start shows on the chooser. Back drops the list and returns to `start` with the form as the user left it. A connection with no logo gets an empty `iconUrl`, as a custom OAuth provider does. -- Email-link return (`__clerk_status`): `verified` with a `__clerk_created_session` this client has activates that session (`clerk-js/src/core/clerk.ts:2620-2636`); any other `verified` continues by step. `transferable` and the error statuses show their own screen, as `ui/src/common/EmailLinkVerify.tsx` does. -- Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now the OAuth return builds its callback URL by hand with a marker, described in the next entry. The marker moves to `useReturnUrl()` when that hook lands. +- Email-link return: the link's redirect URL is the current URL plus the marker `__clerk_mosaic_sign_up=verify`, built the way the OAuth callback URL is (next entry), so there is no `verify` route. FAPI redirects the opened link there and adds `__clerk_status`, and `__clerk_created_session` when verifying completed the sign-up. When sign-up opens with the marker, on any route, the arrival intent is `return`, and the activity machine's `completingReturn` state runs `completeReturn` once, exactly as for an OAuth return. The model's `attempt.pendingReturn` says which of the two it is. `completeReturn` removes the marker and both Clerk parameters, then answers by status, following `clerk.handleEmailLinkVerification` (`clerk-js/src/core/clerk.ts`) and `ui/src/common/EmailLinkVerify.tsx`: + - `verified` with a `__clerk_created_session` this client holds: `session`, so the flow activates it and leaves for the after sign-up URL or its task ([Move on after a submit](#move-on-after-a-submit)). + - `verified` with a session this client does not hold: `email_link_status` with `signed-in`. The link was opened in another browser, and the tab that started the sign-up finishes it. + - `verified` with no session: the sign-up still needs something, so the return answers with the sign-up's step and `next` carries on in this tab. `ui` moves on only for a Protect check, enterprise SSO or a phone to verify, and otherwise leaves its switch-tab card up, which strands a sign-up that is missing a field. When this client holds no sign-up, the step would be `start`, an empty form in a browser that never started one, so the return answers `email_link_status` with `signed-in-other-tab` instead. + - `expired`, `client_mismatch` and `transferable`: `email_link_status` with the matching status. `failed`, a missing status and any other value show `failed`. + + A page opened from the link does not count as arriving signed in. In single-session mode the session the link created is already Clerk's session when the page loads, and the arrival rule would leave for the after sign-up URL before the link's result showed, or leave a second time after the session is activated. The controller records the arrival session as `none` for such a page, so the link's result decides. + +- Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now both returns build their URL by hand with a marker. The marker moves to `useReturnUrl()` when that hook lands. - OAuth return: sign-up's callback URL is the current URL plus the marker `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. It keeps the rest of the query, so `redirect_url` and an invitation's ticket come back with the user. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: - A Protect check comes first. Once it is solved, `next` gets the step that follows, so a transfer after it still runs. - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. @@ -136,7 +149,7 @@ Sign-up redeems invitation tickets, starts enterprise SSO redirects and complete The marker is gone once the return starts, so a reload mid-return lands on `start`. OAuth is a full-page redirect only. Sign-up never passes `sso()` a `popup`, so popup OAuth (`oauthFlow: 'popup'`) is not built. An OAuth transport (`__internal_oauthTransport`) is not supported yet. `SignUpFuture.sso()` still navigates the window, so clerk-js has to honor the transport first. Sign-in-to-sign-up transfers start from sign-in, so they wait for its controller. - `signUp.sso()` updates any sign-up already on the client, so `start` resets a sign-up that isn't the invitation's and calls `sso()` on the client's new sign-up, since the old `SignUpFuture` still points at the reset one; `continue` keeps it. On an instance with no form identifier, where `showFormFields` is false, `start` shows only the providers, without fields or the consent checkbox, as legacy does; consent then comes on `continue`. `continue` hides the providers once the sign-up has a verified external account. -- A step that is already `complete` or `transfer` on mount, such as a reload before it ran, is not handled yet: `routeFor` has no route for `transfer`, and nothing runs `complete` when sign-up mounts. The email-link return will be handled first. +- A step that is already `complete` or `transfer` on mount, such as a reload before it ran, is not handled yet: `routeFor` has no route for `transfer`, and nothing runs `complete` when sign-up mounts. - Hash params: Clerk's URL builders (`redirectToSignUp()`, `buildSignUpUrl`) put the redirect params and initial values in the URL hash, and sign-up reads only the query, so they are not read yet. ## Bridge From 1e048b2d7d4e8a206abf05aaf248d31748d9fe99 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:20:51 -0700 Subject: [PATCH 05/11] chore(repo): add an empty changeset for the sign-up email link --- .changeset/mosaic-sign-up-email-link.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changeset/mosaic-sign-up-email-link.md diff --git a/.changeset/mosaic-sign-up-email-link.md b/.changeset/mosaic-sign-up-email-link.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-sign-up-email-link.md @@ -0,0 +1,2 @@ +--- +--- From 73796bd60884217133ff8c6f145da3571918c12f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 16:07:55 -0700 Subject: [PATCH 06/11] test(mosaic): hold every email link check and control its timer in the sign-up tests --- .../sign-up.email-link.feature.test.tsx | 175 ++++++++++++++---- 1 file changed, 137 insertions(+), 38 deletions(-) diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index c3cb02965e1..af8e8774cc5 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -1,14 +1,17 @@ import type { SignUpVerificationJSON } from '@clerk/shared/types'; -import { screen, waitFor } from '@testing-library/react'; -import { describe, expect, it, vi } from 'vitest'; +import { act, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { holdRequests } from '../../../__tests__/feature/fake-fapi'; +import { holdRequests, worker } from '../../../__tests__/feature/fake-fapi'; import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from '../../../__tests__/feature/fapi'; import { SignUp } from '../sign-up'; import { + continueButton, EMAIL, emailField, environment, + PASSWORD, passwordField, renderSignUp, renderSignUpWithRouteProbe, @@ -18,11 +21,12 @@ import { watchForHeading, } from './sign-up.fixtures'; -const POLL = '/v1/client/sign_ups/:id'; +const CHECK = '/v1/client/sign_ups/:id'; +const CHECK_PATH = /^\/v1\/client\/sign_ups\/([^/]+)$/; const SEND = '/v1/client/sign_ups/:id/prepare_verification'; const LINK_URL = `${window.location.origin}/?__clerk_mosaic_sign_up=verify`; const EXPIRED = 'The verification link expired. Please request a new link.'; -const POLL_INTERVAL_MS = 1000; +const RESEND_COOLDOWN_MS = 60_000; const byLink = (verifications = ['email_link']) => environment({ attributes: { email_address: { required: true, verifications } } }); @@ -51,15 +55,89 @@ const linkOut = (hasPassword = true) => ({ const linkSent = () => screen.findByRole('button', { name: /^Resend \(\d+\)$/ }); +const checkedSignUp = (request: Request) => CHECK_PATH.exec(new URL(request.url).pathname)?.[1]; + +function holdChecks() { + const hold = holdRequests('get', CHECK); + return { ...hold, signUps: () => hold.requests.map(checkedSignUp), abandon: () => hold.fail() }; +} + +const checksInFlight = new Set(); + +function trackCheck({ request, requestId }: { request: Request; requestId: string }) { + if (request.method === 'GET' && checkedSignUp(request)) { + checksInFlight.add(requestId); + } +} + +function untrackCheck({ requestId }: { requestId: string }) { + checksInFlight.delete(requestId); +} + +interface DueCheck { + timers: EventTarget; + id: number; +} + +const dueChecks: DueCheck[] = []; + +function forgetDueChecks(isForgotten: (check: DueCheck) => boolean) { + dueChecks.splice(0, dueChecks.length, ...dueChecks.filter(check => !isForgotten(check))); +} + +class ControlledTimers extends EventTarget { + postMessage({ type, id }: { type: string; id: number }) { + if (type === 'setTimeout') { + dueChecks.push({ timers: this, id }); + } + if (type === 'clearTimeout') { + forgetDueChecks(check => check.timers === this && check.id === id); + } + } + + terminate() { + forgetDueChecks(check => check.timers === this); + } +} + +function runDueChecks() { + for (const { timers, id } of dueChecks.splice(0)) { + timers.dispatchEvent(new MessageEvent('message', { data: { id } })); + } +} + const returnParams = () => { const { searchParams } = new URL(window.location.href); return ['__clerk_mosaic_sign_up', '__clerk_status', '__clerk_created_session'].filter(name => searchParams.has(name)); }; describe('SignUp', () => { + beforeAll(() => { + worker.events.on('request:start', trackCheck); + worker.events.on('request:end', untrackCheck); + }); + + afterAll(() => { + worker.events.removeListener('request:start', trackCheck); + worker.events.removeListener('request:end', untrackCheck); + }); + + beforeEach(() => { + dueChecks.length = 0; + vi.stubGlobal('Worker', ControlledTimers); + }); + + afterEach(async () => { + await waitFor(() => expect(checksInFlight.size, 'checks in flight when the test ended').toBe(0)).finally(() => + checksInFlight.clear(), + ); + expect(dueChecks, 'checks still due when the test ended').toHaveLength(0); + }); + describe('verifying the email by link', () => { it('sends one link that comes back to this page and shows where it went, on an instance that verifies email by link', async () => { const { fapi, user } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); await submitStart(user); @@ -72,16 +150,21 @@ describe('SignUp', () => { const redirectUrl = new URL(fapi.signUp.emailLinkRedirectUrl ?? ''); expect(redirectUrl.origin + redirectUrl.pathname).toBe(window.location.origin + window.location.pathname); expect(redirectUrl.searchParams.get('__clerk_mosaic_sign_up')).toBe('verify'); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.abandon(); }); it('sends a link, not a code, on an instance that verifies email by code or link', async () => { const { fapi, user } = await renderSignUp({ environment: byLink(['email_code', 'email_link']) }); + const checks = holdChecks(); await submitStart(user); expect(await linkSent()).toBeDisabled(); expect(screen.queryByRole('textbox', { name: 'Verification code' })).toBeNull(); expect(fapi.signUp.preparations).toEqual(['email_link']); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.abandon(); }); it('keeps Edit disabled until the link is sent, and shows why when it could not be sent', async () => { @@ -102,48 +185,53 @@ describe('SignUp', () => { it('waits without sending again when it opens with a link already out, and finishes once the link is opened', async () => { const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut()); - const hold = holdRequests('get', POLL); + const checks = holdChecks(); await user.click(screen.getByRole('button', { name: 'Open the verify route' })); expect(await linkSent()).toBeDisabled(); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); expect(fapi.signUp.preparations).toEqual([]); fapi.signUp.openEmailLink('client_other'); - hold.release(); + checks.release(); await waitFor(() => expect(navigate).toHaveBeenCalled()); expect(fapi.client.sessions).toHaveLength(1); expect(fapi.signUp.preparations).toEqual([]); }); - it('signs in and leaves for the after sign-up URL when the link is opened in another browser', async () => { + it('keeps asking until the link is opened in another browser, then signs in and leaves for the after sign-up URL', async () => { const { fapi, user, navigate, clerk } = await renderSignUp( { environment: byLink() }, {}, { signUpFallbackRedirectUrl: '/welcome' }, ); - const hold = holdRequests('get', POLL); + const checks = holdChecks(); await submitStart(user); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.release(); + await waitFor(() => expect(dueChecks).toHaveLength(1)); + expect(navigate).not.toHaveBeenCalled(); + fapi.signUp.openEmailLink('client_other'); - hold.release(); + runDueChecks(); await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/welcome'))); + expect(checks.requests).toHaveLength(2); expect(fapi.client.sessions).toHaveLength(1); expect(clerk.session?.id).toBe(fapi.client.sessions[0].id); }); it('asks for what is still missing when the link is opened in another browser before the sign-up is complete', async () => { const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut(false)); - const hold = holdRequests('get', POLL); + const checks = holdChecks(); await user.click(screen.getByRole('button', { name: 'Open the verify route' })); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); fapi.signUp.openEmailLink('client_other'); - hold.release(); + checks.release(); expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); expect(navigate).not.toHaveBeenCalled(); @@ -151,12 +239,12 @@ describe('SignUp', () => { it('tells the user to go to the other tab when the link is opened in this browser, and signs nobody in here', async () => { const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); - const hold = holdRequests('get', POLL); + const checks = holdChecks(); await submitStart(user); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); fapi.signUp.openEmailLink(); - hold.release(); + checks.release(); expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); @@ -167,27 +255,30 @@ describe('SignUp', () => { }); it('says the link expired without sending another, then sends a new one on Resend', async () => { - vi.useFakeTimers({ toFake: ['Date'] }); + const { fapi } = await renderSignUp({ environment: byLink() }); + vi.useFakeTimers({ shouldAdvanceTime: true }); try { - const { fapi, user } = await renderSignUp({ environment: byLink() }); - const hold = holdRequests('get', POLL); + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const checks = holdChecks(); await submitStart(user); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); fapi.signUp.expireEmailLink(); - hold.release(); + checks.release(); await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(EXPIRED)); expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); expect(fapi.signUp.preparations).toEqual(['email_link']); - vi.setSystemTime(Date.now() + 61_000); - await user.click(await screen.findByRole('button', { name: 'Resend' })); + const checksAfterResend = holdChecks(); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + await user.click(screen.getByRole('button', { name: 'Resend' })); expect(await linkSent()).toBeDisabled(); expect(screen.getByRole('alert')).not.toHaveTextContent(EXPIRED); expect(fapi.signUp.preparations).toEqual(['email_link', 'email_link']); - await waitFor(() => expect(hold.requests).toHaveLength(2)); + await waitFor(() => expect(checksAfterResend.requests).toHaveLength(1)); + checksAfterResend.abandon(); } finally { vi.useRealTimers(); } @@ -195,10 +286,10 @@ describe('SignUp', () => { it('returns to the form with the address kept and the password cleared on Edit, and no longer follows the link', async () => { const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); - const hold = holdRequests('get', POLL); + const checks = holdChecks(); await submitStart(user); - await waitFor(() => expect(hold.requests).toHaveLength(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); await user.click(screen.getByRole('button', { name: 'Edit email address' })); expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); @@ -206,28 +297,36 @@ describe('SignUp', () => { expect(passwordField()).toHaveValue(''); fapi.signUp.openEmailLink('client_other'); - hold.release(); + checks.release(); await waitFor(() => expect(clerk.client?.sessions).toHaveLength(1)); expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); expect(navigate).not.toHaveBeenCalled(); - expect(hold.requests).toHaveLength(1); + expect(checks.requests).toHaveLength(1); }); }); describe('leaving the link screen', () => { - it('stops asking whether the link was opened once the user leaves the screen', async () => { - const { fapi, user } = await renderSignUp({ environment: byLink() }); + it('asks only about the new sign-up after the user edits and continues, although a check on the old one was due', async () => { + const { user } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); await submitStart(user); - await waitFor(() => expect(fapi.signUp.reloads).toBe(1)); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.release(); + await waitFor(() => expect(dueChecks).toHaveLength(1)); + + const checksAfterLeaving = holdChecks(); await user.click(screen.getByRole('button', { name: 'Edit email address' })); await screen.findByRole('heading', { name: 'Create your account' }); - await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS / 2)); - const askedBeforeLeaving = fapi.signUp.reloads; - await new Promise(resolve => setTimeout(resolve, 1.5 * POLL_INTERVAL_MS)); - - expect(fapi.signUp.reloads).toBe(askedBeforeLeaving); + runDueChecks(); + await user.type(passwordField(), PASSWORD); + await user.click(continueButton()); + + await waitFor(() => expect(checksAfterLeaving.signUps()).toContain('sua_2')); + expect(checksAfterLeaving.signUps()).toEqual(['sua_2']); + expect(checks.signUps()).toEqual(['sua_1']); + checksAfterLeaving.abandon(); }); }); From 4d02a2b3c696153d98fd18393b14815bb2d062ff Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 22:59:58 -0700 Subject: [PATCH 07/11] fix(mosaic): keep the email link screen usable when finishing the sign-up fails --- .../sign-up.email-link.feature.test.tsx | 34 +++++++++++++++++++ .../sign-up-email-link.controller.ts | 6 ++-- 2 files changed, 38 insertions(+), 2 deletions(-) diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index af8e8774cc5..d44e1073a2a 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -27,6 +27,8 @@ const SEND = '/v1/client/sign_ups/:id/prepare_verification'; const LINK_URL = `${window.location.origin}/?__clerk_mosaic_sign_up=verify`; const EXPIRED = 'The verification link expired. Please request a new link.'; const RESEND_COOLDOWN_MS = 60_000; +const ACTIVATION = '/v1/client/sessions/:id/touch'; +const ACTIVATION_ERROR = 'The session could not be activated.'; const byLink = (verifications = ['email_link']) => environment({ attributes: { email_address: { required: true, verifications } } }); @@ -284,6 +286,38 @@ describe('SignUp', () => { } }); + it('shows why and keeps Edit and Resend usable when the session cannot be activated after the link is opened', async () => { + const { fapi, navigate } = await renderSignUp({ environment: byLink() }); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const checks = holdChecks(); + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + const activation = holdRequests('post', ACTIVATION); + fapi.signUp.openEmailLink('client_other'); + checks.release(); + await waitFor(() => expect(activation.requests).toHaveLength(1)); + + activation.fail('form_param_invalid', ACTIVATION_ERROR); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(ACTIVATION_ERROR)); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Resend' })).toBeEnabled(); + expect(navigate).not.toHaveBeenCalled(); + + const resend = holdRequests('post', SEND); + await user.click(screen.getByRole('button', { name: 'Resend' })); + await waitFor(() => expect(resend.requests).toHaveLength(1)); + resend.release(); + expect(await linkSent()).toBeDisabled(); + } finally { + vi.useRealTimers(); + } + }); + it('returns to the form with the address kept and the password cleared on Edit, and no longer follows the link', async () => { const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); const checks = holdChecks(); diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts index 5a356c3cc03..b22159b7e55 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts @@ -84,7 +84,9 @@ const linkMachine = link.createMachine({ failed: { on: { RESEND: resend }, }, - verified: {}, + verified: { + on: { RESEND: resend }, + }, }, }); @@ -119,7 +121,7 @@ export function useSignUpEmailLinkController({ useEffect(() => () => cancelWait.current?.(), []); - const isPending = isFlowPending || snapshot.value === 'sending' || snapshot.value === 'verified'; + const isPending = isFlowPending || snapshot.value === 'sending'; return { isPending, From c159a737270f60357bc0b7030b22a4e599aa41a7 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 23:02:05 -0700 Subject: [PATCH 08/11] fix(mosaic): keep Clerk's own query params out of sign-up return URLs --- .../docs/internals/sign-in-sign-up-flow.md | 4 ++-- .../__tests__/feature/fake-fapi/sign-up.ts | 6 ++--- .../sign-up.email-link.feature.test.tsx | 22 +++++++++++++++++++ .../src/features/sign-up/sign-up.model.ts | 6 +++++ 4 files changed, 33 insertions(+), 5 deletions(-) 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 b0067ded035..d17fc42bea2 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -138,12 +138,12 @@ Sign-up redeems invitation tickets, starts enterprise SSO redirects, and complet A page opened from the link does not count as arriving signed in. In single-session mode the session the link created is already Clerk's session when the page loads, and the arrival rule would leave for the after sign-up URL before the link's result showed, or leave a second time after the session is activated. The controller records the arrival session as `none` for such a page, so the link's result decides. - Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now both returns build their URL by hand with a marker. The marker moves to `useReturnUrl()` when that hook lands. -- OAuth return: sign-up's callback URL is the current URL plus the marker `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. It keeps the rest of the query, so `redirect_url` and an invitation's ticket come back with the user. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: +- OAuth return: sign-up's callback URL is the current URL plus the marker `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. It keeps the rest of the query except Clerk's own `__clerk_*` parameters, so `redirect_url` comes back with the user, and a parameter Clerk put on this page, such as an invitation's ticket or its `__clerk_status`, does not, as in `ui`, whose callback URLs carry only the redirect parameters. FAPI adds `__clerk_status` to an email link's URL rather than replacing it, so a stale one left on the page would be the value the return reads. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: - A Protect check comes first. Once it is solved, `next` gets the step that follows, so a transfer after it still runs. - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. - An `identifier_already_signed_in` account activates that session. - A session from a transfer or an existing session is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. - - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. An `action_blocked` error that carries its details resolves with `blocked` instead and shows `actionBlocked`, as legacy's `ActionBlockedCard` does. Removing the ticket keeps the invitation from being redeemed again over the error, as in legacy, where the callback URL has no ticket. + - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. An `action_blocked` error that carries its details resolves with `blocked` instead and shows `actionBlocked`, as legacy's `ActionBlockedCard` does. The callback URL carries no ticket, so the invitation is not redeemed again over the error, as in legacy. - Anything else is `next(step)`. The marker is gone once the return starts, so a reload mid-return lands on `start`. OAuth is a full-page redirect only. Sign-up never passes `sso()` a `popup`, so popup OAuth (`oauthFlow: 'popup'`) is not built. An OAuth transport (`__internal_oauthTransport`) is not supported yet. `SignUpFuture.sso()` still navigates the window, so clerk-js has to honor the transport first. Sign-in-to-sign-up transfers start from sign-in, so they wait for its controller. 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 1e0143a0f6c..34efec06753 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -630,7 +630,7 @@ export function signUpHandlers( state.signUp.openEmailLink = (clientId = state.client.id) => { const { signUp, verifications, pending, landing } = emailLink(); if (pending.status === 'expired') { - landing.searchParams.set('__clerk_status', 'expired'); + landing.searchParams.append('__clerk_status', 'expired'); return landing.toString(); } if (pending.status !== 'unverified') { @@ -644,9 +644,9 @@ export function signUpHandlers( }, }); store(verified); - landing.searchParams.set('__clerk_status', 'verified'); + landing.searchParams.append('__clerk_status', 'verified'); if (verified.created_session_id) { - landing.searchParams.set('__clerk_created_session', verified.created_session_id); + landing.searchParams.append('__clerk_created_session', verified.created_session_id); } return landing.toString(); }; diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index d44e1073a2a..b9bcef4dbdb 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -5,6 +5,7 @@ import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } import { holdRequests, worker } from '../../../__tests__/feature/fake-fapi'; import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from '../../../__tests__/feature/fapi'; +import { renderWithClerk } from '../../../__tests__/feature/render'; import { SignUp } from '../sign-up'; import { continueButton, @@ -378,6 +379,27 @@ describe('SignUp', () => { visitWithQuery(`?${query.toString()}`); } + it('signs in from a link sent after a rejected invitation, although the invitation page carried its own status', async () => { + visitWithQuery('?__clerk_ticket=tkt_unknown&__clerk_status=sign_up'); + const { fapi, user, unmount } = await renderSignUp({ environment: byLink() }); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/no longer valid/)); + const checks = holdChecks(); + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + unmount(); + checks.abandon(); + + const landing = new URL(fapi.signUp.openEmailLink()); + window.history.replaceState(null, '', `${landing.pathname}${landing.search}`); + const sawInvalid = watchForHeading('This verification link is invalid'); + const { navigate, clerk } = await renderWithClerk(, { signUpFallbackRedirectUrl: '/welcome' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/welcome'))); + expect(clerk.session?.id).toBe(fapi.client.sessions[0].id); + expect(sawInvalid()).toBe(false); + expect(returnParams()).toEqual([]); + }); + it('activates the session the link created in this browser, leaves once, and forgets the link', async () => { openLink('verified', newSession.id); const { navigate, clerk, rerender } = await renderSignUp({ 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 fb988b2abce..f081725ee32 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -197,6 +197,7 @@ const DETAILS_FIELDS = [...signUpFieldOrder, 'legalAccepted'] as const; const PREFILL_NAMES = ['emailAddress', 'phoneNumber', 'username', 'firstName', 'lastName'] as const; const ABSOLUTE_URL = /^https?:\/\//; +const CLERK_PARAM_PREFIX = '__clerk_'; const RETURN_PARAM = '__clerk_mosaic_sign_up'; const ENTERPRISE_CONNECTION_REQUIRED = 'enterprise_connection_id_is_required_with_multiple_connections'; const SSO_RETURN = 'sso-callback'; @@ -244,6 +245,11 @@ function transferRoute(signIn: Pick Date: Mon, 30 Nov 2026 23:05:46 -0700 Subject: [PATCH 09/11] fix(mosaic): show a failed link when the session it created cannot be activated --- .../docs/internals/sign-in-sign-up-flow.md | 4 +-- .../sign-up.email-link.feature.test.tsx | 26 ++++++++++++++++++- .../features/sign-up/sign-up.controller.ts | 9 ++++--- 3 files changed, 33 insertions(+), 6 deletions(-) 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 d17fc42bea2..ba77f1189b5 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -63,10 +63,10 @@ submitPassword: async (password: string) => { - `transfer`: sign-up transfers only an OAuth account that already has a user. The OAuth return transfers it before a step reaches `next` ([Entry actions](#entry-actions)), unless a Protect check comes first. Then the Protect screen passes `transfer` to `next`, which runs the return's completion again and shows the loading screen while it does. Sign-in's transfer is planned: the model's `transfer()` will call `signUp.create({ transfer: true, unsafeMetadata })`, then `next` with the sign-up's step; a sign-in with sign-up built in holds the sign-up routes under `create/`, otherwise it leaves for the sign-up page. - `unknown`: nothing. The screen already shows "Start over". - `email_link_status`: the link screen's wait and the email-link return resolve with it, not a step, when all that is left is to tell the user what happened to the link. The controller keeps the status for this mount and `emailLinkStatus` replaces whatever screen the route would show. It stays up whatever the session is, so a signed-in visitor sees it too, as on `ui`'s `verify` route, which has no signed-in guard. -- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. +- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. If the activation fails, the page shows `emailLinkStatus` with `failed` and no error text, as `ui`'s `EmailLinkVerify` shows its failed card for any error. It is not the current screen the next rule names: that screen is `start`, and in single-session mode the session the link created is already Clerk's, so `start` would render nothing. - `blocked`: sign-up's `create`, the Protect proof's `resolve` and the invitation's `redeemTicket` resolve with it, not a step, when FAPI answers `action_blocked`. The OAuth return's `completeReturn` resolves with it when FAPI stored that error on the external account, and `sso` resolves with it from `start`. From `continue`, `sso` rejects and the error shows inline, as `update`'s does. The controller keeps the details for this mount and shows the notice in place of `start` or the Protect route. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does. - Anything else: `go(routeFor(step))`. -- An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. +- An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. The email-link return's activation is the exception (`session` above). After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. ## Routes and steps diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index b9bcef4dbdb..28cb929e03a 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -3,7 +3,7 @@ import { act, screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; -import { holdRequests, worker } from '../../../__tests__/feature/fake-fapi'; +import { holdRequests, serveFapi, worker } from '../../../__tests__/feature/fake-fapi'; import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from '../../../__tests__/feature/fapi'; import { renderWithClerk } from '../../../__tests__/feature/render'; import { SignUp } from '../sign-up'; @@ -432,6 +432,30 @@ describe('SignUp', () => { expect(sawForm()).toBe(false); }); + it.each([ + ['single-session', true], + ['multi-session', false], + ])( + 'shows the link as failed when the session it created cannot be activated, in %s mode', + async (_, singleSession) => { + openLink('verified', newSession.id); + serveFapi({ + environment: environment({ auth_config: { single_session_mode: singleSession } }), + client: fapiClient([newSession]), + }); + const activation = holdRequests('post', ACTIVATION); + const { navigate } = await renderWithClerk(); + await waitFor(() => expect(activation.requests).toHaveLength(1)); + + activation.fail('form_param_invalid', ACTIVATION_ERROR); + + expect(await screen.findByRole('heading', { name: 'This verification link is invalid' })).toBeInTheDocument(); + expect(screen.getByText('Return to the original tab to continue.')).toBeInTheDocument(); + expect(screen.queryByText(ACTIVATION_ERROR)).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }, + ); + it('says the sign-up is done and points back to the original tab when the session belongs to another browser', async () => { openLink('verified', 'sess_elsewhere'); const { navigate } = await renderSignUp({ environment: byLink() }); 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 331e588b382..2fb1e9b7eda 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -367,13 +367,16 @@ export function useSignUpController( activitySnapshot.value === 'startingEnterpriseSso'; const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; + const linkActivationFailed = activitySnapshot.value === 'failed' && activitySnapshot.context.sessionId !== undefined; + const shownEmailLinkStatus: SignUpEmailLinkStatusScreen | undefined = + emailLinkStatus ?? (linkActivationFailed ? { status: 'failed' } : undefined); const screen = isLoading ? 'loading' : (heldScreen ?? screenFor(correctedRoute, model, { isBlocked: blockedDetails !== undefined, hasConnections: connections !== undefined, - hasEmailLinkStatus: emailLinkStatus !== undefined, + hasEmailLinkStatus: shownEmailLinkStatus !== undefined, })); useRouteGuard({ route, go }, correctedRoute); @@ -457,7 +460,7 @@ export function useSignUpController( }, }; - if (isLeaving || (override.type === 'done' && emailLinkStatus === undefined)) { + if (isLeaving || (override.type === 'done' && shownEmailLinkStatus === undefined)) { return { status: 'hidden' }; } @@ -485,7 +488,7 @@ export function useSignUpController( onSignIn: navigation.goToSignIn, }, actionBlocked: blockedDetails, - emailLinkStatus, + emailLinkStatus: shownEmailLinkStatus, enterpriseConnections: connections && { options: connections, pendingConnectionId: connectionActions.pendingKey, From b25475dfc30d957cd4e2335df421288d6a124221 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 23:12:17 -0700 Subject: [PATCH 10/11] fix(mosaic): send a new email link every time the link screen opens --- .../docs/internals/sign-in-sign-up-flow.md | 4 +-- .../sign-up.email-link.feature.test.tsx | 28 +++++++++++++++++-- .../sign-up-email-link.controller.test.ts | 2 +- .../sign-up-email-link.controller.ts | 13 +++------ .../src/features/sign-up/sign-up.model.ts | 2 -- packages/swingset/src/stories/sign-up.mdx | 2 +- .../swingset/src/stories/sign-up.stories.tsx | 1 - 7 files changed, 33 insertions(+), 19 deletions(-) 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 ba77f1189b5..e5b0692a272 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,7 @@ 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. - On an instance whose email address lists `email_link` in its verifications, the wrapper fills the `verifyEmail` slot with `SignUpEmailLink` (`sign-up-email-link/`) instead of the code screen, with the same `key`. The link wins when the code is enabled too, and there is no way back to the code, as in `ui` (`ui/src/components/SignUp/SignUpVerifyEmail.tsx`). The model returns the `verification.emailLink` group only on such an instance, so its presence picks the screen. -- `SignUpEmailLink` holds the link machine. Its states are `idle`, `sending`, `waiting`, `expired`, `failed` and `verified`. It decides once, when it mounts: a step with `sent: false` sends the link, then waits; a step with `sent: true` only waits, so a reload or a second visit never sends again. FAPI limits how often it sends to one address, so a send the user did not ask for costs them a real one. An expired link turns `sent` back to `false` while the screen is up, and the machine ignores that: it shows the expiry and waits for Resend. Resend unlocks 60 seconds after a send or an arrival, stops the current wait, sends, and waits again. A resend inside the link's ten minutes reuses the link and does not extend it. +- `SignUpEmailLink` holds the link machine. Its states are `idle`, `sending`, `waiting`, `expired`, `failed` and `verified`. It sends a link every time it mounts, then waits, whether or not a link is already out, as `ui`'s `SignUpEmailLinkCard` does, so a reload or a second visit sends a new one. Under StrictMode the second mount finds the machine already `sending` and sends nothing more. FAPI limits how often it sends to one address: a refused send shows FAPI's error on the screen and leaves Resend to unlock after the cooldown, as `ui` shows it on its card. An expired link shows the expiry and waits for Resend. Resend unlocks 60 seconds after a send, stops the current wait, sends, and waits again. A resend inside the link's ten minutes reuses the link and does not extend it. - The wait is the model's `emailLink.wait()`, which returns the outcome and a `cancel`. It reloads the client's sign-up once a second through `Poller` (`shared/src/poller.ts`), whose timers run in a worker so a background tab keeps asking. `SignUpFuture.verifications.waitForEmailLinkVerification()` is not used: it cannot be cancelled, and it resolves the same way for a verified and an expired link. The machine cancels the wait when it leaves `waiting`, and the screen cancels it when it unmounts, so Edit, a route change and a remount all stop the requests. `cancel` also marks the wait as cancelled, and the next tick checks that mark before it reloads. `Poller.stop()` alone does not stop a poller that is waiting for its second tick: the first worker timer has id `0`, which `stop()` reads as no timer, and the next `run` clears the stopped flag. - The wait ends in one of three ways. An expired link moves the machine to `expired`. A link opened in another browser returns the sign-up's next step, read from the sign-up the reload returned, and the screen passes it to `next`: a complete sign-up finishes in this tab, since FAPI creates the session on the client that started the sign-up. A link opened in this browser (`verifiedFromTheSameClient()` on the verification, which compares `verified_at_client` with this client) returns `email_link_status` with `signed-in-other-tab`: the tab the link opened is the one that signs in, so this tab only says so, as `ui`'s `SignUpEmailLinkCard` does. - 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. @@ -112,7 +112,7 @@ With no `:factor`, `factorOne` starts on the factor `ui`'s `determineStartingSig - FAPI's state changes only on submit. A route the step doesn't allow is replaced with the step's route. - Back to `start` shows the identifier form; submitting it creates a new sign-in. Forward to `factorOne` still works. -- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up verify route sends a code or a link only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. `ui`'s link card sends a new link on every mount; sign-up does not. +- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up code screen sends a code only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. Reload on the link screen always sends a new link, as `ui`'s link card does. - Virtual routing has no history: a remount starts at `start`, and FAPI's state is kept. ## Entry actions diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx index 28cb929e03a..8a62b2f5535 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -186,7 +186,7 @@ describe('SignUp', () => { expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); }); - it('waits without sending again when it opens with a link already out, and finishes once the link is opened', async () => { + it('sends a new link when it opens with a link already out, and finishes once the link is opened', async () => { const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut()); const checks = holdChecks(); @@ -194,14 +194,36 @@ describe('SignUp', () => { expect(await linkSent()).toBeDisabled(); await waitFor(() => expect(checks.requests).toHaveLength(1)); - expect(fapi.signUp.preparations).toEqual([]); + expect(fapi.signUp.preparations).toEqual(['email_link']); fapi.signUp.openEmailLink('client_other'); checks.release(); await waitFor(() => expect(navigate).toHaveBeenCalled()); expect(fapi.client.sessions).toHaveLength(1); - expect(fapi.signUp.preparations).toEqual([]); + expect(fapi.signUp.preparations).toEqual(['email_link']); + }); + + it('shows why when FAPI refuses to send another link, and offers Resend once the cooldown ends', async () => { + const { user } = await renderSignUpWithRouteProbe(linkOut()); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const send = holdRequests('post', SEND); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(send.requests).toHaveLength(1)); + send.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.'), + ); + expect(await linkSent()).toBeDisabled(); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + expect(screen.getByRole('button', { name: 'Resend' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + } finally { + vi.useRealTimers(); + } }); it('keeps asking until the link is opened in another browser, then signs in and leaves for the after sign-up URL', async () => { diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts index f0f9b62b7cc..ea779c3019f 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts @@ -13,7 +13,7 @@ describe('useSignUpEmailLinkController', () => { const wait = vi.fn(() => ({ outcome: new Promise(() => {}), cancel })); const { result } = renderHook(() => useSignUpEmailLinkController({ - link: { target: 'alice@example.com', needsLink: true, send, wait }, + link: { target: 'alice@example.com', send, wait }, onNext: () => {}, isPending: false, }), diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts index b22159b7e55..2a067b3b5c5 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts @@ -22,7 +22,7 @@ interface LinkContext { error: ErrorDescription | undefined; } -type LinkEvent = { type: 'SEND' } | { type: 'ALREADY_SENT' } | { type: 'RESEND' }; +type LinkEvent = { type: 'SEND' } | { type: 'RESEND' }; const link = setup(); @@ -49,10 +49,7 @@ const linkMachine = link.createMachine({ }, states: { idle: { - on: { - SEND: 'sending', - ALREADY_SENT: { target: 'waiting', actions: startCooldown }, - }, + on: { SEND: 'sending' }, }, sending: { invoke: link.fromPromise(context => context.sendLink(), { @@ -93,7 +90,7 @@ const linkMachine = link.createMachine({ type SignUpEmailLinkOptions = Pick; export function useSignUpEmailLinkController({ - link: { needsLink, send: sendLink, wait }, + link: { send: sendLink, wait }, onNext, isPending: isFlowPending, globalErrorMessage, @@ -113,10 +110,8 @@ export function useSignUpEmailLinkController({ }, }); const resendSeconds = useResendSeconds(snapshot.context.resendAvailableAt, LINK_RESEND_SECONDS); - const arrivedNeedingLink = useRef(needsLink); - useEffect(() => { - send({ type: arrivedNeedingLink.current ? 'SEND' : 'ALREADY_SENT' }); + send({ type: 'SEND' }); }, [send]); useEffect(() => () => cancelWait.current?.(), []); 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 f081725ee32..319bf4b306c 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -133,7 +133,6 @@ export interface SignUpEmailLinkWait { export interface SignUpEmailLinkModel { target: string; - needsLink: boolean; send: () => Promise; wait: () => SignUpEmailLinkWait; } @@ -846,7 +845,6 @@ export function useSignUpModel({ emailLink: verifiesEmailByLink ? { target: signUp.emailAddress ?? '', - needsLink: step.type === 'verify_email' && !step.sent, send: () => run(() => signUp.verifications.sendEmailLink({ verificationUrl: callbackUrl(EMAIL_LINK_RETURN) })), wait: waitForEmailLink, diff --git a/packages/swingset/src/stories/sign-up.mdx b/packages/swingset/src/stories/sign-up.mdx index b3584a53f6e..37a5c0663f1 100644 --- a/packages/swingset/src/stories/sign-up.mdx +++ b/packages/swingset/src/stories/sign-up.mdx @@ -25,7 +25,7 @@ The standalone sign-up view. It reuses the sign-up screens the sign-in view show ## Usage -The view renders its own `Card.Root` and mounts one screen at a time inside it. `screen` says which one: a route of the sign-up, or a screen the flow shows on top of a route, such as `restricted` or `startOver`. Each screen takes its own props under its own name, so `start` and `continue` hold the details form. `verifyEmail` and `verifyPhone` are slots: pass a `SignUpVerify` for each, with its `channel`, a `verification` (the address, whether a code is still needed, and `send` and `verify`) `onNext` for the step a correct code returns, and `isPending` while the flow around it is busy. On an instance that verifies email by link, pass a `SignUpEmailLink` as `verifyEmail` instead, with a `link` (the address, whether a link is still needed, `send`, and `wait`, which returns the outcome and a `cancel`). It sends the link when it mounts with `link.needsLink`, waits for it either way, and cancels the wait when it unmounts. `emailLinkStatus` takes the `status` to show on the page the link opens. `start` and `continue` share one `useForm`, so what the user typed is still there after a trip to a verify screen. A verify screen sends its code when it mounts with `verification.needsCode`; give it the sign-up's id as its `key`, so a new sign-up remounts it. `protectCheck` is a slot too: pass a `SignUpProtect` keyed by its `protect.challengeId`, so each challenge Clerk issues remounts it, with the flow's `expiredReloads` count, which outlives those remounts. `taskChooseOrganization` is a slot for the session task shown on its route. Leaving out a callback hides the control it drives: `onSignIn` for the sign-in link, `onCancel` for a screen's secondary action, `onResend` for the resend line, `onEmailSupport` and `onJoinWaitlist` for the restricted screens. +The view renders its own `Card.Root` and mounts one screen at a time inside it. `screen` says which one: a route of the sign-up, or a screen the flow shows on top of a route, such as `restricted` or `startOver`. Each screen takes its own props under its own name, so `start` and `continue` hold the details form. `verifyEmail` and `verifyPhone` are slots: pass a `SignUpVerify` for each, with its `channel`, a `verification` (the address, whether a code is still needed, and `send` and `verify`) `onNext` for the step a correct code returns, and `isPending` while the flow around it is busy. On an instance that verifies email by link, pass a `SignUpEmailLink` as `verifyEmail` instead, with a `link` (the address, `send`, and `wait`, which returns the outcome and a `cancel`). It sends a link every time it mounts, then waits for it, and cancels the wait when it unmounts. `emailLinkStatus` takes the `status` to show on the page the link opens. `start` and `continue` share one `useForm`, so what the user typed is still there after a trip to a verify screen. A verify screen sends its code when it mounts with `verification.needsCode`; give it the sign-up's id as its `key`, so a new sign-up remounts it. `protectCheck` is a slot too: pass a `SignUpProtect` keyed by its `protect.challengeId`, so each challenge Clerk issues remounts it, with the flow's `expiredReloads` count, which outlives those remounts. `taskChooseOrganization` is a slot for the session task shown on its route. Leaving out a callback hides the control it drives: `onSignIn` for the sign-in link, `onCancel` for a screen's secondary action, `onResend` for the resend line, `onEmailSupport` and `onJoinWaitlist` for the restricted screens. ```tsx import { SignUpProtect, SignUpVerify, SignUpView } from '@clerk/mosaic/features/sign-up'; diff --git a/packages/swingset/src/stories/sign-up.stories.tsx b/packages/swingset/src/stories/sign-up.stories.tsx index 4a06152af50..8bfeadb8ad1 100644 --- a/packages/swingset/src/stories/sign-up.stories.tsx +++ b/packages/swingset/src/stories/sign-up.stories.tsx @@ -88,7 +88,6 @@ function verifyScreen(target: string): SignUpVerifyScreen { const emailLinkScreen: SignUpEmailLinkScreen = { link: { target: EMAIL, - needsLink: false, send: () => Promise.resolve(), wait: () => ({ outcome: new Promise(noop), cancel: noop }), }, From e7288a140a5fc36fe51812a3672fc8264850551b Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 00:29:40 -0700 Subject: [PATCH 11/11] refactor(mosaic): keep the sign-up email-link status in the activity machine The status an email link resolves with is the activity machine's showingLinkStatus state, set by SHOW_LINK_STATUS and kept for the mount. The session a link created goes through FINALIZE with the loading screen and showsFailedLink, so a failed activation moves to that state with the failed status. This replaces the emailLinkStatus state and the sessionId the machine kept only to recognize that failure. --- .../docs/internals/sign-in-sign-up-flow.md | 4 +- .../features/sign-up/sign-up.controller.ts | 75 +++++++++++++------ 2 files changed, 56 insertions(+), 23 deletions(-) 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 e5b0692a272..a7f1085c14f 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -62,8 +62,8 @@ submitPassword: async (password: string) => { - `complete`: the model's `finalize()`, then leave the flow for the after sign-up URL, which honors `redirect_url` and the redirect query params (`clerk.buildAfterSignUpUrl({ params })`). Creating the session clears the sign-up. Sign-up renders the model it left from while `finalize()` runs, and after it until a task that continues in the flow has its data loaded, so the task replaces the screen with no skeleton between them. It keeps the action pending throughout, the way the switcher holds its `frozenModel` ([Controllers → Wrapping actions](../controllers.md#wrapping-actions)). Once the hold ends with the session signed in, the flow is over: if the host keeps the component mounted, it renders nothing. In a modal, don't `close()` when the flow leaves: `finalize()`'s navigation is the last write and takes the modal with it. - `transfer`: sign-up transfers only an OAuth account that already has a user. The OAuth return transfers it before a step reaches `next` ([Entry actions](#entry-actions)), unless a Protect check comes first. Then the Protect screen passes `transfer` to `next`, which runs the return's completion again and shows the loading screen while it does. Sign-in's transfer is planned: the model's `transfer()` will call `signUp.create({ transfer: true, unsafeMetadata })`, then `next` with the sign-up's step; a sign-in with sign-up built in holds the sign-up routes under `create/`, otherwise it leaves for the sign-up page. - `unknown`: nothing. The screen already shows "Start over". -- `email_link_status`: the link screen's wait and the email-link return resolve with it, not a step, when all that is left is to tell the user what happened to the link. The controller keeps the status for this mount and `emailLinkStatus` replaces whatever screen the route would show. It stays up whatever the session is, so a signed-in visitor sees it too, as on `ui`'s `verify` route, which has no signed-in guard. -- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. If the activation fails, the page shows `emailLinkStatus` with `failed` and no error text, as `ui`'s `EmailLinkVerify` shows its failed card for any error. It is not the current screen the next rule names: that screen is `start`, and in single-session mode the session the link created is already Clerk's, so `start` would render nothing. +- `email_link_status`: the link screen's wait and the email-link return resolve with it, not a step, when all that is left is to tell the user what happened to the link. The controller sends it to the activity machine's `showingLinkStatus` state, which keeps it for this mount, and `emailLinkStatus` replaces whatever screen the route would show. It stays up whatever the session is, so a signed-in visitor sees it too, as on `ui`'s `verify` route, which has no signed-in guard. +- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. `FINALIZE` marks this activation with `showsFailedLink`, so if it fails the machine moves to `showingLinkStatus` and the page shows `emailLinkStatus` with `failed` and no error text, as `ui`'s `EmailLinkVerify` shows its failed card for any error. It is not the current screen the next rule names: that screen is `start`, and in single-session mode the session the link created is already Clerk's, so `start` would render nothing. - `blocked`: sign-up's `create`, the Protect proof's `resolve` and the invitation's `redeemTicket` resolve with it, not a step, when FAPI answers `action_blocked`. The OAuth return's `completeReturn` resolves with it when FAPI stored that error on the external account, and `sso` resolves with it from `start`. From `continue`, `sso` rejects and the error shows inline, as `update`'s does. The controller keeps the details for this mount and shows the notice in place of `start` or the Protect route. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does. - Anything else: `go(routeFor(step))`. - An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. The email-link return's activation is the exception (`session` above). After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. 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 2fb1e9b7eda..bbeb4669180 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -41,7 +41,8 @@ interface ActivityContext { frozenModel: SignUpReadyModel | null; activate: (() => Promise) | undefined; frozenScreen: 'loading' | undefined; - sessionId: string | undefined; + showsFailedLink: boolean; + linkStatus: SignUpEmailLinkStatusScreen | undefined; error: ErrorDescription | undefined; onFinalized: (() => void) | undefined; } @@ -51,15 +52,18 @@ type FinalizeStart = { frozenModel: SignUpReadyModel; activate: () => Promise; frozenScreen?: 'loading'; - sessionId?: string; + showsFailedLink?: boolean; onFinalized: () => void; }; type ChooseConnection = { type: 'CHOOSE_CONNECTION'; connections: readonly AuthProvider[] }; +type ShowLinkStatus = { type: 'SHOW_LINK_STATUS'; linkStatus: SignUpEmailLinkStatusScreen }; + type ActivityEvent = | FinalizeStart | ChooseConnection + | ShowLinkStatus | { type: 'COMPLETE_RETURN' } | { type: 'START_ENTERPRISE_SSO' } | { type: 'CANCEL_CONNECTIONS' } @@ -75,7 +79,7 @@ const finalizeShowing = (frozenScreen: 'loading' | undefined) => ({ frozenModel: event.frozenModel, activate: event.activate, frozenScreen: event.frozenScreen ?? frozenScreen, - sessionId: event.sessionId, + showsFailedLink: event.showsFailedLink ?? false, onFinalized: event.onFinalized, error: undefined, })), @@ -108,7 +112,21 @@ const chooseConnection = { }, }; -const whileIdle = { ...startFinalizing, ...startCompletingReturn, ...startEnterpriseSso, ...chooseConnection }; +// The status a page opened from an email link shows stays for the rest of the mount. +const showLinkStatus = { + SHOW_LINK_STATUS: { + target: 'showingLinkStatus' as const, + actions: activity.assign((_, event) => ({ linkStatus: event.linkStatus })), + }, +}; + +const whileIdle = { + ...startFinalizing, + ...startCompletingReturn, + ...startEnterpriseSso, + ...chooseConnection, + ...showLinkStatus, +}; const FIRST_STATE = { visit: 'idle', @@ -131,7 +149,8 @@ const activityMachine = activity.createMachine({ frozenModel: null, activate: undefined, frozenScreen: undefined, - sessionId: undefined, + showsFailedLink: false, + linkStatus: undefined, error: undefined, onFinalized: undefined, }, @@ -153,7 +172,7 @@ const activityMachine = activity.createMachine({ onDone: [{ target: 'redeemingTicket', guard: context => context.canRedeemTicket() }, { target: 'idle' }], onError: arrivalFailed, }), - on: { ...startFinalizing, ...startEnterpriseSso, ...chooseConnection }, + on: { ...startFinalizing, ...startEnterpriseSso, ...chooseConnection, ...showLinkStatus }, }, startingEnterpriseSso: { entry: activity.assign(() => ({ hasStartedEnterpriseSso: true })), @@ -179,17 +198,33 @@ const activityMachine = activity.createMachine({ finalizing: { invoke: activity.fromPromise(context => context.activate?.() ?? Promise.resolve(), { onDone: { target: 'finalized', actions: context => context.onFinalized?.() }, - onError: { - target: 'failed', - actions: activity.assign((_, event) => ({ - frozenModel: null, - activate: undefined, - frozenScreen: undefined, - error: toLocalizableError(event.error), - })), - }, + onError: [ + { + // A session an email link created that can't be activated shows the failed link, as ui does. + target: 'showingLinkStatus', + guard: context => context.showsFailedLink, + actions: activity.assign(() => ({ + frozenModel: null, + activate: undefined, + frozenScreen: undefined, + linkStatus: { status: 'failed' }, + })), + }, + { + target: 'failed', + actions: activity.assign((_, event) => ({ + frozenModel: null, + activate: undefined, + frozenScreen: undefined, + error: toLocalizableError(event.error), + })), + }, + ], }), }, + showingLinkStatus: { + on: whileIdle, + }, failed: { on: { ...whileIdle, @@ -211,6 +246,7 @@ const FINALIZE_STATUS = { completingReturn: 'idle', startingEnterpriseSso: 'idle', choosingConnection: 'idle', + showingLinkStatus: 'idle', arrivalFailed: 'idle', finalizing: 'running', failed: 'failed', @@ -339,7 +375,6 @@ export function useSignUpController( }, }); const [blockedDetails, block] = useBlockedOn(route); - const [emailLinkStatus, setEmailLinkStatus] = useState(); const hasLeft = useRef(false); const connectionActions = usePendingAction(); const expiredProtectReloads = useRef(0); @@ -367,9 +402,7 @@ export function useSignUpController( activitySnapshot.value === 'startingEnterpriseSso'; const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; - const linkActivationFailed = activitySnapshot.value === 'failed' && activitySnapshot.context.sessionId !== undefined; - const shownEmailLinkStatus: SignUpEmailLinkStatusScreen | undefined = - emailLinkStatus ?? (linkActivationFailed ? { status: 'failed' } : undefined); + const shownEmailLinkStatus = activitySnapshot.context.linkStatus; const screen = isLoading ? 'loading' : (heldScreen ?? @@ -387,7 +420,7 @@ export function useSignUpController( return; } if (result.type === 'email_link_status') { - setEmailLinkStatus({ status: result.status }); + sendActivity({ type: 'SHOW_LINK_STATUS', linkStatus: { status: result.status } }); return; } if (result.type === 'complete') { @@ -406,7 +439,7 @@ export function useSignUpController( frozenModel: model, activate: () => model.attempt.finalize(sessionId), frozenScreen: 'loading', - sessionId, + showsFailedLink: true, onFinalized: details.clear, }); return;