From 5d5161ba4918cec146a94a2253f5910f7c92eeaa Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 14:45:13 -0700 Subject: [PATCH 01/16] 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 7953c5313aa..b28e1badc3f 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -46,6 +46,7 @@ export interface FakeSignUpSeed { whatsAppQuotaExceeded?: boolean; tickets?: Record; oauth?: Record; + emailLinkRedirectUrl?: string; } export type FakeOAuthAccount = @@ -84,6 +85,9 @@ export interface FakeSignUpState { transfers: URLSearchParams[]; linkedStrategy?: string; returnFromOAuth: () => void; + emailLinkRedirectUrl?: string; + openEmailLink: (clientId?: string) => string; + expireEmailLink: () => void; issuedProtectChecks: number; reloads: number; proofTokens: string[]; @@ -108,6 +112,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: [], @@ -144,7 +154,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); const MAX_CODE_ATTEMPTS = 3; @@ -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); }; @@ -571,6 +591,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'); @@ -584,13 +609,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, @@ -599,6 +637,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) { const seeded = state.client.sign_up; const enteredEmail = seeded.email_address; @@ -777,7 +860,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(); } @@ -820,7 +903,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 3ff6d0a017658db41f5dfcd50412bfc845548b59 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:11:12 -0700 Subject: [PATCH 02/16] 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 | 84 ++++++- .../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, 569 insertions(+), 94 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 93437749a82..b97dc446a3e 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 @@ -441,8 +441,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', () => { @@ -648,38 +646,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 b417cb7932d..8b3a227a56e 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, SignUpTaskKey } 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'; @@ -258,6 +264,7 @@ type SignUpControllerResult = status: 'ready'; attempt?: string; verifyEmail: SignUpVerifyScreen; + verifyEmailLink?: SignUpEmailLinkScreen; verifyPhone: SignUpVerifyScreen; protectCheck: SignUpProtectScreen; }); @@ -319,6 +326,7 @@ export function useSignUpController( }, }); const [blockedDetails, block] = useBlockedOn(route); + const [emailLinkStatus, setEmailLinkStatus] = useState(); const hasLeft = useRef(false); const connectionActions = usePendingAction(); const expiredProtectReloads = useRef(0); @@ -354,7 +362,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); @@ -367,6 +378,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', @@ -463,6 +478,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, @@ -478,6 +494,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 d744f65a7b5..2f3becf707f 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, @@ -40,7 +41,7 @@ import { useMemo, useRef } from 'react'; import type { ApplicationLogoProps } from '../../blocks/application-logo'; import { applicationLogo } from '../../blocks/application-logo'; -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'; @@ -117,12 +118,32 @@ export interface SignUpEnterpriseConnectionsResult { connections: readonly AuthProvider[]; } +export interface SignUpEmailLinkStatusResult { + type: 'email_link_status'; + status: Exclude; +} + export type SignUpCreateResult = | SignUpNextStep | { type: 'blocked'; details: AuthActionBlockedDetails } | SignUpEnterpriseConnectionsResult + | SignUpEmailLinkStatusResult | { type: 'signed_in'; sessionId: string | undefined }; +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; canSwitchIdentifier: boolean; @@ -171,7 +192,7 @@ export interface SignUpReadyModel { app: SignUpAppModel; navigation: SignUpNavigationModel; details: SignUpDetailsModel; - verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel }; + verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel; emailLink?: SignUpEmailLinkModel }; protect: SignUpProtectModel; } @@ -185,6 +206,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, @@ -217,9 +239,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; }; @@ -475,6 +494,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; @@ -531,7 +588,7 @@ export function useSignUpModel({ const result = await signUp.sso({ strategy: 'enterprise_sso', enterpriseConnectionId: connectionId, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, }); const needsConnection = @@ -676,7 +733,7 @@ export function useSignUpModel({ } const result = await target.sso({ strategy, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, unsafeMetadata, legalAccepted: legalAccepted || undefined, @@ -766,6 +823,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 c6b99554932..1121db9839b 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.tsx @@ -14,6 +14,7 @@ import { useSignUpController } from './sign-up.controller'; import type { SignUpReadyModel } from './sign-up.model'; import { ticketFromUrl, 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'; @@ -83,17 +84,24 @@ function SignUpFlow({ return null; } - const { status: _status, attempt, verifyEmail, verifyPhone, protectCheck, ...view } = controller; + const { status: _status, attempt, verifyEmail, verifyEmailLink, verifyPhone, protectCheck, ...view } = controller; return ( + verifyEmailLink ? ( + + ) : ( + + ) } verifyPhone={ void; isPending: boolean; globalErrorMessage?: string; onEditIdentifier: () => void; - onResend?: () => void; - canResend: boolean; - resendRemainingSeconds?: number; } export interface SignUpEmailLinkStatusScreen { @@ -148,7 +150,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 ab37ff8353b..a6dbe7166ed 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.view.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.view.tsx @@ -2,14 +2,12 @@ import { ApplicationLogo } from '../../blocks/application-logo'; 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'; @@ -41,7 +39,6 @@ export function SignUpView(props: SignUpViewProps) { actionBlocked, startOver, alternativePhone, - verifyEmailLink, emailLinkStatus, enterpriseConnections, wallets, @@ -132,28 +129,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< @@ -356,14 +369,8 @@ export function VerifyPhoneAlternativeChannel() { export function VerifyEmailLink() { return ( } /> ); } From 7f890b8d55fefc76ea22de781250d9a35a3cc42f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:19:33 -0700 Subject: [PATCH 03/16] 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 | 49 +++++-- .../src/features/sign-up/sign-up.model.ts | 46 ++++++- 3 files changed, 200 insertions(+), 18 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 8b3a227a56e..c73c56bd8c2 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, SignUpTaskKey } from './sign-up.routes'; import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRoutes } from './sign-up.routes'; import type { SignUpEmailLinkScreen, + SignUpEmailLinkStatusScreen, SignUpProtectScreen, SignUpScreen, SignUpVerifyScreen, @@ -39,6 +40,7 @@ interface ActivityContext { frozenModel: SignUpReadyModel | null; activate: (() => Promise) | undefined; frozenScreen: 'loading' | undefined; + sessionId: string | undefined; error: ErrorDescription | undefined; onFinalized: (() => void) | undefined; } @@ -48,6 +50,7 @@ type FinalizeStart = { frozenModel: SignUpReadyModel; activate: () => Promise; frozenScreen?: 'loading'; + sessionId?: string; onFinalized: () => void; }; @@ -71,6 +74,7 @@ const finalizeShowing = (frozenScreen: 'loading' | undefined) => ({ frozenModel: event.frozenModel, activate: event.activate, frozenScreen: event.frozenScreen ?? frozenScreen, + sessionId: event.sessionId, onFinalized: event.onFinalized, error: undefined, })), @@ -119,6 +123,7 @@ const activityMachine = activity.createMachine({ frozenModel: null, activate: undefined, frozenScreen: undefined, + sessionId: undefined, error: undefined, onFinalized: undefined, }, @@ -206,9 +211,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'; } @@ -237,7 +248,7 @@ function arrivalIntentFor( route: SignUpRoute, override: AuthSessionOverride, ): SignUpArrivalIntent { - if (model.attempt.hasPendingReturn && override.type !== 'leave') { + if (model.attempt.pendingReturn !== undefined && override.type !== 'leave') { return 'return'; } if (override.type === 'none' && correctRoute(route, override, model.attempt.step) === 'enterpriseConnections') { @@ -283,7 +294,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, @@ -326,7 +337,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); @@ -337,7 +348,7 @@ export function useSignUpController( }); const isHolding = override.type === 'hold'; const isLeaving = override.type === 'leave'; - const isHidden = isLeaving || override.type === 'done'; + const isHidden = isLeaving || (override.type === 'done' && emailLinkStatus === undefined); const isHiddenNow = useRef(isHidden); useEffect(() => { @@ -363,9 +374,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); @@ -379,7 +392,7 @@ export function useSignUpController( return; } if (result.type === 'email_link_status') { - setEmailLinkStatus(result.status); + setEmailLinkStatus({ status: result.status }); return; } if (result.type === 'complete') { @@ -402,6 +415,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; @@ -494,7 +519,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 2f3becf707f..806243d0db8 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -87,9 +87,9 @@ export interface SignUpAttemptModel { redeemTicket: () => Promise<{ result: SignUpCreateResult; emailAddress: string }>; forgetTicket: () => void; startEnterpriseSso: (connectionId?: string) => Promise; - hasPendingReturn: boolean; + pendingReturn: 'sso' | 'email_link' | undefined; completeReturn: () => Promise; - finalize: () => Promise; + finalize: (sessionId?: string) => Promise; finalizeSignIn: (sessionId: string | undefined) => Promise; reset: () => Promise; } @@ -128,6 +128,7 @@ export type SignUpCreateResult = | { type: 'blocked'; details: AuthActionBlockedDetails } | SignUpEnterpriseConnectionsResult | SignUpEmailLinkStatusResult + | { type: 'session'; sessionId: string } | { type: 'signed_in'; sessionId: string | undefined }; export type SignUpEmailLinkOutcome = { type: 'expired' } | { type: 'verified'; result: SignUpCreateResult }; @@ -207,6 +208,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, @@ -348,6 +358,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); @@ -532,6 +543,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; @@ -613,9 +641,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; @@ -653,9 +684,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 })); }, finalizeSignIn: async sessionId => { const navigate = navigateAfter(afterSignInUrl, { keepsTaskInFlow: true }); From 5267a10e85eb778437e23e4399b7c993ec157fbb Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:20:50 -0700 Subject: [PATCH 04/16] 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 e48d9a0af43..19c0d037283 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. It reads `sent` only then. FAPI fails a verification after three wrong codes and expires an old one, and both read as `sent: false` while the screen is open. The screen sends nothing for them until the user presses Resend, as `ui`'s code card does: a code sent on its own would give the user three more tries without their asking. 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 once and held. The `SignUp` wrapper reads the ticket from `__clerk_ticket` or `__clerk_invitation_token` once, when it mounts, and holds it in state, as `ui`'s `SignUpStart` holds it in its form state (`ui/src/components/SignUp/SignUpStart.tsx:121-124`). The model takes the ticket as an option and does not read the URL. The state lives in the wrapper because a model holds no React state ([Models](../models.md)). Forgetting the ticket clears that state and removes the parameters (`forgetTicket` in `mosaic/src/features/sign-up/sign-up.model.ts`). @@ -127,8 +133,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 arrival. A later arrival in the same mount starts it again, as `ui` does after each Protect check (`ui/src/components/SignUp/SignUpProtectCheck.tsx`). `startOver` shows when the start failed, with its error, or when the browser is still on the page after the hold. Start over dismisses that error, so the new `start` form opens without it. - 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 replaces the chooser's history entry with `start`, so the browser's Back never lands on a chooser that has no list to show. Leaving the chooser another way, such as the browser's Back, keeps the list, so Forward shows the chooser again, as `ui`'s chooser does by listing on mount. The next arrival starts enterprise SSO again and replaces the list. 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 visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. 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 resolves with `signed_in`. 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`. @@ -141,7 +154,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 02cbfb55573ba5a7b75dbe15c1bcc849bf21fbc9 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 15:20:51 -0700 Subject: [PATCH 05/16] 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 12aa3d06f896cd79d1438a33e824a542083b927a Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 16:07:55 -0700 Subject: [PATCH 06/16] 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 3ed30dd03eae71f4fa8e0b29cbf775ac4e62b14b Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 22:59:58 -0700 Subject: [PATCH 07/16] 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 7e82b6e9bd286fd20c8fdf1728cd224571f064d5 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 23:02:05 -0700 Subject: [PATCH 08/16] 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 19c0d037283..cc9d8a12ad7 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -142,12 +142,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 visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. 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 visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. 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 resolves with `signed_in`. 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 resolves with `signed_in` and that session's ID. - `next` sends `signed_in` to `FINALIZE` with `finalizeSignIn` as the activation and the loading screen frozen, so a failed activation shows its error like any other finalize error. `finalizeSignIn` lands on the after sign-in URL, and keeps a pending organization task in the card the way a finished sign-up does, as legacy's callback opens the task under sign-up (`baseUrl: signUpUrl`). - - 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. - A sign-up FAPI finished at the provider comes back with no sign-up on the client and its session pending a task. FAPI sends a session with no task straight to the after sign-up URL, so only a pending one reaches the callback (`determineRedirectURL` in `clerk_go/api/fapi/v1/oauth/oauth.go`). A task sign-up shows in its card needs nothing here: the session override moves to it. Any other task resolves with `signed_in` and that session's ID, so `finalizeSignIn` keeps the loading screen up and leaves for the task URL, as the last sign-up branch of `_handleRedirectCallback` does with `redirectToTasks`. The step has to be `start` for this, so a sign-up that still needs something is not skipped because another session on the client has a task. - Anything else is `next(step)`. 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 b28e1badc3f..210294ea406 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -650,7 +650,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') { @@ -664,9 +664,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 806243d0db8..b803b3d12e1 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -204,6 +204,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'; @@ -251,6 +252,11 @@ function transferRoute(signIn: Pick Date: Mon, 30 Nov 2026 23:05:46 -0700 Subject: [PATCH 09/16] 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 | 20 ++++++++------ 3 files changed, 39 insertions(+), 11 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 cc9d8a12ad7..a61dfd86c78 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 c73c56bd8c2..21a46e02487 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -348,12 +348,6 @@ export function useSignUpController( }); const isHolding = override.type === 'hold'; const isLeaving = override.type === 'leave'; - const isHidden = isLeaving || (override.type === 'done' && emailLinkStatus === undefined); - const isHiddenNow = useRef(isHidden); - - useEffect(() => { - isHiddenNow.current = isHidden; - }, [isHidden]); useEffect(() => { if (isLeaving && !hasLeft.current) { @@ -371,13 +365,23 @@ 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 isHidden = isLeaving || (override.type === 'done' && shownEmailLinkStatus === undefined); + const isHiddenNow = useRef(isHidden); + + useEffect(() => { + isHiddenNow.current = isHidden; + }, [isHidden]); + const screen = isLoading ? 'loading' : (heldScreen ?? screenFor(correctedRoute, model, { isBlocked: blockedDetails !== undefined, hasConnections: connections !== undefined, - hasEmailLinkStatus: emailLinkStatus !== undefined, + hasEmailLinkStatus: shownEmailLinkStatus !== undefined, })); useRouteGuard({ route, go }, correctedRoute); @@ -519,7 +523,7 @@ export function useSignUpController( onSignIn: navigation.goToSignIn, }, actionBlocked: blockedDetails, - emailLinkStatus, + emailLinkStatus: shownEmailLinkStatus, enterpriseConnections: connections && { options: connections, pendingConnectionId: connectionActions.pendingKey, From 7531a0fb56a13c2061311fd8955b9cf919bc51a2 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 23:12:17 -0700 Subject: [PATCH 10/16] 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 a61dfd86c78..4979470000c 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. It reads `sent` only then. FAPI fails a verification after three wrong codes and expires an old one, and both read as `sent: false` while the screen is open. The screen sends nothing for them until the user presses Resend, as `ui`'s code card does: a code sent on its own would give the user three more tries without their asking. 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 b803b3d12e1..964b9cfe92f 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -140,7 +140,6 @@ export interface SignUpEmailLinkWait { export interface SignUpEmailLinkModel { target: string; - needsLink: boolean; send: () => Promise; wait: () => SignUpEmailLinkWait; } @@ -868,7 +867,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 ea580183572..a724da94e69 100644 --- a/packages/swingset/src/stories/sign-up.stories.tsx +++ b/packages/swingset/src/stories/sign-up.stories.tsx @@ -93,7 +93,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 c7f0ee2cb5c6111b989ddd78d2fae7f79178705f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 00:29:40 -0700 Subject: [PATCH 11/16] 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 4979470000c..7f04f204fe0 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 21a46e02487..b0c72940985 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -40,7 +40,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; } @@ -50,15 +51,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' } @@ -74,7 +78,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, })), @@ -101,7 +105,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', @@ -123,7 +141,8 @@ const activityMachine = activity.createMachine({ frozenModel: null, activate: undefined, frozenScreen: undefined, - sessionId: undefined, + showsFailedLink: false, + linkStatus: undefined, error: undefined, onFinalized: undefined, }, @@ -145,7 +164,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: { invoke: activity.fromPromise(context => context.startEnterpriseSso(), { @@ -170,17 +189,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, @@ -202,6 +237,7 @@ const FINALIZE_STATUS = { completingReturn: 'idle', startingEnterpriseSso: 'idle', choosingConnection: 'idle', + showingLinkStatus: 'idle', arrivalFailed: 'idle', finalizing: 'running', failed: 'failed', @@ -337,7 +373,6 @@ export function useSignUpController( }, }); const [blockedDetails, block] = useBlockedOn(route); - const [emailLinkStatus, setEmailLinkStatus] = useState(); const hasLeft = useRef(false); const connectionActions = usePendingAction(); const expiredProtectReloads = useRef(0); @@ -365,9 +400,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 isHidden = isLeaving || (override.type === 'done' && shownEmailLinkStatus === undefined); const isHiddenNow = useRef(isHidden); @@ -396,7 +429,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') { @@ -426,7 +459,7 @@ export function useSignUpController( frozenModel: model, activate: () => model.attempt.finalize(sessionId), frozenScreen: 'loading', - sessionId, + showsFailedLink: true, onFinalized: details.clear, }); return; From 527653126a6a16f7a9bb448e6ac31325d1c4c131 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 11:42:21 -0700 Subject: [PATCH 12/16] refactor(mosaic): tell an email-link arrival apart from a signed-in visitor in the session override The page an email link opens now arrives with the intent emailLink, which passes arrivedForResult to sessionOverride in place of recording the arrival session as none. While the link's status shows, isShowingResult keeps the override at none, so the controller no longer renders a done override. --- .../docs/internals/sign-in-sign-up-flow.md | 4 +- .../__tests__/auth-flow.utils.test.ts | 17 ++++++++ .../src/features/auth-flow/auth-flow.types.ts | 4 ++ .../src/features/auth-flow/auth-flow.utils.ts | 42 ++++++++++++++----- .../features/sign-up/sign-up.controller.ts | 23 +++++++--- 5 files changed, 73 insertions(+), 17 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 7f04f204fe0..c23235c20c2 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -92,7 +92,7 @@ Sign-up: The step is the sign-up resource's and says nothing about the session. The model returns the session beside it as `session`: `none`, `activating` while `setActive` runs and Clerk reports no session, `task` (`key`) for a pending task sign-up shows in its own card, or `active`. A task the application gave a URL in `taskUrls`, or one sign-up has no screen for, is `active`, not `task`: the flow leaves for its URL. -The controller passes the session to `sessionOverride` (`features/auth-flow/auth-flow.utils.ts`, shared with sign-in) with the three facts only it holds: the session when the component mounted, where its `finalize()` is (`idle`, `running`, `failed` or `succeeded`), and whether the route is one only a signed-out visitor sees. The override is decided before the step is read, so an unfinished sign-up left on the client cannot override it: +The controller passes the session to `sessionOverride` (`features/auth-flow/auth-flow.utils.ts`, shared with sign-in) with the facts only it holds: the session when the component mounted, whether the visitor arrived to see the result of something started elsewhere (`arrivedForResult`) and whether that result shows (`isShowingResult`), where its `finalize()` is (`idle`, `running`, `failed` or `succeeded`), and whether the route is one only a signed-out visitor sees. The override is decided before the step is read, so an unfinished sign-up left on the client cannot override it: - `none`: the step picks the route, as listed above. This is also the override for a visitor who arrived signed in, in multi-session mode, so `start` shows and the user can add an account. - `task` → `taskChooseOrganization`: only the task route is shown, so a visit to `start` with the task pending moves to it, and the task shows its skeleton until its data loads. @@ -139,7 +139,7 @@ Sign-up redeems invitation tickets, starts enterprise SSO redirects, and complet - `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. + 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. Such a page arrives with the intent `emailLink`, which passes `arrivedForResult`, so the session it arrived with neither leaves nor ends the flow and the link's result decides. While the link's status shows (`showingLinkStatus`), `isShowingResult` keeps a session signed in elsewhere from hiding it. - 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 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 visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. 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: diff --git a/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts b/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts index 2b90895b552..17825eba770 100644 --- a/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts +++ b/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts @@ -8,6 +8,8 @@ const noOverride: AuthSessionOverride = { type: 'none' }; const facts: AuthSessionOverrideFacts = { session: { type: 'none' }, sessionOnArrival: 'none', + arrivedForResult: false, + isShowingResult: false, finalizeStatus: 'idle', isSingleSession: false, isTaskLoaded: true, @@ -52,6 +54,21 @@ describe('session override', () => { { session: { type: 'active' }, sessionOnArrival: 'active', isSingleSession: true }, { type: 'leave' }, ], + [ + 'does not leave when the visitor arrived signed in for a result, in single-session mode', + { session: { type: 'active' }, sessionOnArrival: 'active', arrivedForResult: true, isSingleSession: true }, + { type: 'done' }, + ], + [ + 'is not done for a task the visitor arrived with for a result', + { session: { type: 'active' }, sessionOnArrival: 'task', arrivedForResult: true, isSignedOutOnly: false }, + noOverride, + ], + [ + 'lets the result show over a signed-in session, in single-session mode', + { session: { type: 'active' }, sessionOnArrival: 'active', isShowingResult: true, isSingleSession: true }, + noOverride, + ], [ 'follows the resource to add an account, in multi-session mode', { session: { type: 'active' }, sessionOnArrival: 'active' }, diff --git a/packages/mosaic/src/features/auth-flow/auth-flow.types.ts b/packages/mosaic/src/features/auth-flow/auth-flow.types.ts index 7f939ce0cd1..72ca3e40ed5 100644 --- a/packages/mosaic/src/features/auth-flow/auth-flow.types.ts +++ b/packages/mosaic/src/features/auth-flow/auth-flow.types.ts @@ -36,6 +36,10 @@ export type AuthSessionOverride = export interface AuthSessionOverrideFacts { session: AuthSessionPhase; sessionOnArrival: AuthSessionPhase['type']; + /** The visitor arrived to see the result of something they started elsewhere, such as an email link, not as a visitor who is signed in. */ + arrivedForResult: boolean; + /** The flow is showing that result, which the session does not override. */ + isShowingResult: boolean; finalizeStatus: AuthFinalizeStatus; isSingleSession: boolean; isTaskLoaded: boolean; diff --git a/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts b/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts index ec123bd1469..783abe3389b 100644 --- a/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts +++ b/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts @@ -12,11 +12,16 @@ export function formatPhoneIdentifier(identifier: string): string { export function sessionOverride({ session, sessionOnArrival, + arrivedForResult, + isShowingResult, finalizeStatus, isSingleSession, isTaskLoaded, isSignedOutOnly, }: AuthSessionOverrideFacts): AuthSessionOverride { + if (isShowingResult) { + return { type: 'none' }; + } if (finalizeStatus === 'running') { return { type: 'hold' }; } @@ -28,15 +33,32 @@ export function sessionOverride({ case 'task': return finalizeStatus === 'succeeded' && !isTaskLoaded ? { type: 'hold' } : session; case 'active': - if (finalizeStatus === 'succeeded' || sessionOnArrival === 'task') { - return { type: 'done' }; - } - if (!isSingleSession) { - return { type: 'none' }; - } - if (sessionOnArrival === 'active') { - return { type: 'leave' }; - } - return isSignedOutOnly ? { type: 'done' } : { type: 'none' }; + return activeSessionOverride({ + sessionOnArrival: arrivedForResult ? 'none' : sessionOnArrival, + finalizeStatus, + isSingleSession, + isSignedOutOnly, + }); + } +} + +function activeSessionOverride({ + sessionOnArrival, + finalizeStatus, + isSingleSession, + isSignedOutOnly, +}: Pick< + AuthSessionOverrideFacts, + 'sessionOnArrival' | 'finalizeStatus' | 'isSingleSession' | 'isSignedOutOnly' +>): AuthSessionOverride { + if (finalizeStatus === 'succeeded' || sessionOnArrival === 'task') { + return { type: 'done' }; + } + if (!isSingleSession) { + return { type: 'none' }; + } + if (sessionOnArrival === 'active') { + return { type: 'leave' }; } + return isSignedOutOnly ? { type: 'done' } : { type: 'none' }; } 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 b0c72940985..40c84650d3e 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -28,7 +28,7 @@ import type { } from './sign-up.types'; import { useSignUpDetailsController } from './sign-up-details/sign-up-details.controller'; -type SignUpArrivalIntent = 'visit' | 'ticket' | 'return' | 'enterpriseSso'; +type SignUpArrivalIntent = 'visit' | 'ticket' | 'return' | 'emailLink' | 'enterpriseSso'; interface ActivityContext { arrivalIntent: SignUpArrivalIntent; @@ -125,6 +125,7 @@ const FIRST_STATE = { visit: 'idle', ticket: 'redeemingTicket', return: 'completingReturn', + emailLink: 'completingReturn', enterpriseSso: 'startingEnterpriseSso', } as const satisfies Record; @@ -284,7 +285,10 @@ function arrivalIntentFor( route: SignUpRoute, override: AuthSessionOverride, ): SignUpArrivalIntent { - if (model.attempt.pendingReturn !== undefined && override.type !== 'leave') { + if (model.attempt.pendingReturn === 'email_link') { + return 'emailLink'; + } + if (model.attempt.pendingReturn === 'sso' && override.type !== 'leave') { return 'return'; } if (override.type === 'none' && correctRoute(route, override, model.attempt.step) === 'enterpriseConnections') { @@ -330,8 +334,14 @@ export function useSignUpController( isSignedOutOnly: isSignedOutOnlyRoute(route), }; const [arrival] = useState(() => { - const session = liveModel.attempt.pendingReturn === 'email_link' ? 'none' : liveModel.session.type; - const override = sessionOverride({ ...facts, sessionOnArrival: session, finalizeStatus: 'idle' }); + const session = liveModel.session.type; + const override = sessionOverride({ + ...facts, + sessionOnArrival: session, + arrivedForResult: liveModel.attempt.pendingReturn === 'email_link', + isShowingResult: false, + finalizeStatus: 'idle', + }); return { session, leave: liveModel.navigation.goToAfterSignUp, @@ -379,6 +389,9 @@ export function useSignUpController( const override = sessionOverride({ ...facts, sessionOnArrival: arrival.session, + // A page an email link opens shows the link's result whatever session the visitor has. + arrivedForResult: arrival.intent === 'emailLink', + isShowingResult: activitySnapshot.value === 'showingLinkStatus', finalizeStatus: FINALIZE_STATUS[activitySnapshot.value], }); const isHolding = override.type === 'hold'; @@ -401,7 +414,7 @@ export function useSignUpController( const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const shownEmailLinkStatus = activitySnapshot.context.linkStatus; - const isHidden = isLeaving || (override.type === 'done' && shownEmailLinkStatus === undefined); + const isHidden = isLeaving || override.type === 'done'; const isHiddenNow = useRef(isHidden); useEffect(() => { From 2664e4e280885aa92e8efa2c6ef1b89e5685c5f0 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 21:36:50 -0700 Subject: [PATCH 13/16] fix(mosaic): send no phone code from the tab that waits on a sign-up email link The wait's reload updates the sign-up before the wait resolves, and the route guard followed the new step, so a link opened in the same browser mounted the phone screen in the waiting tab and sent its code from there. The email route now stays allowed while the sign-up has an email link to wait on, so only the wait's outcome moves the tab. --- .../docs/internals/sign-in-sign-up-flow.md | 7 +-- .../sign-up.email-link.feature.test.tsx | 46 +++++++++++++++++++ .../sign-up/__tests__/sign-up.routes.test.ts | 23 +++++++++- .../features/sign-up/sign-up.controller.ts | 19 +++++--- .../src/features/sign-up/sign-up.routes.ts | 16 +++++-- 5 files changed, 96 insertions(+), 15 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 c23235c20c2..b1a9f13f8ef 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -22,10 +22,10 @@ const { route } = useRouterScope(signInRoutes, { routing, path, root: 'start' }) const shown = step.type === 'unknown' ? undefined : allowedRoute(route, step) ? route : routeFor(step); ``` -The flow's `*.routes.ts` exports this rule as one function, so the controller and the unit test share it (`correctRoute` in `mosaic/src/features/sign-up/sign-up.routes.ts`). Sign-up's also takes the session override and reads the step only when the override is `none` ([Routes and steps](#routes-and-steps)). No route means "Start over". +The flow's `*.routes.ts` exports this rule as one function, so the controller and the unit test share it (`correctRoute` in `mosaic/src/features/sign-up/sign-up.routes.ts`). Sign-up's also takes the session override and reads the step only when the override is `none` ([Routes and steps](#routes-and-steps)), and takes whether the sign-up has an email link to wait on ([Mount the screen](#mount-the-screen)). No route means "Start over". - `routeFor(step)` returns the step's route, from the lists below. Sign-up's also takes the current route, so a verify step reached from `continue` stays under it. -- `allowedRoute(route, step)` is `true` for `start`, for the step's own route, and for `continue` while sign-up verifies, so the user can edit a field. `complete` and `transfer` have no route, so they allow any route: the current screen stays up while `next` runs, and shows the error if it fails. +- `allowedRoute(route, step)` is `true` for `start`, for the step's own route, and for `continue` while sign-up verifies, so the user can edit a field. Sign-up's is also `true` for the email route while the sign-up has an email link to wait on, so the link screen's wait moves the tab and the step does not ([Mount the screen](#mount-the-screen)). `complete` and `transfer` have no route, so they allow any route: the current screen stays up while `next` runs, and shows the error if it fails. - The component that owns the route table computes the screen during render, and passes the route shown to `useRouteGuard`, which replaces a route the step does not allow so the stored route never keeps it. It is a guard, not a route table that changes with the step: the route exists, the flow is just not ready for it. - This runs once the model is `ready`, and after Clerk loads there is always a step. Until then the scope gets `ready: false`, so a starting route like `factor-one` isn't reset to `start`. @@ -40,6 +40,7 @@ Sign-up renders one component per screen, so the route decides what is mounted ( - 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 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's reload updates the sign-up before the wait resolves, so the step changes while the link screen is still up. The step does not move the route off the link screen. While the sign-up has an email address on an instance that verifies it by link, `allowedRoute` allows the email route for every step (`hasEmailLink` in `mosaic/src/features/sign-up/sign-up.routes.ts`), and only the wait's outcome moves the tab, through `next`. If the step moved it, a link opened in this browser would mount the next screen in the tab that waits, and a phone screen would send its code from there, before the outcome says this tab only points to the other one. `ui` works the same way: its `SignUpEmailLinkCard` decides where its tab goes when the poll ends, and its route only checks that the sign-up has an email address. An `unknown` step still shows Start over, and the session overrides still come first. - 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)). @@ -112,7 +113,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 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. +- 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. Once the email is verified FAPI refuses that request (`verification_already_verified`), and the step does not move the route off the link screen ([Mount the screen](#mount-the-screen)), so a reload there shows FAPI's error on the link screen, as `ui`'s link card does. Edit leads back to the form. - 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 8a62b2f5535..143e535e35b 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 @@ -8,6 +8,7 @@ import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from import { renderWithClerk } from '../../../__tests__/feature/render'; import { SignUp } from '../sign-up'; import { + codeSent, continueButton, EMAIL, emailField, @@ -56,8 +57,21 @@ const linkOut = (hasPassword = true) => ({ signUp: { emailLinkRedirectUrl: LINK_URL }, }); +const linkOutWithPhone = () => ({ + ...linkOut(), + environment: environment({ + attributes: { + email_address: { required: true, verifications: ['email_link'] }, + phone_number: { enabled: true, required: true, verifications: ['phone_code'], verify_at_sign_up: true }, + }, + }), + client: { ...fapiClient(), sign_up: { ...signUpWithLink({}), phone_number: '+15555550123' } }, +}); + const linkSent = () => screen.findByRole('button', { name: /^Resend \(\d+\)$/ }); +const settle = () => new Promise(resolve => setTimeout(resolve, 100)); + const checkedSignUp = (request: Request) => CHECK_PATH.exec(new URL(request.url).pathname)?.[1]; function holdChecks() { @@ -262,6 +276,21 @@ describe('SignUp', () => { expect(navigate).not.toHaveBeenCalled(); }); + it('moves on to the phone and sends one code when the link is opened in another browser with the phone still to verify', async () => { + const { fapi, user } = await renderSignUpWithRouteProbe(linkOutWithPhone()); + const checks = holdChecks(); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink('client_other'); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + expect(await codeSent()).toBeDisabled(); + await settle(); + expect(fapi.signUp.preparations).toEqual(['email_link', 'phone_code:sms']); + }); + 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 checks = holdChecks(); @@ -279,6 +308,23 @@ describe('SignUp', () => { expect(navigate).not.toHaveBeenCalled(); }); + it('sends no phone code from the tab that waits when the link is opened in this browser with the phone still to verify', async () => { + const { fapi, user } = await renderSignUpWithRouteProbe(linkOutWithPhone()); + const checks = holdChecks(); + const sawPhoneScreen = watchForHeading('Verify your phone'); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink(); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + await settle(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + expect(sawPhoneScreen()).toBe(false); + }); + it('says the link expired without sending another, then sends a new one on Resend', async () => { const { fapi } = await renderSignUp({ environment: byLink() }); vi.useFakeTimers({ shouldAdvanceTime: true }); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts b/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts index d26a0c8aa33..7f180936203 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts @@ -10,6 +10,8 @@ const verifyPhone: SignUpNextStep = { type: 'verify_phone', target: '+1555555014 const fields: SignUpNextStep = { type: 'fields', fields: ['username'] }; const task = { type: 'task', key: 'choose-organization' } as const; const noOverride = { type: 'none' } as const; +const byCode = { hasEmailLink: false }; +const byLink = { hasEmailLink: true }; describe('sign-up corrected route', () => { it.each<[string, SignUpRoute, SignUpNextStep, SignUpRoute | undefined]>([ @@ -53,7 +55,20 @@ describe('sign-up corrected route', () => { ['has no route for an unknown step', 'verifyEmail', { type: 'unknown' }, undefined], ['moves a task route back to start once signed out', 'taskChooseOrganization', { type: 'start' }, 'start'], ])('%s', (_, route, step, expected) => { - expect(correctRoute(route, noOverride, step)).toBe(expected); + expect(correctRoute(route, noOverride, step, byCode)).toBe(expected); + }); + + it.each<[string, SignUpRoute, SignUpNextStep, SignUpRoute | undefined]>([ + ['keeps the link screen once the phone is next', 'verifyEmail', verifyPhone, 'verifyEmail'], + ['keeps the link screen once fields are next', 'verifyEmail', fields, 'verifyEmail'], + ['keeps the link screen once a protect check is next', 'verifyEmail', { type: 'protect' }, 'verifyEmail'], + ['keeps the link screen once enterprise SSO is next', 'verifyEmail', { type: 'enterprise_sso' }, 'verifyEmail'], + ['keeps the link screen under continue', 'continueVerifyEmail', verifyPhone, 'continueVerifyEmail'], + ['has no route for an unknown step', 'verifyEmail', { type: 'unknown' }, undefined], + ['moves the phone screen to the link screen', 'verifyPhone', verifyEmail, 'verifyEmail'], + ['moves the form ahead of the attempt to the step route', 'continue', { type: 'protect' }, 'continueProtectCheck'], + ])('%s, when the email verifies by link', (_, route, step, expected) => { + expect(correctRoute(route, noOverride, step, byLink)).toBe(expected); }); it.each<[string, SignUpRoute, AuthSessionOverride, SignUpRoute]>([ @@ -67,7 +82,11 @@ describe('sign-up corrected route', () => { ], ['keeps the route once the flow is done', 'verifyEmail', { type: 'done' }, 'verifyEmail'], ])('%s', (_, route, override, expected) => { - expect(correctRoute(route, override, verifyEmail)).toBe(expected); + expect(correctRoute(route, override, verifyEmail, byCode)).toBe(expected); + }); + + it('sends a session task from the link screen to its route', () => { + expect(correctRoute('verifyEmail', task, verifyPhone, byLink)).toBe('taskChooseOrganization'); }); }); 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 40c84650d3e..63179e172b0 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -16,7 +16,7 @@ import { REDIRECT_HOLD_MS } from '../../utils/redirect'; import type { AuthFinalizeStatus, AuthSessionOverride } from '../auth-flow/auth-flow.types'; import { sessionOverride } from '../auth-flow/auth-flow.utils'; import type { SignUpCreateResult, SignUpReadyModel } from './sign-up.model'; -import type { SignUpRoute, SignUpTaskKey } from './sign-up.routes'; +import type { SignUpRoute, SignUpRouteFacts, SignUpTaskKey } from './sign-up.routes'; import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRoutes } from './sign-up.routes'; import type { SignUpEmailLinkScreen, @@ -269,15 +269,19 @@ function screenFor( return instance.signUpMode === 'public' || attempt.ticket ? 'start' : instance.signUpMode; } +function routeFacts({ verification }: SignUpReadyModel): SignUpRouteFacts { + return { hasEmailLink: Boolean(verification.emailLink?.target) }; +} + function redeemsTicket( - { attempt }: SignUpReadyModel, + model: SignUpReadyModel, route: SignUpRoute, override: AuthSessionOverride, ): boolean { - if (!attempt.ticket || override.type !== 'none') { + if (!model.attempt.ticket || override.type !== 'none') { return false; } - return route === 'start' || correctRoute(route, override, attempt.step) === 'start'; + return route === 'start' || correctRoute(route, override, model.attempt.step, routeFacts(model)) === 'start'; } function arrivalIntentFor( @@ -291,7 +295,10 @@ function arrivalIntentFor( if (model.attempt.pendingReturn === 'sso' && override.type !== 'leave') { return 'return'; } - if (override.type === 'none' && correctRoute(route, override, model.attempt.step) === 'enterpriseConnections') { + if ( + override.type === 'none' && + correctRoute(route, override, model.attempt.step, routeFacts(model)) === 'enterpriseConnections' + ) { return 'enterpriseSso'; } return redeemsTicket(model, route, override) ? 'ticket' : 'visit'; @@ -411,7 +418,7 @@ export function useSignUpController( activitySnapshot.value === 'redeemingTicket' || activitySnapshot.value === 'completingReturn' || activitySnapshot.value === 'startingEnterpriseSso'; - const correctedRoute = correctRoute(route, override, attempt.step); + const correctedRoute = correctRoute(route, override, attempt.step, routeFacts(model)); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const shownEmailLinkStatus = activitySnapshot.context.linkStatus; const isHidden = isLeaving || override.type === 'done'; diff --git a/packages/mosaic/src/features/sign-up/sign-up.routes.ts b/packages/mosaic/src/features/sign-up/sign-up.routes.ts index 94fa03961e5..8e441e7d6e5 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.routes.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.routes.ts @@ -60,7 +60,11 @@ export function routeFor(step: SignUpNextStep, from: SignUpRoute): SignUpRoute | } } -function allowedRoute(route: SignUpRoute, step: SignUpNextStep): boolean { +export interface SignUpRouteFacts { + hasEmailLink: boolean; +} + +function allowedRoute(route: SignUpRoute, step: SignUpNextStep, { hasEmailLink }: SignUpRouteFacts): boolean { if (route === 'start' || step.type === 'complete' || step.type === 'transfer') { return true; } @@ -70,24 +74,28 @@ function allowedRoute(route: SignUpRoute, step: SignUpNextStep): boolean { ) { return true; } + if (hasEmailLink && (route === 'verifyEmail' || route === 'continueVerifyEmail')) { + return true; + } return route === routeFor(step, route); } -function stepRoute(route: SignUpRoute, step: SignUpNextStep): SignUpRoute | undefined { +function stepRoute(route: SignUpRoute, step: SignUpNextStep, facts: SignUpRouteFacts): SignUpRoute | undefined { if (step.type === 'unknown') { return undefined; } - return allowedRoute(route, step) ? route : routeFor(step, route); + return allowedRoute(route, step, facts) ? route : routeFor(step, route); } export function correctRoute( route: SignUpRoute, override: AuthSessionOverride, step: SignUpNextStep, + facts: SignUpRouteFacts, ): SignUpRoute | undefined { switch (override.type) { case 'none': - return stepRoute(route, step); + return stepRoute(route, step, facts); case 'task': return 'taskChooseOrganization'; case 'hold': From 953424175606c28eca1c18b7026c1da27d5459cc Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 4 Dec 2026 10:30:08 -0700 Subject: [PATCH 14/16] fix(mosaic): keep waiting for the sign-up email link after a host Activity hides and shows it A host's runs the screen's effect cleanups when it hides the sign-up, which cancels the wait while the machine stays in waiting. When it shows the screen again the actor resumes without restarting its invoke, and the SEND the screen sends was ignored because waiting had no SEND handler, so the screen stopped polling. SEND in waiting now re-enters the state, which starts a new wait without sending another link or restarting the Resend countdown. --- .../docs/internals/sign-in-sign-up-flow.md | 2 +- .../sign-up-email-link.controller.test.ts | 32 ++++++++++++++++++- .../sign-up-email-link.controller.ts | 6 ++-- 3 files changed, 36 insertions(+), 4 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 b1a9f13f8ef..ad38cf19dd9 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -39,7 +39,7 @@ Sign-up renders one component per screen, so the route decides what is mounted ( - `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 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 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. A host's `` that hides the sign-up runs the same cleanup but keeps the machine in `waiting`, so when it shows the screen again the screen's `SEND` re-enters `waiting`, which starts a new wait without sending a link or restarting the Resend countdown. `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's reload updates the sign-up before the wait resolves, so the step changes while the link screen is still up. The step does not move the route off the link screen. While the sign-up has an email address on an instance that verifies it by link, `allowedRoute` allows the email route for every step (`hasEmailLink` in `mosaic/src/features/sign-up/sign-up.routes.ts`), and only the wait's outcome moves the tab, through `next`. If the step moved it, a link opened in this browser would mount the next screen in the tab that waits, and a phone screen would send its code from there, before the outcome says this tab only points to the other one. `ui` works the same way: its `SignUpEmailLinkCard` decides where its tab goes when the poll ends, and its route only checks that the sign-up has an email address. An `unknown` step still shows Start over, and the session overrides still come first. - 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. 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 ea779c3019f..dcb84cda105 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 @@ -1,7 +1,37 @@ import { act, renderHook } from '@testing-library/react'; import { afterEach, describe, expect, it, vi } from 'vitest'; -import { useSignUpEmailLinkController } from '../sign-up-email-link.controller'; +import { tick } from '../../../../__tests__/async'; +import { createActor } from '../../../../machine/create-actor'; +import { linkMachine, useSignUpEmailLinkController } from '../sign-up-email-link.controller'; + +describe('linkMachine', () => { + // A host's React 19.2 hides the screen by running its effect cleanups, which stop the + // actor and cancel the wait, and shows it by starting the actor and sending SEND again. + it('waits again without sending a second link or resetting the cooldown when shown after being hidden', async () => { + const sendLink = vi.fn(() => Promise.resolve()); + const waitForLink = vi.fn(() => new Promise(() => {})); + const stopWaiting = vi.fn(); + const actor = createActor(linkMachine, { context: { sendLink, waitForLink, stopWaiting } }).start(); + actor.send({ type: 'SEND' }); + await tick(); + expect(actor.getSnapshot().value).toBe('waiting'); + const { resendAvailableAt } = actor.getSnapshot().context; + + actor.stop(); + actor.start(); + actor.send({ type: 'SEND' }); + + expect(actor.getSnapshot().value).toBe('waiting'); + expect(waitForLink).toHaveBeenCalledTimes(2); + expect(sendLink).toHaveBeenCalledTimes(1); + expect(actor.getSnapshot().context.resendAvailableAt).toBe(resendAvailableAt); + }); + + // Needs React 19.2's Activity around the whole sign-up, which the React 18 test projects cannot + // render. The machine test above covers the transition the shown screen relies on. + it.todo('keeps waiting for the link after a host Activity hides and shows the screen'); +}); describe('useSignUpEmailLinkController', () => { afterEach(() => vi.useRealTimers()); 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 2a067b3b5c5..2f503eae981 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 @@ -36,7 +36,7 @@ const resend = { actions: link.assign(() => ({ error: undefined })), }; -const linkMachine = link.createMachine({ +export const linkMachine = link.createMachine({ id: 'signUpEmailLink', initial: 'idle', context: { @@ -58,7 +58,9 @@ const linkMachine = link.createMachine({ }), }, waiting: { - on: { RESEND: resend }, + // A host's cancels the wait when it hides the screen and sends SEND again when it + // shows it. Re-entering `waiting` starts a new wait without sending another link. + on: { SEND: 'waiting', RESEND: resend }, exit: context => context.stopWaiting(), invoke: link.fromPromise(context => context.waitForLink(), { onDone: [ From b7a15cc6581c33fec5b330ba4b7f9a17b269925e Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 4 Dec 2026 10:30:57 -0700 Subject: [PATCH 15/16] test(mosaic): leave the client's sign-up alone when the fake FAPI answers a sign-up read The fake's GET for a sign-up went through store(), which clears the client's sign_up when the returned sign-up is complete. A late poll for an older, completed sign-up then erased the one in progress. The read now answers with the sign-up and the client as they are, as FAPI does. --- packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 210294ea406..9b6b51776e3 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -865,7 +865,7 @@ export function signUpHandlers( return missing(); } state.signUp.reloads += 1; - return store(signUp); + return envelope(signUp, state.client); }), http.post(fapiUrl('/v1/client/sign_ups/:id'), async ({ params, request }) => { if (new URL(request.url).searchParams.get('_method') !== 'PATCH') { From 16ed1d68fdac32b89d3cd8e0fffb78d6c415f87e Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 4 Dec 2026 10:48:40 -0700 Subject: [PATCH 16/16] fix(mosaic): finish an email-link return while sign-up renders nothing The guard that drops a screen's late result once the flow hides also dropped the results of the activity machine's own work. An email link opened in a signed-in single-session page finishes while sign-up renders nothing, so its session was never activated and the page never left or showed the link's status. The ticket, return and enterprise SSO callbacks now advance the flow directly, and only the screens' `onNext` goes through the guard. --- .../features/sign-up/sign-up.controller.ts | 19 +++++++++++-------- 1 file changed, 11 insertions(+), 8 deletions(-) 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 63179e172b0..6552464f81c 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -369,20 +369,20 @@ export function useSignUpController( attempt.forgetTicket(); } details.adoptInvitation(emailAddress); - next(result); + advance(result); }); }, canRedeemTicket: (): boolean => !model.details.inTicketSignUp && redeemsTicket(model, route, override), completeReturn: async () => { const result = await attempt.completeReturn(); if (result) { - flushSync(() => next(result)); + flushSync(() => advance(result)); } }, startEnterpriseSso: async () => { const result = await attempt.startEnterpriseSso(); if (result) { - flushSync(() => next(result)); + flushSync(() => advance(result)); return; } await new Promise(resolve => setTimeout(resolve, REDIRECT_HOLD_MS)); @@ -439,11 +439,7 @@ export function useSignUpController( useRouteGuard({ route, go }, correctedRoute); - // A screen's action keeps running after the flow hides, and may hold the `next` from when it mounted. - const next = (result: SignUpCreateResult) => { - if (isHiddenNow.current) { - return; - } + const advance = (result: SignUpCreateResult) => { if (result.type === 'blocked') { block(result.details); return; @@ -504,6 +500,13 @@ export function useSignUpController( } }; + // A screen's action keeps running after the flow hides, and may hold the `next` from when it mounted. + const next = (result: SignUpCreateResult) => { + if (!isHiddenNow.current) { + advance(result); + } + }; + const activityError = activitySnapshot.context.error ? errorText(activitySnapshot.context.error) : undefined; const finalizeError = activitySnapshot.value === 'failed' ? activityError : undefined; const arrivalError = activitySnapshot.value === 'arrivalFailed' ? activityError : undefined;