Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(elements): Handle ticket-based sign-in flow #4746

Merged
merged 4 commits into from
Dec 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/itchy-mangos-remember.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/elements': minor
---

Handle ticket-based sign in flows such as impersonation
33 changes: 23 additions & 10 deletions packages/elements/src/internals/machines/sign-in/router.machine.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import {
CHOOSE_SESSION_PATH_ROUTE,
ERROR_CODES,
ROUTING,
SEARCH_PARAMS,
SIGN_IN_DEFAULT_BASE_PATH,
SIGN_UP_DEFAULT_BASE_PATH,
SSO_CALLBACK_PATH_ROUTE,
Expand Down Expand Up @@ -151,6 +152,7 @@ export const SignInRouterMachine = setup({
Boolean(context.clerk.client.signIn.status === null && context.clerk.client.lastActiveSessionId),
hasOAuthError: ({ context }) => Boolean(context.clerk?.client?.signIn?.firstFactorVerification?.error),
hasResource: ({ context }) => Boolean(context.clerk?.client?.signIn?.status),
hasTicket: ({ context }) => Boolean(context.ticket),

isLoggedInAndSingleSession: and(['isLoggedIn', 'isSingleSessionMode', not('isExampleMode')]),
isActivePathRoot: isCurrentPath('/'),
Expand Down Expand Up @@ -253,16 +255,21 @@ export const SignInRouterMachine = setup({
},
on: {
INIT: {
actions: assign(({ event }) => ({
clerk: event.clerk,
exampleMode: event.exampleMode || false,
formRef: event.formRef,
loading: {
isLoading: false,
},
router: event.router,
signUpPath: event.signUpPath || SIGN_UP_DEFAULT_BASE_PATH,
})),
actions: assign(({ event }) => {
const searchParams = event.router?.searchParams();

return {
clerk: event.clerk,
exampleMode: event.exampleMode || false,
formRef: event.formRef,
loading: {
isLoading: false,
},
router: event.router,
signUpPath: event.signUpPath || SIGN_UP_DEFAULT_BASE_PATH,
ticket: searchParams?.get(SEARCH_PARAMS.ticket) || undefined,
};
}),
target: 'Init',
},
},
Expand Down Expand Up @@ -331,6 +338,11 @@ export const SignInRouterMachine = setup({
actions: { type: 'navigateInternal', params: { force: true, path: '/' } },
target: 'Start',
},
{
guard: 'hasTicket',
actions: { type: 'navigateInternal', params: { force: true, path: '/' } },
target: 'Start',
},
],
},
Start: {
Expand All @@ -343,6 +355,7 @@ export const SignInRouterMachine = setup({
basePath: context.router?.basePath,
formRef: context.formRef,
parent: self,
ticket: context.ticket,
}),
onDone: {
actions: 'raiseNext',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,7 @@ export interface SignInRouterContext extends BaseRouterContext {
loading: SignInRouterLoadingContext;
signUpPath: string;
webAuthnAutofillSupport: boolean;
ticket: string | undefined;
}

// ---------------------------------- Input ---------------------------------- //
Expand Down
99 changes: 74 additions & 25 deletions packages/elements/src/internals/machines/sign-in/start.machine.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { SignInResource, Web3Strategy } from '@clerk/types';
import { assertEvent, fromPromise, not, sendTo, setup } from 'xstate';
import { assertEvent, enqueueActions, fromPromise, not, sendTo, setup } from 'xstate';

import { SIGN_IN_DEFAULT_BASE_PATH } from '~/internals/constants';
import { ClerkElementsRuntimeError } from '~/internals/errors';
Expand All @@ -10,10 +10,14 @@ import { assertActorEventError } from '~/internals/machines/utils/assert';
import type { SignInRouterMachineActorRef } from './router.types';
import type { SignInStartSchema } from './start.types';

const DISABLEABLE_FIELDS = ['emailAddress', 'phoneNumber'] as const;

export type TSignInStartMachine = typeof SignInStartMachine;

export const SignInStartMachineId = 'SignInStart';

type AttemptParams = { strategy: 'ticket'; ticket: string } | { strategy?: never; ticket?: never };

export const SignInStartMachine = setup({
actors: {
attemptPasskey: fromPromise<
Expand All @@ -38,33 +42,51 @@ export const SignInStartMachine = setup({
throw new ClerkElementsRuntimeError(`Unsupported Web3 strategy: ${strategy}`);
},
),
attempt: fromPromise<SignInResource, { parent: SignInRouterMachineActorRef; fields: FormFields }>(
({ input: { fields, parent } }) => {
const clerk = parent.getSnapshot().context.clerk;
attempt: fromPromise<
SignInResource,
{ parent: SignInRouterMachineActorRef; fields: FormFields; params?: AttemptParams }
>(({ input: { fields, parent, params } }) => {
const clerk = parent.getSnapshot().context.clerk;

const password = fields.get('password');
const identifier = fields.get('identifier');
const password = fields.get('password');
const identifier = fields.get('identifier');

const passwordParams = password?.value
? {
password: password.value,
strategy: 'password',
}
: {};
const passwordParams = password?.value
? {
password: password.value,
strategy: 'password',
}
: {};

return clerk.client.signIn.create({
identifier: (identifier?.value as string) || '',
...passwordParams,
});
},
),
return clerk.client.signIn.create({
...passwordParams,
...(params?.ticket
? params
: {
identifier: (identifier?.value as string) ?? '',
}),
});
}),
},
actions: {
sendToNext: ({ context, event }) => {
// @ts-expect-error -- We're calling this in onDone, and event.output exists on the actor done event
return context.parent.send({ type: 'NEXT', resource: event?.output });
},
sendToLoading,
setFormDisabledTicketFields: enqueueActions(({ context, enqueue }) => {
if (!context.ticket) {
return;
}

const currentFields = context.formRef.getSnapshot().context.fields;

for (const name of DISABLEABLE_FIELDS) {
if (currentFields.has(name)) {
enqueue.sendTo(context.formRef, { type: 'FIELD.DISABLE', field: { name } });
}
}
}),
setFormErrors: sendTo(
({ context }) => context.formRef,
({ event }) => {
Expand All @@ -77,6 +99,7 @@ export const SignInStartMachine = setup({
),
},
guards: {
hasTicket: ({ context }) => Boolean(context.ticket),
isExampleMode: ({ context }) => Boolean(context.parent.getSnapshot().context.exampleMode),
},
types: {} as SignInStartSchema,
Expand All @@ -87,9 +110,22 @@ export const SignInStartMachine = setup({
parent: input.parent,
formRef: input.formRef,
loadingStep: 'start',
ticket: input.ticket,
}),
initial: 'Pending',
initial: 'Init',
states: {
Init: {
description: 'Handle ticket, if present; Else, default to Pending state.',
always: [
{
guard: 'hasTicket',
target: 'Attempting',
},
{
target: 'Pending',
},
],
},
Pending: {
tags: ['state:pending'],
description: 'Waiting for user input',
Expand Down Expand Up @@ -122,15 +158,28 @@ export const SignInStartMachine = setup({
invoke: {
id: 'attempt',
src: 'attempt',
input: ({ context }) => ({
parent: context.parent,
fields: context.formRef.getSnapshot().context.fields,
}),
input: ({ context }) => {
// Standard fields
const defaultParams = {
fields: context.formRef.getSnapshot().context.fields,
parent: context.parent,
};

// Handle ticket-specific flows
const params: AttemptParams = context.ticket
? {
strategy: 'ticket',
ticket: context.ticket,
}
: {};

return { ...defaultParams, params };
},
onDone: {
actions: ['sendToNext', 'sendToLoading'],
actions: ['setFormDisabledTicketFields', 'sendToNext', 'sendToLoading'],
},
onError: {
actions: ['setFormErrors', 'sendToLoading'],
actions: ['setFormDisabledTicketFields', 'setFormErrors', 'sendToLoading'],
target: 'Pending',
},
},
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ export type SignInStartInput = {
basePath?: string;
formRef: ActorRefFrom<typeof FormMachine>;
parent: SignInRouterMachineActorRef;
ticket?: string | undefined;
};

// ---------------------------------- Context ---------------------------------- //
Expand All @@ -41,6 +42,7 @@ export interface SignInStartContext {
formRef: ActorRefFrom<typeof FormMachine>;
parent: SignInRouterMachineActorRef;
loadingStep: 'start';
ticket?: string | undefined;
}

// ---------------------------------- Schema ---------------------------------- //
Expand Down
Loading