From 1f91d9912f26abee670364e874daca18b593717b Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:03:08 -0700 Subject: [PATCH 01/40] test(mosaic): start and return from OAuth sign-ups in the fake FAPI --- .../__tests__/feature/fake-fapi/sign-up.ts | 147 +++++++++++++++++- 1 file changed, 145 insertions(+), 2 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 4bc67ce3237..ff205fbd627 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -1,10 +1,13 @@ import type { + ClerkAPIErrorJSON, ClientJSON, PhoneCodeChannel, SessionJSON, + SignInJSON, SignUpField, SignUpIdentificationField, SignUpJSON, + SignUpVerificationJSON, } from '@clerk/shared/types'; import { http, HttpResponse } from 'msw'; @@ -37,8 +40,14 @@ export interface FakeSignUpSeed { whatsAppEnabled?: boolean; whatsAppQuotaExceeded?: boolean; tickets?: Record; + oauth?: Record; } +export type FakeOAuthAccount = + | { emailAddress: string; firstName?: string; lastName?: string } + | { existingUser: { emailAddress: string; secondFactor?: boolean } } + | { error: { code: string; message: string } }; + export type FakeTicket = { emailAddress: string } | 'expired'; export interface FakeSignUpState { @@ -56,6 +65,9 @@ export interface FakeSignUpState { whatsAppEnabled: boolean; whatsAppQuotaExceeded: boolean; tickets: Record; + oauth: Record; + transfers: URLSearchParams[]; + returnFromOAuth: () => void; issuedProtectChecks: number; reloads: number; proofTokens: string[]; @@ -74,6 +86,11 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState { whatsAppEnabled: true, whatsAppQuotaExceeded: false, tickets: {}, + oauth: {}, + transfers: [], + returnFromOAuth: () => { + throw new Error('The fake FAPI has not started'); + }, issuedProtectChecks: 0, reloads: 0, proofTokens: [], @@ -120,6 +137,10 @@ function rejected(code: string, message: string, paramName?: string, status = 42 return HttpResponse.json({ errors: [formError(code, message, paramName, meta)] }, { status }); } +function apiError(code: string, message: string): ClerkAPIErrorJSON { + return { code, message, long_message: message, meta: {} }; +} + export function signUpHandlers( state: { client: ClientJSON; environment: FapiEnvironment; signUp: FakeSignUpState }, fapiUrl: (path: string) => string, @@ -192,9 +213,14 @@ export function signUpHandlers( const settle = (signUp: SignUpJSON): SignUpJSON => { const { attributes } = settings(); const { required_fields, optional_fields } = requirements(); + const external = signUp.verifications?.external_account; + const linked = external?.status === 'verified' ? external.strategy : undefined; const provided = (field: SignUpField) => { if (field === 'password') { - return signUp.has_password; + return signUp.has_password || Boolean(linked); + } + if (field.startsWith('oauth_')) { + return field === linked; } if (field === 'legal_accepted') { return signUp.legal_accepted_at !== null; @@ -267,6 +293,69 @@ export function signUpHandlers( return { ...settled, status: 'complete', created_session_id: session.id, created_user_id: user.id }; }; + const startOAuth = (signUp: SignUpJSON, body: URLSearchParams): SignUpJSON | ReturnType => { + const strategy = body.get('strategy') ?? ''; + if (!body.get('redirect_url')) { + return rejected('form_param_missing', 'redirect_url must be included.', 'redirect_url'); + } + return { + ...signUp, + verifications: { + ...signUp.verifications, + external_account: { + ...fapiUnpreparedVerification(), + ...fapiVerification(strategy), + next_action: '', + supported_strategies: [strategy], + external_verification_redirect_url: `https://oauth.example/authorize?strategy=${strategy}`, + }, + }, + }; + }; + + state.signUp.returnFromOAuth = () => { + const signUp = state.client.sign_up; + const external = signUp?.verifications?.external_account; + const account = external ? state.signUp.oauth[external.strategy] : undefined; + if (!signUp?.verifications || !external || !account) { + throw new Error('No OAuth sign-up to return from'); + } + const withExternal = (changes: Partial): SignUpJSON => ({ + ...signUp, + verifications: { ...signUp.verifications!, external_account: { ...external, ...changes } }, + }); + if ('error' in account) { + store(withExternal({ status: 'failed', error: apiError(account.error.code, account.error.message) })); + return; + } + if ('existingUser' in account) { + store( + withExternal({ + status: 'transferable', + error: apiError('external_account_exists', 'This account already exists. Sign in instead.'), + }), + ); + return; + } + const linked = withExternal({ status: 'verified' }); + store( + settle({ + ...linked, + email_address: account.emailAddress, + first_name: account.firstName ?? signUp.first_name, + last_name: account.lastName ?? signUp.last_name, + verifications: { + ...linked.verifications!, + email_address: { + ...linked.verifications!.email_address, + ...fapiVerification(`from_${external.strategy}`, { status: 'verified' }), + next_action: '', + }, + }, + }), + ); + }; + const apply = (signUp: SignUpJSON, body: URLSearchParams) => { const { attributes, password_settings } = settings(); const errors: ReturnType[] = []; @@ -383,6 +472,49 @@ export function signUpHandlers( } return [ + http.post(fapiUrl('/v1/client/sign_ins'), async ({ request }) => { + const body = new URLSearchParams(await request.text()); + const external = state.client.sign_up?.verifications?.external_account; + const account = external ? state.signUp.oauth[external.strategy] : undefined; + if ( + body.get('transfer') !== 'true' || + external?.status !== 'transferable' || + !account || + !('existingUser' in account) + ) { + return rejected('form_param_missing', 'Only sign-up transfers are supported by the fake FAPI.'); + } + state.signUp.transfers.push(body); + const { emailAddress, secondFactor = false } = account.existingUser; + let createdSessionId: string | null = null; + if (!secondFactor) { + const session = fapiSession({ + id: `sess_transferred_${state.signUp.transfers.length}`, + user: fapiUser({ + id: 'user_existing', + email_addresses: [fapiEmailAddress({ id: 'email_existing', email_address: emailAddress })], + }), + }); + state.client = { ...state.client, sessions: [...state.client.sessions, session] }; + createdSessionId = session.id; + } + const signIn = { + object: 'sign_in', + id: `sia_transfer_${state.signUp.transfers.length}`, + status: secondFactor ? 'needs_second_factor' : 'complete', + supported_identifiers: [], + identifier: emailAddress, + user_data: { first_name: null, last_name: null, image_url: '', has_image: false }, + supported_first_factors: [], + supported_second_factors: secondFactor ? [{ strategy: 'totp' }] : [], + first_factor_verification: null, + second_factor_verification: null, + created_session_id: createdSessionId, + timezone: null, + } as unknown as SignInJSON; + state.client = { ...state.client, sign_up: null, sign_in: secondFactor ? signIn : null }; + return envelope(signIn, state.client); + }), http.post(fapiUrl('/v1/client/sign_ups'), async ({ request }) => { const body = new URLSearchParams(await request.text()); state.signUp.creations.push(body); @@ -428,6 +560,13 @@ export function signUpHandlers( }, }; } + if (body.get('strategy')?.startsWith('oauth_')) { + const started = startOAuth(start, body); + if (started instanceof HttpResponse) { + return started; + } + start = started; + } const applied = apply(start, body); if (applied instanceof HttpResponse) { return applied; @@ -494,7 +633,11 @@ export function signUpHandlers( } const body = new URLSearchParams(await request.text()); state.signUp.updates.push(body); - const applied = apply(signUp, body); + const started = body.get('strategy')?.startsWith('oauth_') ? startOAuth(signUp, body) : signUp; + if (started instanceof HttpResponse) { + return started; + } + const applied = apply(started, body); if (applied instanceof HttpResponse) { return applied; } From 1b0d0cf47bb91bdc9af81c2dd897f1c28703b0e4 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:03:09 -0700 Subject: [PATCH 02/40] feat(mosaic): sign up with social providers Sign-up shows the instance's social providers on start and continue and starts the provider's sign-in with signUp.sso(). The callback URL carries a return marker, so sign-up resolves the return when it opens: it continues to what the sign-up still needs, turns an existing account into a sign-in, activates an already signed-in session, or shows the provider's error on start. --- .../__tests__/sign-up.feature.test.tsx | 120 +++++++++++++++++- .../sign-up-details.controller.ts | 39 +++++- .../features/sign-up/sign-up.controller.ts | 20 ++- .../src/features/sign-up/sign-up.model.ts | 92 ++++++++++++++ 4 files changed, 259 insertions(+), 12 deletions(-) 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 78747c0b7db..88b37da1ffb 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 @@ -1,16 +1,18 @@ import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { describe, expect, it, onTestFinished } from 'vitest'; +import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'; -import { holdRequests, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; +import { type FakeFapiSeed, holdRequests, serveFapi, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; import { fapiClient, + type FapiEnvironmentOverrides, fapiMembership, fapiOrganization, fapiSession, fapiSignUp, fapiUser, } from '../../../__tests__/feature/fapi'; +import { renderWithClerk } from '../../../__tests__/feature/render'; import { SignUp } from '../sign-up'; import { codeSent, @@ -1096,3 +1098,117 @@ describe('SignUp', () => { }); }); }); + +describe('SignUp social sign-up', () => { + const GOOGLE = { + enabled: true, + required: false, + authenticatable: true, + strategy: 'oauth_google' as const, + name: 'Google', + logo_url: null, + }; + + afterEach(() => { + window.history.replaceState(null, '', window.location.pathname); + }); + + function socialEnvironment(overrides: FapiEnvironmentOverrides = {}) { + return environment({ + ...overrides, + user_settings: { social: { oauth_google: GOOGLE }, ...overrides.user_settings }, + }); + } + + async function startWithGoogle(seed: FakeFapiSeed, options?: Parameters[1]) { + const fapi = serveFapi({ environment: socialEnvironment(), ...seed }); + const first = await renderWithClerk(, options); + const leave = vi.spyOn(first.clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: /Google/ })); + await waitFor(() => expect(leave).toHaveBeenCalled()); + return { fapi, first, leave, user }; + } + + async function returnFromGoogle( + fapi: ReturnType, + first: Awaited>, + options?: Parameters[1], + ) { + const callback = new URL(fapi.signUp.creations.at(-1)?.get('redirect_url') ?? ''); + first.unmount(); + fapi.signUp.returnFromOAuth(); + window.history.replaceState(null, '', `${callback.pathname}${callback.search}`); + return renderWithClerk(, options); + } + + it('starts Google sign-up with a callback URL that brings the user back to sign-up', async () => { + const { fapi, leave } = await startWithGoogle({}); + + expect(String(leave.mock.calls[0][0])).toBe('https://oauth.example/authorize?strategy=oauth_google'); + expect(fapi.signUp.creations).toHaveLength(1); + expect(fapi.signUp.creations[0].get('strategy')).toBe('oauth_google'); + expect(fapi.signUp.creations[0].get('redirect_url')).toContain('__clerk_mosaic_sign_up=sso-callback'); + expect(fapi.signUp.creations[0].get('action_complete_redirect_url')).toBeTruthy(); + }); + + it('asks for what Google did not provide after the return, then completes', async () => { + const seed: FakeFapiSeed = { + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, + }; + const { fapi, first } = await startWithGoogle(seed); + + const { navigate } = await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + expect(screen.queryByLabelText('Password')).toBeNull(); + + const user = userEvent.setup(); + await user.type(screen.getByRole('textbox', { name: 'Username' }), 'alice'); + await user.click(continueButton()); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.signUp.updates.at(-1)?.get('username')).toBe('alice'); + expect(fapi.client.sessions).toHaveLength(1); + }); + + it('signs in instead when the Google account already belongs to a user', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(fapi.client.sessions).toHaveLength(1); + }); + + it('hands a transfer that still needs a second factor to the sign-in page', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL, secondFactor: true } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInUrl: '/sign-in' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/sign-in'))); + expect(fapi.client.sessions).toHaveLength(0); + }); + + it('shows what went wrong at Google on the start form', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index 93ba9cfdac7..42660a690fe 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -6,7 +6,9 @@ import type { FieldFeedback, FieldsConfig } from '../../../components/form'; import { useForm } from '../../../components/form'; import { useDebouncedAsync } from '../../../hooks/use-debounced-async'; import type { MosaicMessages } from '../../../localization'; +import { usePendingAction } from '../../../hooks/use-pending-action'; import { useMessages } from '../../../localization'; +import { REDIRECT_HOLD_MS } from '../../user-profile/user-profile.utils'; import type { SignUpCreateResult, SignUpDetailsModel, SignUpDetailsValues, SignUpIdentifier } from '../sign-up.model'; import type { SignUpAlternativePhoneScreen, @@ -109,6 +111,7 @@ export function useSignUpDetailsController( const [chosenChannel, setChosenChannel] = useState(undefined); const genericError = useMessages('errors').generic; const m = useMessages('signUp'); + const providerActions = usePendingAction(); const identifier = chosenIdentifier ?? details.initialIdentifier; const startFields = details.startFieldsFor(identifier); const continueFields = details.continueFieldsFor(identifier); @@ -123,6 +126,7 @@ export function useSignUpDetailsController( fields: requiredFields(fields, consentRequired, m), onSubmit: values => { onSubmit?.(); + providerActions.reset(); const submitted = detailsValues(values, fields); if (purpose === 'continue' || details.inTicketSignUp) { return details.update(submitted); @@ -147,14 +151,15 @@ export function useSignUpDetailsController( const passwordFeedback: FieldFeedback | undefined = strength.isError ? { type: 'error', message: genericError } : strength.data; - const isPending = form.isSubmitting || isBusy; + const isPending = form.isSubmitting || isBusy || providerActions.isPending; const screen: Omit = { form, onSubmit: form.handleSubmit, isPending, isDisabled: isPending, - globalErrorMessage: form.error ?? globalErrorMessage, + globalErrorMessage: form.error ?? providerActions.error ?? globalErrorMessage, + pendingProviderId: providerActions.pendingKey, passwordFeedback, onSignIn, }; @@ -177,6 +182,20 @@ export function useSignUpDetailsController( } : undefined; + const selectOAuth = (id: string) => { + const provider = details.oauthProviders.find(oauth => oauth.id === id); + if (!provider) { + return; + } + void providerActions.run(id, async () => { + await details.sso(provider.id, { + legalAccepted: form.values.legalAccepted, + continueSignUp: purpose === 'continue', + }); + await new Promise(resolve => setTimeout(resolve, REDIRECT_HOLD_MS)); + }); + }; + const switchField = (purpose: 'start' | 'continue') => canSwitch(purpose, details) ? () => setChosenIdentifier(otherIdentifier(identifier)) : undefined; @@ -186,16 +205,22 @@ export function useSignUpDetailsController( ...screen, step: detailsStep('start', startFields, details, identifier), onSwitchField: switchField('start'), - socialProviders: details.alternativeChannels, - onSelectProvider: (id: string) => - switchChannel(details.alternativeChannels.find(provider => provider.id === id)?.id), + socialProviders: [...details.oauthProviders, ...details.alternativeChannels], + onSelectProvider: (id: string) => { + const channel = details.alternativeChannels.find(provider => provider.id === id)?.id; + if (channel) { + switchChannel(channel); + return; + } + selectOAuth(id); + }, }, continue: { ...screen, step: detailsStep('continue', continueFields, details, identifier), onSwitchField: switchField('continue'), - socialProviders: [], - onSelectProvider: () => undefined, + socialProviders: details.continueOAuthProviders, + onSelectProvider: selectOAuth, }, error: form.error, leaveChannel: () => switchChannel(undefined), 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 6719e521dbe..9d3cfbfcc3a 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -155,7 +155,7 @@ function arrivalIntentFor( correctedRoute: SignUpRoute | undefined, ): SignUpArrivalIntent { const opensOnStart = route === 'start' || correctedRoute === 'start'; - return attempt.ticket && !details.inTicketSignUp && opensOnStart ? 'ticket' : 'visit'; + return attempt.ticket && !attempt.hasPendingReturn && !details.inTicketSignUp && opensOnStart ? 'ticket' : 'visit'; } function useBlockedOn(route: SignUpRoute) { @@ -185,7 +185,8 @@ export function useSignUpController( { isTaskLoaded, ...options }: MosaicLocationOptions & { isTaskLoaded: boolean }, ): SignUpControllerResult { const { route, go } = useRouterScope(signUpRoutes, { ...options, root: 'start' }); - const actions = usePendingAction<'startOver'>(); + const actions = usePendingAction<'startOver' | 'return'>(); + const completedReturn = useRef(false); const errorText = useErrorText(); const facts = { session: liveModel.session, @@ -238,7 +239,7 @@ export function useSignUpController( const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const screen = - activitySnapshot.value === 'redeemingTicket' + activitySnapshot.value === 'redeemingTicket' || actions.pendingKey === 'return' ? 'loading' : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined)); @@ -279,6 +280,19 @@ export function useSignUpController( onNext: next, onSignIn: navigation.goToSignIn, }); + /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return, or redeems an invitation, once when sign-up opens on start with its marker or ticket in the URL; arriving from a redirect or a link is not an event a handler could run from. */ + useEffect(() => { + if (attempt.hasPendingReturn && route === 'start' && !completedReturn.current) { + completedReturn.current = true; + void actions.run('return', async () => { + const step = await attempt.completeReturn(); + if (step) { + next(step); + } + }); + } + }); + /* eslint-enable react-you-might-not-need-an-effect/no-event-handler */ const verify = { onNext: next, 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 9ba65c332a7..414db08450b 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -17,14 +17,17 @@ import { emailOrPhone, getInitialActiveIdentifier, } from '@clerk/shared/internal/clerk-js/signUpFormFields'; +import { OAUTH_PROVIDERS } from '@clerk/shared/oauth'; import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; import { __internal_useClerkSignal, useClerk, useSession } from '@clerk/shared/react'; import type { ClerkAPIError, + OAuthStrategy, PhoneCodeChannel, SessionTask, SignUpFutureResource, SignUpInitialValues, + UserSettingsResource, } from '@clerk/shared/types'; import { useMemo, useRef } from 'react'; @@ -70,6 +73,8 @@ export interface SignUpAttemptModel { step: SignUpNextStep; ticket: string | undefined; redeemTicket: () => Promise<{ result: SignUpCreateResult; emailAddress: string }>; + hasPendingReturn: boolean; + completeReturn: () => Promise; finalize: () => Promise; reset: () => Promise; } @@ -107,6 +112,9 @@ export interface SignUpDetailsModel { continueLegalConsent?: SignUpLegalConsent; validatePassword: (password: string) => Promise; alternativeChannels: Array; + oauthProviders: Array; + continueOAuthProviders: Array; + sso: (strategy: OAuthStrategy, options: { legalAccepted?: boolean; continueSignUp: boolean }) => Promise; inTicketSignUp: boolean; create: (values: SignUpDetailsValues, options?: { channel?: PhoneCodeChannel }) => Promise; update: (values: SignUpDetailsValues) => Promise; @@ -148,6 +156,36 @@ const DETAILS_FIELDS = [...signUpFieldOrder, 'legalAccepted'] as const; const PREFILL_NAMES = ['emailAddress', 'phoneNumber', 'username', 'firstName', 'lastName'] as const; const ABSOLUTE_URL = /^https?:\/\//; +const RETURN_PARAM = '__clerk_mosaic_sign_up'; +const SSO_RETURN = 'sso-callback'; +const OAUTH_PREFIX = /^oauth_(custom_)?/; + +function ssoCallbackUrl(): string { + const url = new URL(window.location.href); + url.searchParams.set(RETURN_PARAM, SSO_RETURN); + return url.toString(); +} + +function forgetReturn(): void { + const url = new URL(window.location.href); + if (url.searchParams.has(RETURN_PARAM)) { + url.searchParams.delete(RETURN_PARAM); + window.history.replaceState(window.history.state, '', url); + } +} + +function oauthProvidersFrom(userSettings: UserSettingsResource): Array { + return userSettings.authenticatableSocialStrategies + .flatMap(strategy => { + const known = OAUTH_PROVIDERS.find(provider => provider.strategy === strategy); + if (known) { + return [{ id: strategy, name: known.name, iconUrl: iconImageUrl(known.provider) }]; + } + const custom = strategy.startsWith('oauth_custom_') ? userSettings.social[strategy] : undefined; + return custom ? [{ id: strategy, name: custom.name, iconUrl: custom.logo_url || '' }] : []; + }) + .sort((a, b) => a.id.replace(OAUTH_PREFIX, '').localeCompare(b.id.replace(OAUTH_PREFIX, ''))); +} function toViewFields( fields: Partial>, @@ -199,6 +237,7 @@ export function useSignUpModel({ const router = useMosaicRouter(); const supportEmail = useMosaicSupportEmail(); const { signUp } = __internal_useClerkSignal('signUp'); + const { signIn } = __internal_useClerkSignal('signIn'); const { session } = useSession(); const lastCreated = useRef(undefined); const passwordMessages = useMessages('userProfile').password; @@ -269,6 +308,7 @@ export function useSignUpModel({ const ticket = getClerkQueryParam('__clerk_ticket') || getClerkQueryParam('__clerk_invitation_token') || undefined; const inTicketSignUp = Boolean(ticket) && signUp.verifications.emailAddress.strategy === 'ticket'; const phoneCodeChannels = inTicketSignUp ? [] : userSettings.alternativePhoneCodeChannels; + const oauthProviders = oauthProvidersFrom(userSettings); const forgetTicket = () => { removeClerkQueryParam('__clerk_ticket'); removeClerkQueryParam('__clerk_invitation_token'); @@ -383,6 +423,42 @@ export function useSignUpModel({ } return { result: next(signUp), emailAddress: signUp.emailAddress ?? '' }; }, + hasPendingReturn: new URL(window.location.href).searchParams.get(RETURN_PARAM) === SSO_RETURN, + completeReturn: async () => { + forgetReturn(); + if (signUp.isTransferable) { + await run(() => signIn.create({ transfer: true })); + if (signIn.status !== 'complete') { + await router.navigate(clerk.buildSignInUrl()); + return undefined; + } + await run(() => + signIn.finalize({ + navigate: async ({ decorateUrl }) => { + const afterSignInUrl = clerk.buildAfterSignInUrl(); + const decorated = decorateUrl(afterSignInUrl); + if (decorated !== afterSignInUrl && ABSOLUTE_URL.test(decorated)) { + router.windowNavigate(decorated); + return; + } + await router.navigate(afterSignInUrl); + }, + }), + ); + return undefined; + } + const existingSession = signUp.existingSession?.sessionId; + if (existingSession) { + await clerk.setActive({ session: existingSession, redirectUrl: clerk.buildAfterSignInUrl() }); + return undefined; + } + const failure = signUp.verifications.externalAccount.error; + if (failure) { + await run(() => signUp.reset()); + throw new SaveError({ global: { code: failure.code, message: failure.longMessage || failure.message } }); + } + return next(signUp); + }, finalize: async () => { forgetTicket(); await run(() => @@ -463,6 +539,22 @@ export function useSignUpModel({ continueLegalConsent: signUp.missingFields.includes('legal_accepted') ? legalConsent : undefined, validatePassword, inTicketSignUp, + oauthProviders, + continueOAuthProviders: signUp.verifications.externalAccount.status === 'verified' ? [] : oauthProviders, + sso: async (strategy, { legalAccepted, continueSignUp }) => { + if (signUp.id && !continueSignUp && !inTicketSignUp) { + await run(() => signUp.reset()); + } + await run(() => + signUp.sso({ + strategy, + redirectCallbackUrl: ssoCallbackUrl(), + redirectUrl: clerk.buildAfterSignUpUrl(), + unsafeMetadata, + legalAccepted: legalAccepted || undefined, + }), + ); + }, alternativeChannels: phoneCodeChannels.flatMap(channel => { const provider = getAlternativePhoneCodeProviderData(channel); return provider ? [{ id: channel, name: provider.name, iconUrl: iconImageUrl(channel) }] : []; From 542692f2218fe13e264f188b0f9876dec48411f9 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:03:10 -0700 Subject: [PATCH 03/40] docs(mosaic): describe the sign-up OAuth return --- packages/mosaic/docs/internals/sign-in-sign-up-flow.md | 2 ++ 1 file changed, 2 insertions(+) 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 95138de5eb7..7bd70803376 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -121,6 +121,8 @@ Sign-up redeems invitation tickets. The other entries are planned. The controlle - Cleanup, and what waits for sign-in. Finishing or starting over removes the parameters. Choosing between `signUp.ticket()` and `signIn.ticket()` by `__clerk_status`, as `ui/src/components/SignIn/SignInStart.tsx` does, is sign-in's job and waits for its controller. - 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 come from the router (the planned `useReturnUrl(name, params)`), never hand-built. That part waits for the routing follow-up. +- OAuth return: until that follow-up, sign-up marks its callback URL with `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. On `start` with the marker, `useSignUpController` shows the loading screen and runs `completeReturn` once, guarded by a ref like the ticket, and the ticket waits for it. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: a `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`) that finishes in place, or goes to the sign-in URL when it still needs a factor; an `identifier_already_signed_in` account activates that session; an external-account error resets the sign-up and shows on `start`; anything else is `next(step)`. 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 first, and `continue` keeps it. `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: `next(step)` runs it once, from an arrival state like the ticket's. The email-link return is handled first. - 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. From 0b31efcff5e0bc85c7a19163b0a8c847e29a61c3 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:03:11 -0700 Subject: [PATCH 04/40] chore(repo): add an empty changeset for social sign-up --- .changeset/mosaic-sign-up-oauth.md | 2 ++ 1 file changed, 2 insertions(+) create mode 100644 .changeset/mosaic-sign-up-oauth.md diff --git a/.changeset/mosaic-sign-up-oauth.md b/.changeset/mosaic-sign-up-oauth.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-sign-up-oauth.md @@ -0,0 +1,2 @@ +--- +--- From 930ffd126f7088ae4632090ddf52fc18de5d5b6a Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:15:40 -0700 Subject: [PATCH 05/40] feat(mosaic): ask for a required social provider on the sign-up continue screen When FAPI lists an oauth_* provider in missing_fields, continue shows that provider's button instead of Start over, and only the missing providers, since another one can't satisfy the requirement. --- .../docs/internals/sign-in-sign-up-flow.md | 2 +- .../__tests__/sign-up.feature.test.tsx | 31 +++++++++++++++++-- .../sign-up/__tests__/sign-up.utils.test.ts | 4 +-- .../src/features/sign-up/sign-up.model.ts | 18 +++++++++-- .../src/features/sign-up/sign-up.utils.ts | 3 +- 5 files changed, 49 insertions(+), 9 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 7bd70803376..1a051dc9fb9 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. When FAPI lists a requirement `continue` can't ask for, such as a required `oauth_*` provider, 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. 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. 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`. 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 88b37da1ffb..fdf3e46f616 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 @@ -589,10 +589,37 @@ describe('SignUp', () => { await waitFor(() => expect(navigate).toHaveBeenCalled()); expect(fapi.signUp.updates[0].get('legal_accepted')).toBe('true'); }); + + it('asks only for the provider the sign-up still needs on the continue screen', async () => { + const provider = { enabled: true, authenticatable: true, logo_url: null }; + const { clerk, fapi, user } = await renderSignUp({ + environment: environment({ + user_settings: { + social: { + oauth_google: { ...provider, required: true, strategy: 'oauth_google', name: 'Google' }, + oauth_github: { ...provider, required: false, strategy: 'oauth_github', name: 'GitHub' }, + }, + }, + }), + }); + const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + + await submitStart(user); + await enterCode(user); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); + + await user.click(screen.getByRole('button', { name: /Google/ })); + + await waitFor(() => expect(leave).toHaveBeenCalled()); + expect(fapi.signUp.creations).toHaveLength(1); + expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); + }); }); describe('starting over', () => { - it('offers Start over when the sign-up needs a requirement the continue screen cannot ask for', async () => { + it('offers Start over when the sign-up needs a provider that cannot sign the user in', async () => { const { user } = await renderSignUp({ environment: environment({ user_settings: { @@ -600,7 +627,7 @@ describe('SignUp', () => { oauth_google: { enabled: true, required: true, - authenticatable: true, + authenticatable: false, strategy: 'oauth_google', name: 'Google', logo_url: null, diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts b/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts index 53b4942c7b1..a34d587bf8f 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts @@ -173,7 +173,7 @@ describe('continue screen rules', () => { canSatisfy: true, }, { - name: 'cannot finish a sign-up that needs a required provider', + name: 'cannot finish a sign-up that needs a provider the user cannot sign up with', signUp: lists(['username', 'oauth_google']), asks: { username: required }, asksOnPhone: { username: required }, @@ -192,6 +192,6 @@ describe('continue screen rules', () => { expect(continueFields(signUp, 'emailAddress')).toEqual(asks); expect(continueFields(signUp, 'phoneNumber')).toEqual(asksOnPhone); expect(missesEitherIdentifier(signUp)).toBe(canSwitch); - expect(continueCanSatisfy(signUp)).toBe(canSatisfy); + expect(continueCanSatisfy(signUp, [])).toBe(canSatisfy); }); }); 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 414db08450b..08e1efac0b9 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -174,6 +174,17 @@ function forgetReturn(): void { } } +function continueProviders( + signUp: SignUpFutureResource, + providers: T[], +): T[] { + if (signUp.verifications.externalAccount.status === 'verified') { + return []; + } + const missing = providers.filter(provider => signUp.missingFields.includes(provider.id)); + return missing.length > 0 ? missing : providers; +} + function oauthProvidersFrom(userSettings: UserSettingsResource): Array { return userSettings.authenticatableSocialStrategies .flatMap(strategy => { @@ -282,13 +293,15 @@ export function useSignUpModel({ const legalConsentRequired = userSettings.signUp.legal_consent_enabled; const canSwitchIdentifier = emailOrPhone(attributes, isProgressiveSignUp); const verifiesEmailByLink = Boolean(attributes.email_address?.verifications.includes('email_link')); + const oauthProviders = oauthProvidersFrom(userSettings); + const providerIds = oauthProviders.map(provider => provider.id); const next = (resource: SignUpFutureResource): SignUpNextStep => { const step = getSignUpNextStep(resource); if (step.type === 'verify_email' && verifiesEmailByLink) { return { type: 'unknown' }; } - return step.type === 'fields' && !continueCanSatisfy(resource) ? { type: 'unknown' } : step; + return step.type === 'fields' && !continueCanSatisfy(resource, providerIds) ? { type: 'unknown' } : step; }; const sessionPhase = (): AuthSessionPhase => { @@ -308,7 +321,6 @@ export function useSignUpModel({ const ticket = getClerkQueryParam('__clerk_ticket') || getClerkQueryParam('__clerk_invitation_token') || undefined; const inTicketSignUp = Boolean(ticket) && signUp.verifications.emailAddress.strategy === 'ticket'; const phoneCodeChannels = inTicketSignUp ? [] : userSettings.alternativePhoneCodeChannels; - const oauthProviders = oauthProvidersFrom(userSettings); const forgetTicket = () => { removeClerkQueryParam('__clerk_ticket'); removeClerkQueryParam('__clerk_invitation_token'); @@ -540,7 +552,7 @@ export function useSignUpModel({ validatePassword, inTicketSignUp, oauthProviders, - continueOAuthProviders: signUp.verifications.externalAccount.status === 'verified' ? [] : oauthProviders, + continueOAuthProviders: continueProviders(signUp, oauthProviders), sso: async (strategy, { legalAccepted, continueSignUp }) => { if (signUp.id && !continueSignUp && !inTicketSignUp) { await run(() => signUp.reset()); diff --git a/packages/mosaic/src/features/sign-up/sign-up.utils.ts b/packages/mosaic/src/features/sign-up/sign-up.utils.ts index b6759a65012..24736469a5a 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.utils.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.utils.ts @@ -98,11 +98,12 @@ function missingIdentifiers({ missingFields, optionalFields }: SignUpFieldLists) const CONTINUE_REQUIREMENTS: readonly SignUpField[] = ['legal_accepted', 'email_address_or_phone_number']; -export function continueCanSatisfy(signUp: SignUpFieldLists): boolean { +export function continueCanSatisfy(signUp: SignUpFieldLists, providers: readonly string[]): boolean { const asksForIdentifier = missingIdentifiers(signUp).length > 0; return signUp.missingFields.every( field => field in FORM_FIELDS || + providers.includes(field) || CONTINUE_REQUIREMENTS.includes(field) || (asksForIdentifier && signUp.optionalFields.includes(field)), ); From 3665f2fb08a1d269badac0fef08e61a68e23f81c Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:57:11 -0700 Subject: [PATCH 06/40] test(mosaic): mirror FAPI's OAuth sign-up behavior more closely in the fake FAPI Callback errors leave the external account unverified, a start needs an enabled provider that can sign in, a linked provider keeps counting until the next return replaces it, the return fills only empty fields, required providers apply to Progressive Sign Up only, and a transferred session carries the seeded tasks. --- .../__tests__/feature/fake-fapi/sign-up.ts | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 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 ff205fbd627..dac9d16e2b0 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -67,6 +67,7 @@ export interface FakeSignUpState { tickets: Record; oauth: Record; transfers: URLSearchParams[]; + linkedStrategy?: string; returnFromOAuth: () => void; issuedProtectChecks: number; reloads: number; @@ -200,7 +201,7 @@ export function signUpHandlers( required.push('email_address_or_phone_number'); } for (const provider of Object.values(settings().social)) { - if (provider?.enabled && provider.required) { + if (sign_up.progressive && provider?.enabled && provider.required) { required.push(provider.strategy); } } @@ -214,7 +215,7 @@ export function signUpHandlers( const { attributes } = settings(); const { required_fields, optional_fields } = requirements(); const external = signUp.verifications?.external_account; - const linked = external?.status === 'verified' ? external.strategy : undefined; + const linked = external?.status === 'verified' ? external.strategy : state.signUp.linkedStrategy; const provided = (field: SignUpField) => { if (field === 'password') { return signUp.has_password || Boolean(linked); @@ -295,8 +296,12 @@ export function signUpHandlers( const startOAuth = (signUp: SignUpJSON, body: URLSearchParams): SignUpJSON | ReturnType => { const strategy = body.get('strategy') ?? ''; + const provider = settings().social[strategy as keyof FapiEnvironment['user_settings']['social']]; + if (!provider?.enabled || !provider.authenticatable) { + return rejected('form_param_value_invalid', 'strategy does not match one of the allowed values.', 'strategy'); + } if (!body.get('redirect_url')) { - return rejected('form_param_missing', 'redirect_url must be included.', 'redirect_url'); + return rejected('form_conditional_param_missing', 'redirect_url must be included.', 'redirect_url'); } return { ...signUp, @@ -325,7 +330,7 @@ export function signUpHandlers( verifications: { ...signUp.verifications!, external_account: { ...external, ...changes } }, }); if ('error' in account) { - store(withExternal({ status: 'failed', error: apiError(account.error.code, account.error.message) })); + store(withExternal({ status: 'unverified', error: apiError(account.error.code, account.error.message) })); return; } if ('existingUser' in account) { @@ -338,19 +343,22 @@ export function signUpHandlers( return; } const linked = withExternal({ status: 'verified' }); + state.signUp.linkedStrategy = external.strategy; store( settle({ ...linked, - email_address: account.emailAddress, - first_name: account.firstName ?? signUp.first_name, - last_name: account.lastName ?? signUp.last_name, + email_address: signUp.email_address ?? account.emailAddress, + first_name: signUp.first_name ?? account.firstName ?? null, + last_name: signUp.last_name ?? account.lastName ?? null, verifications: { ...linked.verifications!, - email_address: { - ...linked.verifications!.email_address, - ...fapiVerification(`from_${external.strategy}`, { status: 'verified' }), - next_action: '', - }, + email_address: signUp.email_address + ? linked.verifications!.email_address + : { + ...linked.verifications!.email_address, + ...fapiVerification(`from_${external.strategy}`, { status: 'verified' }), + next_action: '', + }, }, }), ); @@ -488,7 +496,9 @@ export function signUpHandlers( const { emailAddress, secondFactor = false } = account.existingUser; let createdSessionId: string | null = null; if (!secondFactor) { + const tasks = state.signUp.sessionTasks; const session = fapiSession({ + ...(tasks?.length ? { status: 'pending' as const, tasks } : {}), id: `sess_transferred_${state.signUp.transfers.length}`, user: fapiUser({ id: 'user_existing', @@ -518,6 +528,7 @@ export function signUpHandlers( http.post(fapiUrl('/v1/client/sign_ups'), async ({ request }) => { const body = new URLSearchParams(await request.text()); state.signUp.creations.push(body); + state.signUp.linkedStrategy = undefined; const mode = settings().sign_up.mode; if (mode !== 'public' && body.get('strategy') !== 'ticket') { return mode === 'waitlist' From 03540398fa45fc213de53ea2f7479fcf6efd3720 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:57:12 -0700 Subject: [PATCH 07/40] fix(mosaic): close the gaps a FAPI and legacy check found in social sign-up Start creates a new sign-up instead of updating a leftover one, social-only instances show their providers without the form, continue asks for a still-missing required provider after another one is linked, two required providers lead to Start over, a transfer or an already signed-in session goes to its pending task, Protect runs before a transfer, unlisted provider errors show the generic message, and the return shows the loading screen from the first paint. --- .../__tests__/sign-up.feature.test.tsx | 119 +++++++++++++++++- .../sign-up/__tests__/sign-up.utils.test.ts | 7 +- .../sign-up-details/sign-up-details.tsx | 2 +- .../features/sign-up/sign-up.controller.ts | 19 +-- .../src/features/sign-up/sign-up.model.ts | 110 +++++++++------- .../src/features/sign-up/sign-up.utils.ts | 8 +- 6 files changed, 210 insertions(+), 55 deletions(-) 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 fdf3e46f616..89434249aa9 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 @@ -27,6 +27,7 @@ import { passwordField, renderSignUp, renderSignUpWithRouteProbe, + RouteProbe, SHORT_PASSWORD, signedInSession, submitStart, @@ -1147,12 +1148,16 @@ describe('SignUp social sign-up', () => { }); } - async function startWithGoogle(seed: FakeFapiSeed, options?: Parameters[1]) { + async function startWithGoogle( + seed: FakeFapiSeed, + options?: Parameters[1], + provider: RegExp = /Google/, + ) { const fapi = serveFapi({ environment: socialEnvironment(), ...seed }); const first = await renderWithClerk(, options); const leave = vi.spyOn(first.clerk, '__internal_windowNavigate').mockImplementation(() => {}); const user = userEvent.setup(); - await user.click(await screen.findByRole('button', { name: /Google/ })); + await user.click(await screen.findByRole('button', { name: provider })); await waitFor(() => expect(leave).toHaveBeenCalled()); return { fapi, first, leave, user }; } @@ -1238,4 +1243,114 @@ describe('SignUp social sign-up', () => { expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); }); + + it('starts a new sign-up from start even when an earlier one is still on the client', async () => { + const fapi = serveFapi({ environment: socialEnvironment() }); + const { clerk } = await renderWithClerk( + <> + + + , + ); + const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + await submitStart(user); + await screen.findByRole('heading', { name: 'Verify your email' }); + await codeSent(); + + await user.click(screen.getByRole('button', { name: 'Open the start route' })); + await user.click(await screen.findByRole('button', { name: /Google/ })); + + await waitFor(() => expect(leave).toHaveBeenCalled()); + expect(fapi.signUp.creations).toHaveLength(2); + expect(fapi.signUp.creations[1].get('strategy')).toBe('oauth_google'); + expect(fapi.signUp.updates.filter(update => update.get('strategy'))).toEqual([]); + }); + + it('offers only the providers on start when the instance signs up with social accounts alone', async () => { + await renderSignUp({ + environment: socialEnvironment({ + attributes: { email_address: { enabled: false }, password: { enabled: false } }, + user_settings: { + social: { oauth_google: GOOGLE }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }), + }); + + expect(await screen.findByRole('button', { name: /Google/ })).toBeInTheDocument(); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(screen.queryByRole('textbox')).toBeNull(); + }); + + it('asks for the required provider after the user signed up with another one', async () => { + const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub' }; + const { fapi, first } = await startWithGoogle( + { + environment: socialEnvironment({ + user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, + }), + signUp: { oauth: { oauth_github: { emailAddress: EMAIL } } }, + }, + undefined, + /GitHub/, + ); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); + }); + + it('offers Start over when the instance requires two providers a sign-up cannot both link', async () => { + const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub', required: true }; + const { user } = await renderSignUp({ + environment: socialEnvironment({ + user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, + }), + }); + + await submitStart(user); + await enterCode(user); + + expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); + }); + + it('takes a user who signs in instead to their pending task', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } }, + sessionTasks: [{ key: 'choose-organization' }], + }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { + signInUrl: '/sign-in', + signInFallbackRedirectUrl: '/home', + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('choose-organization'))); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); + }); + + it('shows a generic error when Google returns one that is not meant for users', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { error: { code: 'internal_clerk_error', message: 'Raw server detail.' } } }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('Something went wrong. Please try again.')).toBeInTheDocument(); + expect(screen.queryByText('Raw server detail.')).toBeNull(); + }); }); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts b/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts index a34d587bf8f..17df198d287 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.utils.test.ts @@ -97,7 +97,12 @@ describe('continue screen rules', () => { missingFields: SignUpField[], optionalFields: SignUpField[] = [], unverifiedFields: SignUpIdentificationField[] = [], - ) => ({ missingFields, optionalFields, unverifiedFields }); + ) => ({ + missingFields, + optionalFields, + unverifiedFields, + requiredFields: missingFields.filter(field => !optionalFields.includes(field)), + }); it.each([ { diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx index 7f78576ba1c..e99b7d5b633 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx @@ -80,7 +80,7 @@ export function SignUpDetailsStep({ {...inertProps(isChallengeShown)} > (); const completedReturn = useRef(false); + const [isReturning, setIsReturning] = useState(liveModel.attempt.hasPendingReturn); const errorText = useErrorText(); const facts = { session: liveModel.session, @@ -239,7 +240,7 @@ export function useSignUpController( const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const screen = - activitySnapshot.value === 'redeemingTicket' || actions.pendingKey === 'return' + isReturning || activitySnapshot.value === 'redeemingTicket' || actions.pendingKey === 'return' ? 'loading' : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined)); @@ -282,14 +283,16 @@ export function useSignUpController( }); /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return, or redeems an invitation, once when sign-up opens on start with its marker or ticket in the URL; arriving from a redirect or a link is not an event a handler could run from. */ useEffect(() => { - if (attempt.hasPendingReturn && route === 'start' && !completedReturn.current) { + if (isReturning && route === 'start' && !completedReturn.current) { completedReturn.current = true; - void actions.run('return', async () => { - const step = await attempt.completeReturn(); - if (step) { - next(step); - } - }); + void actions + .run('return', async () => { + const step = await attempt.completeReturn(); + if (step) { + next(step); + } + }) + .then(() => setIsReturning(false)); } }); /* eslint-enable react-you-might-not-need-an-effect/no-event-handler */ 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 08e1efac0b9..01feffce59f 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -3,6 +3,7 @@ import { iconImageUrl } from '@clerk/shared/constants'; import type { ClerkError } from '@clerk/shared/error'; import { isClerkAPIResponseError } from '@clerk/shared/error'; import { actionBlockedDetailsFrom } from '@clerk/shared/internal/clerk-js/actionBlocked'; +import { ERROR_CODES } from '@clerk/shared/internal/clerk-js/constants'; import type { SignUpNextStep } from '@clerk/shared/internal/clerk-js/nextStep'; import { getSignUpNextStep } from '@clerk/shared/internal/clerk-js/nextStep'; import { validate as validateComplexity } from '@clerk/shared/internal/clerk-js/passwords/complexity'; @@ -16,6 +17,7 @@ import { determineActiveFields, emailOrPhone, getInitialActiveIdentifier, + showFormFields, } from '@clerk/shared/internal/clerk-js/signUpFormFields'; import { OAUTH_PROVIDERS } from '@clerk/shared/oauth'; import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; @@ -25,6 +27,7 @@ import type { OAuthStrategy, PhoneCodeChannel, SessionTask, + SetActiveNavigate, SignUpFutureResource, SignUpInitialValues, UserSettingsResource, @@ -38,7 +41,7 @@ import { useMosaicEnvironment } from '../../hooks/use-mosaic-environment'; import { useMosaicRouter } from '../../hooks/use-mosaic-router'; import { useMosaicSupportEmail } from '../../hooks/use-mosaic-support-email'; import { useErrorText, useLocale, useMessages } from '../../localization'; -import { save, SaveError } from '../../utils/errors'; +import { save, SaveError, UNEXPECTED_ERROR } from '../../utils/errors'; import type { AuthSessionPhase } from '../auth-flow/auth-flow.types'; import { passwordError } from '../user-profile/user-profile-password-section/user-profile-password-errors'; import { passwordFieldFeedback } from '../user-profile/user-profile-password-section/user-profile-password-feedback'; @@ -159,6 +162,25 @@ const ABSOLUTE_URL = /^https?:\/\//; const RETURN_PARAM = '__clerk_mosaic_sign_up'; const SSO_RETURN = 'sso-callback'; const OAUTH_PREFIX = /^oauth_(custom_)?/; +const SHOWN_RETURN_ERRORS: readonly string[] = [ + ERROR_CODES.NOT_ALLOWED_TO_SIGN_UP, + ERROR_CODES.OAUTH_ACCESS_DENIED, + ERROR_CODES.NOT_ALLOWED_ACCESS, + ERROR_CODES.SAML_USER_ATTRIBUTE_MISSING, + ERROR_CODES.OAUTH_EMAIL_DOMAIN_RESERVED_BY_SAML, + ERROR_CODES.USER_LOCKED, + ERROR_CODES.ENTERPRISE_SSO_USER_ATTRIBUTE_MISSING, + ERROR_CODES.ENTERPRISE_SSO_EMAIL_ADDRESS_DOMAIN_MISMATCH, + ERROR_CODES.ENTERPRISE_SSO_HOSTED_DOMAIN_MISMATCH, + ERROR_CODES.SAML_EMAIL_ADDRESS_DOMAIN_MISMATCH, + ERROR_CODES.ORGANIZATION_MEMBERSHIP_QUOTA_EXCEEDED_FOR_SSO, + ERROR_CODES.CAPTCHA_INVALID, + ERROR_CODES.FRAUD_DEVICE_BLOCKED, + ERROR_CODES.FRAUD_ACTION_BLOCKED, + ERROR_CODES.SIGNUP_RATE_LIMIT_EXCEEDED, + ERROR_CODES.USER_BANNED, + ERROR_CODES.USER_DEACTIVATED, +]; function ssoCallbackUrl(): string { const url = new URL(window.location.href); @@ -178,11 +200,11 @@ function continueProviders( signUp: SignUpFutureResource, providers: T[], ): T[] { - if (signUp.verifications.externalAccount.status === 'verified') { - return []; - } const missing = providers.filter(provider => signUp.missingFields.includes(provider.id)); - return missing.length > 0 ? missing : providers; + if (missing.length > 0) { + return missing; + } + return signUp.verifications.externalAccount.status === 'verified' ? [] : providers; } function oauthProvidersFrom(userSettings: UserSettingsResource): Array { @@ -295,6 +317,7 @@ export function useSignUpModel({ const verifiesEmailByLink = Boolean(attributes.email_address?.verifications.includes('email_link')); const oauthProviders = oauthProvidersFrom(userSettings); const providerIds = oauthProviders.map(provider => provider.id); + const showForm = showFormFields(userSettings); const next = (resource: SignUpFutureResource): SignUpNextStep => { const step = getSignUpNextStep(resource); @@ -408,6 +431,25 @@ export function useSignUpModel({ ? { termsUrl: displayConfig.termsUrl || undefined, privacyPolicyUrl: displayConfig.privacyPolicyUrl || undefined } : undefined; + const navigateAfter = + (destination: string, { keepsTaskInFlow }: { keepsTaskInFlow: boolean }): SetActiveNavigate => + async ({ session: created, decorateUrl }) => { + const task = created.currentTask; + if (keepsTaskInFlow && taskInFlow(task)) { + return; + } + if (task) { + await router.navigate(taskUrl(task)); + return; + } + const decorated = decorateUrl(destination); + if (decorated !== destination && ABSOLUTE_URL.test(decorated)) { + router.windowNavigate(decorated); + return; + } + await router.navigate(destination); + }; + const step = next(signUp); const phoneChannel = signUp.verifications.phoneNumber.channel; const preferredPhoneChannel = (phoneNumber: string | undefined): PhoneCodeChannel | undefined => { @@ -438,6 +480,10 @@ export function useSignUpModel({ hasPendingReturn: new URL(window.location.href).searchParams.get(RETURN_PARAM) === SSO_RETURN, completeReturn: async () => { forgetReturn(); + const step = next(signUp); + if (step.type === 'protect') { + return step; + } if (signUp.isTransferable) { await run(() => signIn.create({ transfer: true })); if (signIn.status !== 'complete') { @@ -445,54 +491,32 @@ export function useSignUpModel({ return undefined; } await run(() => - signIn.finalize({ - navigate: async ({ decorateUrl }) => { - const afterSignInUrl = clerk.buildAfterSignInUrl(); - const decorated = decorateUrl(afterSignInUrl); - if (decorated !== afterSignInUrl && ABSOLUTE_URL.test(decorated)) { - router.windowNavigate(decorated); - return; - } - await router.navigate(afterSignInUrl); - }, - }), + signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), ); return undefined; } const existingSession = signUp.existingSession?.sessionId; if (existingSession) { - await clerk.setActive({ session: existingSession, redirectUrl: clerk.buildAfterSignInUrl() }); + await clerk.setActive({ + session: existingSession, + navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }), + }); return undefined; } const failure = signUp.verifications.externalAccount.error; if (failure) { await run(() => signUp.reset()); - throw new SaveError({ global: { code: failure.code, message: failure.longMessage || failure.message } }); + throw new SaveError({ + global: SHOWN_RETURN_ERRORS.includes(failure.code) + ? { code: failure.code, message: failure.longMessage || failure.message } + : UNEXPECTED_ERROR, + }); } - return next(signUp); + return step; }, finalize: async () => { forgetTicket(); - await run(() => - signUp.finalize({ - navigate: async ({ session: created, decorateUrl }) => { - const task = created.currentTask; - if (taskInFlow(task)) { - return; - } - if (task) { - await router.navigate(taskUrl(task)); - return; - } - const decorated = decorateUrl(afterSignUpUrl); - if (decorated !== afterSignUpUrl && ABSOLUTE_URL.test(decorated)) { - router.windowNavigate(decorated); - return; - } - await router.navigate(afterSignUpUrl); - }, - }), - ); + await run(() => signUp.finalize({ navigate: navigateAfter(afterSignUpUrl, { keepsTaskInFlow: true }) })); }, reset: () => { forgetTicket(); @@ -533,7 +557,7 @@ export function useSignUpModel({ }) ?? null, canSwitchIdentifier, prefill, - startFieldsFor: identifier => toViewFields(activeFields(identifier), isShown), + startFieldsFor: identifier => (showForm ? toViewFields(activeFields(identifier), isShown) : {}), continueFieldsFor: identifier => continueFields(signUp, identifier), continueCanSwitchIdentifier: missesEitherIdentifier(signUp), startHiddenValuesFor: identifier => { @@ -547,18 +571,20 @@ export function useSignUpModel({ } return hidden; }, - legalConsent, + legalConsent: showForm ? legalConsent : undefined, continueLegalConsent: signUp.missingFields.includes('legal_accepted') ? legalConsent : undefined, validatePassword, inTicketSignUp, oauthProviders, continueOAuthProviders: continueProviders(signUp, oauthProviders), sso: async (strategy, { legalAccepted, continueSignUp }) => { + let target = signUp; if (signUp.id && !continueSignUp && !inTicketSignUp) { await run(() => signUp.reset()); + target = clerk.client?.signUp.__internal_future ?? signUp; } await run(() => - signUp.sso({ + target.sso({ strategy, redirectCallbackUrl: ssoCallbackUrl(), redirectUrl: clerk.buildAfterSignUpUrl(), diff --git a/packages/mosaic/src/features/sign-up/sign-up.utils.ts b/packages/mosaic/src/features/sign-up/sign-up.utils.ts index 24736469a5a..b22b82cddea 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.utils.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.utils.ts @@ -85,7 +85,10 @@ const FORM_FIELDS: Partial> = { phone_number: 'phoneNumber', }; -type SignUpFieldLists = Pick; +type SignUpFieldLists = Pick< + SignUpFutureResource, + 'missingFields' | 'optionalFields' | 'requiredFields' | 'unverifiedFields' +>; function missingIdentifiers({ missingFields, optionalFields }: SignUpFieldLists): SignUpField[] { return missingFields.filter( @@ -99,6 +102,9 @@ function missingIdentifiers({ missingFields, optionalFields }: SignUpFieldLists) const CONTINUE_REQUIREMENTS: readonly SignUpField[] = ['legal_accepted', 'email_address_or_phone_number']; export function continueCanSatisfy(signUp: SignUpFieldLists, providers: readonly string[]): boolean { + if (signUp.requiredFields.filter(field => field.startsWith('oauth_')).length > 1) { + return false; + } const asksForIdentifier = missingIdentifiers(signUp).length > 0; return signUp.missingFields.every( field => From 125073c39537bd8489ba0b4f259776e72e25c449 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Fri, 20 Nov 2026 17:57:13 -0700 Subject: [PATCH 08/40] docs(mosaic): correct the sign-up OAuth return and on-mount notes --- packages/mosaic/docs/internals/sign-in-sign-up-flow.md | 6 +++--- 1 file changed, 3 insertions(+), 3 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 1a051dc9fb9..89c8e227b6d 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -121,9 +121,9 @@ Sign-up redeems invitation tickets. The other entries are planned. The controlle - Cleanup, and what waits for sign-in. Finishing or starting over removes the parameters. Choosing between `signUp.ticket()` and `signIn.ticket()` by `__clerk_status`, as `ui/src/components/SignIn/SignInStart.tsx` does, is sign-in's job and waits for its controller. - 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 come from the router (the planned `useReturnUrl(name, params)`), never hand-built. That part waits for the routing follow-up. -- OAuth return: until that follow-up, sign-up marks its callback URL with `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. On `start` with the marker, `useSignUpController` shows the loading screen and runs `completeReturn` once, guarded by a ref like the ticket, and the ticket waits for it. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: a `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`) that finishes in place, or goes to the sign-in URL when it still needs a factor; an `identifier_already_signed_in` account activates that session; an external-account error resets the sign-up and shows on `start`; anything else is `next(step)`. 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 first, and `continue` keeps it. `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: `next(step)` runs it once, from an arrival state like the ticket's. The email-link return is handled first. +- OAuth return: until that follow-up, sign-up marks its callback URL with `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. `useSignUpController` reads the marker once on mount, shows the loading screen from the first paint, and runs `completeReturn` once on `start`, guarded by a ref like the ticket; the ticket waits until the return is done. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: a Protect check comes first; a `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`) that finishes in place, or goes to the sign-in URL when it still needs a factor; an `identifier_already_signed_in` account activates that session. A session from either of those is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. An external-account error 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; anything else is `next(step)`. The marker is gone once the return starts, so a reload mid-return lands on `start`. 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 the TODO in `useSignUpController` covers `complete`. The email-link return will be handled first. - 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 ce7ec095a1a58364afe5025c9f83be926c5a02e7 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:34:54 -0700 Subject: [PATCH 09/40] refactor(mosaic): keep the sign-up model under the complexity limit with social sign-up The restack onto the invitation fixes put `useSignUpModel` at a cognitive complexity of 18. Choosing which legal consent start and continue show moves above the returned model, where each choice counts once instead of at the model's nesting depth. --- packages/mosaic/src/features/sign-up/sign-up.model.ts | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 01feffce59f..2e603298038 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -430,6 +430,8 @@ export function useSignUpModel({ const legalConsent = legalConsentRequired ? { termsUrl: displayConfig.termsUrl || undefined, privacyPolicyUrl: displayConfig.privacyPolicyUrl || undefined } : undefined; + const startLegalConsent = showForm ? legalConsent : undefined; + const continueLegalConsent = signUp.missingFields.includes('legal_accepted') ? legalConsent : undefined; const navigateAfter = (destination: string, { keepsTaskInFlow }: { keepsTaskInFlow: boolean }): SetActiveNavigate => @@ -571,8 +573,8 @@ export function useSignUpModel({ } return hidden; }, - legalConsent: showForm ? legalConsent : undefined, - continueLegalConsent: signUp.missingFields.includes('legal_accepted') ? legalConsent : undefined, + legalConsent: startLegalConsent, + continueLegalConsent, validatePassword, inTicketSignUp, oauthProviders, From 19145ad23a9596f70b820f0c35211f2967103253 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:35:35 -0700 Subject: [PATCH 10/40] test(mosaic): show an invitee's denied Google sign-up without redeeming the invitation again --- .../__tests__/sign-up.feature.test.tsx | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) 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 89434249aa9..776fbde6ef2 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 @@ -1167,7 +1167,8 @@ describe('SignUp social sign-up', () => { first: Awaited>, options?: Parameters[1], ) { - const callback = new URL(fapi.signUp.creations.at(-1)?.get('redirect_url') ?? ''); + const started = [...fapi.signUp.creations, ...fapi.signUp.updates].filter(body => body.has('redirect_url')); + const callback = new URL(started.at(-1)?.get('redirect_url') ?? ''); first.unmount(); fapi.signUp.returnFromOAuth(); window.history.replaceState(null, '', `${callback.pathname}${callback.search}`); @@ -1244,6 +1245,24 @@ describe('SignUp social sign-up', () => { expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); }); + it('keeps the denial on screen when an invitee comes back from Google, and does not redeem the ticket again', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?__clerk_ticket=tkt_invite`); + const { fapi, first } = await startWithGoogle({ + signUp: { + tickets: { tkt_invite: { emailAddress: EMAIL } }, + oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, + }, + }); + expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); + await waitFor(() => expect(window.location.search).not.toContain('__clerk_ticket')); + expect(screen.getByText('You did not grant access to your account.')).toBeInTheDocument(); + expect(fapi.signUp.creations.filter(body => body.get('strategy') === 'ticket')).toHaveLength(1); + }); + it('starts a new sign-up from start even when an earlier one is still on the client', async () => { const fapi = serveFapi({ environment: socialEnvironment() }); const { clerk } = await renderWithClerk( From 1e981e2efbb036e0edd66350fe98c379881b512d Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:35:53 -0700 Subject: [PATCH 11/40] fix(mosaic): forget the invitation when a social sign-up comes back with an error The error path reset the sign-up but left the ticket in the URL, so the invitation effect redeemed it again and cleared the provider's error. It now removes the ticket first, as the flow's own reset does. A successful return keeps the ticket, so the invitee stays on the invitation's sign-up. --- packages/mosaic/src/features/sign-up/sign-up.model.ts | 1 + 1 file changed, 1 insertion(+) 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 2e603298038..7c54a02da11 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -507,6 +507,7 @@ export function useSignUpModel({ } const failure = signUp.verifications.externalAccount.error; if (failure) { + forgetTicket(); await run(() => signUp.reset()); throw new SaveError({ global: SHOWN_RETURN_ERRORS.includes(failure.code) From e4a24e78e63d5c1ee21300260d5f46d8110947d3 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:36:27 -0700 Subject: [PATCH 12/40] test(mosaic): complete a social sign-up return that opens on the continue route --- .../__tests__/sign-up.feature.test.tsx | 35 ++++++++++++++++++- 1 file changed, 34 insertions(+), 1 deletion(-) 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 776fbde6ef2..94ee3e5c49f 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 @@ -1,5 +1,6 @@ import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; +import { type ReactElement, useState } from 'react'; import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'; import { type FakeFapiSeed, holdRequests, serveFapi, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; @@ -13,6 +14,7 @@ import { fapiUser, } from '../../../__tests__/feature/fapi'; import { renderWithClerk } from '../../../__tests__/feature/render'; +import { useVirtualWrite } from '../../../routing/virtual-store'; import { SignUp } from '../sign-up'; import { codeSent, @@ -1166,13 +1168,14 @@ describe('SignUp social sign-up', () => { fapi: ReturnType, first: Awaited>, options?: Parameters[1], + ui: ReactElement = , ) { const started = [...fapi.signUp.creations, ...fapi.signUp.updates].filter(body => body.has('redirect_url')); const callback = new URL(started.at(-1)?.get('redirect_url') ?? ''); first.unmount(); fapi.signUp.returnFromOAuth(); window.history.replaceState(null, '', `${callback.pathname}${callback.search}`); - return renderWithClerk(, options); + return renderWithClerk(ui, options); } it('starts Google sign-up with a callback URL that brings the user back to sign-up', async () => { @@ -1208,6 +1211,36 @@ describe('SignUp social sign-up', () => { expect(fapi.client.sessions).toHaveLength(1); }); + it('completes the return when sign-up opens on the continue route', async () => { + function OpenOnContinue() { + const write = useVirtualWrite(); + const [opened, setOpened] = useState(false); + return opened ? ( + + ) : ( + + ); + } + const { fapi, first } = await startWithGoogle({ + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + + await returnFromGoogle(fapi, first, undefined, ); + await userEvent.setup().click(screen.getByRole('button', { name: 'Open sign-up on continue' })); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); + it('signs in instead when the Google account already belongs to a user', async () => { const { fapi, first } = await startWithGoogle({ signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, From e465f52a1a418e1d4e30480790f80542e0371367 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:37:09 -0700 Subject: [PATCH 13/40] fix(mosaic): complete a social sign-up return on whichever route sign-up opens The return only ran on start, so a return that opened on continue showed the loading screen forever. It now runs once on any route, and the guard then moves the screen to the step's route. --- packages/mosaic/src/features/sign-up/sign-up.controller.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 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 d46fc6e1785..ec746ea632d 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -281,9 +281,9 @@ export function useSignUpController( onNext: next, onSignIn: navigation.goToSignIn, }); - /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return, or redeems an invitation, once when sign-up opens on start with its marker or ticket in the URL; arriving from a redirect or a link is not an event a handler could run from. */ + /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return once when sign-up opens with its marker in the URL, on any route, or redeems an invitation once when it opens on start with its ticket; arriving from a redirect or a link is not an event a handler could run from. */ useEffect(() => { - if (isReturning && route === 'start' && !completedReturn.current) { + if (isReturning && !completedReturn.current) { completedReturn.current = true; void actions .run('return', async () => { From 5d094784634f1ea9b4bcfadb94886f5d2682fd52 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:39:40 -0700 Subject: [PATCH 14/40] refactor(mosaic): derive the sign-up OAuth return's busy state from its pending action The controller kept `isReturning` in its own state beside `usePendingAction`, a second busy flag. It now reads the return marker until the return action has run, then the action's pending key, so the loading screen still shows from the first paint. --- .../features/sign-up/sign-up.controller.ts | 23 ++++++++----------- 1 file changed, 10 insertions(+), 13 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 ec746ea632d..b7f8e750dce 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -186,8 +186,6 @@ export function useSignUpController( ): SignUpControllerResult { const { route, go } = useRouterScope(signUpRoutes, { ...options, root: 'start' }); const actions = usePendingAction<'startOver' | 'return'>(); - const completedReturn = useRef(false); - const [isReturning, setIsReturning] = useState(liveModel.attempt.hasPendingReturn); const errorText = useErrorText(); const facts = { session: liveModel.session, @@ -237,10 +235,12 @@ export function useSignUpController( const model = isHolding ? (activitySnapshot.context.frozenModel ?? liveModel) : liveModel; const { attempt, navigation, verification } = model; + // The marker is in the URL from the first paint, before the effect starts the return. `lastKey` is set once it ran. + const isReturning = actions.pendingKey === 'return' || (attempt.hasPendingReturn && actions.lastKey === undefined); const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; const screen = - isReturning || activitySnapshot.value === 'redeemingTicket' || actions.pendingKey === 'return' + isReturning || activitySnapshot.value === 'redeemingTicket' ? 'loading' : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined)); @@ -283,16 +283,13 @@ export function useSignUpController( }); /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return once when sign-up opens with its marker in the URL, on any route, or redeems an invitation once when it opens on start with its ticket; arriving from a redirect or a link is not an event a handler could run from. */ useEffect(() => { - if (isReturning && !completedReturn.current) { - completedReturn.current = true; - void actions - .run('return', async () => { - const step = await attempt.completeReturn(); - if (step) { - next(step); - } - }) - .then(() => setIsReturning(false)); + if (attempt.hasPendingReturn && actions.lastKey === undefined) { + void actions.run('return', async () => { + const step = await attempt.completeReturn(); + if (step) { + next(step); + } + }); } }); /* eslint-enable react-you-might-not-need-an-effect/no-event-handler */ From 9c46c4f313579e97fa81b7decafbcf9d9648e90c Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:40:04 -0700 Subject: [PATCH 15/40] test(mosaic): send the redirect_url as social sign-up's after-sign-up URL --- .../features/sign-up/__tests__/sign-up.feature.test.tsx | 9 +++++++++ 1 file changed, 9 insertions(+) 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 94ee3e5c49f..368626a3787 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 @@ -1188,6 +1188,15 @@ describe('SignUp social sign-up', () => { expect(fapi.signUp.creations[0].get('action_complete_redirect_url')).toBeTruthy(); }); + it('sends the redirect_url from the query as the URL to land on after Google', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); + + const { fapi } = await startWithGoogle({}); + + const afterGoogle = new URL(fapi.signUp.creations[0].get('action_complete_redirect_url') ?? ''); + expect(afterGoogle.pathname).toBe('/dashboard'); + }); + it('asks for what Google did not provide after the return, then completes', async () => { const seed: FakeFapiSeed = { environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), From 9549d0c742cfcaae47904aa00f796317a00bc62a Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:40:46 -0700 Subject: [PATCH 16/40] fix(mosaic): honor redirect_url as the URL a social sign-up lands on `sso` built the after-sign-up URL without the query, so a `redirect_url` on the page was dropped once the provider finished. It now passes the same after-sign-up URL the rest of sign-up uses. --- packages/mosaic/src/features/sign-up/sign-up.model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7c54a02da11..6533200054e 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -590,7 +590,7 @@ export function useSignUpModel({ target.sso({ strategy, redirectCallbackUrl: ssoCallbackUrl(), - redirectUrl: clerk.buildAfterSignUpUrl(), + redirectUrl: afterSignUpUrl, unsafeMetadata, legalAccepted: legalAccepted || undefined, }), From a4d6e84c869b051d6eb3d0fc83371c94b32af997 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:41:17 -0700 Subject: [PATCH 17/40] test(mosaic): send a social sign-up transfer that needs a second factor to sign-in's factor-two route --- .../features/sign-up/__tests__/sign-up.feature.test.tsx | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) 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 368626a3787..438bf42449e 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 @@ -1262,7 +1262,8 @@ describe('SignUp social sign-up', () => { expect(fapi.client.sessions).toHaveLength(1); }); - it('hands a transfer that still needs a second factor to the sign-in page', async () => { + it('hands a transfer that still needs a second factor to the sign-in factor-two route, keeping redirect_url', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); const { fapi, first } = await startWithGoogle({ signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL, secondFactor: true } } } }, }); @@ -1270,6 +1271,11 @@ describe('SignUp social sign-up', () => { const { navigate } = await returnFromGoogle(fapi, first, { signInUrl: '/sign-in' }); await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/sign-in'))); + const target = new URL(String(navigate.mock.calls.at(-1)?.[0]), window.location.origin); + const route = new URL(target.hash.slice(1), target.origin); + expect(target.pathname).toBe('/sign-in'); + expect(route.pathname).toBe('/factor-two'); + expect(new URL(route.searchParams.get('redirect_url') ?? '', target.origin).pathname).toBe('/dashboard'); expect(fapi.client.sessions).toHaveLength(0); }); From 83c2d12a4f59a46d9f0110745571575ece097d37 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:44:22 -0700 Subject: [PATCH 18/40] fix(mosaic): send a social sign-up transfer to the sign-in step it still needs A transfer that did not complete went to the sign-in root. It now goes to `factor-one`, `factor-two`, `reset-password` or `protect-check` by the sign-in's status, as `clerk.ts` `_handleRedirectCallback` does, on the sign-in URL that keeps `redirect_url`. --- .../src/features/sign-up/sign-up.model.ts | 19 ++++++++++++++++++- 1 file changed, 18 insertions(+), 1 deletion(-) 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 6533200054e..15a904eb964 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -19,6 +19,7 @@ import { getInitialActiveIdentifier, showFormFields, } from '@clerk/shared/internal/clerk-js/signUpFormFields'; +import { buildURL } from '@clerk/shared/internal/clerk-js/url'; import { OAUTH_PROVIDERS } from '@clerk/shared/oauth'; import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; import { __internal_useClerkSignal, useClerk, useSession } from '@clerk/shared/react'; @@ -28,6 +29,8 @@ import type { PhoneCodeChannel, SessionTask, SetActiveNavigate, + SignInFutureResource, + SignInStatus, SignUpFutureResource, SignUpInitialValues, UserSettingsResource, @@ -182,6 +185,18 @@ const SHOWN_RETURN_ERRORS: readonly string[] = [ ERROR_CODES.USER_DEACTIVATED, ]; +// The sign-in routes `clerk.ts` `_handleRedirectCallback` sends a transfer to when it does not complete. +const TRANSFER_ROUTES: Partial> = { + needs_first_factor: '/factor-one', + needs_second_factor: '/factor-two', + needs_new_password: '/reset-password', + needs_protect_check: '/protect-check', +}; + +function transferRoute(signIn: Pick): string { + return signIn.protectCheck ? '/protect-check' : (TRANSFER_ROUTES[signIn.status] ?? ''); +} + function ssoCallbackUrl(): string { const url = new URL(window.location.href); url.searchParams.set(RETURN_PARAM, SSO_RETURN); @@ -489,7 +504,9 @@ export function useSignUpModel({ if (signUp.isTransferable) { await run(() => signIn.create({ transfer: true })); if (signIn.status !== 'complete') { - await router.navigate(clerk.buildSignInUrl()); + await router.navigate( + buildURL({ base: signInUrl(), hashPath: transferRoute(signIn) }, { stringify: true }), + ); return undefined; } await run(() => From 144ef28330e2128bdd13c5fdb8b1bc2d8fdb0b59 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:46:09 -0700 Subject: [PATCH 19/40] refactor(mosaic): move the sign-up OAuth completion out of the model hook The return completion (Protect, transfer, existing session, provider error, next step) becomes a module function, so the return and the Protect check after it share one path. --- .../src/features/sign-up/sign-up.model.ts | 94 +++++++++++-------- 1 file changed, 57 insertions(+), 37 deletions(-) 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 15a904eb964..1567c9dfa83 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -275,6 +275,44 @@ async function run(call: () => Promise<{ error: ClerkError | null }>): Promise SignUpNextStep; + transfer: () => Promise; + activate: (sessionId: string) => Promise; + forgetTicket: () => void; +} + +/** Settles a sign-up the provider sent back. Resolves no step when the flow leaves sign-up. */ +async function completeOAuth( + signUp: SignUpFutureResource, + { next, transfer, activate, forgetTicket }: OAuthOutcomeActions, +): Promise { + const step = next(signUp); + if (step.type === 'protect') { + return step; + } + if (signUp.isTransferable) { + await transfer(); + return undefined; + } + const existingSession = signUp.existingSession?.sessionId; + if (existingSession) { + await activate(existingSession); + return undefined; + } + const failure = signUp.verifications.externalAccount.error; + if (failure) { + forgetTicket(); + await run(() => signUp.reset()); + throw new SaveError({ + global: SHOWN_RETURN_ERRORS.includes(failure.code) + ? { code: failure.code, message: failure.longMessage || failure.message } + : UNEXPECTED_ERROR, + }); + } + return step; +} + export function useSignUpModel({ initialValues = {}, unsafeMetadata, @@ -467,6 +505,23 @@ export function useSignUpModel({ await router.navigate(destination); }; + const oauthOutcome: OAuthOutcomeActions = { + next, + forgetTicket, + transfer: async () => { + await run(() => signIn.create({ transfer: true })); + if (signIn.status !== 'complete') { + await router.navigate(buildURL({ base: signInUrl(), hashPath: transferRoute(signIn) }, { stringify: true })); + return; + } + await run(() => + signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), + ); + }, + activate: session => + clerk.setActive({ session, navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), + }; + const step = next(signUp); const phoneChannel = signUp.verifications.phoneNumber.channel; const preferredPhoneChannel = (phoneNumber: string | undefined): PhoneCodeChannel | undefined => { @@ -495,44 +550,9 @@ export function useSignUpModel({ return { result: next(signUp), emailAddress: signUp.emailAddress ?? '' }; }, hasPendingReturn: new URL(window.location.href).searchParams.get(RETURN_PARAM) === SSO_RETURN, - completeReturn: async () => { + completeReturn: () => { forgetReturn(); - const step = next(signUp); - if (step.type === 'protect') { - return step; - } - if (signUp.isTransferable) { - await run(() => signIn.create({ transfer: true })); - if (signIn.status !== 'complete') { - await router.navigate( - buildURL({ base: signInUrl(), hashPath: transferRoute(signIn) }, { stringify: true }), - ); - return undefined; - } - await run(() => - signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), - ); - return undefined; - } - const existingSession = signUp.existingSession?.sessionId; - if (existingSession) { - await clerk.setActive({ - session: existingSession, - navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }), - }); - return undefined; - } - const failure = signUp.verifications.externalAccount.error; - if (failure) { - forgetTicket(); - await run(() => signUp.reset()); - throw new SaveError({ - global: SHOWN_RETURN_ERRORS.includes(failure.code) - ? { code: failure.code, message: failure.longMessage || failure.message } - : UNEXPECTED_ERROR, - }); - } - return step; + return completeOAuth(signUp, oauthOutcome); }, finalize: async () => { forgetTicket(); From 23d3d2a41336c2734ec02089bcc0d1c3de1c647c Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:48:27 -0700 Subject: [PATCH 20/40] test(mosaic): cover social sign-up's existing session, Protect after the return, and the sso body The fake FAPI can now return an OAuth sign-up for an account already signed in on the client, with FAPI's `identifier_already_signed_in` error and its session id. --- .../__tests__/feature/fake-fapi/sign-up.ts | 14 +++++ .../__tests__/sign-up.feature.test.tsx | 55 +++++++++++++++++++ 2 files changed, 69 insertions(+) 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 dac9d16e2b0..2965dcf9ee8 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,8 @@ export interface FakeSignUpSeed { export type FakeOAuthAccount = | { emailAddress: string; firstName?: string; lastName?: string } | { existingUser: { emailAddress: string; secondFactor?: boolean } } + /** The account is already signed in on this client, in the session with this id. */ + | { signedInSession: string } | { error: { code: string; message: string } }; export type FakeTicket = { emailAddress: string } | 'expired'; @@ -333,6 +335,18 @@ export function signUpHandlers( store(withExternal({ status: 'unverified', error: apiError(account.error.code, account.error.message) })); return; } + if ('signedInSession' in account) { + store( + withExternal({ + status: 'unverified', + error: { + ...apiError('identifier_already_signed_in', "You're already signed in."), + meta: { session_id: account.signedInSession }, + }, + }), + ); + return; + } if ('existingUser' in account) { store( withExternal({ 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 438bf42449e..2677d554bd4 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 @@ -1390,6 +1390,61 @@ describe('SignUp social sign-up', () => { expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); }); + it('switches to the session already signed in to the Google account', async () => { + const otherSession = fapiSession({ id: 'sess_other', user: fapiUser({ id: 'user_other' }) }); + const { fapi, first } = await startWithGoogle({ + client: fapiClient([otherSession, signedInSession]), + signUp: { oauth: { oauth_google: { signedInSession: signedInSession.id } } }, + }); + + const { clerk, navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); + expect(clerk.session?.id).toBe(signedInSession.id); + expect(fapi.signUp.transfers).toHaveLength(0); + }); + + it('runs the Protect check the sign-up still has after the return, then continues', async () => { + const { fapi, first } = await startWithGoogle({ + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { protectChecks: 1, oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + }); + + it('sends the accepted legal terms and the unsafe metadata with the Google sign-up', async () => { + const fapi = serveFapi({ + environment: socialEnvironment({ + user_settings: { + social: { oauth_google: GOOGLE }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }), + }); + const { clerk } = await renderWithClerk(); + vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + + await user.click(await screen.findByRole('checkbox')); + await user.click(screen.getByRole('button', { name: /Google/ })); + + await waitFor(() => expect(fapi.signUp.creations).toHaveLength(1)); + expect(fapi.signUp.creations[0].get('legal_accepted')).toBe('true'); + expect(JSON.parse(fapi.signUp.creations[0].get('unsafe_metadata') ?? '{}')).toEqual({ plan: 'pro' }); + }); + it('takes a user who signs in instead to their pending task', async () => { const { fapi, first } = await startWithGoogle({ signUp: { From 41bb3752c463a2828e005597943fe6a4d2a735d0 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:48:57 -0700 Subject: [PATCH 21/40] refactor(mosaic): share the redirect hold between sign-up and user profile Sign-up imported `REDIRECT_HOLD_MS` from `user-profile.utils`. It moves to `src/utils/redirect.ts`, beside the other cross-feature values, and AGENTS.md lists it. --- packages/mosaic/AGENTS.md | 1 + .../sign-up/sign-up-details/sign-up-details.controller.ts | 2 +- .../user-profile-connected-accounts-section.controller.ts | 2 +- .../user-profile-enterprise-accounts-section.controller.ts | 2 +- packages/mosaic/src/features/user-profile/user-profile.utils.ts | 2 -- packages/mosaic/src/utils/redirect.ts | 2 ++ 6 files changed, 6 insertions(+), 5 deletions(-) create mode 100644 packages/mosaic/src/utils/redirect.ts diff --git a/packages/mosaic/AGENTS.md b/packages/mosaic/AGENTS.md index 5f7c73bdde8..71736525d7d 100644 --- a/packages/mosaic/AGENTS.md +++ b/packages/mosaic/AGENTS.md @@ -85,6 +85,7 @@ Most problems a feature hits already have a shared answer. Find the line for you - Moving focus after a list row is removed → `useListRemovalFocus` (`src/hooks/`) - A debounced, abortable async check as the user types → `useDebouncedAsync` (`src/hooks/`) - A spinner that should not flash or flicker → `useSpinDelay` (`src/hooks/`) +- Keeping an action pending after it starts a full-page redirect, such as to an OAuth provider → `REDIRECT_HOLD_MS` (`src/utils/redirect.ts`) - A placeholder for content that is still loading → `Skeleton` (`src/components/skeleton/`), see [Skeletons](docs/skeletons.md) - A date shown to the user → `formatDate` (`src/utils/format-date.ts`) - Any current time read during render → `useNow` (`src/hooks/`), with `until` to stop ticking at a deadline diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index 42660a690fe..5411a5555c7 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -8,7 +8,7 @@ import { useDebouncedAsync } from '../../../hooks/use-debounced-async'; import type { MosaicMessages } from '../../../localization'; import { usePendingAction } from '../../../hooks/use-pending-action'; import { useMessages } from '../../../localization'; -import { REDIRECT_HOLD_MS } from '../../user-profile/user-profile.utils'; +import { REDIRECT_HOLD_MS } from '../../../utils/redirect'; import type { SignUpCreateResult, SignUpDetailsModel, SignUpDetailsValues, SignUpIdentifier } from '../sign-up.model'; import type { SignUpAlternativePhoneScreen, diff --git a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.controller.ts b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.controller.ts index 46617d0748d..6fa299c23f0 100644 --- a/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.controller.ts +++ b/packages/mosaic/src/features/user-profile/user-profile-connected-accounts-section/user-profile-connected-accounts-section.controller.ts @@ -8,8 +8,8 @@ import { usePanelTitle } from '../../../components/panel/panel'; import { useListRemovalFocus } from '../../../hooks/use-list-removal-focus'; import { usePendingAction } from '../../../hooks/use-pending-action'; import { useMessages } from '../../../localization'; +import { REDIRECT_HOLD_MS } from '../../../utils/redirect'; import type { ReverificationController } from '../../reverification'; -import { REDIRECT_HOLD_MS } from '../user-profile.utils'; import type { ConnectedAccountActionResult, UserProfileConnectedAccount, diff --git a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.controller.ts b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.controller.ts index d92ec9df897..b780499bd54 100644 --- a/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.controller.ts +++ b/packages/mosaic/src/features/user-profile/user-profile-enterprise-accounts-section/user-profile-enterprise-accounts-section.controller.ts @@ -1,6 +1,6 @@ import { usePendingAction } from '../../../hooks/use-pending-action'; +import { REDIRECT_HOLD_MS } from '../../../utils/redirect'; import type { ReverificationController } from '../../reverification'; -import { REDIRECT_HOLD_MS } from '../user-profile.utils'; import type { EnterpriseAccountActionResult, UserProfileEnterpriseAccount, diff --git a/packages/mosaic/src/features/user-profile/user-profile.utils.ts b/packages/mosaic/src/features/user-profile/user-profile.utils.ts index 2d714fc83c5..fa2aabc8e4f 100644 --- a/packages/mosaic/src/features/user-profile/user-profile.utils.ts +++ b/packages/mosaic/src/features/user-profile/user-profile.utils.ts @@ -3,5 +3,3 @@ import type { AttributeData } from '@clerk/shared/types'; export function isAttributeAvailable(attribute: AttributeData | undefined): boolean { return Boolean(attribute?.enabled || attribute?.used_for_first_factor || attribute?.used_for_second_factor); } - -export const REDIRECT_HOLD_MS = 2000; diff --git a/packages/mosaic/src/utils/redirect.ts b/packages/mosaic/src/utils/redirect.ts new file mode 100644 index 00000000000..9341697aa66 --- /dev/null +++ b/packages/mosaic/src/utils/redirect.ts @@ -0,0 +1,2 @@ +/** How long an action stays pending after it starts a full-page redirect, so its button does not come back before the page unloads. */ +export const REDIRECT_HOLD_MS = 2000; From 9527fd238c9a6e4e067a1d41fec824d6c6aa7e75 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:49:29 -0700 Subject: [PATCH 22/40] docs(mosaic): describe the sign-up OAuth return as built The flow doc said redirect URLs are never hand-built and that sign-up keeps the screen on every transfer, while the OAuth return builds a marked callback URL and transfers an existing account itself. It now says the marker is temporary until the router's `useReturnUrl()` lands, and describes the return as built: any route, the ticket kept on success and removed on error, the sign-in route a transfer needs, `redirect_url`, and the OAuth transport. --- .../docs/internals/sign-in-sign-up-flow.md | 17 +++++++++++++---- 1 file changed, 13 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 89c8e227b6d..d47da107584 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -56,7 +56,7 @@ 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`: planned, not built. From sign-in, 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. From sign-up, when the identifier already has an account, it will call `signIn.create({ transfer: true })`, then `next` with the sign-in's step. Until then sign-up keeps the current screen on a `transfer` step. +- `transfer`: sign-up keeps the current screen. Sign-up transfers only an OAuth account that already has a user, and it does that inside the OAuth return, before a step reaches `next` ([Entry actions](#entry-actions)). 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". - `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 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))`. @@ -111,7 +111,7 @@ With no `:factor`, `factorOne` starts on the factor `ui`'s `determineStartingSig ## Entry actions -Sign-up redeems invitation tickets. 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 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. - Ticket: - Read and redeem once. Sign-up reads the ticket from `__clerk_ticket` or `__clerk_invitation_token`, as `ui`'s `SignUpStart` does, redeems it with `signUp.ticket({ unsafeMetadata })`, and shows the loading screen while it redeems. Sign-up redeems when it opens on `start`, or when the route guard sends it there. A ticket works only once, and the machine's `redeemingTicket` state runs the redemption once, so StrictMode can't redeem it twice. A failed redemption shows its error on `start` and removes the parameters, so `start` then works as a normal sign-up. A blocked redemption removes them too and shows `actionBlocked`. @@ -120,8 +120,17 @@ Sign-up redeems invitation tickets. The other entries are planned. The controlle - An invitation that needs nothing more. FAPI can answer the redemption with `complete`. The model does not pick the loading screen, so freezing the model alone would show `start` while `finalize()` runs. `FINALIZE` sent from `redeemingTicket` freezes the loading screen with the model, since arrival work has no screen of its own, and it stays up through `finalize()` and the wait for a task. If `finalize()` fails, the hold ends and `start` shows the error. `finalize()` has removed the ticket by then, so `start` is a normal sign-up form with its sign-in link. - Cleanup, and what waits for sign-in. Finishing or starting over removes the parameters. Choosing between `signUp.ticket()` and `signIn.ticket()` by `__clerk_status`, as `ui/src/components/SignIn/SignInStart.tsx` does, is sign-in's job and waits for its controller. - 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 come from the router (the planned `useReturnUrl(name, params)`), never hand-built. That part waits for the routing follow-up. -- OAuth return: until that follow-up, sign-up marks its callback URL with `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. `useSignUpController` reads the marker once on mount, shows the loading screen from the first paint, and runs `completeReturn` once on `start`, guarded by a ref like the ticket; the ticket waits until the return is done. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: a Protect check comes first; a `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`) that finishes in place, or goes to the sign-in URL when it still needs a factor; an `identifier_already_signed_in` account activates that session. A session from either of those is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. An external-account error 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; anything else is `next(step)`. The marker is gone once the return starts, so a reload mid-return lands on `start`. Sign-in-to-sign-up transfers start from sign-in, so they wait for its controller. +- 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. +- 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, `useSignUpController` shows the loading screen from the first paint and runs `completeReturn` once as its `return` action. The loading screen reads the marker until that action has run, then the action's pending state, so busy has one source. The ticket waits until the return is done. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: + - A Protect check comes first. + - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. + - An `identifier_already_signed_in` account activates that session. + - A session from a transfer or an existing session is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. + - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. Removing the ticket keeps the invitation from being redeemed again over the error, as in legacy, where the callback URL has no ticket. + - Anything else is `next(step)`. + + The marker is gone once the return starts, so a reload mid-return lands on `start`. 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 the TODO in `useSignUpController` covers `complete`. The email-link return will be handled first. - 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. From dc668bcaf3620590e68c9dd04cabbc44f2ef94f6 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:53:54 -0700 Subject: [PATCH 23/40] test(mosaic): cover a sign-up transfer after the Protect check on the OAuth return --- .../sign-up/__tests__/sign-up.feature.test.tsx | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) 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 2677d554bd4..5b800a515f0 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 @@ -1418,6 +1418,23 @@ describe('SignUp social sign-up', () => { expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); }); + it('signs in instead after the Protect check when the Google account already belongs to a user', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { protectChecks: 1, oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + expect(fapi.signUp.transfers).toHaveLength(0); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(fapi.client.sessions).toHaveLength(1); + }); + it('sends the accepted legal terms and the unsafe metadata with the Google sign-up', async () => { const fapi = serveFapi({ environment: socialEnvironment({ From 8097999301d19a218e6103db822df3424b4a6e32 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 01:56:28 -0700 Subject: [PATCH 24/40] fix(mosaic): transfer a social sign-up after its Protect check is solved --- .../docs/internals/sign-in-sign-up-flow.md | 4 ++-- .../features/sign-up/sign-up.controller.ts | 19 +++++++++++++------ 2 files changed, 15 insertions(+), 8 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 d47da107584..e7327448bfb 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -56,7 +56,7 @@ 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 keeps the current screen. Sign-up transfers only an OAuth account that already has a user, and it does that inside the OAuth return, before a step reaches `next` ([Entry actions](#entry-actions)). 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. +- `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". - `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 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))`. @@ -122,7 +122,7 @@ Sign-up redeems invitation tickets and completes OAuth returns. The other entrie - 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. - 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, `useSignUpController` shows the loading screen from the first paint and runs `completeReturn` once as its `return` action. The loading screen reads the marker until that action has run, then the action's pending state, so busy has one source. The ticket waits until the return is done. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: - - A Protect check comes first. + - A Protect check comes first. Once it is solved, `next` gets the step that follows, so a transfer after it still runs. - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. - An `identifier_already_signed_in` account activates that session. - A session from a transfer or an existing session is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. 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 b7f8e750dce..ea9e0df0212 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -260,6 +260,10 @@ export function useSignUpController( }); return; } + if (result.type === 'transfer') { + completeReturn(); + return; + } const nextRoute = routeFor(result, route); if (nextRoute) { details.clearPassword(); @@ -267,6 +271,14 @@ export function useSignUpController( } }; + const completeReturn = () => + void actions.run('return', async () => { + const step = await attempt.completeReturn(); + if (step) { + next(step); + } + }); + const activityError = activitySnapshot.context.error ? errorText(activitySnapshot.context.error) : undefined; const finalizeError = activitySnapshot.value === 'failed' ? activityError : undefined; const flowError = activityError ?? actions.error; @@ -284,12 +296,7 @@ export function useSignUpController( /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return once when sign-up opens with its marker in the URL, on any route, or redeems an invitation once when it opens on start with its ticket; arriving from a redirect or a link is not an event a handler could run from. */ useEffect(() => { if (attempt.hasPendingReturn && actions.lastKey === undefined) { - void actions.run('return', async () => { - const step = await attempt.completeReturn(); - if (step) { - next(step); - } - }); + completeReturn(); } }); /* eslint-enable react-you-might-not-need-an-effect/no-event-handler */ From bf884b60e0d9027cadc461d4a0965508e3aa9dd9 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 07:28:11 -0700 Subject: [PATCH 25/40] refactor(mosaic): read the sign-up OAuth return marker through the router --- packages/mosaic/src/features/sign-up/sign-up.model.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 1567c9dfa83..09dfdfc1546 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -549,7 +549,7 @@ export function useSignUpModel({ } return { result: next(signUp), emailAddress: signUp.emailAddress ?? '' }; }, - hasPendingReturn: new URL(window.location.href).searchParams.get(RETURN_PARAM) === SSO_RETURN, + hasPendingReturn: query.get(RETURN_PARAM) === SSO_RETURN, completeReturn: () => { forgetReturn(); return completeOAuth(signUp, oauthOutcome); From c9d16ef6e6f529fbc46244dbd7229880ff80f43f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 09:58:57 -0700 Subject: [PATCH 26/40] test(mosaic): run a Protect check raised on the return from Google clerk_go 8bb8f66dde runs the sign-up Protect check on the OAuth callback for a new account (api/fapi/v1/oauth/oauth.go:2767, FlowOpOAuthCallback in api/shared/sign_up/flow_stage.go:93-96 surfaces it on the next read). An account that already exists returns before that check (oauth.go:2747-2752), so a check raised on the return never leads to a transfer. The fake FAPI can now raise the check on the return (protectCheckOn: 'oauth_callback'), keeping a pending, unexpired check the way runProtectCheck does. The new test lands on the Protect screen after Google and completes the sign-up once the user solves it. --- .../__tests__/feature/fake-fapi/sign-up.ts | 51 +++++++++++-------- .../__tests__/sign-up.feature.test.tsx | 17 +++++++ 2 files changed, 46 insertions(+), 22 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 2965dcf9ee8..0af638ca58c 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -32,7 +32,7 @@ export interface FakeSignUpSeed { blocked?: Record; weakPasswords?: Record; protectChecks?: number; - protectCheckOn?: 'create' | 'update'; + protectCheckOn?: ProtectCheckOn; protectCheckExpired?: boolean; protectCheckResolvedElsewhere?: boolean; protectCheckBlocked?: Record; @@ -46,10 +46,11 @@ export interface FakeSignUpSeed { export type FakeOAuthAccount = | { emailAddress: string; firstName?: string; lastName?: string } | { existingUser: { emailAddress: string; secondFactor?: boolean } } - /** The account is already signed in on this client, in the session with this id. */ | { signedInSession: string } | { error: { code: string; message: string } }; +type ProtectCheckOn = 'create' | 'update' | 'oauth_callback'; + export type FakeTicket = { emailAddress: string } | 'expired'; export interface FakeSignUpState { @@ -59,7 +60,7 @@ export interface FakeSignUpState { blocked?: Record; weakPasswords: Record; protectChecks: number; - protectCheckOn?: 'create' | 'update'; + protectCheckOn?: ProtectCheckOn; protectCheckExpired?: boolean; protectCheckResolvedElsewhere?: boolean; protectCheckBlocked?: Record; @@ -160,7 +161,7 @@ export function signUpHandlers( ...(expired ? { expires_at: 1 } : {}), }; }; - const issueProtectCheck = (signUp: SignUpJSON, on: 'create' | 'update' = 'create'): SignUpJSON => { + const issueProtectCheck = (signUp: SignUpJSON, on: ProtectCheckOn = 'create'): SignUpJSON => { if ( (state.signUp.protectCheckOn ?? 'create') !== on || state.signUp.issuedProtectChecks >= state.signUp.protectChecks @@ -171,6 +172,8 @@ export function signUpHandlers( }; const isExpired = (check: NonNullable) => check.expires_at !== undefined && check.expires_at < Date.now(); + const runProtectCheck = (signUp: SignUpJSON, on: ProtectCheckOn): SignUpJSON => + signUp.protect_check && !isExpired(signUp.protect_check) ? signUp : issueProtectCheck(signUp, on); const clientError = async (response: Response) => { const body = (await response.json()) as object; @@ -359,22 +362,27 @@ export function signUpHandlers( const linked = withExternal({ status: 'verified' }); state.signUp.linkedStrategy = external.strategy; store( - settle({ - ...linked, - email_address: signUp.email_address ?? account.emailAddress, - first_name: signUp.first_name ?? account.firstName ?? null, - last_name: signUp.last_name ?? account.lastName ?? null, - verifications: { - ...linked.verifications!, - email_address: signUp.email_address - ? linked.verifications!.email_address - : { - ...linked.verifications!.email_address, - ...fapiVerification(`from_${external.strategy}`, { status: 'verified' }), - next_action: '', - }, - }, - }), + settle( + runProtectCheck( + { + ...linked, + email_address: signUp.email_address ?? account.emailAddress, + first_name: signUp.first_name ?? account.firstName ?? null, + last_name: signUp.last_name ?? account.lastName ?? null, + verifications: { + ...linked.verifications!, + email_address: signUp.email_address + ? linked.verifications!.email_address + : { + ...fapiUnpreparedVerification(), + ...fapiVerification(`from_${external.strategy}`, { status: 'verified' }), + next_action: '', + }, + }, + }, + 'oauth_callback', + ), + ), ); }; @@ -666,8 +674,7 @@ export function signUpHandlers( if (applied instanceof HttpResponse) { return applied; } - const pending = applied.protect_check && !isExpired(applied.protect_check); - return store(settle(pending ? applied : issueProtectCheck(applied, 'update'))); + return store(settle(runProtectCheck(applied, 'update'))); }), http.post(fapiUrl('/v1/client/sign_ups/:id/prepare_verification'), async ({ params, request }) => { const signUp = current(params.id); 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 5b800a515f0..48a5e976af2 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 @@ -1418,6 +1418,23 @@ describe('SignUp social sign-up', () => { expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); }); + it('runs the Protect check raised on the return from Google, then completes the sign-up', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { protectChecks: 1, protectCheckOn: 'oauth_callback', oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + expect(fapi.client.sign_up?.protect_check).toBeNull(); + + const { navigate } = await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + expect(fapi.client.sign_up?.missing_fields).toEqual(['protect_check']); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + expect(fapi.client.sessions).toHaveLength(1); + }); + it('signs in instead after the Protect check when the Google account already belongs to a user', async () => { const { fapi, first } = await startWithGoogle({ signUp: { protectChecks: 1, oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, From 5bf956e09a7f45f67c8b2f75048b70bec0321c07 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 23 Nov 2026 20:50:18 -0700 Subject: [PATCH 27/40] refactor(mosaic): let the sign-up details controller decide which providers continue shows --- .../sign-up/sign-up-details/sign-up-details.controller.ts | 5 ++++- .../src/features/sign-up/sign-up-details/sign-up-details.tsx | 3 +-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index 5411a5555c7..ff8893198d4 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -219,7 +219,10 @@ export function useSignUpDetailsController( ...screen, step: detailsStep('continue', continueFields, details, identifier), onSwitchField: switchField('continue'), - socialProviders: details.continueOAuthProviders, + socialProviders: + details.continueLegalConsent && signUpFieldNames(continueFields).length === 0 + ? [] + : details.continueOAuthProviders, onSelectProvider: selectOAuth, }, error: form.error, diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx index e99b7d5b633..71d90331a17 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.tsx @@ -49,7 +49,6 @@ export function SignUpDetailsStep({ const { fields, legalConsent } = step; const heading = signUpDetailsHeading(step, m); const [first] = signUpFieldNames(fields); - const onlyLegalConsent = Boolean(legalConsent) && !first; const hasFields = Boolean(first) || Boolean(legalConsent); const hasForm = hasFields || step.purpose === 'continue'; const [isChallengeShown, setIsChallengeShown] = useState(false); @@ -80,7 +79,7 @@ export function SignUpDetailsStep({ {...inertProps(isChallengeShown)} > Date: Mon, 23 Nov 2026 22:42:33 -0700 Subject: [PATCH 28/40] fix(mosaic): hide Continue's providers only when legal consent is all a sign-up needs --- .../__tests__/sign-up.feature.test.tsx | 51 +++++++++++++++++++ .../sign-up-details.controller.ts | 5 +- .../src/features/sign-up/sign-up.model.ts | 3 ++ 3 files changed, 55 insertions(+), 4 deletions(-) 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 48a5e976af2..c399f74860b 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 @@ -619,6 +619,57 @@ describe('SignUp', () => { expect(fapi.signUp.creations).toHaveLength(1); expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); }); + describe('with legal consent missing', () => { + const legalConsentEnvironment = (google: { required: boolean }) => + environment({ + user_settings: { + social: { + oauth_google: { + enabled: true, + authenticatable: true, + logo_url: null, + strategy: 'oauth_google', + name: 'Google', + ...google, + }, + }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }); + const signUpWithPassword = { ...fapiClient(), sign_up: fapiSignUp({ email_address: EMAIL, has_password: true }) }; + + it('offers the provider the sign-up still needs alongside legal consent', async () => { + const { user } = await renderSignUpWithRouteProbe({ + environment: legalConsentEnvironment({ required: true }), + client: signUpWithPassword, + }); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await enterCode(user); + + expect(await screen.findByRole('checkbox')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); + }); + + it('offers no provider when legal consent is all the sign-up needs', async () => { + const { user } = await renderSignUpWithRouteProbe({ + environment: legalConsentEnvironment({ required: false }), + client: signUpWithPassword, + }); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await enterCode(user); + + expect(await screen.findByRole('heading', { name: 'Legal consent' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + }); + }); }); describe('starting over', () => { diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index ff8893198d4..5411a5555c7 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -219,10 +219,7 @@ export function useSignUpDetailsController( ...screen, step: detailsStep('continue', continueFields, details, identifier), onSwitchField: switchField('continue'), - socialProviders: - details.continueLegalConsent && signUpFieldNames(continueFields).length === 0 - ? [] - : details.continueOAuthProviders, + socialProviders: details.continueOAuthProviders, onSelectProvider: selectOAuth, }, error: form.error, 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 09dfdfc1546..82abc06ade9 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -215,6 +215,9 @@ function continueProviders( signUp: SignUpFutureResource, providers: T[], ): T[] { + if (signUp.missingFields.length === 1 && signUp.missingFields[0] === 'legal_accepted') { + return []; + } const missing = providers.filter(provider => signUp.missingFields.includes(provider.id)); if (missing.length > 0) { return missing; From 07065296e039614fba2d45987a11164f4a03c110 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 11:55:45 -0700 Subject: [PATCH 29/40] refactor(mosaic): settle the sign-up OAuth return inside completeReturn Inlines the one-caller completeOAuth and its actions object, drops a guard the early return already covers, and stops asserting the internal return marker. --- .../__tests__/sign-up.feature.test.tsx | 2 +- .../features/sign-up/sign-up.controller.ts | 1 - .../src/features/sign-up/sign-up.model.ts | 95 ++++++++----------- packages/mosaic/src/utils/redirect.ts | 1 - 4 files changed, 38 insertions(+), 61 deletions(-) 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 c399f74860b..a6016f7272a 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 @@ -1235,7 +1235,7 @@ describe('SignUp social sign-up', () => { expect(String(leave.mock.calls[0][0])).toBe('https://oauth.example/authorize?strategy=oauth_google'); expect(fapi.signUp.creations).toHaveLength(1); expect(fapi.signUp.creations[0].get('strategy')).toBe('oauth_google'); - expect(fapi.signUp.creations[0].get('redirect_url')).toContain('__clerk_mosaic_sign_up=sso-callback'); + expect(fapi.signUp.creations[0].get('redirect_url')).toBeTruthy(); expect(fapi.signUp.creations[0].get('action_complete_redirect_url')).toBeTruthy(); }); 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 ea9e0df0212..8922030e124 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -235,7 +235,6 @@ export function useSignUpController( const model = isHolding ? (activitySnapshot.context.frozenModel ?? liveModel) : liveModel; const { attempt, navigation, verification } = model; - // The marker is in the URL from the first paint, before the effect starts the return. `lastKey` is set once it ran. const isReturning = actions.pendingKey === 'return' || (attempt.hasPendingReturn && actions.lastKey === undefined); const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; 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 82abc06ade9..ff6ad81badc 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -185,7 +185,6 @@ const SHOWN_RETURN_ERRORS: readonly string[] = [ ERROR_CODES.USER_DEACTIVATED, ]; -// The sign-in routes `clerk.ts` `_handleRedirectCallback` sends a transfer to when it does not complete. const TRANSFER_ROUTES: Partial> = { needs_first_factor: '/factor-one', needs_second_factor: '/factor-two', @@ -278,44 +277,6 @@ async function run(call: () => Promise<{ error: ClerkError | null }>): Promise SignUpNextStep; - transfer: () => Promise; - activate: (sessionId: string) => Promise; - forgetTicket: () => void; -} - -/** Settles a sign-up the provider sent back. Resolves no step when the flow leaves sign-up. */ -async function completeOAuth( - signUp: SignUpFutureResource, - { next, transfer, activate, forgetTicket }: OAuthOutcomeActions, -): Promise { - const step = next(signUp); - if (step.type === 'protect') { - return step; - } - if (signUp.isTransferable) { - await transfer(); - return undefined; - } - const existingSession = signUp.existingSession?.sessionId; - if (existingSession) { - await activate(existingSession); - return undefined; - } - const failure = signUp.verifications.externalAccount.error; - if (failure) { - forgetTicket(); - await run(() => signUp.reset()); - throw new SaveError({ - global: SHOWN_RETURN_ERRORS.includes(failure.code) - ? { code: failure.code, message: failure.longMessage || failure.message } - : UNEXPECTED_ERROR, - }); - } - return step; -} - export function useSignUpModel({ initialValues = {}, unsafeMetadata, @@ -508,23 +469,6 @@ export function useSignUpModel({ await router.navigate(destination); }; - const oauthOutcome: OAuthOutcomeActions = { - next, - forgetTicket, - transfer: async () => { - await run(() => signIn.create({ transfer: true })); - if (signIn.status !== 'complete') { - await router.navigate(buildURL({ base: signInUrl(), hashPath: transferRoute(signIn) }, { stringify: true })); - return; - } - await run(() => - signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), - ); - }, - activate: session => - clerk.setActive({ session, navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), - }; - const step = next(signUp); const phoneChannel = signUp.verifications.phoneNumber.channel; const preferredPhoneChannel = (phoneNumber: string | undefined): PhoneCodeChannel | undefined => { @@ -553,9 +497,44 @@ export function useSignUpModel({ return { result: next(signUp), emailAddress: signUp.emailAddress ?? '' }; }, hasPendingReturn: query.get(RETURN_PARAM) === SSO_RETURN, - completeReturn: () => { + completeReturn: async () => { forgetReturn(); - return completeOAuth(signUp, oauthOutcome); + const returned = next(signUp); + if (returned.type === 'protect') { + return returned; + } + if (signUp.isTransferable) { + await run(() => signIn.create({ transfer: true })); + if (signIn.status !== 'complete') { + await router.navigate( + buildURL({ base: signInUrl(), hashPath: transferRoute(signIn) }, { stringify: true }), + ); + return undefined; + } + await run(() => + signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), + ); + return undefined; + } + const existingSession = signUp.existingSession?.sessionId; + if (existingSession) { + await clerk.setActive({ + session: existingSession, + navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }), + }); + return undefined; + } + const failure = signUp.verifications.externalAccount.error; + if (failure) { + forgetTicket(); + await run(() => signUp.reset()); + throw new SaveError({ + global: SHOWN_RETURN_ERRORS.includes(failure.code) + ? { code: failure.code, message: failure.longMessage || failure.message } + : UNEXPECTED_ERROR, + }); + } + return returned; }, finalize: async () => { forgetTicket(); diff --git a/packages/mosaic/src/utils/redirect.ts b/packages/mosaic/src/utils/redirect.ts index 9341697aa66..08f43b89e16 100644 --- a/packages/mosaic/src/utils/redirect.ts +++ b/packages/mosaic/src/utils/redirect.ts @@ -1,2 +1 @@ -/** How long an action stays pending after it starts a full-page redirect, so its button does not come back before the page unloads. */ export const REDIRECT_HOLD_MS = 2000; From 34b5748ac0c24a2204600120dd40e09970a23632 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 13:24:36 -0700 Subject: [PATCH 30/40] test(mosaic): land on the redirect_url when a social sign-up turns into a sign-in --- .../__tests__/sign-up.feature.test.tsx | 28 +++++++++++++++++++ 1 file changed, 28 insertions(+) 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 a6016f7272a..5a0811649cf 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 @@ -1313,6 +1313,19 @@ describe('SignUp social sign-up', () => { expect(fapi.client.sessions).toHaveLength(1); }); + it('lands on the redirect_url when the Google account already belongs to a user', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); + const { fapi, first } = await startWithGoogle({ + signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith('/dashboard')); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); + expect(fapi.signUp.transfers).toHaveLength(1); + }); + it('hands a transfer that still needs a second factor to the sign-in factor-two route, keeping redirect_url', async () => { window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); const { fapi, first } = await startWithGoogle({ @@ -1455,6 +1468,21 @@ describe('SignUp social sign-up', () => { expect(fapi.signUp.transfers).toHaveLength(0); }); + it('lands on the redirect_url after switching to the session already signed in to the Google account', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); + const otherSession = fapiSession({ id: 'sess_other', user: fapiUser({ id: 'user_other' }) }); + const { fapi, first } = await startWithGoogle({ + client: fapiClient([otherSession, signedInSession]), + signUp: { oauth: { oauth_google: { signedInSession: signedInSession.id } } }, + }); + + const { clerk, navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith('/dashboard')); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); + expect(clerk.session?.id).toBe(signedInSession.id); + }); + it('runs the Protect check the sign-up still has after the return, then continues', async () => { const { fapi, first } = await startWithGoogle({ environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), From e598d1123f75a06b76dfb194e2f410995361b64b Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 13:24:57 -0700 Subject: [PATCH 31/40] fix(mosaic): keep redirect_url when a social sign-up turns into a sign-in The sign-up model built the after sign-in URL without the query, so a Google account that already had a user, or was already signed in on this client, landed on the sign-in fallback instead of the redirect_url. Both paths now pass the query to buildAfterSignInUrl, as sign-up does for the after sign-up URL and as legacy does (ui/src/contexts/components/SignUp.ts). --- packages/mosaic/src/features/sign-up/sign-up.model.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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 ff6ad81badc..3cf82044788 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -297,6 +297,7 @@ export function useSignUpModel({ const query = router.getSearchParams(); const returnUrl = query.get('redirect_url') ?? undefined; const afterSignUpUrl = clerk.buildAfterSignUpUrl({ params: query }); + const afterSignInUrl = clerk.buildAfterSignInUrl({ params: query }); const signInUrl = () => clerk.buildSignInUrl(returnUrl ? { redirectUrl: returnUrl } : undefined); const taskInFlow = (task: SessionTask | undefined): SignUpTaskKey | undefined => task?.key === 'choose-organization' && !clerk.__internal_getOption('taskUrls')?.[task.key] ? task.key : undefined; @@ -511,16 +512,14 @@ export function useSignUpModel({ ); return undefined; } - await run(() => - signIn.finalize({ navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }) }), - ); + await run(() => signIn.finalize({ navigate: navigateAfter(afterSignInUrl, { keepsTaskInFlow: false }) })); return undefined; } const existingSession = signUp.existingSession?.sessionId; if (existingSession) { await clerk.setActive({ session: existingSession, - navigate: navigateAfter(clerk.buildAfterSignInUrl(), { keepsTaskInFlow: false }), + navigate: navigateAfter(afterSignInUrl, { keepsTaskInFlow: false }), }); return undefined; } From ed100652b248637e4249c730c8017a829eddd943 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 13:25:16 -0700 Subject: [PATCH 32/40] docs(mosaic): say sign-up OAuth is a full-page redirect and popup OAuth is not built --- packages/mosaic/docs/internals/sign-in-sign-up-flow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e7327448bfb..67cc5bdc258 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -129,7 +129,7 @@ Sign-up redeems invitation tickets and completes OAuth returns. The other entrie - 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. Removing the ticket keeps the invitation from being redeemed again over the error, as in legacy, where the callback URL has no ticket. - Anything else is `next(step)`. - The marker is gone once the return starts, so a reload mid-return lands on `start`. 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. + 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 the TODO in `useSignUpController` covers `complete`. The email-link return will be handled first. From c18b608e164169644dd4fb423e7c6b86f855f924 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 14:39:11 -0700 Subject: [PATCH 33/40] test(mosaic): show the blocked notice when a social sign-up return was blocked Fails today. FAPI stores `action_blocked` with its details on the external account verification when Protect blocks the callback, and sign-up shows it as an inline error on the start form. The fake FAPI's OAuth error takes the `meta` FAPI stores with it. --- .../__tests__/feature/fake-fapi/sign-up.ts | 9 ++++++-- .../__tests__/sign-up.feature.test.tsx | 23 +++++++++++++++++++ 2 files changed, 30 insertions(+), 2 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 0af638ca58c..f77889d4cd8 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -47,7 +47,7 @@ export type FakeOAuthAccount = | { emailAddress: string; firstName?: string; lastName?: string } | { existingUser: { emailAddress: string; secondFactor?: boolean } } | { signedInSession: string } - | { error: { code: string; message: string } }; + | { error: { code: string; message: string; meta?: ClerkAPIErrorJSON['meta'] } }; type ProtectCheckOn = 'create' | 'update' | 'oauth_callback'; @@ -335,7 +335,12 @@ export function signUpHandlers( verifications: { ...signUp.verifications!, external_account: { ...external, ...changes } }, }); if ('error' in account) { - store(withExternal({ status: 'unverified', error: apiError(account.error.code, account.error.message) })); + store( + withExternal({ + status: 'unverified', + error: { ...apiError(account.error.code, account.error.message), meta: account.error.meta ?? {} }, + }), + ); return; } if ('signedInSession' in account) { 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 5a0811649cf..5df00e26b54 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 @@ -1357,6 +1357,29 @@ describe('SignUp social sign-up', () => { expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); }); + it('replaces the form with the blocked notice when the return from Google was blocked', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { + oauth_google: { + error: { + code: 'action_blocked', + message: 'Request blocked', + meta: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' }, + }, + }, + }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); + expect(screen.getByText('Contact support.')).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Create your account' })).toBeNull(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); + it('keeps the denial on screen when an invitee comes back from Google, and does not redeem the ticket again', async () => { window.history.replaceState(null, '', `${window.location.pathname}?__clerk_ticket=tkt_invite`); const { fapi, first } = await startWithGoogle({ From dbaa2bba7d7488c21e777734e465b800aeaeabc6 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 14:39:49 -0700 Subject: [PATCH 34/40] fix(mosaic): show the blocked notice when a social sign-up return was blocked `completeReturn` resolves with the blocked result when the external account's error is `action_blocked` with its details, as legacy's `SignUpStart` shows `ActionBlockedCard` for it. The controller keeps the result for the mount, like a blocked create. An `action_blocked` error without details still shows inline on the start form. --- packages/mosaic/docs/internals/sign-in-sign-up-flow.md | 4 ++-- .../mosaic/src/features/sign-up/sign-up.controller.ts | 6 +++--- packages/mosaic/src/features/sign-up/sign-up.model.ts | 8 ++++++-- 3 files changed, 11 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 67cc5bdc258..4e1f7abe4b3 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -58,7 +58,7 @@ 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". -- `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 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. +- `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. 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`. @@ -126,7 +126,7 @@ Sign-up redeems invitation tickets and completes OAuth returns. The other entrie - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. - An `identifier_already_signed_in` account activates that session. - A session from a transfer or an existing session is a sign-in, so a pending task goes to its task URL rather than staying in sign-up. - - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. 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. Removing the ticket keeps the invitation from being redeemed again over the error, as in legacy, where the callback URL has no ticket. - Anything else is `next(step)`. The marker is gone once the return starts, so a reload mid-return lands on `start`. OAuth is a full-page redirect only. Sign-up never passes `sso()` a `popup`, so popup OAuth (`oauthFlow: 'popup'`) is not built. An OAuth transport (`__internal_oauthTransport`) is not supported yet. `SignUpFuture.sso()` still navigates the window, so clerk-js has to honor the transport first. Sign-in-to-sign-up transfers start from sign-in, so they wait for its controller. diff --git a/packages/mosaic/src/features/sign-up/sign-up.controller.ts b/packages/mosaic/src/features/sign-up/sign-up.controller.ts index 8922030e124..d7eda670854 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -272,9 +272,9 @@ export function useSignUpController( const completeReturn = () => void actions.run('return', async () => { - const step = await attempt.completeReturn(); - if (step) { - next(step); + const result = await attempt.completeReturn(); + if (result) { + next(result); } }); 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 3cf82044788..aec19e39f10 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -80,7 +80,7 @@ export interface SignUpAttemptModel { ticket: string | undefined; redeemTicket: () => Promise<{ result: SignUpCreateResult; emailAddress: string }>; hasPendingReturn: boolean; - completeReturn: () => Promise; + completeReturn: () => Promise; finalize: () => Promise; reset: () => Promise; } @@ -261,7 +261,7 @@ function emailSupportFor( return () => window.location.assign(`mailto:${address}`); } -function blockedBy(error: ClerkError | null): AuthActionBlockedDetails | undefined { +function blockedBy(error: ClerkError | ClerkAPIError | null): AuthActionBlockedDetails | undefined { const blocked = actionBlockedDetailsFrom(error && isClerkAPIResponseError(error) ? error.errors[0] : error); if (!blocked) { return undefined; @@ -527,6 +527,10 @@ export function useSignUpModel({ if (failure) { forgetTicket(); await run(() => signUp.reset()); + const blocked = blockedBy(failure); + if (blocked) { + return { type: 'blocked', details: blocked }; + } throw new SaveError({ global: SHOWN_RETURN_ERRORS.includes(failure.code) ? { code: failure.code, message: failure.longMessage || failure.message } From 484e97b8d85ea0d06a1899c478e23de2513f37e9 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 14:42:22 -0700 Subject: [PATCH 35/40] test(mosaic): show the blocked notice when starting a social sign-up is blocked Fails today. The blocked notice now comes from the result a request resolves with, and `sso` still rejects with the error, so the start form shows it inline. --- .../sign-up/__tests__/sign-up.feature.test.tsx | 15 +++++++++++++++ 1 file changed, 15 insertions(+) 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 5df00e26b54..30835a8a960 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 @@ -1380,6 +1380,21 @@ describe('SignUp social sign-up', () => { expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); }); + it('replaces the form with the blocked notice when starting with Google is blocked', async () => { + serveFapi({ + environment: socialEnvironment(), + signUp: { blocked: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' } }, + }); + await renderWithClerk(); + const user = userEvent.setup(); + + await user.click(await screen.findByRole('button', { name: /Google/ })); + + expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); + expect(screen.getByText('Contact support.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + }); + it('keeps the denial on screen when an invitee comes back from Google, and does not redeem the ticket again', async () => { window.history.replaceState(null, '', `${window.location.pathname}?__clerk_ticket=tkt_invite`); const { fapi, first } = await startWithGoogle({ From 4fd1a6a8fd2ed77a418ac0b5e13be27eb7d3e3fd Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 14:42:47 -0700 Subject: [PATCH 36/40] fix(mosaic): show the blocked notice when starting a social sign-up is blocked `sso` resolves with the blocked result from the start form when FAPI answers `action_blocked`, and the details controller hands it to the flow, which keeps it for the mount. From the continue form it still rejects, so the error shows inline, as a blocked update does and as legacy's `SignUpContinue` shows it. --- .../docs/internals/sign-in-sign-up-flow.md | 2 +- .../sign-up-details.controller.ts | 6 ++++- .../src/features/sign-up/sign-up.model.ts | 27 ++++++++++++------- 3 files changed, 23 insertions(+), 12 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 4e1f7abe4b3..40bb0b0dec0 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -58,7 +58,7 @@ 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". -- `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. 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. +- `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`. diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index 5411a5555c7..fed29a77467 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -188,10 +188,14 @@ export function useSignUpDetailsController( return; } void providerActions.run(id, async () => { - await details.sso(provider.id, { + const result = await details.sso(provider.id, { legalAccepted: form.values.legalAccepted, continueSignUp: purpose === 'continue', }); + if (result) { + onNext(result); + return; + } await new Promise(resolve => setTimeout(resolve, REDIRECT_HOLD_MS)); }); }; 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 aec19e39f10..90ca0d88f66 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -120,7 +120,10 @@ export interface SignUpDetailsModel { alternativeChannels: Array; oauthProviders: Array; continueOAuthProviders: Array; - sso: (strategy: OAuthStrategy, options: { legalAccepted?: boolean; continueSignUp: boolean }) => Promise; + sso: ( + strategy: OAuthStrategy, + options: { legalAccepted?: boolean; continueSignUp: boolean }, + ) => Promise; inTicketSignUp: boolean; create: (values: SignUpDetailsValues, options?: { channel?: PhoneCodeChannel }) => Promise; update: (values: SignUpDetailsValues) => Promise; @@ -608,15 +611,19 @@ export function useSignUpModel({ await run(() => signUp.reset()); target = clerk.client?.signUp.__internal_future ?? signUp; } - await run(() => - target.sso({ - strategy, - redirectCallbackUrl: ssoCallbackUrl(), - redirectUrl: afterSignUpUrl, - unsafeMetadata, - legalAccepted: legalAccepted || undefined, - }), - ); + const result = await target.sso({ + strategy, + redirectCallbackUrl: ssoCallbackUrl(), + redirectUrl: afterSignUpUrl, + unsafeMetadata, + legalAccepted: legalAccepted || undefined, + }); + const blocked = continueSignUp ? undefined : blockedBy(result.error); + if (blocked) { + return { type: 'blocked', details: blocked }; + } + await run(() => Promise.resolve(result)); + return undefined; }, alternativeChannels: phoneCodeChannels.flatMap(channel => { const provider = getAlternativePhoneCodeProviderData(channel); From bd0cf5aebd340a3b8a049e91a2d64544243aade5 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Tue, 24 Nov 2026 17:47:33 -0700 Subject: [PATCH 37/40] test(mosaic): give the social sign-up tests their own file The social sign-up tests move out of the shared sign-up feature test, with the three provider tests that sat among the continue screen tests, and are grouped by what the user is doing in place of one "SignUp social sign-up" block. Starting with Google, signing in instead, and switching to a signed-in session each had one test for the fallback URL and one for the redirect_url in the query. Each pair is now one table over the two landings. --- .../__tests__/sign-up.feature.test.tsx | 535 +---------------- .../__tests__/sign-up.social.feature.test.tsx | 544 ++++++++++++++++++ 2 files changed, 546 insertions(+), 533 deletions(-) create mode 100644 packages/mosaic/src/features/sign-up/__tests__/sign-up.social.feature.test.tsx 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 30835a8a960..9a5c7bcf28b 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 @@ -1,20 +1,16 @@ import { screen, waitFor } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; -import { type ReactElement, useState } from 'react'; -import { afterEach, describe, expect, it, onTestFinished, vi } from 'vitest'; +import { describe, expect, it, onTestFinished } from 'vitest'; -import { type FakeFapiSeed, holdRequests, serveFapi, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; +import { holdRequests, VERIFICATION_CODE } from '../../../__tests__/feature/fake-fapi'; import { fapiClient, - type FapiEnvironmentOverrides, fapiMembership, fapiOrganization, fapiSession, fapiSignUp, fapiUser, } from '../../../__tests__/feature/fapi'; -import { renderWithClerk } from '../../../__tests__/feature/render'; -import { useVirtualWrite } from '../../../routing/virtual-store'; import { SignUp } from '../sign-up'; import { codeSent, @@ -29,7 +25,6 @@ import { passwordField, renderSignUp, renderSignUpWithRouteProbe, - RouteProbe, SHORT_PASSWORD, signedInSession, submitStart, @@ -592,84 +587,6 @@ describe('SignUp', () => { await waitFor(() => expect(navigate).toHaveBeenCalled()); expect(fapi.signUp.updates[0].get('legal_accepted')).toBe('true'); }); - - it('asks only for the provider the sign-up still needs on the continue screen', async () => { - const provider = { enabled: true, authenticatable: true, logo_url: null }; - const { clerk, fapi, user } = await renderSignUp({ - environment: environment({ - user_settings: { - social: { - oauth_google: { ...provider, required: true, strategy: 'oauth_google', name: 'Google' }, - oauth_github: { ...provider, required: false, strategy: 'oauth_github', name: 'GitHub' }, - }, - }, - }), - }); - const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); - - await submitStart(user); - await enterCode(user); - - expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); - - await user.click(screen.getByRole('button', { name: /Google/ })); - - await waitFor(() => expect(leave).toHaveBeenCalled()); - expect(fapi.signUp.creations).toHaveLength(1); - expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); - }); - describe('with legal consent missing', () => { - const legalConsentEnvironment = (google: { required: boolean }) => - environment({ - user_settings: { - social: { - oauth_google: { - enabled: true, - authenticatable: true, - logo_url: null, - strategy: 'oauth_google', - name: 'Google', - ...google, - }, - }, - sign_up: { - allowlist_only: false, - progressive: true, - captcha_enabled: false, - mode: 'public', - legal_consent_enabled: true, - }, - }, - }); - const signUpWithPassword = { ...fapiClient(), sign_up: fapiSignUp({ email_address: EMAIL, has_password: true }) }; - - it('offers the provider the sign-up still needs alongside legal consent', async () => { - const { user } = await renderSignUpWithRouteProbe({ - environment: legalConsentEnvironment({ required: true }), - client: signUpWithPassword, - }); - - await user.click(screen.getByRole('button', { name: 'Open the verify route' })); - await enterCode(user); - - expect(await screen.findByRole('checkbox')).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); - }); - - it('offers no provider when legal consent is all the sign-up needs', async () => { - const { user } = await renderSignUpWithRouteProbe({ - environment: legalConsentEnvironment({ required: false }), - client: signUpWithPassword, - }); - - await user.click(screen.getByRole('button', { name: 'Open the verify route' })); - await enterCode(user); - - expect(await screen.findByRole('heading', { name: 'Legal consent' })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); - }); - }); }); describe('starting over', () => { @@ -1179,451 +1096,3 @@ describe('SignUp', () => { }); }); }); - -describe('SignUp social sign-up', () => { - const GOOGLE = { - enabled: true, - required: false, - authenticatable: true, - strategy: 'oauth_google' as const, - name: 'Google', - logo_url: null, - }; - - afterEach(() => { - window.history.replaceState(null, '', window.location.pathname); - }); - - function socialEnvironment(overrides: FapiEnvironmentOverrides = {}) { - return environment({ - ...overrides, - user_settings: { social: { oauth_google: GOOGLE }, ...overrides.user_settings }, - }); - } - - async function startWithGoogle( - seed: FakeFapiSeed, - options?: Parameters[1], - provider: RegExp = /Google/, - ) { - const fapi = serveFapi({ environment: socialEnvironment(), ...seed }); - const first = await renderWithClerk(, options); - const leave = vi.spyOn(first.clerk, '__internal_windowNavigate').mockImplementation(() => {}); - const user = userEvent.setup(); - await user.click(await screen.findByRole('button', { name: provider })); - await waitFor(() => expect(leave).toHaveBeenCalled()); - return { fapi, first, leave, user }; - } - - async function returnFromGoogle( - fapi: ReturnType, - first: Awaited>, - options?: Parameters[1], - ui: ReactElement = , - ) { - const started = [...fapi.signUp.creations, ...fapi.signUp.updates].filter(body => body.has('redirect_url')); - const callback = new URL(started.at(-1)?.get('redirect_url') ?? ''); - first.unmount(); - fapi.signUp.returnFromOAuth(); - window.history.replaceState(null, '', `${callback.pathname}${callback.search}`); - return renderWithClerk(ui, options); - } - - it('starts Google sign-up with a callback URL that brings the user back to sign-up', async () => { - const { fapi, leave } = await startWithGoogle({}); - - expect(String(leave.mock.calls[0][0])).toBe('https://oauth.example/authorize?strategy=oauth_google'); - expect(fapi.signUp.creations).toHaveLength(1); - expect(fapi.signUp.creations[0].get('strategy')).toBe('oauth_google'); - expect(fapi.signUp.creations[0].get('redirect_url')).toBeTruthy(); - expect(fapi.signUp.creations[0].get('action_complete_redirect_url')).toBeTruthy(); - }); - - it('sends the redirect_url from the query as the URL to land on after Google', async () => { - window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); - - const { fapi } = await startWithGoogle({}); - - const afterGoogle = new URL(fapi.signUp.creations[0].get('action_complete_redirect_url') ?? ''); - expect(afterGoogle.pathname).toBe('/dashboard'); - }); - - it('asks for what Google did not provide after the return, then completes', async () => { - const seed: FakeFapiSeed = { - environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), - signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, - }; - const { fapi, first } = await startWithGoogle(seed); - - const { navigate } = await returnFromGoogle(fapi, first); - - expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); - expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); - expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); - expect(screen.queryByLabelText('Password')).toBeNull(); - - const user = userEvent.setup(); - await user.type(screen.getByRole('textbox', { name: 'Username' }), 'alice'); - await user.click(continueButton()); - - await waitFor(() => expect(navigate).toHaveBeenCalled()); - expect(fapi.signUp.updates.at(-1)?.get('username')).toBe('alice'); - expect(fapi.client.sessions).toHaveLength(1); - }); - - it('completes the return when sign-up opens on the continue route', async () => { - function OpenOnContinue() { - const write = useVirtualWrite(); - const [opened, setOpened] = useState(false); - return opened ? ( - - ) : ( - - ); - } - const { fapi, first } = await startWithGoogle({ - environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), - signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, - }); - - await returnFromGoogle(fapi, first, undefined, ); - await userEvent.setup().click(screen.getByRole('button', { name: 'Open sign-up on continue' })); - - expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); - expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); - }); - - it('signs in instead when the Google account already belongs to a user', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, - }); - - const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); - expect(fapi.signUp.transfers).toHaveLength(1); - expect(fapi.client.sessions).toHaveLength(1); - }); - - it('lands on the redirect_url when the Google account already belongs to a user', async () => { - window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); - const { fapi, first } = await startWithGoogle({ - signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, - }); - - const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith('/dashboard')); - expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); - expect(fapi.signUp.transfers).toHaveLength(1); - }); - - it('hands a transfer that still needs a second factor to the sign-in factor-two route, keeping redirect_url', async () => { - window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); - const { fapi, first } = await startWithGoogle({ - signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL, secondFactor: true } } } }, - }); - - const { navigate } = await returnFromGoogle(fapi, first, { signInUrl: '/sign-in' }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/sign-in'))); - const target = new URL(String(navigate.mock.calls.at(-1)?.[0]), window.location.origin); - const route = new URL(target.hash.slice(1), target.origin); - expect(target.pathname).toBe('/sign-in'); - expect(route.pathname).toBe('/factor-two'); - expect(new URL(route.searchParams.get('redirect_url') ?? '', target.origin).pathname).toBe('/dashboard'); - expect(fapi.client.sessions).toHaveLength(0); - }); - - it('shows what went wrong at Google on the start form', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { - oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, - }, - }); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); - expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); - expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); - }); - - it('replaces the form with the blocked notice when the return from Google was blocked', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { - oauth: { - oauth_google: { - error: { - code: 'action_blocked', - message: 'Request blocked', - meta: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' }, - }, - }, - }, - }, - }); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); - expect(screen.getByText('Contact support.')).toBeInTheDocument(); - expect(screen.queryByRole('heading', { name: 'Create your account' })).toBeNull(); - expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); - }); - - it('replaces the form with the blocked notice when starting with Google is blocked', async () => { - serveFapi({ - environment: socialEnvironment(), - signUp: { blocked: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' } }, - }); - await renderWithClerk(); - const user = userEvent.setup(); - - await user.click(await screen.findByRole('button', { name: /Google/ })); - - expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); - expect(screen.getByText('Contact support.')).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); - }); - - it('keeps the denial on screen when an invitee comes back from Google, and does not redeem the ticket again', async () => { - window.history.replaceState(null, '', `${window.location.pathname}?__clerk_ticket=tkt_invite`); - const { fapi, first } = await startWithGoogle({ - signUp: { - tickets: { tkt_invite: { emailAddress: EMAIL } }, - oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, - }, - }); - expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); - await waitFor(() => expect(window.location.search).not.toContain('__clerk_ticket')); - expect(screen.getByText('You did not grant access to your account.')).toBeInTheDocument(); - expect(fapi.signUp.creations.filter(body => body.get('strategy') === 'ticket')).toHaveLength(1); - }); - - it('starts a new sign-up from start even when an earlier one is still on the client', async () => { - const fapi = serveFapi({ environment: socialEnvironment() }); - const { clerk } = await renderWithClerk( - <> - - - , - ); - const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); - const user = userEvent.setup(); - await submitStart(user); - await screen.findByRole('heading', { name: 'Verify your email' }); - await codeSent(); - - await user.click(screen.getByRole('button', { name: 'Open the start route' })); - await user.click(await screen.findByRole('button', { name: /Google/ })); - - await waitFor(() => expect(leave).toHaveBeenCalled()); - expect(fapi.signUp.creations).toHaveLength(2); - expect(fapi.signUp.creations[1].get('strategy')).toBe('oauth_google'); - expect(fapi.signUp.updates.filter(update => update.get('strategy'))).toEqual([]); - }); - - it('offers only the providers on start when the instance signs up with social accounts alone', async () => { - await renderSignUp({ - environment: socialEnvironment({ - attributes: { email_address: { enabled: false }, password: { enabled: false } }, - user_settings: { - social: { oauth_google: GOOGLE }, - sign_up: { - allowlist_only: false, - progressive: true, - captcha_enabled: false, - mode: 'public', - legal_consent_enabled: true, - }, - }, - }), - }); - - expect(await screen.findByRole('button', { name: /Google/ })).toBeInTheDocument(); - expect(screen.queryByRole('checkbox')).toBeNull(); - expect(screen.queryByRole('textbox')).toBeNull(); - }); - - it('asks for the required provider after the user signed up with another one', async () => { - const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub' }; - const { fapi, first } = await startWithGoogle( - { - environment: socialEnvironment({ - user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, - }), - signUp: { oauth: { oauth_github: { emailAddress: EMAIL } } }, - }, - undefined, - /GitHub/, - ); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); - expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); - expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); - }); - - it('offers Start over when the instance requires two providers a sign-up cannot both link', async () => { - const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub', required: true }; - const { user } = await renderSignUp({ - environment: socialEnvironment({ - user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, - }), - }); - - await submitStart(user); - await enterCode(user); - - expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); - }); - - it('switches to the session already signed in to the Google account', async () => { - const otherSession = fapiSession({ id: 'sess_other', user: fapiUser({ id: 'user_other' }) }); - const { fapi, first } = await startWithGoogle({ - client: fapiClient([otherSession, signedInSession]), - signUp: { oauth: { oauth_google: { signedInSession: signedInSession.id } } }, - }); - - const { clerk, navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); - expect(clerk.session?.id).toBe(signedInSession.id); - expect(fapi.signUp.transfers).toHaveLength(0); - }); - - it('lands on the redirect_url after switching to the session already signed in to the Google account', async () => { - window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); - const otherSession = fapiSession({ id: 'sess_other', user: fapiUser({ id: 'user_other' }) }); - const { fapi, first } = await startWithGoogle({ - client: fapiClient([otherSession, signedInSession]), - signUp: { oauth: { oauth_google: { signedInSession: signedInSession.id } } }, - }); - - const { clerk, navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith('/dashboard')); - expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); - expect(clerk.session?.id).toBe(signedInSession.id); - }); - - it('runs the Protect check the sign-up still has after the return, then continues', async () => { - const { fapi, first } = await startWithGoogle({ - environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), - signUp: { protectChecks: 1, oauth: { oauth_google: { emailAddress: EMAIL } } }, - }); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); - await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); - expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); - expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); - }); - - it('runs the Protect check raised on the return from Google, then completes the sign-up', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { protectChecks: 1, protectCheckOn: 'oauth_callback', oauth: { oauth_google: { emailAddress: EMAIL } } }, - }); - expect(fapi.client.sign_up?.protect_check).toBeNull(); - - const { navigate } = await returnFromGoogle(fapi, first); - - expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); - expect(fapi.client.sign_up?.missing_fields).toEqual(['protect_check']); - await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); - - await waitFor(() => expect(navigate).toHaveBeenCalled()); - expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); - expect(fapi.client.sessions).toHaveLength(1); - }); - - it('signs in instead after the Protect check when the Google account already belongs to a user', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { protectChecks: 1, oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, - }); - - const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); - - expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); - expect(fapi.signUp.transfers).toHaveLength(0); - await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); - expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); - expect(fapi.signUp.transfers).toHaveLength(1); - expect(fapi.client.sessions).toHaveLength(1); - }); - - it('sends the accepted legal terms and the unsafe metadata with the Google sign-up', async () => { - const fapi = serveFapi({ - environment: socialEnvironment({ - user_settings: { - social: { oauth_google: GOOGLE }, - sign_up: { - allowlist_only: false, - progressive: true, - captcha_enabled: false, - mode: 'public', - legal_consent_enabled: true, - }, - }, - }), - }); - const { clerk } = await renderWithClerk(); - vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); - const user = userEvent.setup(); - - await user.click(await screen.findByRole('checkbox')); - await user.click(screen.getByRole('button', { name: /Google/ })); - - await waitFor(() => expect(fapi.signUp.creations).toHaveLength(1)); - expect(fapi.signUp.creations[0].get('legal_accepted')).toBe('true'); - expect(JSON.parse(fapi.signUp.creations[0].get('unsafe_metadata') ?? '{}')).toEqual({ plan: 'pro' }); - }); - - it('takes a user who signs in instead to their pending task', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { - oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } }, - sessionTasks: [{ key: 'choose-organization' }], - }, - }); - - const { navigate } = await returnFromGoogle(fapi, first, { - signInUrl: '/sign-in', - signInFallbackRedirectUrl: '/home', - }); - - await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('choose-organization'))); - expect(fapi.signUp.transfers).toHaveLength(1); - expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); - }); - - it('shows a generic error when Google returns one that is not meant for users', async () => { - const { fapi, first } = await startWithGoogle({ - signUp: { - oauth: { oauth_google: { error: { code: 'internal_clerk_error', message: 'Raw server detail.' } } }, - }, - }); - - await returnFromGoogle(fapi, first); - - expect(await screen.findByText('Something went wrong. Please try again.')).toBeInTheDocument(); - expect(screen.queryByText('Raw server detail.')).toBeNull(); - }); -}); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.social.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.social.feature.test.tsx new file mode 100644 index 00000000000..0840a8cc968 --- /dev/null +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.social.feature.test.tsx @@ -0,0 +1,544 @@ +import { screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { type ReactElement, useState } from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { type FakeFapiSeed, serveFapi } from '../../../__tests__/feature/fake-fapi'; +import { + fapiClient, + type FapiEnvironmentOverrides, + fapiSession, + fapiSignUp, + fapiUser, +} from '../../../__tests__/feature/fapi'; +import { renderWithClerk } from '../../../__tests__/feature/render'; +import { useVirtualWrite } from '../../../routing/virtual-store'; +import { SignUp } from '../sign-up'; +import { + codeSent, + continueButton, + EMAIL, + enterCode, + environment, + renderSignUp, + renderSignUpWithRouteProbe, + RouteProbe, + signedInSession, + submitStart, +} from './sign-up.fixtures'; + +const GOOGLE = { + enabled: true, + required: false, + authenticatable: true, + strategy: 'oauth_google' as const, + name: 'Google', + logo_url: null, +}; + +afterEach(() => { + window.history.replaceState(null, '', window.location.pathname); +}); + +function socialEnvironment(overrides: FapiEnvironmentOverrides = {}) { + return environment({ + ...overrides, + user_settings: { social: { oauth_google: GOOGLE }, ...overrides.user_settings }, + }); +} + +async function startWithGoogle( + seed: FakeFapiSeed, + options?: Parameters[1], + provider: RegExp = /Google/, +) { + const fapi = serveFapi({ environment: socialEnvironment(), ...seed }); + const first = await renderWithClerk(, options); + const leave = vi.spyOn(first.clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + await user.click(await screen.findByRole('button', { name: provider })); + await waitFor(() => expect(leave).toHaveBeenCalled()); + return { fapi, first, leave, user }; +} + +async function returnFromGoogle( + fapi: ReturnType, + first: Awaited>, + options?: Parameters[1], + ui: ReactElement = , +) { + const started = [...fapi.signUp.creations, ...fapi.signUp.updates].filter(body => body.has('redirect_url')); + const callback = new URL(started.at(-1)?.get('redirect_url') ?? ''); + first.unmount(); + fapi.signUp.returnFromOAuth(); + window.history.replaceState(null, '', `${callback.pathname}${callback.search}`); + return renderWithClerk(ui, options); +} + +const SIGN_IN_LANDINGS = [ + { landing: 'the sign-in fallback URL', search: '', to: expect.stringContaining('/home'), elsewhere: '/dashboard' }, + { + landing: 'the redirect_url from the query', + search: '?redirect_url=%2Fdashboard', + to: '/dashboard', + elsewhere: '/home', + }, +]; + +const legalConsentEnvironment = (google: { required: boolean }) => + environment({ + user_settings: { + social: { oauth_google: { ...GOOGLE, ...google } }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }); + +const signUpWithPassword = { ...fapiClient(), sign_up: fapiSignUp({ email_address: EMAIL, has_password: true }) }; + +describe('starting with a social provider', () => { + it.each([ + { landing: 'the after sign-up URL', search: '', pathname: '/welcome' }, + { landing: 'the redirect_url from the query', search: '?redirect_url=%2Fdashboard', pathname: '/dashboard' }, + ])( + 'starts Google sign-up with a callback URL that brings the user back to sign-up, then on to $landing', + async ({ search, pathname }) => { + window.history.replaceState(null, '', `${window.location.pathname}${search}`); + + const { fapi, leave } = await startWithGoogle({}, { signUpFallbackRedirectUrl: '/welcome' }); + + expect(String(leave.mock.calls[0][0])).toBe('https://oauth.example/authorize?strategy=oauth_google'); + expect(fapi.signUp.creations).toHaveLength(1); + expect(fapi.signUp.creations[0].get('strategy')).toBe('oauth_google'); + expect(fapi.signUp.creations[0].get('redirect_url')).toBeTruthy(); + expect(new URL(fapi.signUp.creations[0].get('action_complete_redirect_url') ?? '').pathname).toBe(pathname); + }, + ); + + it('sends the accepted legal terms and the unsafe metadata with the Google sign-up', async () => { + const fapi = serveFapi({ + environment: socialEnvironment({ + user_settings: { + social: { oauth_google: GOOGLE }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }), + }); + const { clerk } = await renderWithClerk(); + vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + + await user.click(await screen.findByRole('checkbox')); + await user.click(screen.getByRole('button', { name: /Google/ })); + + await waitFor(() => expect(fapi.signUp.creations).toHaveLength(1)); + expect(fapi.signUp.creations[0].get('legal_accepted')).toBe('true'); + expect(JSON.parse(fapi.signUp.creations[0].get('unsafe_metadata') ?? '{}')).toEqual({ plan: 'pro' }); + }); + + it('starts a new sign-up from start even when an earlier one is still on the client', async () => { + const fapi = serveFapi({ environment: socialEnvironment() }); + const { clerk } = await renderWithClerk( + <> + + + , + ); + const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + const user = userEvent.setup(); + await submitStart(user); + await screen.findByRole('heading', { name: 'Verify your email' }); + await codeSent(); + + await user.click(screen.getByRole('button', { name: 'Open the start route' })); + await user.click(await screen.findByRole('button', { name: /Google/ })); + + await waitFor(() => expect(leave).toHaveBeenCalled()); + expect(fapi.signUp.creations).toHaveLength(2); + expect(fapi.signUp.creations[1].get('strategy')).toBe('oauth_google'); + expect(fapi.signUp.updates.filter(update => update.get('strategy'))).toEqual([]); + }); + + it('offers only the providers on start when the instance signs up with social accounts alone', async () => { + await renderSignUp({ + environment: socialEnvironment({ + attributes: { email_address: { enabled: false }, password: { enabled: false } }, + user_settings: { + social: { oauth_google: GOOGLE }, + sign_up: { + allowlist_only: false, + progressive: true, + captcha_enabled: false, + mode: 'public', + legal_consent_enabled: true, + }, + }, + }), + }); + + expect(await screen.findByRole('button', { name: /Google/ })).toBeInTheDocument(); + expect(screen.queryByRole('checkbox')).toBeNull(); + expect(screen.queryByRole('textbox')).toBeNull(); + }); + + it('replaces the form with the blocked notice when starting with Google is blocked', async () => { + serveFapi({ + environment: socialEnvironment(), + signUp: { blocked: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' } }, + }); + await renderWithClerk(); + const user = userEvent.setup(); + + await user.click(await screen.findByRole('button', { name: /Google/ })); + + expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); + expect(screen.getByText('Contact support.')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + }); +}); + +describe('coming back from the provider', () => { + it('asks for what Google did not provide after the return, then completes', async () => { + const seed: FakeFapiSeed = { + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, + }; + const { fapi, first } = await startWithGoogle(seed); + + const { navigate } = await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + expect(screen.queryByLabelText('Password')).toBeNull(); + + const user = userEvent.setup(); + await user.type(screen.getByRole('textbox', { name: 'Username' }), 'alice'); + await user.click(continueButton()); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.signUp.updates.at(-1)?.get('username')).toBe('alice'); + expect(fapi.client.sessions).toHaveLength(1); + }); + + it('completes the return when sign-up opens on the continue route', async () => { + function OpenOnContinue() { + const write = useVirtualWrite(); + const [opened, setOpened] = useState(false); + return opened ? ( + + ) : ( + + ); + } + const { fapi, first } = await startWithGoogle({ + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + + await returnFromGoogle(fapi, first, undefined, ); + await userEvent.setup().click(screen.getByRole('button', { name: 'Open sign-up on continue' })); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); + + it('shows what went wrong at Google on the start form', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); + expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); + + it('shows a generic error when Google returns one that is not meant for users', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { error: { code: 'internal_clerk_error', message: 'Raw server detail.' } } }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('Something went wrong. Please try again.')).toBeInTheDocument(); + expect(screen.queryByText('Raw server detail.')).toBeNull(); + }); + + it('keeps the denial on screen when an invitee comes back from Google, and does not redeem the ticket again', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?__clerk_ticket=tkt_invite`); + const { fapi, first } = await startWithGoogle({ + signUp: { + tickets: { tkt_invite: { emailAddress: EMAIL } }, + oauth: { oauth_google: { error: { code: 'oauth_access_denied', message: 'Access was denied.' } } }, + }, + }); + expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByText('You did not grant access to your account.')).toBeInTheDocument(); + await waitFor(() => expect(window.location.search).not.toContain('__clerk_ticket')); + expect(screen.getByText('You did not grant access to your account.')).toBeInTheDocument(); + expect(fapi.signUp.creations.filter(body => body.get('strategy') === 'ticket')).toHaveLength(1); + }); + + it('replaces the form with the blocked notice when the return from Google was blocked', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { + oauth_google: { + error: { + code: 'action_blocked', + message: 'Request blocked', + meta: { trace_id: 'trace_123', title: 'Request blocked', description: 'Contact support.' }, + }, + }, + }, + }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Request blocked' })).toBeInTheDocument(); + expect(screen.getByText('Contact support.')).toBeInTheDocument(); + expect(screen.queryByRole('heading', { name: 'Create your account' })).toBeNull(); + expect(window.location.search).not.toContain('__clerk_mosaic_sign_up'); + }); +}); + +describe('coming back with an account that already has a user', () => { + it.each(SIGN_IN_LANDINGS)( + 'signs in instead and lands on $landing when the Google account already belongs to a user', + async ({ search, to, elsewhere }) => { + window.history.replaceState(null, '', `${window.location.pathname}${search}`); + const { fapi, first } = await startWithGoogle({ + signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(to)); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining(elsewhere)); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(fapi.client.sessions).toHaveLength(1); + }, + ); + + it('hands a transfer that still needs a second factor to the sign-in factor-two route, keeping redirect_url', async () => { + window.history.replaceState(null, '', `${window.location.pathname}?redirect_url=%2Fdashboard`); + const { fapi, first } = await startWithGoogle({ + signUp: { oauth: { oauth_google: { existingUser: { emailAddress: EMAIL, secondFactor: true } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInUrl: '/sign-in' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/sign-in'))); + const target = new URL(String(navigate.mock.calls.at(-1)?.[0]), window.location.origin); + const route = new URL(target.hash.slice(1), target.origin); + expect(target.pathname).toBe('/sign-in'); + expect(route.pathname).toBe('/factor-two'); + expect(new URL(route.searchParams.get('redirect_url') ?? '', target.origin).pathname).toBe('/dashboard'); + expect(fapi.client.sessions).toHaveLength(0); + }); + + it('takes a user who signs in instead to their pending task', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { + oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } }, + sessionTasks: [{ key: 'choose-organization' }], + }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { + signInUrl: '/sign-in', + signInFallbackRedirectUrl: '/home', + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('choose-organization'))); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining('/home')); + }); + + it.each(SIGN_IN_LANDINGS)( + 'switches to the session already signed in to the Google account and lands on $landing', + async ({ search, to, elsewhere }) => { + window.history.replaceState(null, '', `${window.location.pathname}${search}`); + const otherSession = fapiSession({ id: 'sess_other', user: fapiUser({ id: 'user_other' }) }); + const { fapi, first } = await startWithGoogle({ + client: fapiClient([otherSession, signedInSession]), + signUp: { oauth: { oauth_google: { signedInSession: signedInSession.id } } }, + }); + + const { clerk, navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(to)); + expect(navigate).not.toHaveBeenCalledWith(expect.stringContaining(elsewhere)); + expect(clerk.session?.id).toBe(signedInSession.id); + expect(fapi.signUp.transfers).toHaveLength(0); + }, + ); +}); + +describe('running the Protect check after the return', () => { + it('runs the Protect check the sign-up still has after the return, then continues', async () => { + const { fapi, first } = await startWithGoogle({ + environment: socialEnvironment({ attributes: { username: { enabled: true, required: true } } }), + signUp: { protectChecks: 1, oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + }); + + it('runs the Protect check raised on the return from Google, then completes the sign-up', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { protectChecks: 1, protectCheckOn: 'oauth_callback', oauth: { oauth_google: { emailAddress: EMAIL } } }, + }); + expect(fapi.client.sign_up?.protect_check).toBeNull(); + + const { navigate } = await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + expect(fapi.client.sign_up?.missing_fields).toEqual(['protect_check']); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + expect(fapi.client.sessions).toHaveLength(1); + }); + + it('signs in instead after the Protect check when the Google account already belongs to a user', async () => { + const { fapi, first } = await startWithGoogle({ + signUp: { protectChecks: 1, oauth: { oauth_google: { existingUser: { emailAddress: EMAIL } } } }, + }); + + const { navigate } = await returnFromGoogle(fapi, first, { signInFallbackRedirectUrl: '/home' }); + + expect(await screen.findByRole('heading', { name: 'Verifying your request' })).toBeInTheDocument(); + expect(fapi.signUp.transfers).toHaveLength(0); + await userEvent.setup().click(await screen.findByRole('button', { name: 'I am human' })); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/home'))); + expect(fapi.signUp.proofTokens).toEqual(['proof_ptk_1']); + expect(fapi.signUp.transfers).toHaveLength(1); + expect(fapi.client.sessions).toHaveLength(1); + }); +}); + +describe('linking a provider the instance requires', () => { + it('asks only for the provider the sign-up still needs on the continue screen', async () => { + const provider = { enabled: true, authenticatable: true, logo_url: null }; + const { clerk, fapi, user } = await renderSignUp({ + environment: environment({ + user_settings: { + social: { + oauth_google: { ...provider, required: true, strategy: 'oauth_google', name: 'Google' }, + oauth_github: { ...provider, required: false, strategy: 'oauth_github', name: 'GitHub' }, + }, + }, + }), + }); + const leave = vi.spyOn(clerk, '__internal_windowNavigate').mockImplementation(() => {}); + + await submitStart(user); + await enterCode(user); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); + + await user.click(screen.getByRole('button', { name: /Google/ })); + + await waitFor(() => expect(leave).toHaveBeenCalled()); + expect(fapi.signUp.creations).toHaveLength(1); + expect(fapi.signUp.updates.at(-1)?.get('strategy')).toBe('oauth_google'); + }); + + it('offers the provider the sign-up still needs alongside legal consent', async () => { + const { user } = await renderSignUpWithRouteProbe({ + environment: legalConsentEnvironment({ required: true }), + client: signUpWithPassword, + }); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await enterCode(user); + + expect(await screen.findByRole('checkbox')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); + }); + + it('offers no provider when legal consent is all the sign-up needs', async () => { + const { user } = await renderSignUpWithRouteProbe({ + environment: legalConsentEnvironment({ required: false }), + client: signUpWithPassword, + }); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await enterCode(user); + + expect(await screen.findByRole('heading', { name: 'Legal consent' })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /Google/ })).toBeNull(); + }); + + it('asks for the required provider after the user signed up with another one', async () => { + const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub' }; + const { fapi, first } = await startWithGoogle( + { + environment: socialEnvironment({ + user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, + }), + signUp: { oauth: { oauth_github: { emailAddress: EMAIL } } }, + }, + undefined, + /GitHub/, + ); + + await returnFromGoogle(fapi, first); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /Google/ })).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /GitHub/ })).toBeNull(); + }); + + it('offers Start over when the instance requires two providers a sign-up cannot both link', async () => { + const github = { ...GOOGLE, strategy: 'oauth_github' as const, name: 'GitHub', required: true }; + const { user } = await renderSignUp({ + environment: socialEnvironment({ + user_settings: { social: { oauth_google: { ...GOOGLE, required: true }, oauth_github: github } }, + }), + }); + + await submitStart(user); + await enterCode(user); + + expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); + }); +}); From 991d0d1a699566fd578e60ed721ab662c57e2f99 Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 25 Nov 2026 16:10:45 -0700 Subject: [PATCH 38/40] style(mosaic): sort imports in the sign-up details controller --- .../sign-up/sign-up-details/sign-up-details.controller.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts index fed29a77467..93202508a78 100644 --- a/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up-details/sign-up-details.controller.ts @@ -5,8 +5,8 @@ import { useState } from 'react'; import type { FieldFeedback, FieldsConfig } from '../../../components/form'; import { useForm } from '../../../components/form'; import { useDebouncedAsync } from '../../../hooks/use-debounced-async'; -import type { MosaicMessages } from '../../../localization'; import { usePendingAction } from '../../../hooks/use-pending-action'; +import type { MosaicMessages } from '../../../localization'; import { useMessages } from '../../../localization'; import { REDIRECT_HOLD_MS } from '../../../utils/redirect'; import type { SignUpCreateResult, SignUpDetailsModel, SignUpDetailsValues, SignUpIdentifier } from '../sign-up.model'; From 14ee7b05f561bb9916730e38d5fcfde6c335e70c Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Mon, 30 Nov 2026 14:04:41 -0700 Subject: [PATCH 39/40] docs(mosaic): stop citing a TODO that sign-up does not have The flow guide said a TODO in useSignUpController covers a sign-up that is already complete on mount. There is no such TODO. The note now says what happens: nothing runs it. --- packages/mosaic/docs/internals/sign-in-sign-up-flow.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 40bb0b0dec0..62b09eefb6c 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -132,7 +132,7 @@ Sign-up redeems invitation tickets and completes OAuth returns. The other entrie 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 the TODO in `useSignUpController` covers `complete`. 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. The email-link return will be handled first. - 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 f3c022f03013251cabc08b55244d156c9911db1f Mon Sep 17 00:00:00 2001 From: austincalvelage Date: Wed, 2 Dec 2026 00:20:51 -0700 Subject: [PATCH 40/40] refactor(mosaic): complete the sign-up OAuth return from the activity machine's arrival state A return marker makes the arrival intent return, so the activity machine starts in completingReturn and its invoke completes the return once. A transfer after a solved Protect check sends COMPLETE_RETURN to the same state. This replaces the return's pending-action key, the lastKey check and the effect that ran it. A ticket that came back with the return is still redeemed once the return is done. --- .../docs/internals/sign-in-sign-up-flow.md | 2 +- .../features/sign-up/sign-up.controller.ts | 99 ++++++++++++------- 2 files changed, 64 insertions(+), 37 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 62b09eefb6c..0a5a55741df 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -121,7 +121,7 @@ Sign-up redeems invitation tickets and completes OAuth returns. The other entrie - Cleanup, and what waits for sign-in. Finishing or starting over removes the parameters. Choosing between `signUp.ticket()` and `signIn.ticket()` by `__clerk_status`, as `ui/src/components/SignIn/SignInStart.tsx` does, is sign-in's job and waits for its controller. - 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. -- 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, `useSignUpController` shows the loading screen from the first paint and runs `completeReturn` once as its `return` action. The loading screen reads the marker until that action has run, then the action's pending state, so busy has one source. The ticket waits until the return is done. `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, so `redirect_url` and an invitation's ticket come back with the user. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: - A Protect check comes first. Once it is solved, `next` gets the step that follows, so a transfer after it still runs. - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in finishes in place. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. - An `identifier_already_signed_in` account activates that session. 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 d7eda670854..7f46a3df2ad 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -20,11 +20,13 @@ import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRo import type { SignUpProtectScreen, SignUpScreen, SignUpVerifyScreen, SignUpViewProps } from './sign-up.types'; import { useSignUpDetailsController } from './sign-up-details/sign-up-details.controller'; -type SignUpArrivalIntent = 'visit' | 'ticket'; +type SignUpArrivalIntent = 'visit' | 'ticket' | 'return'; interface ActivityContext { arrivalIntent: SignUpArrivalIntent; redeemTicket: () => Promise; + completeReturn: () => Promise; + canRedeemTicket: () => boolean; frozenModel: SignUpReadyModel | null; activate: (() => Promise) | undefined; frozenScreen: 'loading' | undefined; @@ -39,7 +41,7 @@ type FinalizeStart = { onFinalized: () => void; }; -type ActivityEvent = FinalizeStart | { type: 'DISMISS' } | { type: 'SUBMIT' }; +type ActivityEvent = FinalizeStart | { type: 'COMPLETE_RETURN' } | { type: 'DISMISS' } | { type: 'SUBMIT' }; const activity = setup(); @@ -60,12 +62,27 @@ const startFinalizing = finalizeShowing(undefined); const clearError = activity.assign(() => ({ error: undefined })); +const arrivalFailed = { + target: 'arrivalFailed' as const, + actions: activity.assign((_, event) => ({ error: toLocalizableError(event.error) })), +}; + +const startCompletingReturn = { COMPLETE_RETURN: { target: 'completingReturn' as const } }; + +const FIRST_STATE = { + visit: 'idle', + ticket: 'redeemingTicket', + return: 'completingReturn', +} as const satisfies Record; + const activityMachine = activity.createMachine({ id: 'signUpActivity', - initial: context => (context.arrivalIntent === 'ticket' ? 'redeemingTicket' : 'idle'), + initial: context => FIRST_STATE[context.arrivalIntent], context: { arrivalIntent: 'visit', redeemTicket: () => Promise.resolve(), + completeReturn: () => Promise.resolve(), + canRedeemTicket: () => false, frozenModel: null, activate: undefined, frozenScreen: undefined, @@ -74,22 +91,28 @@ const activityMachine = activity.createMachine({ }, states: { idle: { - on: startFinalizing, + on: { ...startFinalizing, ...startCompletingReturn }, }, redeemingTicket: { invoke: activity.fromPromise(context => context.redeemTicket(), { onDone: { target: 'idle' }, - onError: { - target: 'redeemFailed', - actions: activity.assign((_, event) => ({ error: toLocalizableError(event.error) })), - }, + onError: arrivalFailed, }), // An invitation that completes on redemption finalizes before it settles. Arrival work has no screen to freeze, so loading stays up. on: finalizeShowing('loading'), }, - redeemFailed: { + completingReturn: { + invoke: activity.fromPromise(context => context.completeReturn(), { + // A ticket that came back with the return is redeemed once the return is done. + onDone: [{ target: 'redeemingTicket', guard: context => context.canRedeemTicket() }, { target: 'idle' }], + onError: arrivalFailed, + }), + on: startFinalizing, + }, + arrivalFailed: { on: { ...startFinalizing, + ...startCompletingReturn, SUBMIT: { target: 'idle', actions: clearError }, DISMISS: { target: 'idle', actions: clearError }, }, @@ -111,6 +134,7 @@ const activityMachine = activity.createMachine({ failed: { on: { ...startFinalizing, + ...startCompletingReturn, DISMISS: { target: 'idle', actions: clearError }, }, }, @@ -126,7 +150,8 @@ type ActivityState = const FINALIZE_STATUS = { idle: 'idle', redeemingTicket: 'idle', - redeemFailed: 'idle', + completingReturn: 'idle', + arrivalFailed: 'idle', finalizing: 'running', failed: 'failed', finalized: 'succeeded', @@ -149,13 +174,24 @@ function screenFor( return instance.signUpMode === 'public' || attempt.ticket ? 'start' : instance.signUpMode; } -function arrivalIntentFor( +function redeemsTicket( { attempt, details }: SignUpReadyModel, route: SignUpRoute, correctedRoute: SignUpRoute | undefined, -): SignUpArrivalIntent { +): boolean { const opensOnStart = route === 'start' || correctedRoute === 'start'; - return attempt.ticket && !attempt.hasPendingReturn && !details.inTicketSignUp && opensOnStart ? 'ticket' : 'visit'; + return Boolean(attempt.ticket) && !details.inTicketSignUp && opensOnStart; +} + +function arrivalIntentFor( + model: SignUpReadyModel, + route: SignUpRoute, + correctedRoute: SignUpRoute | undefined, +): SignUpArrivalIntent { + if (model.attempt.hasPendingReturn) { + return 'return'; + } + return redeemsTicket(model, route, correctedRoute) ? 'ticket' : 'visit'; } function useBlockedOn(route: SignUpRoute) { @@ -185,7 +221,7 @@ export function useSignUpController( { isTaskLoaded, ...options }: MosaicLocationOptions & { isTaskLoaded: boolean }, ): SignUpControllerResult { const { route, go } = useRouterScope(signUpRoutes, { ...options, root: 'start' }); - const actions = usePendingAction<'startOver' | 'return'>(); + const actions = usePendingAction<'startOver'>(); const errorText = useErrorText(); const facts = { session: liveModel.session, @@ -213,6 +249,13 @@ export function useSignUpController( next(result); }); }, + canRedeemTicket: (): boolean => redeemsTicket(model, route, correctedRoute), + completeReturn: async () => { + const result = await attempt.completeReturn(); + if (result) { + flushSync(() => next(result)); + } + }, }, }); const [blockedDetails, block] = useBlockedOn(route); @@ -235,13 +278,12 @@ export function useSignUpController( const model = isHolding ? (activitySnapshot.context.frozenModel ?? liveModel) : liveModel; const { attempt, navigation, verification } = model; - const isReturning = actions.pendingKey === 'return' || (attempt.hasPendingReturn && actions.lastKey === undefined); + const isArriving = activitySnapshot.value === 'redeemingTicket' || activitySnapshot.value === 'completingReturn'; const correctedRoute = correctRoute(route, override, attempt.step); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; - const screen = - isReturning || activitySnapshot.value === 'redeemingTicket' - ? 'loading' - : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined)); + const screen = isArriving + ? 'loading' + : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined)); useRouteGuard({ route, go }, correctedRoute); @@ -260,7 +302,7 @@ export function useSignUpController( return; } if (result.type === 'transfer') { - completeReturn(); + sendActivity({ type: 'COMPLETE_RETURN' }); return; } const nextRoute = routeFor(result, route); @@ -270,20 +312,12 @@ export function useSignUpController( } }; - const completeReturn = () => - void actions.run('return', async () => { - const result = await attempt.completeReturn(); - if (result) { - next(result); - } - }); - const activityError = activitySnapshot.context.error ? errorText(activitySnapshot.context.error) : undefined; const finalizeError = activitySnapshot.value === 'failed' ? activityError : undefined; const flowError = activityError ?? actions.error; const details = useSignUpDetailsController(model.details, { purpose: screen === 'continue' ? 'continue' : 'start', - isBusy: actions.isPending || isHolding, + isBusy: actions.isPending || isHolding || isArriving, globalErrorMessage: flowError, onSubmit: () => { actions.reset(); @@ -292,13 +326,6 @@ export function useSignUpController( onNext: next, onSignIn: navigation.goToSignIn, }); - /* eslint-disable react-you-might-not-need-an-effect/no-event-handler -- Completes an OAuth return once when sign-up opens with its marker in the URL, on any route, or redeems an invitation once when it opens on start with its ticket; arriving from a redirect or a link is not an event a handler could run from. */ - useEffect(() => { - if (attempt.hasPendingReturn && actions.lastKey === undefined) { - completeReturn(); - } - }); - /* eslint-enable react-you-might-not-need-an-effect/no-event-handler */ const verify = { onNext: next,