Skip to content
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/metal-geese-double.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/types': patch
---

Fix `UseSessionReturn['session']` JSDocs to not mention active status, since pending sessions are also returned
5 changes: 5 additions & 0 deletions .changeset/yummy-ghosts-share.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Fix SSO callback for after-auth custom flows
112 changes: 112 additions & 0 deletions packages/clerk-js/src/core/__tests__/clerk.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -923,6 +923,118 @@ describe('Clerk singleton', () => {
mockEnvironmentFetch.mockReset();
});

describe('with after-auth flows', () => {
beforeEach(() => {
mockClientFetch.mockReset();
mockEnvironmentFetch.mockReturnValue(
Promise.resolve({
userSettings: mockUserSettings,
displayConfig: mockDisplayConfig,
isSingleSession: () => false,
isProduction: () => false,
isDevelopmentOrStaging: () => true,
organizationSettings: {
forceOrganizationSelection: true,
},
}),
);
});

it('redirects to pending task', async () => {
const mockSession = {
id: '1',
status: 'pending',
user: {},
tasks: [{ key: 'select-organization' }],
currentTask: { key: 'select-organization', __internal_getUrl: () => 'https://sut/tasks/select-organization' },
lastActiveToken: { getRawString: () => 'mocked-token' },
};

const mockResource = {
...mockSession,
remove: jest.fn(),
touch: jest.fn(() => Promise.resolve()),
getToken: jest.fn(),
reload: jest.fn(() => Promise.resolve(mockSession)),
};

mockResource.touch.mockReturnValueOnce(Promise.resolve());
mockClientFetch.mockReturnValue(
Promise.resolve({
signedInSessions: [mockResource],
signIn: new SignIn(null),
signUp: new SignUp({
status: 'complete',
} as any as SignUpJSON),
}),
);

const mockSetActive = jest.fn();
const mockSignUpCreate = jest
.fn()
.mockReturnValue(Promise.resolve({ status: 'complete', createdSessionId: '123' }));

const sut = new Clerk(productionPublishableKey);
await sut.load(mockedLoadOptions);
if (!sut.client) {
fail('we should always have a client');
}
sut.client.signUp.create = mockSignUpCreate;
sut.setActive = mockSetActive;

await sut.handleRedirectCallback();

await waitFor(() => {
expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/tasks/select-organization');
});
});

it('redirects to after sign-in URL when task has been resolved', async () => {
const mockSession = {
id: '1',
status: 'active',
user: {},
lastActiveToken: { getRawString: () => 'mocked-token' },
};

const mockResource = {
...mockSession,
remove: jest.fn(),
touch: jest.fn(() => Promise.resolve()),
getToken: jest.fn(),
reload: jest.fn(() => Promise.resolve(mockSession)),
};

mockResource.touch.mockReturnValueOnce(Promise.resolve());
mockClientFetch.mockReturnValue(
Promise.resolve({
signedInSessions: [mockResource],
signIn: new SignIn(null),
signUp: new SignUp(null),
}),
);

const mockSetActive = jest.fn();
const mockSignUpCreate = jest
.fn()
.mockReturnValue(Promise.resolve({ status: 'complete', createdSessionId: '123' }));

const sut = new Clerk(productionPublishableKey);
await sut.load(mockedLoadOptions);
if (!sut.client) {
fail('we should always have a client');
}
sut.client.signUp.create = mockSignUpCreate;
sut.setActive = mockSetActive;

await sut.handleRedirectCallback();

await waitFor(() => {
expect(mockNavigate.mock.calls[0][0]).toBe('/');
});
});
});

it('creates a new user and calls setActive if the user was not found during sso signup', async () => {
mockEnvironmentFetch.mockReturnValue(
Promise.resolve({
Expand Down
16 changes: 12 additions & 4 deletions packages/clerk-js/src/core/clerk.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1879,10 +1879,11 @@ export class Clerk implements ClerkInterface {
};

if (si.status === 'complete') {
return this.setActive({
await this.setActive({
session: si.sessionId,
redirectUrl: redirectUrls.getAfterSignInUrl(),
});
return this.__internal_navigateToTaskIfAvailable();
}

const userExistsButNeedsToSignIn =
Expand All @@ -1892,10 +1893,11 @@ export class Clerk implements ClerkInterface {
const res = await signIn.create({ transfer: true });
switch (res.status) {
case 'complete':
return this.setActive({
await this.setActive({
session: res.createdSessionId,
redirectUrl: redirectUrls.getAfterSignInUrl(),
});
return this.__internal_navigateToTaskIfAvailable();
case 'needs_first_factor':
return navigateToFactorOne();
case 'needs_second_factor':
Expand Down Expand Up @@ -1941,10 +1943,11 @@ export class Clerk implements ClerkInterface {
const res = await signUp.create({ transfer: true });
switch (res.status) {
case 'complete':
return this.setActive({
await this.setActive({
session: res.createdSessionId,
redirectUrl: redirectUrls.getAfterSignUpUrl(),
});
return this.__internal_navigateToTaskIfAvailable();
case 'missing_requirements':
return navigateToNextStepSignUp({ missingFields: res.missingFields });
default:
Expand All @@ -1953,10 +1956,11 @@ export class Clerk implements ClerkInterface {
}

if (su.status === 'complete') {
return this.setActive({
await this.setActive({
session: su.sessionId,
redirectUrl: redirectUrls.getAfterSignUpUrl(),
});
return this.__internal_navigateToTaskIfAvailable();
}

if (si.status === 'needs_second_factor') {
Expand Down Expand Up @@ -1992,6 +1996,10 @@ export class Clerk implements ClerkInterface {
return navigateToNextStepSignUp({ missingFields: signUp.missingFields });
}

if (this.__internal_hasAfterAuthFlows) {
return this.__internal_navigateToTaskIfAvailable({ redirectUrlComplete: redirectUrls.getAfterSignInUrl() });
}

return navigateToSignIn();
};

Expand Down
6 changes: 5 additions & 1 deletion packages/clerk-js/src/core/resources/SignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ import type {
} from '@clerk/types';

import {
buildURL,
generateSignatureWithCoinbaseWallet,
generateSignatureWithMetamask,
generateSignatureWithOKXWallet,
Expand Down Expand Up @@ -239,7 +240,10 @@ export class SignIn extends BaseResource implements SignInResource {
// This ensures organization selection tasks are displayed after sign-in,
// rather than redirecting to potentially unprotected pages while the session is pending.
const actionCompleteRedirectUrl = SignIn.clerk.__internal_hasAfterAuthFlows
? redirectUrlWithAuthToken
? buildURL({
base: redirectUrlWithAuthToken,
search: `?redirect_url=${redirectUrlComplete}`,
}).toString()
: redirectUrlComplete;

if (!this.id || !continueSignIn) {
Expand Down
8 changes: 1 addition & 7 deletions packages/clerk-js/src/ui/common/SSOCallback.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,19 +19,13 @@ export const SSOCallback = withCardStateProvider<HandleOAuthCallbackParams | Han
});

export const SSOCallbackCard = (props: HandleOAuthCallbackParams | HandleSamlCallbackParams) => {
const { handleRedirectCallback, __internal_setActiveInProgress, __internal_navigateToTaskIfAvailable, session } =
useClerk();
const { handleRedirectCallback, __internal_setActiveInProgress } = useClerk();
const { navigate } = useRouter();
const card = useCardState();

React.useEffect(() => {
let timeoutId: ReturnType<typeof setTimeout>;
if (__internal_setActiveInProgress !== true) {
if (session?.currentTask) {
void __internal_navigateToTaskIfAvailable();
return;
}

const intent = new URLSearchParams(window.location.search).get('intent');
const reloadResource = intent === 'signIn' || intent === 'signUp' ? intent : undefined;
handleRedirectCallback({ ...props, reloadResource }, navigate).catch(e => {
Expand Down
2 changes: 1 addition & 1 deletion packages/types/src/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export type UseSessionReturn =
*/
isSignedIn: undefined;
/**
* The current active session for the user.
* The current session for the user.
*/
session: undefined;
}
Expand Down