diff --git a/.changeset/mosaic-sign-up-email-link.md b/.changeset/mosaic-sign-up-email-link.md new file mode 100644 index 00000000000..a845151cc84 --- /dev/null +++ b/.changeset/mosaic-sign-up-email-link.md @@ -0,0 +1,2 @@ +--- +--- diff --git a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md index e48d9a0af43..ad38cf19dd9 100644 --- a/packages/mosaic/docs/internals/sign-in-sign-up-flow.md +++ b/packages/mosaic/docs/internals/sign-in-sign-up-flow.md @@ -8,7 +8,7 @@ FAPI tracks which requirements are outstanding and whether a code has been sent. Today FAPI sends `status`, `missing_fields` and `unverified_fields`, not a step. Until it sends `nextStep`, `getSignInNextStep` and `getSignUpNextStep` in `shared` compute it from those fields (see [Bridge](#bridge)). -Sign-up's `continue` screen asks for what FAPI lists in `missing_fields`, not for what the instance's settings would require, so the client never re-derives a rule FAPI already applied (`continueFields` in `mosaic/src/features/sign-up/sign-up.utils.ts`). A missing email, phone or username that FAPI also lists in `optional_fields` is a choice, so the form asks for one of them, with the email/phone switch when both are allowed. An email or phone FAPI lists in `unverified_fields` stays on the form, prefilled, so Edit on a verify screen reached from `continue` has an address to change. FAPI drops the old verification whenever an update sends the address, changed or not, so the verify screen sends a new code. Requirements another step owns, such as `enterprise_sso`, don't appear. A missing `oauth_*` provider shows that provider's button, and only the missing ones, since another provider can't satisfy it; the user links the rest from their profile. When FAPI lists a requirement `continue` can't ask for, such as a provider that can't sign the user in, the step is `unknown` and the user sees Start over instead of a form that can't finish. A sign-up that must verify its email on an instance that enables the email link is `unknown` too, until the link screen is built; `ui` shows its link card there (`ui/src/components/SignUp/SignUpVerifyEmail.tsx`). `start` has no sign-up yet, so it reads the instance's settings. +Sign-up's `continue` screen asks for what FAPI lists in `missing_fields`, not for what the instance's settings would require, so the client never re-derives a rule FAPI already applied (`continueFields` in `mosaic/src/features/sign-up/sign-up.utils.ts`). A missing email, phone or username that FAPI also lists in `optional_fields` is a choice, so the form asks for one of them, with the email/phone switch when both are allowed. An email or phone FAPI lists in `unverified_fields` stays on the form, prefilled, so Edit on a verify screen reached from `continue` has an address to change. FAPI drops the old verification whenever an update sends the address, changed or not, so the verify screen sends a new code. Requirements another step owns, such as `enterprise_sso`, don't appear. A missing `oauth_*` provider shows that provider's button, and only the missing ones, since another provider can't satisfy it; the user links the rest from their profile. When FAPI lists a requirement `continue` can't ask for, such as a provider that can't sign the user in, the step is `unknown` and the user sees Start over instead of a form that can't finish. `start` has no sign-up yet, so it reads the instance's settings. There is no step machine and no local copy of the step. What the step can't say lives in the route, such as the factor the user picked in `factorOne`'s `:factor` param, or whether a sign-up verify screen was reached from `continue`. @@ -22,10 +22,10 @@ const { route } = useRouterScope(signInRoutes, { routing, path, root: 'start' }) const shown = step.type === 'unknown' ? undefined : allowedRoute(route, step) ? route : routeFor(step); ``` -The flow's `*.routes.ts` exports this rule as one function, so the controller and the unit test share it (`correctRoute` in `mosaic/src/features/sign-up/sign-up.routes.ts`). Sign-up's also takes the session override and reads the step only when the override is `none` ([Routes and steps](#routes-and-steps)). No route means "Start over". +The flow's `*.routes.ts` exports this rule as one function, so the controller and the unit test share it (`correctRoute` in `mosaic/src/features/sign-up/sign-up.routes.ts`). Sign-up's also takes the session override and reads the step only when the override is `none` ([Routes and steps](#routes-and-steps)), and takes whether the sign-up has an email link to wait on ([Mount the screen](#mount-the-screen)). No route means "Start over". - `routeFor(step)` returns the step's route, from the lists below. Sign-up's also takes the current route, so a verify step reached from `continue` stays under it. -- `allowedRoute(route, step)` is `true` for `start`, for the step's own route, and for `continue` while sign-up verifies, so the user can edit a field. `complete` and `transfer` have no route, so they allow any route: the current screen stays up while `next` runs, and shows the error if it fails. +- `allowedRoute(route, step)` is `true` for `start`, for the step's own route, and for `continue` while sign-up verifies, so the user can edit a field. Sign-up's is also `true` for the email route while the sign-up has an email link to wait on, so the link screen's wait moves the tab and the step does not ([Mount the screen](#mount-the-screen)). `complete` and `transfer` have no route, so they allow any route: the current screen stays up while `next` runs, and shows the error if it fails. - The component that owns the route table computes the screen during render, and passes the route shown to `useRouteGuard`, which replaces a route the step does not allow so the stored route never keeps it. It is a guard, not a route table that changes with the step: the route exists, the flow is just not ready for it. - This runs once the model is `ready`, and after Clerk loads there is always a step. Until then the scope gets `ready: false`, so a starting route like `factor-one` isn't reset to `start`. @@ -37,6 +37,11 @@ Sign-up renders one component per screen, so the route decides what is mounted ( - Each screen has a folder that takes its group of the model (`sign-up-details/`, `sign-up-verify/`, `sign-up-restricted/`), as [Features → A flow with several screens](../features.md#a-flow-with-several-screens) describes. - A screen with work to do on arrival owns its controller. `SignUpVerify` holds the code machine and sends the code when it mounts on a step with `sent: false`. A submit, a reload and a redirect all arrive that way. It reads `sent` only then. FAPI fails a verification after three wrong codes and expires an old one, and both read as `sent: false` while the screen is open. The screen sends nothing for them until the user presses Resend, as `ui`'s code card does: a code sent on its own would give the user three more tries without their asking. A screen that runs a controller reaches the view as a slot the wrapper builds, as the profile section's `nameAction` does, so `SignUpView` renders plain props only. - `SignUpVerify` takes the sign-up's id as its `key`, so a new sign-up never reuses the last one's screen. +- On an instance whose email address lists `email_link` in its verifications, the wrapper fills the `verifyEmail` slot with `SignUpEmailLink` (`sign-up-email-link/`) instead of the code screen, with the same `key`. The link wins when the code is enabled too, and there is no way back to the code, as in `ui` (`ui/src/components/SignUp/SignUpVerifyEmail.tsx`). The model returns the `verification.emailLink` group only on such an instance, so its presence picks the screen. +- `SignUpEmailLink` holds the link machine. Its states are `idle`, `sending`, `waiting`, `expired`, `failed` and `verified`. It sends a link every time it mounts, then waits, whether or not a link is already out, as `ui`'s `SignUpEmailLinkCard` does, so a reload or a second visit sends a new one. Under StrictMode the second mount finds the machine already `sending` and sends nothing more. FAPI limits how often it sends to one address: a refused send shows FAPI's error on the screen and leaves Resend to unlock after the cooldown, as `ui` shows it on its card. An expired link shows the expiry and waits for Resend. Resend unlocks 60 seconds after a send, stops the current wait, sends, and waits again. A resend inside the link's ten minutes reuses the link and does not extend it. +- The wait is the model's `emailLink.wait()`, which returns the outcome and a `cancel`. It reloads the client's sign-up once a second through `Poller` (`shared/src/poller.ts`), whose timers run in a worker so a background tab keeps asking. `SignUpFuture.verifications.waitForEmailLinkVerification()` is not used: it cannot be cancelled, and it resolves the same way for a verified and an expired link. The machine cancels the wait when it leaves `waiting`, and the screen cancels it when it unmounts, so Edit, a route change and a remount all stop the requests. A host's `` that hides the sign-up runs the same cleanup but keeps the machine in `waiting`, so when it shows the screen again the screen's `SEND` re-enters `waiting`, which starts a new wait without sending a link or restarting the Resend countdown. `cancel` also marks the wait as cancelled, and the next tick checks that mark before it reloads. `Poller.stop()` alone does not stop a poller that is waiting for its second tick: the first worker timer has id `0`, which `stop()` reads as no timer, and the next `run` clears the stopped flag. +- The wait's reload updates the sign-up before the wait resolves, so the step changes while the link screen is still up. The step does not move the route off the link screen. While the sign-up has an email address on an instance that verifies it by link, `allowedRoute` allows the email route for every step (`hasEmailLink` in `mosaic/src/features/sign-up/sign-up.routes.ts`), and only the wait's outcome moves the tab, through `next`. If the step moved it, a link opened in this browser would mount the next screen in the tab that waits, and a phone screen would send its code from there, before the outcome says this tab only points to the other one. `ui` works the same way: its `SignUpEmailLinkCard` decides where its tab goes when the poll ends, and its route only checks that the sign-up has an email address. An `unknown` step still shows Start over, and the session overrides still come first. +- The wait ends in one of three ways. An expired link moves the machine to `expired`. A link opened in another browser returns the sign-up's next step, read from the sign-up the reload returned, and the screen passes it to `next`: a complete sign-up finishes in this tab, since FAPI creates the session on the client that started the sign-up. A link opened in this browser (`verifiedFromTheSameClient()` on the verification, which compares `verified_at_client` with this client) returns `email_link_status` with `signed-in-other-tab`: the tab the link opened is the one that signs in, so this tab only says so, as `ui`'s `SignUpEmailLinkCard` does. - A screen another feature owns arrives as a slot. The wrapper runs the task's model once, passes it to `TaskChooseOrganizationContent` (the task without its card), and tells the controller whether the task has loaded. The view mounts the slot on the task route. - A screen that is not a route sits on top of one. `restricted` and `waitlist` replace `start`, `alternativePhone` replaces `start` while the user has picked a phone channel such as WhatsApp there, `actionBlocked` replaces `start` and the Protect routes, and `startOver` replaces any route. `enterpriseConnections` shows its own screen, the connection chooser, only while the controller holds a list of connections. Otherwise an entry that lands on it shows `loading` while the redirect to the IdP starts, and `startOver` once that attempt is over ([Entry actions](#entry-actions)). - The channel `alternativePhone` shows is state in `useSignUpDetailsController`, not a route. The user picks it on the start form before any sign-up exists, the screen edits that same form, and no step `getSignUpNextStep` returns leads to it, so there is nothing for a route to restore. Use another method on that screen and Edit on the code screen both clear it. @@ -58,9 +63,11 @@ submitPassword: async (password: string) => { - `complete`: the model's `finalize()`, then leave the flow for the after sign-up URL, which honors `redirect_url` and the redirect query params (`clerk.buildAfterSignUpUrl({ params })`). Creating the session clears the sign-up. Sign-up renders the model it left from while `finalize()` runs, and after it until a task that continues in the flow has its data loaded, so the task replaces the screen with no skeleton between them. It keeps the action pending throughout, the way the switcher holds its `frozenModel` ([Controllers → Wrapping actions](../controllers.md#wrapping-actions)). Once the hold ends with the session signed in, the flow is over: if the host keeps the component mounted, it renders nothing. In a modal, don't `close()` when the flow leaves: `finalize()`'s navigation is the last write and takes the modal with it. - `transfer`: sign-up transfers only an OAuth account that already has a user. The OAuth return transfers it before a step reaches `next` ([Entry actions](#entry-actions)), unless a Protect check comes first. Then the Protect screen passes `transfer` to `next`, which runs the return's completion again and shows the loading screen while it does. Sign-in's transfer is planned: the model's `transfer()` will call `signUp.create({ transfer: true, unsafeMetadata })`, then `next` with the sign-up's step; a sign-in with sign-up built in holds the sign-up routes under `create/`, otherwise it leaves for the sign-up page. - `unknown`: nothing. The screen already shows "Start over". +- `email_link_status`: the link screen's wait and the email-link return resolve with it, not a step, when all that is left is to tell the user what happened to the link. The controller sends it to the activity machine's `showingLinkStatus` state, which keeps it for this mount, and `emailLinkStatus` replaces whatever screen the route would show. It stays up whatever the session is, so a signed-in visitor sees it too, as on `ui`'s `verify` route, which has no signed-in guard. +- `session` (`sessionId`): the email-link return resolves with it when the link created a session this client holds. The controller finishes as for `complete`, with the loading screen frozen, but `finalize(sessionId)` activates that session with `clerk.setActive`: the page the link opened loads after FAPI has cleared the sign-up, so there is no sign-up left to finalize. `FINALIZE` marks this activation with `showsFailedLink`, so if it fails the machine moves to `showingLinkStatus` and the page shows `emailLinkStatus` with `failed` and no error text, as `ui`'s `EmailLinkVerify` shows its failed card for any error. It is not the current screen the next rule names: that screen is `start`, and in single-session mode the session the link created is already Clerk's, so `start` would render nothing. - `blocked`: sign-up's `create`, the Protect proof's `resolve` and the invitation's `redeemTicket` resolve with it, not a step, when FAPI answers `action_blocked`. The OAuth return's `completeReturn` resolves with it when FAPI stored that error on the external account, and `sso` resolves with it from `start`. From `continue`, `sso` rejects and the error shows inline, as `update`'s does. The controller keeps the details for this mount and shows the notice in place of `start` or the Protect route. The notice is not read from Clerk's sign-up error, which outlives the component, so a remount shows the form again, as `ui`'s card error does. - Anything else: `go(routeFor(step))`. -- An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. +- An error from `finalize()` or the transfer stays on the current screen until the user leaves it, so Edit clears it. The email-link return's activation is the exception (`session` above). After an invitation that completed on redemption, that screen is `start` ([Entry actions](#entry-actions)). A sign-up that is already complete skips the request and returns `complete`, so entering the code again, or pressing Continue again on `start` or `continue`, runs `finalize()` again. Sending the request again would fail: the user now exists, so FAPI answers `form_identifier_exists`. ## Routes and steps @@ -80,13 +87,13 @@ Sign-up: - `start` → `start` - `protect` → `protectCheck`, or `continueProtectCheck` when reached from `continue`, where `SignUpProtect` runs the challenge through shared `runProtectCheck` when it mounts. It takes the challenge token as its `key`, so a chained or reissued challenge remounts it and runs again. The controller keeps the expired-reload count above it, so the cap holds across those remounts. A blocked proof shows `actionBlocked`. A check that completes the sign-up keeps the screen busy while `finalize()` runs. After a failed `finalize()` no challenge is left, so Try again runs `finalize()` again. The host must not load the legacy Clerk UI (`prefetchUI={false}` on the provider), because clerk-js otherwise opens its own Protect modal for the same check and this screen never renders (`__internal_openProtectCheckModal` in `clerk-js/src/core/clerk.ts`, called from `clerk-js/src/core/protectCheckGate.ts`) - `enterprise_sso` → the IdP. A submit on `start` or `continue` stays on its route and starts the redirect from the form. Every other entry goes to `enterpriseConnections`, which starts it on arrival ([Entry actions](#entry-actions)). When the domain has several connections, both paths end on `enterpriseConnections` with the chooser -- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue` +- `verify_email` (`target`, `sent`) → `verifyEmail`, or `continueVerifyEmail` when reached from `continue`. The route shows the code screen, or the link screen on an instance that enables the email link ([Mount the screen](#mount-the-screen)) - `verify_phone` (`target`, `sent`) → `verifyPhone`, or `continueVerifyPhone` when reached from `continue` - `fields` (`fields`) → `continue` The step is the sign-up resource's and says nothing about the session. The model returns the session beside it as `session`: `none`, `activating` while `setActive` runs and Clerk reports no session, `task` (`key`) for a pending task sign-up shows in its own card, or `active`. A task the application gave a URL in `taskUrls`, or one sign-up has no screen for, is `active`, not `task`: the flow leaves for its URL. -The controller passes the session to `sessionOverride` (`features/auth-flow/auth-flow.utils.ts`, shared with sign-in) with the three facts only it holds: the session when the component mounted, where its `finalize()` is (`idle`, `running`, `failed` or `succeeded`), and whether the route is one only a signed-out visitor sees. The override is decided before the step is read, so an unfinished sign-up left on the client cannot override it: +The controller passes the session to `sessionOverride` (`features/auth-flow/auth-flow.utils.ts`, shared with sign-in) with the facts only it holds: the session when the component mounted, whether the visitor arrived to see the result of something started elsewhere (`arrivedForResult`) and whether that result shows (`isShowingResult`), where its `finalize()` is (`idle`, `running`, `failed` or `succeeded`), and whether the route is one only a signed-out visitor sees. The override is decided before the step is read, so an unfinished sign-up left on the client cannot override it: - `none`: the step picks the route, as listed above. This is also the override for a visitor who arrived signed in, in multi-session mode, so `start` shows and the user can add an account. - `task` → `taskChooseOrganization`: only the task route is shown, so a visit to `start` with the task pending moves to it, and the task shows its skeleton until its data loads. @@ -106,12 +113,12 @@ With no `:factor`, `factorOne` starts on the factor `ui`'s `determineStartingSig - FAPI's state changes only on submit. A route the step doesn't allow is replaced with the step's route. - Back to `start` shows the identifier form; submitting it creates a new sign-in. Forward to `factorOne` still works. -- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up verify route sends a code only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. +- Reload on `factorOne` keeps the picked factor (`:factor`) and sends no second code (`sent`). Reload on a sign-up code screen sends a code only when `sent` is false, and starts the resend countdown either way, as `ui`'s code card does. Reload on the link screen always sends a new link, as `ui`'s link card does. Once the email is verified FAPI refuses that request (`verification_already_verified`), and the step does not move the route off the link screen ([Mount the screen](#mount-the-screen)), so a reload there shows FAPI's error on the link screen, as `ui`'s link card does. Edit leads back to the form. - Virtual routing has no history: a remount starts at `start`, and FAPI's state is kept. ## Entry actions -Sign-up redeems invitation tickets, starts enterprise SSO redirects and completes OAuth returns. The other entries are planned. The controller records why the visitor arrived when sign-up opens (`arrival.intent`), and that intent picks the activity machine's first state. Each entry is that state's `invoke`, which calls the model callback and then `next(step)`, so it runs once. +Sign-up redeems invitation tickets, starts enterprise SSO redirects, and completes OAuth and email-link returns. The other entries are planned. The controller records why the visitor arrived when sign-up opens (`arrival.intent`), and that intent picks the activity machine's first state. Each entry is that state's `invoke`, which calls the model callback and then `next(step)`, so it runs once. - Ticket: - Read once and held. The `SignUp` wrapper reads the ticket from `__clerk_ticket` or `__clerk_invitation_token` once, when it mounts, and holds it in state, as `ui`'s `SignUpStart` holds it in its form state (`ui/src/components/SignUp/SignUpStart.tsx:121-124`). The model takes the ticket as an option and does not read the URL. The state lives in the wrapper because a model holds no React state ([Models](../models.md)). Forgetting the ticket clears that state and removes the parameters (`forgetTicket` in `mosaic/src/features/sign-up/sign-up.model.ts`). @@ -127,21 +134,28 @@ Sign-up redeems invitation tickets, starts enterprise SSO redirects and complete - From the `start` and `continue` forms. When the submit returns `enterprise_sso`, `useSignUpDetailsController` starts the redirect inside the form's own submit and keeps it pending for `REDIRECT_HOLD_MS`, as the social buttons do, then resolves without a step so `next` never runs. Both routes are allowed while the step is `enterprise_sso`, so the route stays and the form stays busy, as `ui`'s does. A failed start shows in the form's banner. If the browser is still on the page after the hold, the form is usable again, and Continue starts the redirect again: `start` with a new sign-up, `continue` on the same one. A sign-up that opens on `continue` with the step already `enterprise_sso` shows that form and waits for Continue. - On arrival. A ticket, a code, a Protect check and a return have no form to hold, so `next` sends them to `enterpriseConnections`. `next` also sends `START_ENTERPRISE_SSO`, and a visit that opens on that route starts there, so the activity machine's `startingEnterpriseSso` state shows the loading screen and runs `startEnterpriseSso` once per arrival. A later arrival in the same mount starts it again, as `ui` does after each Protect check (`ui/src/components/SignUp/SignUpProtectCheck.tsx`). `startOver` shows when the start failed, with its error, or when the browser is still on the page after the hold. Start over dismisses that error, so the new `start` form opens without it. - Several connections. FAPI answers the first start with `enterprise_connection_id_is_required_with_multiple_connections`. The model then lists the connections and resolves with `enterprise_connections` instead of throwing, as `create` resolves with `blocked`. `SignUpFuture` has no list call, so the model reads `__experimental_getEnterpriseConnections()` from the legacy resource. A list that fails, or comes back empty, rejects: the form shows the reason in its banner, and an arrival shows `startOver`. `next` keeps the list in the controller for this mount and goes to `enterpriseConnections`, which shows the chooser while that list is set and does not start a redirect of its own. Picking a connection calls `startEnterpriseSso(id)` under its own pending action, so the picked button is busy and the others are disabled for `REDIRECT_HOLD_MS`, and a failed start shows on the chooser. Back drops the list and replaces the chooser's history entry with `start`, so the browser's Back never lands on a chooser that has no list to show. Leaving the chooser another way, such as the browser's Back, keeps the list, so Forward shows the chooser again, as `ui`'s chooser does by listing on mount. The next arrival starts enterprise SSO again and replaces the list. A connection with no logo gets an empty `iconUrl`, as a custom OAuth provider does. -- Email-link return (`__clerk_status`): `verified` with a `__clerk_created_session` this client has activates that session (`clerk-js/src/core/clerk.ts:2620-2636`); any other `verified` continues by step. `transferable` and the error statuses show their own screen, as `ui/src/common/EmailLinkVerify.tsx` does. -- Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now the OAuth return builds its callback URL by hand with a marker, described in the next entry. The marker moves to `useReturnUrl()` when that hook lands. -- OAuth return: sign-up's callback URL is the current URL plus the marker `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. It keeps the rest of the query, so `redirect_url` and an invitation's ticket come back with the user. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: +- Email-link return: the link's redirect URL is the current URL plus the marker `__clerk_mosaic_sign_up=verify`, built the way the OAuth callback URL is (next entry), so there is no `verify` route. FAPI redirects the opened link there and adds `__clerk_status`, and `__clerk_created_session` when verifying completed the sign-up. When sign-up opens with the marker, on any route, the arrival intent is `return`, and the activity machine's `completingReturn` state runs `completeReturn` once, exactly as for an OAuth return. The model's `attempt.pendingReturn` says which of the two it is. `completeReturn` removes the marker and both Clerk parameters, then answers by status, following `clerk.handleEmailLinkVerification` (`clerk-js/src/core/clerk.ts`) and `ui/src/common/EmailLinkVerify.tsx`: + - `verified` with a `__clerk_created_session` this client holds: `session`, so the flow activates it and leaves for the after sign-up URL or its task ([Move on after a submit](#move-on-after-a-submit)). + - `verified` with a session this client does not hold: `email_link_status` with `signed-in`. The link was opened in another browser, and the tab that started the sign-up finishes it. + - `verified` with no session: the sign-up still needs something, so the return answers with the sign-up's step and `next` carries on in this tab. `ui` moves on only for a Protect check, enterprise SSO or a phone to verify, and otherwise leaves its switch-tab card up, which strands a sign-up that is missing a field. When this client holds no sign-up, the step would be `start`, an empty form in a browser that never started one, so the return answers `email_link_status` with `signed-in-other-tab` instead. + - `expired`, `client_mismatch` and `transferable`: `email_link_status` with the matching status. `failed`, a missing status and any other value show `failed`. + + A page opened from the link does not count as arriving signed in. In single-session mode the session the link created is already Clerk's session when the page loads, and the arrival rule would leave for the after sign-up URL before the link's result showed, or leave a second time after the session is activated. Such a page arrives with the intent `emailLink`, which passes `arrivedForResult`, so the session it arrived with neither leaves nor ends the flow and the link's result decides. While the link's status shows (`showingLinkStatus`), `isShowingResult` keeps a session signed in elsewhere from hiding it. + +- Redirect URLs for email links and OAuth/SAML returns will come from the router's `useReturnUrl(name, params)` (#10860). For now both returns build their URL by hand with a marker. The marker moves to `useReturnUrl()` when that hook lands. +- OAuth return: sign-up's callback URL is the current URL plus the marker `__clerk_mosaic_sign_up=sso-callback`, the way `withUserProfileModalReturn` marks a profile return. It keeps the rest of the query except Clerk's own `__clerk_*` parameters, so `redirect_url` comes back with the user, and a parameter Clerk put on this page, such as an invitation's ticket or its `__clerk_status`, does not, as in `ui`, whose callback URLs carry only the redirect parameters. FAPI adds `__clerk_status` to an email link's URL rather than replacing it, so a stale one left on the page would be the value the return reads. `sso()` sends the after sign-up URL that honors `redirect_url` as the URL to land on after the provider. When sign-up opens with the marker, on any route, the arrival intent is `return`, so the activity machine starts in `completingReturn`: the loading screen shows from the first paint and the state's `invoke` runs `completeReturn` once. A visitor the session override sends away on arrival (`leave`) is the exception: sign-up is already leaving for the task URL or the after sign-up URL, so the return is not completed and nothing navigates twice. A transfer after a solved Protect check sends `COMPLETE_RETURN` to the same state. The ticket waits until the return is done, and the machine moves to `redeemingTicket` if sign-up is then on `start` with a ticket that isn't its own. `completeReturn` removes the marker and follows `clerk.handleRedirectCallback`'s sign-up branches on the Future API: - A Protect check comes first. Once it is solved, `next` gets the step that follows, so a transfer after it still runs. - A `transferable` account becomes a sign-in (`signIn.create({ transfer: true })`). A complete sign-in resolves with `signed_in`. Otherwise the user goes to the sign-in route its status needs, as `_handleRedirectCallback` does: `factor-one`, `factor-two`, `reset-password`, or `protect-check` when the sign-in has a Protect check. The route goes in the hash of the sign-in URL, which keeps `redirect_url`. - An `identifier_already_signed_in` account resolves with `signed_in` and that session's ID. - `next` sends `signed_in` to `FINALIZE` with `finalizeSignIn` as the activation and the loading screen frozen, so a failed activation shows its error like any other finalize error. `finalizeSignIn` lands on the after sign-in URL, and keeps a pending organization task in the card the way a finished sign-up does, as legacy's callback opens the task under sign-up (`baseUrl: signUpUrl`). - - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. An `action_blocked` error that carries its details resolves with `blocked` instead and shows `actionBlocked`, as legacy's `ActionBlockedCard` does. Removing the ticket keeps the invitation from being redeemed again over the error, as in legacy, where the callback URL has no ticket. + - An external-account error removes the ticket, resets the sign-up and shows on `start`, with FAPI's message only for the codes legacy's `SignUpStart` shows and the generic error otherwise. An `action_blocked` error that carries its details resolves with `blocked` instead and shows `actionBlocked`, as legacy's `ActionBlockedCard` does. The callback URL carries no ticket, so the invitation is not redeemed again over the error, as in legacy. - A sign-up FAPI finished at the provider comes back with no sign-up on the client and its session pending a task. FAPI sends a session with no task straight to the after sign-up URL, so only a pending one reaches the callback (`determineRedirectURL` in `clerk_go/api/fapi/v1/oauth/oauth.go`). A task sign-up shows in its card needs nothing here: the session override moves to it. Any other task resolves with `signed_in` and that session's ID, so `finalizeSignIn` keeps the loading screen up and leaves for the task URL, as the last sign-up branch of `_handleRedirectCallback` does with `redirectToTasks`. The step has to be `start` for this, so a sign-up that still needs something is not skipped because another session on the client has a task. - Anything else is `next(step)`. The marker is gone once the return starts, so a reload mid-return lands on `start`. OAuth is a full-page redirect only. Sign-up never passes `sso()` a `popup`, so popup OAuth (`oauthFlow: 'popup'`) is not built. An OAuth transport (`__internal_oauthTransport`) is not supported yet. `SignUpFuture.sso()` still navigates the window, so clerk-js has to honor the transport first. Sign-in-to-sign-up transfers start from sign-in, so they wait for its controller. - `signUp.sso()` updates any sign-up already on the client, so `start` resets a sign-up that isn't the invitation's and calls `sso()` on the client's new sign-up, since the old `SignUpFuture` still points at the reset one; `continue` keeps it. On an instance with no form identifier, where `showFormFields` is false, `start` shows only the providers, without fields or the consent checkbox, as legacy does; consent then comes on `continue`. `continue` hides the providers once the sign-up has a verified external account. -- A step that is already `complete` or `transfer` on mount, such as a reload before it ran, is not handled yet: `routeFor` has no route for `transfer`, and nothing runs `complete` when sign-up mounts. The email-link return will be handled first. +- A step that is already `complete` or `transfer` on mount, such as a reload before it ran, is not handled yet: `routeFor` has no route for `transfer`, and nothing runs `complete` when sign-up mounts. - Hash params: Clerk's URL builders (`redirectToSignUp()`, `buildSignUpUrl`) put the redirect params and initial values in the URL hash, and sign-up reads only the query, so they are not read yet. ## Bridge diff --git a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts index 7953c5313aa..9b6b51776e3 100644 --- a/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts +++ b/packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts @@ -46,6 +46,7 @@ export interface FakeSignUpSeed { whatsAppQuotaExceeded?: boolean; tickets?: Record; oauth?: Record; + emailLinkRedirectUrl?: string; } export type FakeOAuthAccount = @@ -84,6 +85,9 @@ export interface FakeSignUpState { transfers: URLSearchParams[]; linkedStrategy?: string; returnFromOAuth: () => void; + emailLinkRedirectUrl?: string; + openEmailLink: (clientId?: string) => string; + expireEmailLink: () => void; issuedProtectChecks: number; reloads: number; proofTokens: string[]; @@ -108,6 +112,12 @@ export function createSignUpState(seed: FakeSignUpSeed = {}): FakeSignUpState { returnFromOAuth: () => { throw new Error('The fake FAPI has not started'); }, + openEmailLink: () => { + throw new Error('The fake FAPI has not started'); + }, + expireEmailLink: () => { + throw new Error('The fake FAPI has not started'); + }, issuedProtectChecks: 0, reloads: 0, proofTokens: [], @@ -144,7 +154,12 @@ export default (container, { token, setWidgetVisible }) => let scriptIds = 0; -const STRATEGIES: Record = { email_code: 'email_address', phone_code: 'phone_number' }; +const STRATEGIES: Record = { + email_code: 'email_address', + email_link: 'email_address', + phone_code: 'phone_number', +}; +const EMAIL_LINK_LIFETIME_MS = 600_000; const TEXT_FIELDS = ['email_address', 'phone_number', 'username', 'first_name', 'last_name'] as const; const createdAt = Date.UTC(2026, 0, 1); const MAX_CODE_ATTEMPTS = 3; @@ -196,7 +211,12 @@ export function signUpHandlers( return HttpResponse.json({ ...body, meta: { client: state.client } }, { status: response.status }); }; + const completed = new Map(); + const store = (signUp: SignUpJSON) => { + if (signUp.status === 'complete') { + completed.set(signUp.id, signUp); + } state.client = { ...state.client, sign_up: signUp.status === 'complete' ? null : signUp }; return envelope(signUp, state.client); }; @@ -571,6 +591,11 @@ export function signUpHandlers( if (signUp.verifications?.[field].status === 'verified') { return rejected('verification_already_verified', 'This verification has already been verified.', undefined, 400); } + const isLink = strategy === 'email_link'; + const redirectUrl = body.get('redirect_url'); + if (isLink && !redirectUrl) { + return rejected('form_conditional_param_missing', 'redirect_url must be included.', 'redirect_url'); + } const isPhone = field === 'phone_number'; if (isPhone && channel && channel !== 'sms' && channel !== 'whatsapp') { return rejected('form_param_value_invalid', `${channel} does not match one of the allowed values.`, 'channel'); @@ -584,13 +609,26 @@ export function signUpHandlers( } const sentOver = channel === 'whatsapp' && state.signUp.whatsAppQuotaExceeded ? 'sms' : (channel ?? 'sms'); state.signUp.preparations.push(isPhone && channel ? `${strategy}:${channel}` : strategy); + const pending = signUp.verifications![field]; + const linkStillOut = pending.strategy === 'email_link' && pending.status === 'unverified'; + if (isLink && redirectUrl) { + state.signUp.emailLinkRedirectUrl = redirectUrl; + } return { ...signUp, verifications: { ...signUp.verifications!, [field]: { - ...signUp.verifications![field], - ...fapiVerification(strategy), + ...pending, + ...fapiVerification( + strategy, + isLink + ? { + object: 'verification_email_link', + expire_at: linkStillOut ? pending.expire_at : Date.now() + EMAIL_LINK_LIFETIME_MS, + } + : {}, + ), next_action: 'needs_attempt', supported_strategies: [strategy], channel: isPhone ? (sentOver as PhoneCodeChannel) : undefined, @@ -599,6 +637,51 @@ export function signUpHandlers( }; }; + const emailLink = () => { + const signUp = state.client.sign_up; + const pending = signUp?.verifications?.email_address; + const redirectUrl = state.signUp.emailLinkRedirectUrl; + if (!signUp?.verifications || pending?.strategy !== 'email_link' || !redirectUrl) { + throw new Error('No email link has been sent'); + } + return { signUp, verifications: signUp.verifications, pending, landing: new URL(redirectUrl) }; + }; + + state.signUp.openEmailLink = (clientId = state.client.id) => { + const { signUp, verifications, pending, landing } = emailLink(); + if (pending.status === 'expired') { + landing.searchParams.append('__clerk_status', 'expired'); + return landing.toString(); + } + if (pending.status !== 'unverified') { + throw new Error('The email link has already been opened'); + } + const verified = settle({ + ...signUp, + verifications: { + ...verifications, + email_address: { ...pending, status: 'verified', next_action: '', verified_at_client: clientId }, + }, + }); + store(verified); + landing.searchParams.append('__clerk_status', 'verified'); + if (verified.created_session_id) { + landing.searchParams.append('__clerk_created_session', verified.created_session_id); + } + return landing.toString(); + }; + + state.signUp.expireEmailLink = () => { + const { signUp, verifications, pending } = emailLink(); + store({ + ...signUp, + verifications: { + ...verifications, + email_address: { ...pending, status: 'expired', next_action: 'needs_prepare' }, + }, + }); + }; + if (state.client.sign_up) { const seeded = state.client.sign_up; const enteredEmail = seeded.email_address; @@ -777,12 +860,12 @@ export function signUpHandlers( ); }), http.get(fapiUrl('/v1/client/sign_ups/:id'), ({ params }) => { - const signUp = current(params.id); + const signUp = current(params.id) ?? completed.get(String(params.id)); if (!signUp) { return missing(); } state.signUp.reloads += 1; - return store(signUp); + return envelope(signUp, state.client); }), http.post(fapiUrl('/v1/client/sign_ups/:id'), async ({ params, request }) => { if (new URL(request.url).searchParams.get('_method') !== 'PATCH') { @@ -820,7 +903,7 @@ export function signUpHandlers( const body = new URLSearchParams(await request.text()); const strategy = body.get('strategy') ?? ''; const code = body.get('code') ?? ''; - const field = STRATEGIES[strategy]; + const field = strategy === 'email_link' ? undefined : STRATEGIES[strategy]; if (!field) { return rejected( 'form_param_value_invalid', diff --git a/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts b/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts index 2b90895b552..17825eba770 100644 --- a/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts +++ b/packages/mosaic/src/features/auth-flow/__tests__/auth-flow.utils.test.ts @@ -8,6 +8,8 @@ const noOverride: AuthSessionOverride = { type: 'none' }; const facts: AuthSessionOverrideFacts = { session: { type: 'none' }, sessionOnArrival: 'none', + arrivedForResult: false, + isShowingResult: false, finalizeStatus: 'idle', isSingleSession: false, isTaskLoaded: true, @@ -52,6 +54,21 @@ describe('session override', () => { { session: { type: 'active' }, sessionOnArrival: 'active', isSingleSession: true }, { type: 'leave' }, ], + [ + 'does not leave when the visitor arrived signed in for a result, in single-session mode', + { session: { type: 'active' }, sessionOnArrival: 'active', arrivedForResult: true, isSingleSession: true }, + { type: 'done' }, + ], + [ + 'is not done for a task the visitor arrived with for a result', + { session: { type: 'active' }, sessionOnArrival: 'task', arrivedForResult: true, isSignedOutOnly: false }, + noOverride, + ], + [ + 'lets the result show over a signed-in session, in single-session mode', + { session: { type: 'active' }, sessionOnArrival: 'active', isShowingResult: true, isSingleSession: true }, + noOverride, + ], [ 'follows the resource to add an account, in multi-session mode', { session: { type: 'active' }, sessionOnArrival: 'active' }, diff --git a/packages/mosaic/src/features/auth-flow/auth-flow.types.ts b/packages/mosaic/src/features/auth-flow/auth-flow.types.ts index 7f939ce0cd1..72ca3e40ed5 100644 --- a/packages/mosaic/src/features/auth-flow/auth-flow.types.ts +++ b/packages/mosaic/src/features/auth-flow/auth-flow.types.ts @@ -36,6 +36,10 @@ export type AuthSessionOverride = export interface AuthSessionOverrideFacts { session: AuthSessionPhase; sessionOnArrival: AuthSessionPhase['type']; + /** The visitor arrived to see the result of something they started elsewhere, such as an email link, not as a visitor who is signed in. */ + arrivedForResult: boolean; + /** The flow is showing that result, which the session does not override. */ + isShowingResult: boolean; finalizeStatus: AuthFinalizeStatus; isSingleSession: boolean; isTaskLoaded: boolean; diff --git a/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts b/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts index ec123bd1469..783abe3389b 100644 --- a/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts +++ b/packages/mosaic/src/features/auth-flow/auth-flow.utils.ts @@ -12,11 +12,16 @@ export function formatPhoneIdentifier(identifier: string): string { export function sessionOverride({ session, sessionOnArrival, + arrivedForResult, + isShowingResult, finalizeStatus, isSingleSession, isTaskLoaded, isSignedOutOnly, }: AuthSessionOverrideFacts): AuthSessionOverride { + if (isShowingResult) { + return { type: 'none' }; + } if (finalizeStatus === 'running') { return { type: 'hold' }; } @@ -28,15 +33,32 @@ export function sessionOverride({ case 'task': return finalizeStatus === 'succeeded' && !isTaskLoaded ? { type: 'hold' } : session; case 'active': - if (finalizeStatus === 'succeeded' || sessionOnArrival === 'task') { - return { type: 'done' }; - } - if (!isSingleSession) { - return { type: 'none' }; - } - if (sessionOnArrival === 'active') { - return { type: 'leave' }; - } - return isSignedOutOnly ? { type: 'done' } : { type: 'none' }; + return activeSessionOverride({ + sessionOnArrival: arrivedForResult ? 'none' : sessionOnArrival, + finalizeStatus, + isSingleSession, + isSignedOutOnly, + }); + } +} + +function activeSessionOverride({ + sessionOnArrival, + finalizeStatus, + isSingleSession, + isSignedOutOnly, +}: Pick< + AuthSessionOverrideFacts, + 'sessionOnArrival' | 'finalizeStatus' | 'isSingleSession' | 'isSignedOutOnly' +>): AuthSessionOverride { + if (finalizeStatus === 'succeeded' || sessionOnArrival === 'task') { + return { type: 'done' }; + } + if (!isSingleSession) { + return { type: 'none' }; + } + if (sessionOnArrival === 'active') { + return { type: 'leave' }; } + return isSignedOutOnly ? { type: 'done' } : { type: 'none' }; } diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx new file mode 100644 index 00000000000..143e535e35b --- /dev/null +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.email-link.feature.test.tsx @@ -0,0 +1,592 @@ +import type { SignUpVerificationJSON } from '@clerk/shared/types'; +import { act, screen, waitFor } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'; + +import { holdRequests, serveFapi, worker } from '../../../__tests__/feature/fake-fapi'; +import { fapiClient, fapiSession, fapiSignUp, fapiUser, fapiVerification } from '../../../__tests__/feature/fapi'; +import { renderWithClerk } from '../../../__tests__/feature/render'; +import { SignUp } from '../sign-up'; +import { + codeSent, + continueButton, + EMAIL, + emailField, + environment, + PASSWORD, + passwordField, + renderSignUp, + renderSignUpWithRouteProbe, + signedInSession, + submitStart, + visitWithQuery, + watchForHeading, +} from './sign-up.fixtures'; + +const CHECK = '/v1/client/sign_ups/:id'; +const CHECK_PATH = /^\/v1\/client\/sign_ups\/([^/]+)$/; +const SEND = '/v1/client/sign_ups/:id/prepare_verification'; +const LINK_URL = `${window.location.origin}/?__clerk_mosaic_sign_up=verify`; +const EXPIRED = 'The verification link expired. Please request a new link.'; +const RESEND_COOLDOWN_MS = 60_000; +const ACTIVATION = '/v1/client/sessions/:id/touch'; +const ACTIVATION_ERROR = 'The session could not be activated.'; + +const byLink = (verifications = ['email_link']) => + environment({ attributes: { email_address: { required: true, verifications } } }); + +function signUpWithLink(emailAddress: Partial, hasPassword = true) { + const signUp = fapiSignUp({ email_address: EMAIL, has_password: hasPassword }); + return { + ...signUp, + verifications: { + ...signUp.verifications!, + email_address: { + ...fapiVerification('email_link'), + next_action: 'needs_attempt', + supported_strategies: ['email_link'], + ...emailAddress, + }, + }, + }; +} + +const linkOut = (hasPassword = true) => ({ + environment: byLink(), + client: { ...fapiClient(), sign_up: signUpWithLink({}, hasPassword) }, + signUp: { emailLinkRedirectUrl: LINK_URL }, +}); + +const linkOutWithPhone = () => ({ + ...linkOut(), + environment: environment({ + attributes: { + email_address: { required: true, verifications: ['email_link'] }, + phone_number: { enabled: true, required: true, verifications: ['phone_code'], verify_at_sign_up: true }, + }, + }), + client: { ...fapiClient(), sign_up: { ...signUpWithLink({}), phone_number: '+15555550123' } }, +}); + +const linkSent = () => screen.findByRole('button', { name: /^Resend \(\d+\)$/ }); + +const settle = () => new Promise(resolve => setTimeout(resolve, 100)); + +const checkedSignUp = (request: Request) => CHECK_PATH.exec(new URL(request.url).pathname)?.[1]; + +function holdChecks() { + const hold = holdRequests('get', CHECK); + return { ...hold, signUps: () => hold.requests.map(checkedSignUp), abandon: () => hold.fail() }; +} + +const checksInFlight = new Set(); + +function trackCheck({ request, requestId }: { request: Request; requestId: string }) { + if (request.method === 'GET' && checkedSignUp(request)) { + checksInFlight.add(requestId); + } +} + +function untrackCheck({ requestId }: { requestId: string }) { + checksInFlight.delete(requestId); +} + +interface DueCheck { + timers: EventTarget; + id: number; +} + +const dueChecks: DueCheck[] = []; + +function forgetDueChecks(isForgotten: (check: DueCheck) => boolean) { + dueChecks.splice(0, dueChecks.length, ...dueChecks.filter(check => !isForgotten(check))); +} + +class ControlledTimers extends EventTarget { + postMessage({ type, id }: { type: string; id: number }) { + if (type === 'setTimeout') { + dueChecks.push({ timers: this, id }); + } + if (type === 'clearTimeout') { + forgetDueChecks(check => check.timers === this && check.id === id); + } + } + + terminate() { + forgetDueChecks(check => check.timers === this); + } +} + +function runDueChecks() { + for (const { timers, id } of dueChecks.splice(0)) { + timers.dispatchEvent(new MessageEvent('message', { data: { id } })); + } +} + +const returnParams = () => { + const { searchParams } = new URL(window.location.href); + return ['__clerk_mosaic_sign_up', '__clerk_status', '__clerk_created_session'].filter(name => searchParams.has(name)); +}; + +describe('SignUp', () => { + beforeAll(() => { + worker.events.on('request:start', trackCheck); + worker.events.on('request:end', untrackCheck); + }); + + afterAll(() => { + worker.events.removeListener('request:start', trackCheck); + worker.events.removeListener('request:end', untrackCheck); + }); + + beforeEach(() => { + dueChecks.length = 0; + vi.stubGlobal('Worker', ControlledTimers); + }); + + afterEach(async () => { + await waitFor(() => expect(checksInFlight.size, 'checks in flight when the test ended').toBe(0)).finally(() => + checksInFlight.clear(), + ); + expect(dueChecks, 'checks still due when the test ended').toHaveLength(0); + }); + + describe('verifying the email by link', () => { + it('sends one link that comes back to this page and shows where it went, on an instance that verifies email by link', async () => { + const { fapi, user } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); + + await submitStart(user); + + expect(await screen.findByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByText('Use the verification link sent to your email address')).toBeInTheDocument(); + expect(screen.getByText(EMAIL)).toBeInTheDocument(); + expect(screen.queryByRole('textbox', { name: 'Verification code' })).toBeNull(); + expect(await linkSent()).toBeDisabled(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + const redirectUrl = new URL(fapi.signUp.emailLinkRedirectUrl ?? ''); + expect(redirectUrl.origin + redirectUrl.pathname).toBe(window.location.origin + window.location.pathname); + expect(redirectUrl.searchParams.get('__clerk_mosaic_sign_up')).toBe('verify'); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.abandon(); + }); + + it('sends a link, not a code, on an instance that verifies email by code or link', async () => { + const { fapi, user } = await renderSignUp({ environment: byLink(['email_code', 'email_link']) }); + const checks = holdChecks(); + + await submitStart(user); + + expect(await linkSent()).toBeDisabled(); + expect(screen.queryByRole('textbox', { name: 'Verification code' })).toBeNull(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.abandon(); + }); + + it('keeps Edit disabled until the link is sent, and shows why when it could not be sent', async () => { + const { user } = await renderSignUp({ environment: byLink() }); + const hold = holdRequests('post', SEND); + + await submitStart(user); + await waitFor(() => expect(hold.requests).toHaveLength(1)); + + expect(await screen.findByRole('button', { name: 'Edit email address' })).toBeDisabled(); + + hold.fail('form_param_invalid', 'The email link could not be sent.'); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent('The email link could not be sent.')); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + }); + + it('sends a new link when it opens with a link already out, and finishes once the link is opened', async () => { + const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut()); + const checks = holdChecks(); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + + expect(await linkSent()).toBeDisabled(); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + expect(fapi.signUp.preparations).toEqual(['email_link']); + + fapi.signUp.openEmailLink('client_other'); + checks.release(); + + await waitFor(() => expect(navigate).toHaveBeenCalled()); + expect(fapi.client.sessions).toHaveLength(1); + expect(fapi.signUp.preparations).toEqual(['email_link']); + }); + + it('shows why when FAPI refuses to send another link, and offers Resend once the cooldown ends', async () => { + const { user } = await renderSignUpWithRouteProbe(linkOut()); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const send = holdRequests('post', SEND); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(send.requests).toHaveLength(1)); + send.fail('too_many_requests', 'Too many requests. Please try again later.'); + + await waitFor(() => + expect(screen.getByRole('alert')).toHaveTextContent('Too many requests. Please try again later.'), + ); + expect(await linkSent()).toBeDisabled(); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + expect(screen.getByRole('button', { name: 'Resend' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + } finally { + vi.useRealTimers(); + } + }); + + it('keeps asking until the link is opened in another browser, then signs in and leaves for the after sign-up URL', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp( + { environment: byLink() }, + {}, + { signUpFallbackRedirectUrl: '/welcome' }, + ); + const checks = holdChecks(); + + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.release(); + await waitFor(() => expect(dueChecks).toHaveLength(1)); + expect(navigate).not.toHaveBeenCalled(); + + fapi.signUp.openEmailLink('client_other'); + runDueChecks(); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/welcome'))); + expect(checks.requests).toHaveLength(2); + expect(fapi.client.sessions).toHaveLength(1); + expect(clerk.session?.id).toBe(fapi.client.sessions[0].id); + }); + + it('asks for what is still missing when the link is opened in another browser before the sign-up is complete', async () => { + const { fapi, user, navigate } = await renderSignUpWithRouteProbe(linkOut(false)); + const checks = holdChecks(); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink('client_other'); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('moves on to the phone and sends one code when the link is opened in another browser with the phone still to verify', async () => { + const { fapi, user } = await renderSignUpWithRouteProbe(linkOutWithPhone()); + const checks = holdChecks(); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink('client_other'); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Verify your phone' })).toBeInTheDocument(); + expect(await codeSent()).toBeDisabled(); + await settle(); + expect(fapi.signUp.preparations).toEqual(['email_link', 'phone_code:sms']); + }); + + it('tells the user to go to the other tab when the link is opened in this browser, and signs nobody in here', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); + + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink(); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + expect(screen.queryByRole('button', { name: /^Resend/ })).toBeNull(); + expect(fapi.client.sessions).toHaveLength(1); + expect(clerk.session).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }); + + it('sends no phone code from the tab that waits when the link is opened in this browser with the phone still to verify', async () => { + const { fapi, user } = await renderSignUpWithRouteProbe(linkOutWithPhone()); + const checks = holdChecks(); + const sawPhoneScreen = watchForHeading('Verify your phone'); + + await user.click(screen.getByRole('button', { name: 'Open the verify route' })); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.openEmailLink(); + checks.release(); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + await settle(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + expect(sawPhoneScreen()).toBe(false); + }); + + it('says the link expired without sending another, then sends a new one on Resend', async () => { + const { fapi } = await renderSignUp({ environment: byLink() }); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const checks = holdChecks(); + + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + fapi.signUp.expireEmailLink(); + checks.release(); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(EXPIRED)); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(fapi.signUp.preparations).toEqual(['email_link']); + + const checksAfterResend = holdChecks(); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + await user.click(screen.getByRole('button', { name: 'Resend' })); + + expect(await linkSent()).toBeDisabled(); + expect(screen.getByRole('alert')).not.toHaveTextContent(EXPIRED); + expect(fapi.signUp.preparations).toEqual(['email_link', 'email_link']); + await waitFor(() => expect(checksAfterResend.requests).toHaveLength(1)); + checksAfterResend.abandon(); + } finally { + vi.useRealTimers(); + } + }); + + it('shows why and keeps Edit and Resend usable when the session cannot be activated after the link is opened', async () => { + const { fapi, navigate } = await renderSignUp({ environment: byLink() }); + vi.useFakeTimers({ shouldAdvanceTime: true }); + try { + const user = userEvent.setup({ advanceTimers: vi.advanceTimersByTime }); + const checks = holdChecks(); + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + const activation = holdRequests('post', ACTIVATION); + fapi.signUp.openEmailLink('client_other'); + checks.release(); + await waitFor(() => expect(activation.requests).toHaveLength(1)); + + activation.fail('form_param_invalid', ACTIVATION_ERROR); + + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(ACTIVATION_ERROR)); + await act(() => vi.advanceTimersByTimeAsync(RESEND_COOLDOWN_MS)); + expect(screen.getByRole('heading', { name: 'Verify your email' })).toBeInTheDocument(); + expect(screen.getByRole('button', { name: 'Edit email address' })).toBeEnabled(); + expect(screen.getByRole('button', { name: 'Resend' })).toBeEnabled(); + expect(navigate).not.toHaveBeenCalled(); + + const resend = holdRequests('post', SEND); + await user.click(screen.getByRole('button', { name: 'Resend' })); + await waitFor(() => expect(resend.requests).toHaveLength(1)); + resend.release(); + expect(await linkSent()).toBeDisabled(); + } finally { + vi.useRealTimers(); + } + }); + + it('returns to the form with the address kept and the password cleared on Edit, and no longer follows the link', async () => { + const { fapi, user, navigate, clerk } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); + + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + await user.click(screen.getByRole('button', { name: 'Edit email address' })); + + expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(emailField()).toHaveValue(EMAIL); + expect(passwordField()).toHaveValue(''); + + fapi.signUp.openEmailLink('client_other'); + checks.release(); + await waitFor(() => expect(clerk.client?.sessions).toHaveLength(1)); + + expect(screen.getByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(checks.requests).toHaveLength(1); + }); + }); + + describe('leaving the link screen', () => { + it('asks only about the new sign-up after the user edits and continues, although a check on the old one was due', async () => { + const { user } = await renderSignUp({ environment: byLink() }); + const checks = holdChecks(); + + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + checks.release(); + await waitFor(() => expect(dueChecks).toHaveLength(1)); + + const checksAfterLeaving = holdChecks(); + await user.click(screen.getByRole('button', { name: 'Edit email address' })); + await screen.findByRole('heading', { name: 'Create your account' }); + runDueChecks(); + await user.type(passwordField(), PASSWORD); + await user.click(continueButton()); + + await waitFor(() => expect(checksAfterLeaving.signUps()).toContain('sua_2')); + expect(checksAfterLeaving.signUps()).toEqual(['sua_2']); + expect(checks.signUps()).toEqual(['sua_1']); + checksAfterLeaving.abandon(); + }); + }); + + describe('opening the email link', () => { + const newSession = fapiSession({ id: 'sess_new', user: fapiUser({ id: 'user_new' }) }); + + function openLink(status: string | undefined, createdSession?: string) { + const query = new URLSearchParams({ __clerk_mosaic_sign_up: 'verify', redirect_url: '/after' }); + if (status) { + query.set('__clerk_status', status); + } + if (createdSession) { + query.set('__clerk_created_session', createdSession); + } + visitWithQuery(`?${query.toString()}`); + } + + it('signs in from a link sent after a rejected invitation, although the invitation page carried its own status', async () => { + visitWithQuery('?__clerk_ticket=tkt_unknown&__clerk_status=sign_up'); + const { fapi, user, unmount } = await renderSignUp({ environment: byLink() }); + await waitFor(() => expect(screen.getByRole('alert')).toHaveTextContent(/no longer valid/)); + const checks = holdChecks(); + await submitStart(user); + await waitFor(() => expect(checks.requests).toHaveLength(1)); + unmount(); + checks.abandon(); + + const landing = new URL(fapi.signUp.openEmailLink()); + window.history.replaceState(null, '', `${landing.pathname}${landing.search}`); + const sawInvalid = watchForHeading('This verification link is invalid'); + const { navigate, clerk } = await renderWithClerk(, { signUpFallbackRedirectUrl: '/welcome' }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/welcome'))); + expect(clerk.session?.id).toBe(fapi.client.sessions[0].id); + expect(sawInvalid()).toBe(false); + expect(returnParams()).toEqual([]); + }); + + it('activates the session the link created in this browser, leaves once, and forgets the link', async () => { + openLink('verified', newSession.id); + const { navigate, clerk, rerender } = await renderSignUp({ + environment: byLink(), + client: fapiClient([signedInSession, newSession]), + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/after'))); + rerender(); + + expect(clerk.session?.id).toBe(newSession.id); + expect(navigate).toHaveBeenCalledTimes(1); + expect(returnParams()).toEqual([]); + expect(new URL(window.location.href).searchParams.get('redirect_url')).toBe('/after'); + }); + + it('leaves once for a visitor the link signed in, in single-session mode', async () => { + openLink('verified', newSession.id); + const sawForm = watchForHeading('Create your account'); + const { navigate, clerk, rerender } = await renderSignUp({ + environment: environment({ auth_config: { single_session_mode: true } }), + client: fapiClient([newSession]), + }); + + await waitFor(() => expect(navigate).toHaveBeenCalledWith(expect.stringContaining('/after'))); + rerender(); + + expect(clerk.session?.id).toBe(newSession.id); + expect(navigate).toHaveBeenCalledTimes(1); + expect(sawForm()).toBe(false); + }); + + it.each([ + ['single-session', true], + ['multi-session', false], + ])( + 'shows the link as failed when the session it created cannot be activated, in %s mode', + async (_, singleSession) => { + openLink('verified', newSession.id); + serveFapi({ + environment: environment({ auth_config: { single_session_mode: singleSession } }), + client: fapiClient([newSession]), + }); + const activation = holdRequests('post', ACTIVATION); + const { navigate } = await renderWithClerk(); + await waitFor(() => expect(activation.requests).toHaveLength(1)); + + activation.fail('form_param_invalid', ACTIVATION_ERROR); + + expect(await screen.findByRole('heading', { name: 'This verification link is invalid' })).toBeInTheDocument(); + expect(screen.getByText('Return to the original tab to continue.')).toBeInTheDocument(); + expect(screen.queryByText(ACTIVATION_ERROR)).toBeNull(); + expect(navigate).not.toHaveBeenCalled(); + }, + ); + + it('says the sign-up is done and points back to the original tab when the session belongs to another browser', async () => { + openLink('verified', 'sess_elsewhere'); + const { navigate } = await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: 'Successfully signed up' })).toBeInTheDocument(); + expect(screen.getByText('Return to original tab to continue')).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(returnParams()).toEqual([]); + }); + + it('asks for what is still missing when the link verified the email but created no session', async () => { + openLink('verified'); + const { navigate } = await renderSignUp({ + environment: byLink(), + client: { + ...fapiClient(), + sign_up: signUpWithLink({ status: 'verified', next_action: '', verified_at_client: 'client_1' }, false), + }, + }); + + expect(await screen.findByRole('heading', { name: 'Fill in missing fields' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + expect(returnParams()).toEqual([]); + }); + + it('points back to the other tab when the link verified the email and this browser holds no sign-up', async () => { + openLink('verified'); + await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: 'Successfully verified email' })).toBeInTheDocument(); + expect(screen.getByText('Return to previous tab to continue')).toBeInTheDocument(); + }); + + it.each([ + ['expired', 'This verification link has expired'], + ['client_mismatch', 'Verification link is invalid for this device'], + ['transferable', 'Email verified'], + ['failed', 'This verification link is invalid'], + ['bogus', 'This verification link is invalid'], + [undefined, 'This verification link is invalid'], + ])('shows what happened to a link that comes back %s', async (status, title) => { + openLink(status); + const { fapi, rerender } = await renderSignUp({ environment: byLink() }); + + expect(await screen.findByRole('heading', { name: title })).toBeInTheDocument(); + expect(screen.getByText('You may close this tab')).toBeInTheDocument(); + expect(returnParams()).toEqual([]); + + rerender(); + + expect(screen.getByRole('heading', { name: title })).toBeInTheDocument(); + expect(fapi.signUp.creations).toHaveLength(0); + }); + + it('shows what happened to the link to a visitor who is signed in, without leaving', async () => { + openLink('expired'); + const { navigate } = await renderSignUp({ + environment: environment({ auth_config: { single_session_mode: true } }), + client: fapiClient([signedInSession]), + }); + + expect(await screen.findByRole('heading', { name: 'This verification link has expired' })).toBeInTheDocument(); + expect(navigate).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx b/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx index 93437749a82..b97dc446a3e 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.feature.test.tsx @@ -441,8 +441,6 @@ describe('SignUp', () => { expect(emailField()).toHaveValue(EMAIL); expect(passwordField()).toHaveValue(''); }); - - it.todo('sends an email link instead of a code whenever the instance enables the email link'); }); describe('filling in missing fields', () => { @@ -648,38 +646,6 @@ describe('SignUp', () => { expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); expect(screen.queryByRole('heading', { name: 'Fill in missing fields' })).toBeNull(); }); - - it('offers Start over on an instance that verifies email by link', async () => { - const { fapi, user } = await renderSignUp({ - environment: environment({ attributes: { email_address: { required: true, verifications: ['email_link'] } } }), - }); - - await submitStart(user); - - expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); - expect(screen.getByRole('alert')).toHaveTextContent( - 'We couldn’t continue signing you up. Start over to try again.', - ); - expect(fapi.signUp.preparations).toEqual([]); - - await user.click(screen.getByRole('button', { name: 'Start over' })); - - expect(await screen.findByRole('heading', { name: 'Create your account' })).toBeInTheDocument(); - expect(emailField()).toHaveValue(''); - }); - - it('offers Start over on an instance that verifies email by code or link', async () => { - const { fapi, user } = await renderSignUp({ - environment: environment({ - attributes: { email_address: { required: true, verifications: ['email_code', 'email_link'] } }, - }), - }); - - await submitStart(user); - - expect(await screen.findByRole('button', { name: 'Start over' })).toBeInTheDocument(); - expect(fapi.signUp.preparations).toEqual([]); - }); }); describe('finishing', () => { diff --git a/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts b/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts index d26a0c8aa33..7f180936203 100644 --- a/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts +++ b/packages/mosaic/src/features/sign-up/__tests__/sign-up.routes.test.ts @@ -10,6 +10,8 @@ const verifyPhone: SignUpNextStep = { type: 'verify_phone', target: '+1555555014 const fields: SignUpNextStep = { type: 'fields', fields: ['username'] }; const task = { type: 'task', key: 'choose-organization' } as const; const noOverride = { type: 'none' } as const; +const byCode = { hasEmailLink: false }; +const byLink = { hasEmailLink: true }; describe('sign-up corrected route', () => { it.each<[string, SignUpRoute, SignUpNextStep, SignUpRoute | undefined]>([ @@ -53,7 +55,20 @@ describe('sign-up corrected route', () => { ['has no route for an unknown step', 'verifyEmail', { type: 'unknown' }, undefined], ['moves a task route back to start once signed out', 'taskChooseOrganization', { type: 'start' }, 'start'], ])('%s', (_, route, step, expected) => { - expect(correctRoute(route, noOverride, step)).toBe(expected); + expect(correctRoute(route, noOverride, step, byCode)).toBe(expected); + }); + + it.each<[string, SignUpRoute, SignUpNextStep, SignUpRoute | undefined]>([ + ['keeps the link screen once the phone is next', 'verifyEmail', verifyPhone, 'verifyEmail'], + ['keeps the link screen once fields are next', 'verifyEmail', fields, 'verifyEmail'], + ['keeps the link screen once a protect check is next', 'verifyEmail', { type: 'protect' }, 'verifyEmail'], + ['keeps the link screen once enterprise SSO is next', 'verifyEmail', { type: 'enterprise_sso' }, 'verifyEmail'], + ['keeps the link screen under continue', 'continueVerifyEmail', verifyPhone, 'continueVerifyEmail'], + ['has no route for an unknown step', 'verifyEmail', { type: 'unknown' }, undefined], + ['moves the phone screen to the link screen', 'verifyPhone', verifyEmail, 'verifyEmail'], + ['moves the form ahead of the attempt to the step route', 'continue', { type: 'protect' }, 'continueProtectCheck'], + ])('%s, when the email verifies by link', (_, route, step, expected) => { + expect(correctRoute(route, noOverride, step, byLink)).toBe(expected); }); it.each<[string, SignUpRoute, AuthSessionOverride, SignUpRoute]>([ @@ -67,7 +82,11 @@ describe('sign-up corrected route', () => { ], ['keeps the route once the flow is done', 'verifyEmail', { type: 'done' }, 'verifyEmail'], ])('%s', (_, route, override, expected) => { - expect(correctRoute(route, override, verifyEmail)).toBe(expected); + expect(correctRoute(route, override, verifyEmail, byCode)).toBe(expected); + }); + + it('sends a session task from the link screen to its route', () => { + expect(correctRoute('verifyEmail', task, verifyPhone, byLink)).toBe('taskChooseOrganization'); }); }); diff --git a/packages/mosaic/src/features/sign-up/index.ts b/packages/mosaic/src/features/sign-up/index.ts index 400c31c9e5a..e709e9b2e0f 100644 --- a/packages/mosaic/src/features/sign-up/index.ts +++ b/packages/mosaic/src/features/sign-up/index.ts @@ -1,11 +1,13 @@ export { SignUp } from './sign-up'; export type { SignUpProps } from './sign-up'; +export { SignUpEmailLink } from './sign-up-email-link/sign-up-email-link'; export { SignUpProtect } from './sign-up-protect/sign-up-protect'; export { SignUpVerify } from './sign-up-verify/sign-up-verify'; export { SignUpView } from './sign-up.view'; export type { SignUpDetails, SignUpDetailsScreen, + SignUpEmailLinkScreen, SignUpFieldName, SignUpFields, SignUpLegalConsent, diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts new file mode 100644 index 00000000000..dcb84cda105 --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/__tests__/sign-up-email-link.controller.test.ts @@ -0,0 +1,75 @@ +import { act, renderHook } from '@testing-library/react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; + +import { tick } from '../../../../__tests__/async'; +import { createActor } from '../../../../machine/create-actor'; +import { linkMachine, useSignUpEmailLinkController } from '../sign-up-email-link.controller'; + +describe('linkMachine', () => { + // A host's React 19.2 hides the screen by running its effect cleanups, which stop the + // actor and cancel the wait, and shows it by starting the actor and sending SEND again. + it('waits again without sending a second link or resetting the cooldown when shown after being hidden', async () => { + const sendLink = vi.fn(() => Promise.resolve()); + const waitForLink = vi.fn(() => new Promise(() => {})); + const stopWaiting = vi.fn(); + const actor = createActor(linkMachine, { context: { sendLink, waitForLink, stopWaiting } }).start(); + actor.send({ type: 'SEND' }); + await tick(); + expect(actor.getSnapshot().value).toBe('waiting'); + const { resendAvailableAt } = actor.getSnapshot().context; + + actor.stop(); + actor.start(); + actor.send({ type: 'SEND' }); + + expect(actor.getSnapshot().value).toBe('waiting'); + expect(waitForLink).toHaveBeenCalledTimes(2); + expect(sendLink).toHaveBeenCalledTimes(1); + expect(actor.getSnapshot().context.resendAvailableAt).toBe(resendAvailableAt); + }); + + // Needs React 19.2's Activity around the whole sign-up, which the React 18 test projects cannot + // render. The machine test above covers the transition the shown screen relies on. + it.todo('keeps waiting for the link after a host Activity hides and shows the screen'); +}); + +describe('useSignUpEmailLinkController', () => { + afterEach(() => vi.useRealTimers()); + + it('locks resend for sixty seconds, then stops the current wait, sends a second link and waits again', async () => { + vi.useFakeTimers(); + const send = vi.fn(() => Promise.resolve()); + const cancel = vi.fn(); + const wait = vi.fn(() => ({ outcome: new Promise(() => {}), cancel })); + const { result } = renderHook(() => + useSignUpEmailLinkController({ + link: { target: 'alice@example.com', send, wait }, + onNext: () => {}, + isPending: false, + }), + ); + await act(async () => vi.advanceTimersByTimeAsync(0)); + expect(send).toHaveBeenCalledTimes(1); + expect(wait).toHaveBeenCalledTimes(1); + expect(result.current.canResend).toBe(false); + + await act(async () => vi.advanceTimersByTimeAsync(59_000)); + expect(result.current.canResend).toBe(false); + act(() => result.current.onResend()); + expect(send).toHaveBeenCalledTimes(1); + + await act(async () => vi.advanceTimersByTimeAsync(1000)); + expect(result.current.canResend).toBe(true); + expect(cancel).not.toHaveBeenCalled(); + + await act(async () => { + result.current.onResend(); + await vi.advanceTimersByTimeAsync(0); + }); + + expect(cancel).toHaveBeenCalledTimes(1); + expect(send).toHaveBeenCalledTimes(2); + expect(wait).toHaveBeenCalledTimes(2); + expect(result.current.canResend).toBe(false); + }); +}); diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts new file mode 100644 index 00000000000..2f503eae981 --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.controller.ts @@ -0,0 +1,131 @@ +import { useEffect, useRef } from 'react'; + +import { useResendSeconds } from '../../../hooks/use-resend-seconds'; +import type { ErrorDescription } from '../../../localization'; +import { useErrorText } from '../../../localization'; +import { setup } from '../../../machine/setup'; +import type { DoneInvokeEvent, ErrorInvokeEvent } from '../../../machine/types'; +import { useMachine } from '../../../machine/use-machine'; +import { toLocalizableError } from '../../../utils/errors'; +import { isResendUnlocked, resendUnlockTime } from '../../../utils/verification'; +import type { SignUpCreateResult, SignUpEmailLinkOutcome } from '../sign-up.model'; +import type { SignUpEmailLinkScreen } from '../sign-up.types'; + +const LINK_RESEND_SECONDS = 60; + +interface LinkContext { + sendLink: () => Promise; + waitForLink: () => Promise; + stopWaiting: () => void; + onVerified: (result: SignUpCreateResult) => void; + resendAvailableAt: number | undefined; + error: ErrorDescription | undefined; +} + +type LinkEvent = { type: 'SEND' } | { type: 'RESEND' }; + +const link = setup(); + +const startCooldown = link.assign(() => ({ resendAvailableAt: resendUnlockTime(LINK_RESEND_SECONDS) })); + +const fail = link.assign((_, event) => ({ error: toLocalizableError(event.error) })); + +const resend = { + target: 'sending' as const, + guard: (context: LinkContext) => isResendUnlocked(context.resendAvailableAt), + actions: link.assign(() => ({ error: undefined })), +}; + +export const linkMachine = link.createMachine({ + id: 'signUpEmailLink', + initial: 'idle', + context: { + sendLink: () => Promise.resolve(), + waitForLink: () => Promise.resolve({ type: 'expired' }), + stopWaiting: () => {}, + onVerified: () => {}, + resendAvailableAt: undefined, + error: undefined, + }, + states: { + idle: { + on: { SEND: 'sending' }, + }, + sending: { + invoke: link.fromPromise(context => context.sendLink(), { + onDone: { target: 'waiting', actions: startCooldown }, + onError: { target: 'failed', actions: [fail, startCooldown] }, + }), + }, + waiting: { + // A host's cancels the wait when it hides the screen and sends SEND again when it + // shows it. Re-entering `waiting` starts a new wait without sending another link. + on: { SEND: 'waiting', RESEND: resend }, + exit: context => context.stopWaiting(), + invoke: link.fromPromise(context => context.waitForLink(), { + onDone: [ + { target: 'expired', guard: (_, event) => event.output.type === 'expired' }, + { + target: 'verified', + actions: (context: LinkContext, event: DoneInvokeEvent) => { + if (event.output.type === 'verified') { + context.onVerified(event.output.result); + } + }, + }, + ], + onError: { target: 'failed', actions: fail }, + }), + }, + expired: { + on: { RESEND: resend }, + }, + failed: { + on: { RESEND: resend }, + }, + verified: { + on: { RESEND: resend }, + }, + }, +}); + +type SignUpEmailLinkOptions = Pick; + +export function useSignUpEmailLinkController({ + link: { send: sendLink, wait }, + onNext, + isPending: isFlowPending, + globalErrorMessage, +}: SignUpEmailLinkOptions) { + const errorText = useErrorText(); + const cancelWait = useRef<() => void>(undefined); + const [snapshot, send] = useMachine(linkMachine, { + context: { + sendLink, + waitForLink: () => { + const waiting = wait(); + cancelWait.current = waiting.cancel; + return waiting.outcome; + }, + stopWaiting: () => cancelWait.current?.(), + onVerified: onNext, + }, + }); + const resendSeconds = useResendSeconds(snapshot.context.resendAvailableAt, LINK_RESEND_SECONDS); + useEffect(() => { + send({ type: 'SEND' }); + }, [send]); + + useEffect(() => () => cancelWait.current?.(), []); + + const isPending = isFlowPending || snapshot.value === 'sending'; + + return { + isPending, + isExpired: snapshot.value === 'expired', + globalErrorMessage: snapshot.context.error ? errorText(snapshot.context.error) : globalErrorMessage, + onResend: () => send({ type: 'RESEND' }), + canResend: snapshot.value !== 'idle' && resendSeconds === 0 && !isPending, + resendRemainingSeconds: resendSeconds || undefined, + }; +} diff --git a/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx new file mode 100644 index 00000000000..e4fb3e0106f --- /dev/null +++ b/packages/mosaic/src/features/sign-up/sign-up-email-link/sign-up-email-link.tsx @@ -0,0 +1,31 @@ +import { AuthEmailLink } from '../../../blocks/auth'; +import { verificationResend } from '../../../blocks/verification'; +import { useMessages } from '../../../localization'; +import type { SignUpEmailLinkScreen } from '../sign-up.types'; +import { useSignUpEmailLinkController } from './sign-up-email-link.controller'; + +export function SignUpEmailLink({ onEditIdentifier, ...options }: SignUpEmailLinkScreen) { + const m = useMessages('signUp'); + const { isPending, isExpired, globalErrorMessage, onResend, canResend, resendRemainingSeconds } = + useSignUpEmailLinkController(options); + + return ( + + ); +} diff --git a/packages/mosaic/src/features/sign-up/sign-up.controller.ts b/packages/mosaic/src/features/sign-up/sign-up.controller.ts index b417cb7932d..6552464f81c 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.controller.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.controller.ts @@ -16,12 +16,19 @@ import { REDIRECT_HOLD_MS } from '../../utils/redirect'; import type { AuthFinalizeStatus, AuthSessionOverride } from '../auth-flow/auth-flow.types'; import { sessionOverride } from '../auth-flow/auth-flow.utils'; import type { SignUpCreateResult, SignUpReadyModel } from './sign-up.model'; -import type { SignUpRoute, SignUpTaskKey } from './sign-up.routes'; +import type { SignUpRoute, SignUpRouteFacts, SignUpTaskKey } from './sign-up.routes'; import { correctRoute, detailsRouteFor, isSignedOutOnlyRoute, routeFor, signUpRoutes } from './sign-up.routes'; -import type { SignUpProtectScreen, SignUpScreen, SignUpVerifyScreen, SignUpViewProps } from './sign-up.types'; +import type { + SignUpEmailLinkScreen, + SignUpEmailLinkStatusScreen, + SignUpProtectScreen, + SignUpScreen, + SignUpVerifyScreen, + SignUpViewProps, +} from './sign-up.types'; import { useSignUpDetailsController } from './sign-up-details/sign-up-details.controller'; -type SignUpArrivalIntent = 'visit' | 'ticket' | 'return' | 'enterpriseSso'; +type SignUpArrivalIntent = 'visit' | 'ticket' | 'return' | 'emailLink' | 'enterpriseSso'; interface ActivityContext { arrivalIntent: SignUpArrivalIntent; @@ -33,6 +40,8 @@ interface ActivityContext { frozenModel: SignUpReadyModel | null; activate: (() => Promise) | undefined; frozenScreen: 'loading' | undefined; + showsFailedLink: boolean; + linkStatus: SignUpEmailLinkStatusScreen | undefined; error: ErrorDescription | undefined; onFinalized: (() => void) | undefined; } @@ -42,14 +51,18 @@ type FinalizeStart = { frozenModel: SignUpReadyModel; activate: () => Promise; frozenScreen?: 'loading'; + showsFailedLink?: boolean; onFinalized: () => void; }; type ChooseConnection = { type: 'CHOOSE_CONNECTION'; connections: readonly AuthProvider[] }; +type ShowLinkStatus = { type: 'SHOW_LINK_STATUS'; linkStatus: SignUpEmailLinkStatusScreen }; + type ActivityEvent = | FinalizeStart | ChooseConnection + | ShowLinkStatus | { type: 'COMPLETE_RETURN' } | { type: 'START_ENTERPRISE_SSO' } | { type: 'CANCEL_CONNECTIONS' } @@ -65,6 +78,7 @@ const finalizeShowing = (frozenScreen: 'loading' | undefined) => ({ frozenModel: event.frozenModel, activate: event.activate, frozenScreen: event.frozenScreen ?? frozenScreen, + showsFailedLink: event.showsFailedLink ?? false, onFinalized: event.onFinalized, error: undefined, })), @@ -91,12 +105,27 @@ const chooseConnection = { }, }; -const whileIdle = { ...startFinalizing, ...startCompletingReturn, ...startEnterpriseSso, ...chooseConnection }; +// The status a page opened from an email link shows stays for the rest of the mount. +const showLinkStatus = { + SHOW_LINK_STATUS: { + target: 'showingLinkStatus' as const, + actions: activity.assign((_, event) => ({ linkStatus: event.linkStatus })), + }, +}; + +const whileIdle = { + ...startFinalizing, + ...startCompletingReturn, + ...startEnterpriseSso, + ...chooseConnection, + ...showLinkStatus, +}; const FIRST_STATE = { visit: 'idle', ticket: 'redeemingTicket', return: 'completingReturn', + emailLink: 'completingReturn', enterpriseSso: 'startingEnterpriseSso', } as const satisfies Record; @@ -113,6 +142,8 @@ const activityMachine = activity.createMachine({ frozenModel: null, activate: undefined, frozenScreen: undefined, + showsFailedLink: false, + linkStatus: undefined, error: undefined, onFinalized: undefined, }, @@ -134,7 +165,7 @@ const activityMachine = activity.createMachine({ onDone: [{ target: 'redeemingTicket', guard: context => context.canRedeemTicket() }, { target: 'idle' }], onError: arrivalFailed, }), - on: { ...startFinalizing, ...startEnterpriseSso, ...chooseConnection }, + on: { ...startFinalizing, ...startEnterpriseSso, ...chooseConnection, ...showLinkStatus }, }, startingEnterpriseSso: { invoke: activity.fromPromise(context => context.startEnterpriseSso(), { @@ -159,17 +190,33 @@ const activityMachine = activity.createMachine({ finalizing: { invoke: activity.fromPromise(context => context.activate?.() ?? Promise.resolve(), { onDone: { target: 'finalized', actions: context => context.onFinalized?.() }, - onError: { - target: 'failed', - actions: activity.assign((_, event) => ({ - frozenModel: null, - activate: undefined, - frozenScreen: undefined, - error: toLocalizableError(event.error), - })), - }, + onError: [ + { + // A session an email link created that can't be activated shows the failed link, as ui does. + target: 'showingLinkStatus', + guard: context => context.showsFailedLink, + actions: activity.assign(() => ({ + frozenModel: null, + activate: undefined, + frozenScreen: undefined, + linkStatus: { status: 'failed' }, + })), + }, + { + target: 'failed', + actions: activity.assign((_, event) => ({ + frozenModel: null, + activate: undefined, + frozenScreen: undefined, + error: toLocalizableError(event.error), + })), + }, + ], }), }, + showingLinkStatus: { + on: whileIdle, + }, failed: { on: { ...whileIdle, @@ -191,6 +238,7 @@ const FINALIZE_STATUS = { completingReturn: 'idle', startingEnterpriseSso: 'idle', choosingConnection: 'idle', + showingLinkStatus: 'idle', arrivalFailed: 'idle', finalizing: 'running', failed: 'failed', @@ -200,9 +248,15 @@ const FINALIZE_STATUS = { function screenFor( route: SignUpRoute | undefined, { attempt, instance }: SignUpReadyModel, - isBlocked: boolean, - hasConnections: boolean, + { + isBlocked, + hasConnections, + hasEmailLinkStatus, + }: { isBlocked: boolean; hasConnections: boolean; hasEmailLinkStatus: boolean }, ): SignUpScreen { + if (hasEmailLinkStatus) { + return 'emailLinkStatus'; + } if (route === undefined || (route === 'enterpriseConnections' && !hasConnections)) { return 'startOver'; } @@ -215,15 +269,19 @@ function screenFor( return instance.signUpMode === 'public' || attempt.ticket ? 'start' : instance.signUpMode; } +function routeFacts({ verification }: SignUpReadyModel): SignUpRouteFacts { + return { hasEmailLink: Boolean(verification.emailLink?.target) }; +} + function redeemsTicket( - { attempt }: SignUpReadyModel, + model: SignUpReadyModel, route: SignUpRoute, override: AuthSessionOverride, ): boolean { - if (!attempt.ticket || override.type !== 'none') { + if (!model.attempt.ticket || override.type !== 'none') { return false; } - return route === 'start' || correctRoute(route, override, attempt.step) === 'start'; + return route === 'start' || correctRoute(route, override, model.attempt.step, routeFacts(model)) === 'start'; } function arrivalIntentFor( @@ -231,10 +289,16 @@ function arrivalIntentFor( route: SignUpRoute, override: AuthSessionOverride, ): SignUpArrivalIntent { - if (model.attempt.hasPendingReturn && override.type !== 'leave') { + if (model.attempt.pendingReturn === 'email_link') { + return 'emailLink'; + } + if (model.attempt.pendingReturn === 'sso' && override.type !== 'leave') { return 'return'; } - if (override.type === 'none' && correctRoute(route, override, model.attempt.step) === 'enterpriseConnections') { + if ( + override.type === 'none' && + correctRoute(route, override, model.attempt.step, routeFacts(model)) === 'enterpriseConnections' + ) { return 'enterpriseSso'; } return redeemsTicket(model, route, override) ? 'ticket' : 'visit'; @@ -258,6 +322,7 @@ type SignUpControllerResult = status: 'ready'; attempt?: string; verifyEmail: SignUpVerifyScreen; + verifyEmailLink?: SignUpEmailLinkScreen; verifyPhone: SignUpVerifyScreen; protectCheck: SignUpProtectScreen; }); @@ -277,7 +342,13 @@ export function useSignUpController( }; const [arrival] = useState(() => { const session = liveModel.session.type; - const override = sessionOverride({ ...facts, sessionOnArrival: session, finalizeStatus: 'idle' }); + const override = sessionOverride({ + ...facts, + sessionOnArrival: session, + arrivedForResult: liveModel.attempt.pendingReturn === 'email_link', + isShowingResult: false, + finalizeStatus: 'idle', + }); return { session, leave: liveModel.navigation.goToAfterSignUp, @@ -298,20 +369,20 @@ export function useSignUpController( attempt.forgetTicket(); } details.adoptInvitation(emailAddress); - next(result); + advance(result); }); }, canRedeemTicket: (): boolean => !model.details.inTicketSignUp && redeemsTicket(model, route, override), completeReturn: async () => { const result = await attempt.completeReturn(); if (result) { - flushSync(() => next(result)); + flushSync(() => advance(result)); } }, startEnterpriseSso: async () => { const result = await attempt.startEnterpriseSso(); if (result) { - flushSync(() => next(result)); + flushSync(() => advance(result)); return; } await new Promise(resolve => setTimeout(resolve, REDIRECT_HOLD_MS)); @@ -325,16 +396,13 @@ export function useSignUpController( const override = sessionOverride({ ...facts, sessionOnArrival: arrival.session, + // A page an email link opens shows the link's result whatever session the visitor has. + arrivedForResult: arrival.intent === 'emailLink', + isShowingResult: activitySnapshot.value === 'showingLinkStatus', finalizeStatus: FINALIZE_STATUS[activitySnapshot.value], }); const isHolding = override.type === 'hold'; const isLeaving = override.type === 'leave'; - const isHidden = isLeaving || override.type === 'done'; - const isHiddenNow = useRef(isHidden); - - useEffect(() => { - isHiddenNow.current = isHidden; - }, [isHidden]); useEffect(() => { if (isLeaving && !hasLeft.current) { @@ -350,23 +418,36 @@ export function useSignUpController( activitySnapshot.value === 'redeemingTicket' || activitySnapshot.value === 'completingReturn' || activitySnapshot.value === 'startingEnterpriseSso'; - const correctedRoute = correctRoute(route, override, attempt.step); + const correctedRoute = correctRoute(route, override, attempt.step, routeFacts(model)); const heldScreen = isHolding ? activitySnapshot.context.frozenScreen : undefined; + const shownEmailLinkStatus = activitySnapshot.context.linkStatus; + const isHidden = isLeaving || override.type === 'done'; + const isHiddenNow = useRef(isHidden); + + useEffect(() => { + isHiddenNow.current = isHidden; + }, [isHidden]); + const screen = isLoading ? 'loading' - : (heldScreen ?? screenFor(correctedRoute, model, blockedDetails !== undefined, connections !== undefined)); + : (heldScreen ?? + screenFor(correctedRoute, model, { + isBlocked: blockedDetails !== undefined, + hasConnections: connections !== undefined, + hasEmailLinkStatus: shownEmailLinkStatus !== undefined, + })); useRouteGuard({ route, go }, correctedRoute); - // A screen's action keeps running after the flow hides, and may hold the `next` from when it mounted. - const next = (result: SignUpCreateResult) => { - if (isHiddenNow.current) { - return; - } + const advance = (result: SignUpCreateResult) => { if (result.type === 'blocked') { block(result.details); return; } + if (result.type === 'email_link_status') { + sendActivity({ type: 'SHOW_LINK_STATUS', linkStatus: { status: result.status } }); + return; + } if (result.type === 'complete') { sendActivity({ type: 'FINALIZE', @@ -387,6 +468,18 @@ export function useSignUpController( }); return; } + if (result.type === 'session') { + const { sessionId } = result; + sendActivity({ + type: 'FINALIZE', + frozenModel: model, + activate: () => model.attempt.finalize(sessionId), + frozenScreen: 'loading', + showsFailedLink: true, + onFinalized: details.clear, + }); + return; + } if (result.type === 'transfer') { sendActivity({ type: 'COMPLETE_RETURN' }); return; @@ -407,6 +500,13 @@ export function useSignUpController( } }; + // A screen's action keeps running after the flow hides, and may hold the `next` from when it mounted. + const next = (result: SignUpCreateResult) => { + if (!isHiddenNow.current) { + advance(result); + } + }; + const activityError = activitySnapshot.context.error ? errorText(activitySnapshot.context.error) : undefined; const finalizeError = activitySnapshot.value === 'failed' ? activityError : undefined; const arrivalError = activitySnapshot.value === 'arrivalFailed' ? activityError : undefined; @@ -463,6 +563,7 @@ export function useSignUpController( start: details.start, continue: details.continue, verifyEmail: { ...verify, verification: verification.email }, + verifyEmailLink: verification.emailLink && { ...verify, link: verification.emailLink }, verifyPhone: { ...verify, verification: verification.phone }, protectCheck: { protect: model.protect, @@ -478,6 +579,7 @@ export function useSignUpController( onSignIn: navigation.goToSignIn, }, actionBlocked: blockedDetails, + emailLinkStatus: shownEmailLinkStatus, enterpriseConnections: connections && { options: connections, pendingConnectionId: connectionActions.pendingKey, diff --git a/packages/mosaic/src/features/sign-up/sign-up.messages.ts b/packages/mosaic/src/features/sign-up/sign-up.messages.ts index 7a5334717a0..a70051871fd 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.messages.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.messages.ts @@ -87,6 +87,7 @@ export const signUpMessages = { verifyEmailLink: { title: 'Verify your email', description: 'Use the verification link sent to your email address', + expired: 'The verification link expired. Please request a new link.', resendText: 'Didn’t receive a link?', resend: 'Resend', resendCountdown: 'Resend ({seconds})', diff --git a/packages/mosaic/src/features/sign-up/sign-up.model.ts b/packages/mosaic/src/features/sign-up/sign-up.model.ts index d744f65a7b5..964b9cfe92f 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.model.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.model.ts @@ -22,6 +22,7 @@ import { import { buildURL } from '@clerk/shared/internal/clerk-js/url'; import { OAUTH_PROVIDERS } from '@clerk/shared/oauth'; import { getPreferredPhoneCodeChannelByCountry } from '@clerk/shared/phone'; +import { Poller } from '@clerk/shared/poller'; import { __internal_useClerkSignal, useClerk, useSession } from '@clerk/shared/react'; import type { ClerkAPIError, @@ -40,7 +41,7 @@ import { useMemo, useRef } from 'react'; import type { ApplicationLogoProps } from '../../blocks/application-logo'; import { applicationLogo } from '../../blocks/application-logo'; -import type { AuthActionBlockedDetails, AuthProvider } from '../../blocks/auth'; +import type { AuthActionBlockedDetails, AuthEmailLinkStatusValue, AuthProvider } from '../../blocks/auth'; import type { FieldFeedback, FormFieldErrors } from '../../components/form'; import { FormSubmitError } from '../../components/form'; import { useMosaicEnvironment } from '../../hooks/use-mosaic-environment'; @@ -86,9 +87,9 @@ export interface SignUpAttemptModel { redeemTicket: () => Promise<{ result: SignUpCreateResult; emailAddress: string }>; forgetTicket: () => void; startEnterpriseSso: (connectionId?: string) => Promise; - hasPendingReturn: boolean; + pendingReturn: 'sso' | 'email_link' | undefined; completeReturn: () => Promise; - finalize: () => Promise; + finalize: (sessionId?: string) => Promise; finalizeSignIn: (sessionId: string | undefined) => Promise; reset: () => Promise; } @@ -117,12 +118,32 @@ export interface SignUpEnterpriseConnectionsResult { connections: readonly AuthProvider[]; } +export interface SignUpEmailLinkStatusResult { + type: 'email_link_status'; + status: Exclude; +} + export type SignUpCreateResult = | SignUpNextStep | { type: 'blocked'; details: AuthActionBlockedDetails } | SignUpEnterpriseConnectionsResult + | SignUpEmailLinkStatusResult + | { type: 'session'; sessionId: string } | { type: 'signed_in'; sessionId: string | undefined }; +export type SignUpEmailLinkOutcome = { type: 'expired' } | { type: 'verified'; result: SignUpCreateResult }; + +export interface SignUpEmailLinkWait { + outcome: Promise; + cancel: () => void; +} + +export interface SignUpEmailLinkModel { + target: string; + send: () => Promise; + wait: () => SignUpEmailLinkWait; +} + export interface SignUpDetailsModel { initialIdentifier: SignUpIdentifier; canSwitchIdentifier: boolean; @@ -171,7 +192,7 @@ export interface SignUpReadyModel { app: SignUpAppModel; navigation: SignUpNavigationModel; details: SignUpDetailsModel; - verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel }; + verification: { email: SignUpVerificationModel; phone: SignUpVerificationModel; emailLink?: SignUpEmailLinkModel }; protect: SignUpProtectModel; } @@ -182,9 +203,20 @@ const DETAILS_FIELDS = [...signUpFieldOrder, 'legalAccepted'] as const; const PREFILL_NAMES = ['emailAddress', 'phoneNumber', 'username', 'firstName', 'lastName'] as const; const ABSOLUTE_URL = /^https?:\/\//; +const CLERK_PARAM_PREFIX = '__clerk_'; const RETURN_PARAM = '__clerk_mosaic_sign_up'; const ENTERPRISE_CONNECTION_REQUIRED = 'enterprise_connection_id_is_required_with_multiple_connections'; const SSO_RETURN = 'sso-callback'; +const EMAIL_LINK_RETURN = 'verify'; +const RETURNS: Partial> = { + [SSO_RETURN]: 'sso', + [EMAIL_LINK_RETURN]: 'email_link', +}; +const EMAIL_LINK_STATUSES: Partial> = { + expired: 'expired', + client_mismatch: 'client-mismatch', + transferable: 'transferable', +}; const OAUTH_PREFIX = /^oauth_(custom_)?/; const SHOWN_RETURN_ERRORS: readonly string[] = [ ERROR_CODES.NOT_ALLOWED_TO_SIGN_UP, @@ -217,9 +249,14 @@ function transferRoute(signIn: Pick clerk.buildSignInUrl(returnUrl ? { redirectUrl: returnUrl } : undefined); @@ -369,9 +407,6 @@ export function useSignUpModel({ const next = (resource: SignUpFutureResource): SignUpNextStep => { const step = getSignUpNextStep(resource); - if (step.type === 'verify_email' && verifiesEmailByLink) { - return { type: 'unknown' }; - } return step.type === 'fields' && !continueCanSatisfy(resource, providerIds) ? { type: 'unknown' } : step; }; @@ -475,6 +510,61 @@ export function useSignUpModel({ return next(signUp); }; + const waitForEmailLink = (): SignUpEmailLinkWait => { + const resource = clerk.client?.signUp; + const { run: poll, stop } = Poller(); + let cancelled = false; + const cancel = () => { + cancelled = true; + stop(); + }; + const outcome = new Promise((resolve, reject) => { + void poll(async () => { + if (cancelled) { + stop(); + return; + } + try { + const reloaded = await resource?.reload(); + const verification = reloaded?.verifications.emailAddress; + if (verification?.status === 'expired') { + cancel(); + resolve({ type: 'expired' }); + } else if (reloaded && verification?.status === 'verified') { + cancel(); + resolve({ + type: 'verified', + result: verification.verifiedFromTheSameClient() + ? { type: 'email_link_status', status: 'signed-in-other-tab' } + : next(reloaded.__internal_future), + }); + } + } catch (cause) { + cancel(); + reject(cause instanceof Error ? cause : new Error(String(cause))); + } + }); + }); + return { outcome, cancel }; + }; + + const completeEmailLinkReturn = (): SignUpCreateResult => { + const status = getClerkQueryParam('__clerk_status'); + const createdSessionId = getClerkQueryParam('__clerk_created_session'); + removeClerkQueryParam('__clerk_status'); + removeClerkQueryParam('__clerk_created_session'); + if (status !== 'verified') { + return { type: 'email_link_status', status: EMAIL_LINK_STATUSES[status ?? ''] ?? 'failed' }; + } + if (createdSessionId) { + return clerk.client?.sessions.some(({ id }) => id === createdSessionId) + ? { type: 'session', sessionId: createdSessionId } + : { type: 'email_link_status', status: 'signed-in' }; + } + const returned = next(signUp); + return returned.type === 'start' ? { type: 'email_link_status', status: 'signed-in-other-tab' } : returned; + }; + const legalConsent = legalConsentRequired ? { termsUrl: displayConfig.termsUrl || undefined, privacyPolicyUrl: displayConfig.privacyPolicyUrl || undefined } : undefined; @@ -531,7 +621,7 @@ export function useSignUpModel({ const result = await signUp.sso({ strategy: 'enterprise_sso', enterpriseConnectionId: connectionId, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, }); const needsConnection = @@ -556,9 +646,12 @@ export function useSignUpModel({ } return undefined; }, - hasPendingReturn: query.get(RETURN_PARAM) === SSO_RETURN, + pendingReturn: returning, completeReturn: async () => { forgetReturn(); + if (returning === 'email_link') { + return completeEmailLinkReturn(); + } const returned = next(signUp); if (returned.type === 'protect') { return returned; @@ -596,9 +689,14 @@ export function useSignUpModel({ } return returned; }, - finalize: async () => { + finalize: async sessionId => { forgetTicket(); - await run(() => signUp.finalize({ navigate: navigateAfter(afterSignUpUrl, { keepsTaskInFlow: true }) })); + const navigate = navigateAfter(afterSignUpUrl, { keepsTaskInFlow: true }); + if (sessionId) { + await clerk.setActive({ session: sessionId, navigate }); + return; + } + await run(() => signUp.finalize({ navigate })); }, finalizeSignIn: async sessionId => { const navigate = navigateAfter(afterSignInUrl, { keepsTaskInFlow: true }); @@ -676,7 +774,7 @@ export function useSignUpModel({ } const result = await target.sso({ strategy, - redirectCallbackUrl: ssoCallbackUrl(), + redirectCallbackUrl: callbackUrl(SSO_RETURN), redirectUrl: afterSignUpUrl, unsafeMetadata, legalAccepted: legalAccepted || undefined, @@ -766,6 +864,14 @@ export function useSignUpModel({ send: ({ channel } = {}) => run(() => signUp.verifications.sendPhoneCode({ channel: channel ?? phoneChannel })), verify: code => verify(() => signUp.verifications.verifyPhoneCode({ code })), }, + emailLink: verifiesEmailByLink + ? { + target: signUp.emailAddress ?? '', + send: () => + run(() => signUp.verifications.sendEmailLink({ verificationUrl: callbackUrl(EMAIL_LINK_RETURN) })), + wait: waitForEmailLink, + } + : undefined, }, }; } diff --git a/packages/mosaic/src/features/sign-up/sign-up.routes.ts b/packages/mosaic/src/features/sign-up/sign-up.routes.ts index 94fa03961e5..8e441e7d6e5 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.routes.ts +++ b/packages/mosaic/src/features/sign-up/sign-up.routes.ts @@ -60,7 +60,11 @@ export function routeFor(step: SignUpNextStep, from: SignUpRoute): SignUpRoute | } } -function allowedRoute(route: SignUpRoute, step: SignUpNextStep): boolean { +export interface SignUpRouteFacts { + hasEmailLink: boolean; +} + +function allowedRoute(route: SignUpRoute, step: SignUpNextStep, { hasEmailLink }: SignUpRouteFacts): boolean { if (route === 'start' || step.type === 'complete' || step.type === 'transfer') { return true; } @@ -70,24 +74,28 @@ function allowedRoute(route: SignUpRoute, step: SignUpNextStep): boolean { ) { return true; } + if (hasEmailLink && (route === 'verifyEmail' || route === 'continueVerifyEmail')) { + return true; + } return route === routeFor(step, route); } -function stepRoute(route: SignUpRoute, step: SignUpNextStep): SignUpRoute | undefined { +function stepRoute(route: SignUpRoute, step: SignUpNextStep, facts: SignUpRouteFacts): SignUpRoute | undefined { if (step.type === 'unknown') { return undefined; } - return allowedRoute(route, step) ? route : routeFor(step, route); + return allowedRoute(route, step, facts) ? route : routeFor(step, route); } export function correctRoute( route: SignUpRoute, override: AuthSessionOverride, step: SignUpNextStep, + facts: SignUpRouteFacts, ): SignUpRoute | undefined { switch (override.type) { case 'none': - return stepRoute(route, step); + return stepRoute(route, step, facts); case 'task': return 'taskChooseOrganization'; case 'hold': diff --git a/packages/mosaic/src/features/sign-up/sign-up.tsx b/packages/mosaic/src/features/sign-up/sign-up.tsx index c6b99554932..1121db9839b 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.tsx @@ -14,6 +14,7 @@ import { useSignUpController } from './sign-up.controller'; import type { SignUpReadyModel } from './sign-up.model'; import { ticketFromUrl, useSignUpModel } from './sign-up.model'; import { SignUpView } from './sign-up.view'; +import { SignUpEmailLink } from './sign-up-email-link/sign-up-email-link'; import { SignUpProtect } from './sign-up-protect/sign-up-protect'; import { SignUpVerify } from './sign-up-verify/sign-up-verify'; @@ -83,17 +84,24 @@ function SignUpFlow({ return null; } - const { status: _status, attempt, verifyEmail, verifyPhone, protectCheck, ...view } = controller; + const { status: _status, attempt, verifyEmail, verifyEmailLink, verifyPhone, protectCheck, ...view } = controller; return ( + verifyEmailLink ? ( + + ) : ( + + ) } verifyPhone={ void; isPending: boolean; globalErrorMessage?: string; onEditIdentifier: () => void; - onResend?: () => void; - canResend: boolean; - resendRemainingSeconds?: number; } export interface SignUpEmailLinkStatusScreen { @@ -148,7 +150,6 @@ export interface SignUpViewProps { actionBlocked?: AuthActionBlockedDetails; startOver: SignUpStartOverScreen; alternativePhone?: SignUpAlternativePhoneScreen; - verifyEmailLink?: SignUpEmailLinkScreen; emailLinkStatus?: SignUpEmailLinkStatusScreen; enterpriseConnections?: SignUpEnterpriseConnectionsScreen; wallets?: SignUpWalletsScreen; diff --git a/packages/mosaic/src/features/sign-up/sign-up.view.tsx b/packages/mosaic/src/features/sign-up/sign-up.view.tsx index ab37ff8353b..a6dbe7166ed 100644 --- a/packages/mosaic/src/features/sign-up/sign-up.view.tsx +++ b/packages/mosaic/src/features/sign-up/sign-up.view.tsx @@ -2,14 +2,12 @@ import { ApplicationLogo } from '../../blocks/application-logo'; import { AuthActionBlocked, AuthAlternativeChannel, - AuthEmailLink, AuthEmailLinkStatus, AuthEnterpriseConnections, AuthLoading, AuthStartOver, AuthWallets, } from '../../blocks/auth'; -import { verificationResend } from '../../blocks/verification'; import { Card } from '../../components/card'; import { Flow } from '../../components/flow'; import { useMessages } from '../../localization'; @@ -41,7 +39,6 @@ export function SignUpView(props: SignUpViewProps) { actionBlocked, startOver, alternativePhone, - verifyEmailLink, emailLinkStatus, enterpriseConnections, wallets, @@ -132,28 +129,6 @@ export function SignUpView(props: SignUpViewProps) { ) : null} - - {verifyEmailLink ? ( - - ) : null} - - {emailLinkStatus ? ( Promise.resolve(), + wait: () => ({ outcome: new Promise(noop), cancel: noop }), + }, + onNext: noop, + isPending: false, + onEditIdentifier: noop, +}; + type DetailsOverrides = Partial>; type ScreenOverrides = Partial< @@ -356,14 +368,8 @@ export function VerifyPhoneAlternativeChannel() { export function VerifyEmailLink() { return ( } /> ); }