Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/mosaic-sign-up-enterprise-sso.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
10 changes: 7 additions & 3 deletions packages/mosaic/docs/internals/sign-in-sign-up-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ Sign-up renders one component per screen, so the route decides what is mounted (
- A screen with work to do on arrival owns its controller. `SignUpVerify` holds the code machine and sends the code when it mounts on a step with `sent: false`. A submit, a reload and a redirect all arrive that way. A screen that runs a controller reaches the view as a slot the wrapper builds, as the profile section's `nameAction` does, so `SignUpView` renders plain props only.
- `SignUpVerify` takes the sign-up's id as its `key`, so a new sign-up never reuses the last one's screen.
- A screen another feature owns arrives as a slot. The wrapper runs the task's model once, passes it to `TaskChooseOrganizationContent` (the task without its card), and tells the controller whether the task has loaded. The view mounts the slot on the task route.
- A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `alternativePhone` replaces `start` while the user has picked a phone channel such as WhatsApp there, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. A route whose screen is not built yet (`enterpriseConnections`) shows `startOver`.
- A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `alternativePhone` replaces `start` while the user has picked a phone channel such as WhatsApp there, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. `enterpriseConnections` shows its own screen, the connection chooser, only while the controller holds a list of connections. Otherwise an entry that lands on it shows `loading` while the redirect to the IdP starts, and `startOver` once that attempt is over ([Entry actions](#entry-actions)).
- The channel `alternativePhone` shows is state in `useSignUpDetailsController`, not a route. The user picks it on the start form before any sign-up exists, the screen edits that same form, and no step `getSignUpNextStep` returns leads to it, so there is nothing for a route to restore. Use another method on that screen and Edit on the code screen both clear it.

## Move on after a submit
Expand Down Expand Up @@ -79,7 +79,7 @@ Sign-up:

- `start` → `start`
- `protect` → `protectCheck`, or `continueProtectCheck` when reached from `continue`, where `SignUpProtect` runs the challenge through shared `runProtectCheck` when it mounts. It takes the challenge token as its `key`, so a chained or reissued challenge remounts it and runs again. The controller keeps the expired-reload count above it, so the cap holds across those remounts. A blocked proof shows `actionBlocked`. A check that completes the sign-up keeps the screen busy while `finalize()` runs. After a failed `finalize()` no challenge is left, so Try again runs `finalize()` again. The host must not load the legacy Clerk UI (`prefetchUI={false}` on the provider), because clerk-js otherwise opens its own Protect modal for the same check and this screen never renders (`__internal_openProtectCheckModal` in `clerk-js/src/core/clerk.ts`, called from `clerk-js/src/core/protectCheckGate.ts`)
- `enterprise_sso` → `enterpriseConnections`, which goes straight to the IdP unless there are several connections to pick from
- `enterprise_sso` → the IdP. A submit on `start` or `continue` stays on its route and starts the redirect from the form. Every other entry goes to `enterpriseConnections`, which starts it on arrival ([Entry actions](#entry-actions)). When the domain has several connections, both paths end on `enterpriseConnections` with the chooser
- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue`
- `verify_phone` (`target`, `sent`) → `verifyPhone`, or `continueVerifyPhone` when reached from `continue`
- `fields` (`fields`) → `continue`
Expand Down Expand Up @@ -111,14 +111,18 @@ With no `:factor`, `factorOne` starts on the factor `ui`'s `determineStartingSig

## Entry actions

Sign-up redeems invitation tickets and completes OAuth returns. The other entries are planned. The controller calls these model callbacks when sign-up opens, then `next(step)`.
Sign-up redeems invitation tickets, starts enterprise SSO redirects and completes OAuth returns. The other entries are planned. The controller calls these model callbacks when sign-up opens, then `next(step)`.

- 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. A ticket works only once, so `useSignUpController` keeps the redeemed ticket in a ref, and a remount or 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`.
- Which sign-up is the invitation's. A sign-up is the invitation's when FAPI verified its email with the `ticket` strategy and the ticket is still in the URL, as `ui`'s `SignUpStart` checks. So a sign-up already on the client doesn't stop the redemption, and a later visit without the ticket starts a new sign-up.
- What `start` does meanwhile. While the invitation's sign-up is in progress, `start` locks the invited email and updates that sign-up instead of creating a new one, so going back never drops the invitation. With a ticket in the URL, `start` shows the form in restricted and waitlist mode, because FAPI lets a ticket through.
- 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. The ticket action hands `next` the loading screen to freeze with the model, 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.
- Enterprise SSO: the model's `startEnterpriseSso` calls `sso({ strategy: 'enterprise_sso' })` on the sign-up the user started, with the OAuth return's callback URL, so the email stays and the OAuth return entry below completes it. `sso()` resolves without an error when FAPI returns no redirect URL, so the model throws in that case. Two paths start it, and each press or arrival sends one request:
- From the `start` and `continue` forms. When the submit returns `enterprise_sso`, `useSignUpDetailsController` starts the redirect inside the form's own submit and keeps it pending for `REDIRECT_HOLD_MS`, as the social buttons do, then resolves without a step so `next` never runs. Both routes are allowed while the step is `enterprise_sso`, so the route stays and the form stays busy, as `ui`'s does. A failed start shows in the form's banner. If the browser is still on the page after the hold, the form is usable again, and Continue starts the redirect again: `start` with a new sign-up, `continue` on the same one. A sign-up that opens on `continue` with the step already `enterprise_sso` shows that form and waits for Continue.
- On arrival. A ticket, a code, a Protect check and a return have no form to hold, so `next` sends them to `enterpriseConnections`. `useSignUpController` shows the loading screen there and runs `startEnterpriseSso` once as its `enterpriseSso` action. The loading screen reads the route until the action has run, then the action's pending state. `startOver` shows when the start failed, with its error, or when the browser is still on the page after the hold.
- Several connections. FAPI answers the first start with `enterprise_connection_id_is_required_with_multiple_connections`. The model then lists the connections and resolves with `enterprise_connections` instead of throwing, as `create` resolves with `blocked`. `SignUpFuture` has no list call, so the model reads `__experimental_getEnterpriseConnections()` from the legacy resource. A list that fails, or comes back empty, rejects: the form shows the reason in its banner, and an arrival shows `startOver`. `next` keeps the list in the controller for this mount and goes to `enterpriseConnections`, which shows the chooser while that list is set and does not start a redirect of its own. Picking a connection calls `startEnterpriseSso(id)` under its own pending action, so the picked button is busy and the others are disabled for `REDIRECT_HOLD_MS`, and a failed start shows on the chooser. Back drops the list and returns to `start` with the form as the user left it. A connection with no logo gets an empty `iconUrl`, as a custom OAuth provider does.
- Email-link return (`__clerk_status`): `verified` with a `__clerk_created_session` this client has activates that session (`clerk-js/src/core/clerk.ts:2620-2636`); any other `verified` continues by step. `transferable` and the error statuses show their own screen, as `ui/src/common/EmailLinkVerify.tsx` does.
- Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now the OAuth return builds its callback URL by hand with a marker, described in the next entry. The marker moves to `useReturnUrl()` when that hook lands.
- 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:
Expand Down
121 changes: 105 additions & 16 deletions packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
PhoneCodeChannel,
SessionJSON,
SignInJSON,
SignUpEnterpriseConnectionJSON,
SignUpField,
SignUpIdentificationField,
SignUpJSON,
Expand All @@ -28,6 +29,9 @@ type Identifier = 'email_address' | 'phone_number';
export interface FakeSignUpSeed {
takenEmailAddresses?: string[];
enterpriseDomains?: string[];
enterpriseConnectionCount?: number;
enterpriseConnectionListing?: 'feature_not_enabled' | 'empty';
enterpriseSsoRejected?: FakeEnterpriseSsoRejection;
sessionTasks?: SessionJSON['tasks'];
blocked?: Record<string, string>;
weakPasswords?: Record<string, string[]>;
Expand All @@ -49,13 +53,22 @@ export type FakeOAuthAccount =
| { signedInSession: string }
| { error: { code: string; message: string; meta?: ClerkAPIErrorJSON['meta'] } };

export interface FakeEnterpriseSsoRejection {
connectionId?: string;
code: string;
message: string;
}

type ProtectCheckOn = 'create' | 'update' | 'oauth_callback';

export type FakeTicket = { emailAddress: string } | 'expired';

export interface FakeSignUpState {
takenEmailAddresses: string[];
enterpriseDomains: string[];
enterpriseConnectionCount: number;
enterpriseConnectionListing?: 'feature_not_enabled' | 'empty';
enterpriseSsoRejected?: FakeEnterpriseSsoRejection;
sessionTasks: SessionJSON['tasks'];
blocked?: Record<string, string>;
weakPasswords: Record<string, string[]>;
Expand Down Expand Up @@ -84,6 +97,7 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState {
return {
takenEmailAddresses: [],
enterpriseDomains: [],
enterpriseConnectionCount: 1,
sessionTasks: null,
weakPasswords: {},
protectChecks: 0,
Expand All @@ -105,6 +119,8 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState {
};
}

const ENTERPRISE_LOGO = "data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg'/%3E";

export const PROTECT_CHECK_SCRIPT = `
export default (container, { token, setWidgetVisible }) =>
new Promise((resolve, reject) => {
Expand Down Expand Up @@ -216,6 +232,9 @@ export function signUpHandlers(
};
};

const inEnterpriseDomain = (signUp: SignUpJSON) =>
state.signUp.enterpriseDomains.includes(signUp.email_address?.split('@')[1] ?? '');

const settle = (signUp: SignUpJSON): SignUpJSON => {
const { attributes } = settings();
const { required_fields, optional_fields } = requirements();
Expand Down Expand Up @@ -250,7 +269,7 @@ export function signUpHandlers(
settings().sign_up.progressive &&
identifierNames.every(name => !attributes[name].required) &&
!identifierNames.some(name => provided(name));
const enterprise = state.signUp.enterpriseDomains.includes(signUp.email_address?.split('@')[1] ?? '');
const enterprise = inEnterpriseDomain(signUp) && linked !== 'enterprise_sso';
const missingFields: SignUpField[] = [
...required_fields.filter(field => !provided(field)),
...(anyIdentifierMissing ? identifierNames : []),
Expand Down Expand Up @@ -331,6 +350,64 @@ export function signUpHandlers(
};
};

const enterpriseConnections = (): SignUpEnterpriseConnectionJSON[] =>
Array.from({ length: state.signUp.enterpriseConnectionCount }, (_, index) => ({
object: 'enterprise_connection',
id: `entc_${index + 1}`,
name: `Acme SSO ${index + 1}`,
provider: 'saml_okta',
logo_public_url: index === 0 ? ENTERPRISE_LOGO : null,
}));

const startEnterpriseSso = (signUp: SignUpJSON, body: URLSearchParams): SignUpJSON | ReturnType<typeof rejected> => {
if (!inEnterpriseDomain(signUp)) {
return rejected('form_param_value_invalid', 'strategy does not match one of the allowed values.', 'strategy');
}
const connectionId = body.get('enterprise_connection_id') ?? undefined;
const rejection = state.signUp.enterpriseSsoRejected;
if (rejection && rejection.connectionId === connectionId) {
return rejected(rejection.code, rejection.message);
}
if (connectionId && !enterpriseConnections().some(connection => connection.id === connectionId)) {
return rejected(
'form_param_value_invalid',
'enterprise_connection_id does not match one of the allowed values.',
'enterprise_connection_id',
);
}
if (state.signUp.enterpriseConnectionCount > 1 && !connectionId) {
return rejected(
'enterprise_connection_id_is_required_with_multiple_connections',
'An enterprise connection ID is required when the domain has several connections.',
'enterprise_connection_id',
);
}
if (!body.get('redirect_url')) {
return rejected('form_conditional_param_missing', 'redirect_url must be included.', 'redirect_url');
}
return {
...signUp,
verifications: {
...signUp.verifications,
external_account: {
...fapiUnpreparedVerification(),
...fapiVerification('enterprise_sso'),
next_action: '',
supported_strategies: ['enterprise_sso'],
external_verification_redirect_url: `https://idp.example/sso?strategy=enterprise_sso${connectionId ? `&connection=${connectionId}` : ''}`,
},
},
};
};

const startExternal = (signUp: SignUpJSON, body: URLSearchParams) => {
const strategy = body.get('strategy');
if (strategy === 'enterprise_sso') {
return startEnterpriseSso(signUp, body);
}
return strategy?.startsWith('oauth_') ? startOAuth(signUp, body) : signUp;
};

state.signUp.returnFromOAuth = () => {
const signUp = state.client.sign_up;
const external = signUp?.verifications?.external_account;
Expand Down Expand Up @@ -374,29 +451,29 @@ export function signUpHandlers(
}
const linked = withExternal({ status: 'verified' });
state.signUp.linkedStrategy = external.strategy;
store(
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
const returned = 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 && external.strategy !== 'enterprise_sso'
? linked.verifications!.email_address
: {
...fapiUnpreparedVerification(),
...fapiVerification(`from_${external.strategy}`, { status: 'verified' }),
next_action: '',
},
},
},
'oauth_callback',
),
},
'oauth_callback',
),
);
state.client = { ...state.client, sign_up: returned };
};

const apply = (signUp: SignUpJSON, body: URLSearchParams) => {
Expand Down Expand Up @@ -660,6 +737,18 @@ export function signUpHandlers(
}
return store(settle(issueProtectCheck({ ...signUp, protect_check: null }, state.signUp.protectCheckOn)));
}),
http.get(fapiUrl('/v1/client/sign_ups/:id/enterprise_connections'), ({ params }) => {
if (!current(params.id)) {
return missing();
}
if (state.signUp.enterpriseConnectionListing === 'feature_not_enabled') {
return rejected('feature_not_enabled', 'This feature is not enabled on this instance.', undefined, 403);
}
return envelope(
state.signUp.enterpriseConnectionListing === 'empty' ? [] : enterpriseConnections(),
state.client,
);
}),
http.get(fapiUrl('/v1/client/sign_ups/:id'), ({ params }) => {
const signUp = current(params.id);
if (!signUp) {
Expand All @@ -678,7 +767,7 @@ export function signUpHandlers(
}
const body = new URLSearchParams(await request.text());
state.signUp.updates.push(body);
const started = body.get('strategy')?.startsWith('oauth_') ? startOAuth(signUp, body) : signUp;
const started = startExternal(signUp, body);
if (started instanceof HttpResponse) {
return started;
}
Expand Down
Loading
Loading