Skip to content

Commit fe4d5f5

Browse files
committed
fix(ui): hand the next card its error through the active Clerk instance
The card that a navigation leads to read its error from window.Clerk, so an error handed over between steps was lost when Clerk came from the npm package and window.Clerk was not set. This included the reset-required screen after an autofilled password on the first sign-in step. Cards now read the error from the Clerk instance they render with, which is where __internal_navigateWithError already stores it. The first sign-in step and the SSO callback hand errors over the same way.
1 parent 4db418f commit fe4d5f5

11 files changed

Lines changed: 160 additions & 124 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'@clerk/ui': patch
3+
---
4+
5+
Errors that a step of `<SignIn />` or `<SignUp />` hands to the screen it navigates to, such as a locked account or a blocked sign-in, now show when Clerk is loaded from the npm package and `window.Clerk` is not set.

‎packages/ui/src/common/SSOCallback.tsx‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ import React from 'react';
55
import { Flow } from '../customizables';
66
import { CaptchaElement } from '../elements/CaptchaElement';
77
import { Card } from '../elements/Card';
8-
import { useCardState, withCardStateProvider } from '../elements/contexts';
8+
import { showErrorOnNextCard, useCardState, withCardStateProvider } from '../elements/contexts';
99
import { LoadingCardContainer } from '../elements/LoadingCard';
1010
import { useRouter } from '../router';
1111
import { handleError } from '../utils/errorHandler';
@@ -19,7 +19,8 @@ export const SSOCallback = withCardStateProvider<HandleOAuthCallbackParams | Han
1919
});
2020

2121
export const SSOCallbackCard = (props: HandleOAuthCallbackParams | HandleSamlCallbackParams) => {
22-
const { handleRedirectCallback, __internal_setActiveInProgress } = useClerk();
22+
const clerk = useClerk();
23+
const { handleRedirectCallback, __internal_setActiveInProgress } = clerk;
2324
const { navigate } = useRouter();
2425
const card = useCardState();
2526

@@ -43,9 +44,7 @@ export const SSOCallbackCard = (props: HandleOAuthCallbackParams | HandleSamlCal
4344
};
4445

4546
bounceTimeoutRef.current = setTimeout(() => {
46-
if (window.Clerk) {
47-
window.Clerk.__internal_last_error = shownError;
48-
}
47+
showErrorOnNextCard(clerk, shownError);
4948
void navigate('../');
5049
}, 4000);
5150
try {

‎packages/ui/src/components/SignIn/SignInStart.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -313,7 +313,7 @@ function SignInStartInternal(): JSX.Element {
313313
}
314314
if (options?.passwordResetRequiredError) {
315315
// Factor one opens on the password reset screen when it receives this error.
316-
showErrorOnNextCard(options.passwordResetRequiredError);
316+
showErrorOnNextCard(clerk, options.passwordResetRequiredError);
317317
}
318318
return navigate('factor-one');
319319
}

‎packages/ui/src/components/SignIn/__tests__/SignInActionBlocked.test.tsx‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { ClerkAPIResponseError } from '@clerk/shared/error';
22
import type { ClerkAPIErrorJSON, SignInResource } from '@clerk/shared/types';
3-
import { afterEach, describe, expect, it } from 'vitest';
3+
import { describe, expect, it } from 'vitest';
44

55
import { bindCreateFixtures } from '@/test/create-fixtures';
66
import { render, screen } from '@/test/utils';
7+
import { showErrorOnNextCard } from '@/ui/elements/contexts';
78

89
import { SignInFactorOne } from '../SignInFactorOne';
910
import { SignInStart } from '../SignInStart';
@@ -19,11 +20,6 @@ const blockedError = (meta?: ClerkAPIErrorJSON['meta']) =>
1920
const INLINE_ERROR = /This action couldn't be completed/i;
2021

2122
describe('a blocked sign-in', () => {
22-
const originalClerk = window.Clerk;
23-
afterEach(() => {
24-
window.Clerk = originalClerk;
25-
});
26-
2723
it('replaces the start form with the blocked screen', async () => {
2824
const { wrapper, fixtures } = await createFixtures(f => {
2925
f.withEmailAddress();
@@ -54,17 +50,10 @@ describe('a blocked sign-in', () => {
5450
});
5551

5652
it('shows the blocked screen for an error handed over from another card', async () => {
57-
const { wrapper } = await createFixtures(f => {
53+
const { wrapper, fixtures } = await createFixtures(f => {
5854
f.withEmailAddress();
5955
});
60-
let lastError: unknown = blockedError({ trace_id: '7Q8ikxgt' }).errors[0];
61-
window.Clerk = {
62-
get __internal_last_error() {
63-
const value = lastError;
64-
lastError = null;
65-
return value;
66-
},
67-
} as typeof window.Clerk;
56+
showErrorOnNextCard(fixtures.clerk, blockedError({ trace_id: '7Q8ikxgt' }).errors[0]);
6857

6958
render(<SignInStart />, { wrapper });
7059

‎packages/ui/src/components/SignIn/__tests__/SignInFactorOne.test.tsx‎

Lines changed: 20 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { describe, expect, it, vi } from 'vitest';
55

66
import { bindCreateFixtures } from '@/test/create-fixtures';
77
import { act, mockWebAuthn, render, screen } from '@/test/utils';
8+
import { showErrorOnNextCard } from '@/ui/elements/contexts';
89

910
import { SIGN_IN_RESET_PASSWORD_INTENT_PARAM } from '../shared';
1011
import { SignInFactorOne } from '../SignInFactorOne';
@@ -503,36 +504,27 @@ describe('SignInFactorOne', () => {
503504
});
504505
fixtures.signIn.prepareFirstFactor.mockReturnValueOnce(Promise.resolve({} as SignInResource));
505506

506-
const originalClerk = window.Clerk;
507-
let errorFromFirstStep: unknown = parseError({
508-
code: 'password_reset_required',
509-
long_message:
510-
'This account requires a password reset before sign-in can continue. Please reset your password or contact support.',
511-
message: 'password reset required',
512-
});
513-
window.Clerk = {
514-
get __internal_last_error() {
515-
const value = errorFromFirstStep;
516-
errorFromFirstStep = null;
517-
return value;
518-
},
519-
} as typeof window.Clerk;
507+
showErrorOnNextCard(
508+
fixtures.clerk,
509+
parseError({
510+
code: 'password_reset_required',
511+
long_message:
512+
'This account requires a password reset before sign-in can continue. Please reset your password or contact support.',
513+
message: 'password reset required',
514+
}),
515+
);
520516

521-
try {
522-
const { userEvent } = render(<SignInFactorOne />, { wrapper });
517+
const { userEvent } = render(<SignInFactorOne />, { wrapper });
518+
519+
await screen.findByText('Password reset required');
520+
screen.getByText('You need to reset your password before you can use it again.');
521+
screen.getByText('Email code to hello@clerk.com');
522+
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
523+
expect(screen.queryByText('Back')).not.toBeInTheDocument();
524+
expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled();
523525

524-
await screen.findByText('Password reset required');
525-
screen.getByText('You need to reset your password before you can use it again.');
526-
screen.getByText('Email code to hello@clerk.com');
527-
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
528-
expect(screen.queryByText('Back')).not.toBeInTheDocument();
529-
expect(fixtures.signIn.attemptFirstFactor).not.toHaveBeenCalled();
530-
531-
await userEvent.click(screen.getByText('Reset your password'));
532-
await screen.findByText('First, enter the code sent to your email address');
533-
} finally {
534-
window.Clerk = originalClerk;
535-
}
526+
await userEvent.click(screen.getByText('Reset your password'));
527+
await screen.findByText('First, enter the code sent to your email address');
536528
});
537529
});
538530

Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
import { ClerkAPIResponseError } from '@clerk/shared/error';
2+
import type { SignInResource } from '@clerk/shared/types';
3+
import { fireEvent } from '@testing-library/react';
4+
import React from 'react';
5+
import { afterEach, describe, expect, it, vi } from 'vitest';
6+
7+
import { bindCreateFixtures } from '@/test/create-fixtures';
8+
import { render, screen } from '@/test/utils';
9+
10+
import { PathRouter } from '../../../router';
11+
import { SignIn } from '../index';
12+
13+
const { createFixtures } = bindCreateFixtures('SignIn');
14+
15+
const passwordError = (code: string, long_message: string) =>
16+
new ClerkAPIResponseError('Error', {
17+
data: [{ code, long_message, message: long_message, meta: { param_name: 'password' } }],
18+
status: 422,
19+
});
20+
21+
const PASSWORD_RESET_REQUIRED = passwordError(
22+
'password_reset_required',
23+
'This account requires a password reset before sign-in can continue. Please reset your password or contact support.',
24+
);
25+
26+
const setup = async ({ globalClerk, error }: { globalClerk: boolean; error: ClerkAPIResponseError }) => {
27+
const { wrapper, fixtures } = await createFixtures(f => {
28+
f.withEmailAddress();
29+
f.withPassword({ required: true });
30+
f.startSignInWithEmailAddress({ supportEmailCode: true, supportPassword: true, supportResetPassword: true });
31+
});
32+
vi.mocked(fixtures.clerk.navigate).mockImplementation((to: string) => {
33+
window.history.pushState({}, '', new URL(to, window.location.href).href);
34+
return Promise.resolve();
35+
});
36+
fixtures.signIn.create
37+
.mockRejectedValueOnce(error)
38+
.mockResolvedValueOnce({ status: 'needs_first_factor' } as SignInResource);
39+
fixtures.signIn.prepareFirstFactor.mockResolvedValue({} as SignInResource);
40+
window.Clerk = globalClerk ? (fixtures.clerk as typeof window.Clerk) : undefined;
41+
42+
return { wrapper, fixtures };
43+
};
44+
45+
const submitAutofilledPassword = async (wrapper: React.FC<{ children: React.ReactNode }>) => {
46+
window.history.replaceState({}, '', '/sign-in');
47+
const result = render(
48+
<PathRouter basePath='/sign-in'>
49+
<SignIn />
50+
</PathRouter>,
51+
{ wrapper },
52+
);
53+
await result.userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com');
54+
fireEvent.change(result.container.querySelector('#password-field') as Element, {
55+
target: { value: 'some-password' },
56+
});
57+
fireEvent.submit(result.container.querySelector('form') as Element);
58+
return result;
59+
};
60+
61+
describe('SignIn with a password autofilled on the first step', () => {
62+
const originalClerk = window.Clerk;
63+
64+
afterEach(() => {
65+
window.Clerk = originalClerk;
66+
window.history.replaceState({}, '', '/');
67+
});
68+
69+
it.each([
70+
['Clerk is also window.Clerk', true],
71+
['Clerk comes from the npm package and window.Clerk is not set', false],
72+
])('opens the password reset screen when the password needs a reset and %s', async (_, globalClerk) => {
73+
const { wrapper, fixtures } = await setup({ globalClerk, error: PASSWORD_RESET_REQUIRED });
74+
const { userEvent } = await submitAutofilledPassword(wrapper);
75+
76+
await screen.findByText('Password reset required');
77+
expect(window.location.pathname).toBe('/sign-in/factor-one');
78+
screen.getByText('You need to reset your password before you can use it again.');
79+
screen.getByText('Email code to hello@clerk.com');
80+
expect(screen.queryByLabelText('Password')).not.toBeInTheDocument();
81+
expect(fixtures.signIn.create).toHaveBeenCalledTimes(2);
82+
expect(fixtures.signIn.create).toHaveBeenLastCalledWith(
83+
expect.not.objectContaining({ password: expect.anything() }),
84+
);
85+
86+
await userEvent.click(screen.getByText('Reset your password'));
87+
await screen.findByText('First, enter the code sent to your email address');
88+
});
89+
90+
it('asks for the password again on the next step when the password was found in a breach', async () => {
91+
const { wrapper } = await setup({
92+
globalClerk: false,
93+
error: passwordError('form_password_pwned', 'Password has been found in an online data breach.'),
94+
});
95+
await submitAutofilledPassword(wrapper);
96+
97+
await screen.findByLabelText('Password');
98+
expect(window.location.pathname).toBe('/sign-in/factor-one');
99+
expect(screen.queryByText('Password reset required')).not.toBeInTheDocument();
100+
});
101+
});

‎packages/ui/src/components/SignIn/__tests__/SignInStart.test.tsx‎

Lines changed: 0 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -844,51 +844,6 @@ describe('SignInStart', () => {
844844
});
845845
});
846846
});
847-
848-
describe('after the identifier-only retry', () => {
849-
const originalClerk = window.Clerk;
850-
851-
afterEach(() => {
852-
window.Clerk = originalClerk;
853-
});
854-
855-
const submitWithInstantPassword = async (code: string) => {
856-
const { wrapper, fixtures } = await createFixtures(f => {
857-
f.withEmailAddress();
858-
f.withPassword({ required: true });
859-
});
860-
fixtures.signIn.create
861-
.mockRejectedValueOnce(
862-
new ClerkAPIResponseError('Error', {
863-
data: [{ code, long_message: '', message: '', meta: { param_name: 'password' } }],
864-
status: 422,
865-
}),
866-
)
867-
.mockReturnValueOnce(Promise.resolve({ status: 'needs_first_factor' } as SignInResource));
868-
window.Clerk = {} as typeof window.Clerk;
869-
870-
const { userEvent, container } = render(<SignInStart />, { wrapper });
871-
await userEvent.type(screen.getByLabelText(/email address/i), 'hello@clerk.com');
872-
fireEvent.change(container.querySelector('#password-field') as Element, {
873-
target: { value: 'some-password' },
874-
});
875-
fireEvent.submit(container.querySelector('form') as Element);
876-
877-
await waitFor(() => expect(fixtures.router.navigate).toHaveBeenCalledWith('factor-one'));
878-
};
879-
880-
it('passes a required password reset on to the next step', async () => {
881-
await submitWithInstantPassword('password_reset_required');
882-
883-
expect(window.Clerk?.__internal_last_error).toMatchObject({ code: 'password_reset_required' });
884-
});
885-
886-
it('passes no error on to the next step for a breached password', async () => {
887-
await submitWithInstantPassword('form_password_pwned');
888-
889-
expect(window.Clerk?.__internal_last_error).toBeUndefined();
890-
});
891-
});
892847
});
893848

894849
describe('Instant password field a11y', () => {

‎packages/ui/src/components/SignUp/__tests__/SignUpActionBlocked.test.tsx‎

Lines changed: 4 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
11
import { ClerkAPIResponseError } from '@clerk/shared/error';
22
import type { ClerkAPIErrorJSON } from '@clerk/shared/types';
3-
import { afterEach, describe, expect, it } from 'vitest';
3+
import { describe, expect, it } from 'vitest';
44

55
import { bindCreateFixtures } from '@/test/create-fixtures';
66
import { render, screen } from '@/test/utils';
7+
import { showErrorOnNextCard } from '@/ui/elements/contexts';
78

89
import { SignUpStart } from '../SignUpStart';
910

@@ -16,11 +17,6 @@ const blockedError = (meta?: ClerkAPIErrorJSON['meta']) =>
1617
});
1718

1819
describe('a blocked sign-up', () => {
19-
const originalClerk = window.Clerk;
20-
afterEach(() => {
21-
window.Clerk = originalClerk;
22-
});
23-
2420
it('replaces the start form with the blocked screen', async () => {
2521
const { wrapper, fixtures } = await createFixtures(f => {
2622
f.withEmailAddress({ required: true });
@@ -38,17 +34,10 @@ describe('a blocked sign-up', () => {
3834
});
3935

4036
it('shows the blocked screen rather than the restricted-access screen', async () => {
41-
const { wrapper } = await createFixtures(f => {
37+
const { wrapper, fixtures } = await createFixtures(f => {
4238
f.withRestrictedMode();
4339
});
44-
let lastError: unknown = blockedError({ trace_id: '7Q8ikxgt' }).errors[0];
45-
window.Clerk = {
46-
get __internal_last_error() {
47-
const value = lastError;
48-
lastError = null;
49-
return value;
50-
},
51-
} as typeof window.Clerk;
40+
showErrorOnNextCard(fixtures.clerk, blockedError({ trace_id: '7Q8ikxgt' }).errors[0]);
5241

5342
render(<SignUpStart />, { wrapper });
5443

‎packages/ui/src/elements/contexts/__tests__/cardState.test.tsx‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,11 @@ vi.mock('@/ui/router', () => ({
1515
useRouter: () => ({ currentPath: '/' }),
1616
}));
1717

18+
vi.mock('@clerk/shared/react', async importOriginal => ({
19+
...(await importOriginal<typeof import('@clerk/shared/react')>()),
20+
useClerk: () => ({}),
21+
}));
22+
1823
const blocked: ClerkAPIError = {
1924
code: 'action_blocked',
2025
message: 'Action blocked',

0 commit comments

Comments
 (0)