Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
5d5161b
test(mosaic): let the fake FAPI send, open and expire a sign-up email…
austincalvelage Nov 30, 2026
3ff6d0a
feat(mosaic): verify a sign-up email by link
austincalvelage Nov 30, 2026
7f890b8
feat(mosaic): handle the page a sign-up email link opens
austincalvelage Nov 30, 2026
5267a10
docs(mosaic): describe how sign-up verifies an email by link
austincalvelage Nov 30, 2026
02cbfb5
chore(repo): add an empty changeset for the sign-up email link
austincalvelage Nov 30, 2026
12aa3d0
test(mosaic): hold every email link check and control its timer in th…
austincalvelage Nov 30, 2026
3ed30dd
fix(mosaic): keep the email link screen usable when finishing the sig…
austincalvelage Dec 1, 2026
7e82b6e
fix(mosaic): keep Clerk's own query params out of sign-up return URLs
austincalvelage Dec 1, 2026
a851dc7
fix(mosaic): show a failed link when the session it created cannot be…
austincalvelage Dec 1, 2026
7531a0f
fix(mosaic): send a new email link every time the link screen opens
austincalvelage Dec 1, 2026
c7f0ee2
refactor(mosaic): keep the sign-up email-link status in the activity …
austincalvelage Dec 2, 2026
5276531
refactor(mosaic): tell an email-link arrival apart from a signed-in v…
austincalvelage Dec 2, 2026
2664e4e
fix(mosaic): send no phone code from the tab that waits on a sign-up …
austincalvelage Dec 3, 2026
9534241
fix(mosaic): keep waiting for the sign-up email link after a host Act…
austincalvelage Dec 4, 2026
b7a15cc
test(mosaic): leave the client's sign-up alone when the fake FAPI ans…
austincalvelage Dec 4, 2026
16ed1d6
fix(mosaic): finish an email-link return while sign-up renders nothing
austincalvelage Dec 4, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .changeset/mosaic-sign-up-email-link.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
---
---
40 changes: 27 additions & 13 deletions packages/mosaic/docs/internals/sign-in-sign-up-flow.md

Large diffs are not rendered by default.

95 changes: 89 additions & 6 deletions packages/mosaic/src/__tests__/feature/fake-fapi/sign-up.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ export interface FakeSignUpSeed {
whatsAppQuotaExceeded?: boolean;
tickets?: Record<string, FakeTicket>;
oauth?: Record<string, FakeOAuthAccount>;
emailLinkRedirectUrl?: string;
}

export type FakeOAuthAccount =
Expand Down Expand Up @@ -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[];
Expand All @@ -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: [],
Expand Down Expand Up @@ -144,7 +154,12 @@ export default (container, { token, setWidgetVisible }) =>

let scriptIds = 0;

const STRATEGIES: Record<string, Identifier> = { email_code: 'email_address', phone_code: 'phone_number' };
const STRATEGIES: Record<string, Identifier> = {
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;
Expand Down Expand Up @@ -196,7 +211,12 @@ export function signUpHandlers(
return HttpResponse.json({ ...body, meta: { client: state.client } }, { status: response.status });
};

const completed = new Map<string, SignUpJSON>();

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);
};
Expand Down Expand Up @@ -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');
Expand All @@ -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,
Expand All @@ -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;
Expand Down Expand Up @@ -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));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
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') {
Expand Down Expand Up @@ -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',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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' },
Expand Down
4 changes: 4 additions & 0 deletions packages/mosaic/src/features/auth-flow/auth-flow.types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,10 @@ export type AuthSessionOverride<TaskKey extends string = string> =
export interface AuthSessionOverrideFacts<TaskKey extends string = string> {
session: AuthSessionPhase<TaskKey>;
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;
Expand Down
42 changes: 32 additions & 10 deletions packages/mosaic/src/features/auth-flow/auth-flow.utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,16 @@ export function formatPhoneIdentifier(identifier: string): string {
export function sessionOverride<TaskKey extends string>({
session,
sessionOnArrival,
arrivedForResult,
isShowingResult,
finalizeStatus,
isSingleSession,
isTaskLoaded,
isSignedOutOnly,
}: AuthSessionOverrideFacts<TaskKey>): AuthSessionOverride<TaskKey> {
if (isShowingResult) {
return { type: 'none' };
}
if (finalizeStatus === 'running') {
return { type: 'hold' };
}
Expand All @@ -28,15 +33,32 @@ export function sessionOverride<TaskKey extends string>({
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<never> {
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' };
}
Loading
Loading