Skip to content

Commit 917748a

Browse files
authored
fix(clerk-js): preserve trusted clients after satellite sign-out (#10470)
1 parent 7569f02 commit 917748a

24 files changed

Lines changed: 726 additions & 67 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'@clerk/clerk-js': patch
3+
'@clerk/shared': patch
4+
'@clerk/ui': patch
5+
---
6+
7+
Fixes signing out of all accounts on satellite domains to preserve device recognition when Device Trust and client persistence are enabled. Preserves existing navigation callbacks when cross-domain repair is unavailable, and skips the repair redirect when Device Trust or client persistence is disabled. Malformed redirect URLs no longer prevent the sign-out request.

‎packages/clerk-js/bundlewatch.config.json‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,9 +2,9 @@
22
"files": [
33
{ "path": "./dist/clerk.js", "maxSize": "556KB" },
44
{ "path": "./dist/clerk.browser.js", "maxSize": "83KB" },
5-
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "126KB" },
5+
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "128KB" },
66
{ "path": "./dist/clerk.no-rhc.js", "maxSize": "324KB" },
7-
{ "path": "./dist/clerk.native.js", "maxSize": "82.5KB" },
7+
{ "path": "./dist/clerk.native.js", "maxSize": "84KB" },
88
{ "path": "./dist/vendors*.js", "maxSize": "7KB" },
99
{ "path": "./dist/coinbase*.js", "maxSize": "36KB" },
1010
{ "path": "./dist/base-account-sdk*.js", "maxSize": "207KB" },

‎packages/clerk-js/src/core/__tests__/clerk.test.ts‎

Lines changed: 326 additions & 0 deletions
Large diffs are not rendered by default.

‎packages/clerk-js/src/core/clerk.ts‎

Lines changed: 42 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -37,6 +37,7 @@ import {
3737
navigateIfTaskExists,
3838
warnMissingPendingTaskHandlers,
3939
} from '@clerk/shared/internal/clerk-js/sessionTasks';
40+
import { isValidUrl } from '@clerk/shared/internal/clerk-js/url';
4041
import { warnings } from '@clerk/shared/internal/clerk-js/warnings';
4142
import { windowNavigate } from '@clerk/shared/internal/clerk-js/windowNavigate';
4243
import { parsePublishableKey } from '@clerk/shared/keys';
@@ -748,26 +749,34 @@ export class Clerk implements ClerkInterface {
748749
const opts = callbackOrOptions && typeof callbackOrOptions === 'object' ? callbackOrOptions : options || {};
749750

750751
const redirectUrl = opts?.redirectUrl || this.buildAfterSignOutUrl();
752+
let debugRedirectUrl: string | undefined;
753+
try {
754+
debugRedirectUrl = stripOrigin(redirectUrl);
755+
} catch {
756+
debugRedirectUrl = undefined;
757+
}
751758
debugLogger.debug(
752759
'signOut() start',
753760
{
754761
hasClient: Boolean(this.client),
755762
multiSessionCount: this.client?.signedInSessions.length ?? 0,
756-
redirectUrl,
763+
redirectUrl: debugRedirectUrl,
757764
sessionTarget: opts?.sessionId ?? null,
758765
},
759766
'clerk',
760767
);
761768
const signOutCallback = typeof callbackOrOptions === 'function' ? callbackOrOptions : undefined;
762769

763-
const executeSignOut = async () => {
770+
const executeSignOut = async (signOutUrl?: string) => {
764771
const tracker = createBeforeUnloadTracker(this.#options.standardBrowser);
765772

766773
// Notify other tabs that user is signing out and clean up cookies.
767774
eventBus.emit(events.UserSignOut, null);
768775

769776
await tracker.track(async () => {
770-
if (signOutCallback) {
777+
if (signOutUrl) {
778+
await this.navigate(signOutUrl);
779+
} else if (signOutCallback) {
771780
await signOutCallback();
772781
} else {
773782
// The client outlives sign-out and is what Client Trust uses to recognize a
@@ -795,8 +804,33 @@ export class Clerk implements ClerkInterface {
795804
if (!opts.sessionId || this.client.signedInSessions.length === 1) {
796805
this.#setTransitiveState();
797806

807+
const persistClient = this.#options.experimental?.persistClient ?? true;
808+
let repairRedirectUrl: URL | undefined;
809+
if (
810+
persistClient &&
811+
(!signOutCallback || !!opts.__internal_satelliteSignOutRedirectUrl) &&
812+
this.#instanceType === 'production' &&
813+
this.#options.standardBrowser &&
814+
inBrowser() &&
815+
typeof window.location !== 'undefined' &&
816+
this.isSatellite
817+
) {
818+
try {
819+
const target = new URL(opts.__internal_satelliteSignOutRedirectUrl || redirectUrl, window.location.href);
820+
if (target.protocol === 'https:' && !target.username && !target.password) {
821+
repairRedirectUrl = target;
822+
}
823+
} catch {
824+
repairRedirectUrl = undefined;
825+
}
826+
}
827+
let signOutUrl: string | undefined;
798828
try {
799-
if (this.#options.experimental?.persistClient ?? true) {
829+
if (repairRedirectUrl && Client.isClientResource(this.client)) {
830+
({ signOutUrl } = await this.client.__internal_signOut({
831+
redirectUrl: repairRedirectUrl.href,
832+
}));
833+
} else if (persistClient) {
800834
await this.client.removeSessions();
801835
} else {
802836
await this.client.destroy();
@@ -807,9 +841,10 @@ export class Clerk implements ClerkInterface {
807841
}
808842
}
809843

810-
await executeSignOut();
844+
const repairUrl = isValidUrl(signOutUrl) && signOutUrl?.startsWith('https://') ? signOutUrl : undefined;
845+
await executeSignOut(repairUrl);
811846

812-
debugLogger.info('signOut() complete', { redirectUrl: stripOrigin(redirectUrl) }, 'clerk');
847+
debugLogger.info('signOut() complete', { redirectUrl: debugRedirectUrl }, 'clerk');
813848
return;
814849
}
815850

@@ -821,7 +856,7 @@ export class Clerk implements ClerkInterface {
821856
this.#setTransitiveState();
822857
await session?.remove();
823858
await executeSignOut();
824-
debugLogger.info('signOut() complete', { redirectUrl: stripOrigin(redirectUrl) }, 'clerk');
859+
debugLogger.info('signOut() complete', { redirectUrl: debugRedirectUrl }, 'clerk');
825860
} else {
826861
await session?.remove();
827862
}

‎packages/clerk-js/src/core/fapiClient.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -43,6 +43,7 @@ export type FapiRequestCallback<T> = (request: FapiRequestInit, response?: FapiR
4343
export interface FapiResponseJSON<T> {
4444
response: T;
4545
client?: ClientJSON;
46+
sign_out_url?: string;
4647
errors?: ClerkAPIErrorJSON[];
4748
meta?: {
4849
client?: ClientJSON;

‎packages/clerk-js/src/core/resources/Client.ts‎

Lines changed: 24 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -82,15 +82,7 @@ export class Client extends BaseResource implements ClientResource {
8282
// TODO: Make it restful by introducing a DELETE /client/:id endpoint
8383
return this._baseDelete({ path: '/client' }).then(() => {
8484
SessionTokenCache.clear();
85-
this.id = '';
86-
this.sessions = [];
87-
this.signUp = new SignUp(null);
88-
this.signIn = new SignIn(null);
89-
this.lastActiveSessionId = null;
90-
this.lastAuthenticationStrategy = null;
91-
this.cookieExpiresAt = null;
92-
this.createdAt = null;
93-
this.updatedAt = null;
85+
this.resetClient();
9486
});
9587
}
9688

@@ -103,6 +95,29 @@ export class Client extends BaseResource implements ClientResource {
10395
});
10496
}
10597

98+
async __internal_signOut({ redirectUrl }: { redirectUrl: string }): Promise<{ signOutUrl?: string }> {
99+
const json = await BaseResource._fetch<ClientJSON>({
100+
method: 'DELETE',
101+
path: this.path() + '/sessions',
102+
search: { sign_out_redirect_url: redirectUrl },
103+
});
104+
this.fromJSON((json?.response || json) as ClientJSON | null);
105+
SessionTokenCache.clear();
106+
return { signOutUrl: json?.sign_out_url };
107+
}
108+
109+
private resetClient(): void {
110+
this.id = '';
111+
this.sessions = [];
112+
this.signUp = new SignUp(null);
113+
this.signIn = new SignIn(null);
114+
this.lastActiveSessionId = null;
115+
this.lastAuthenticationStrategy = null;
116+
this.cookieExpiresAt = null;
117+
this.createdAt = null;
118+
this.updatedAt = null;
119+
}
120+
106121
resetSignIn(): void {
107122
this.signIn = new SignIn(null);
108123
// Cast needed because this.signIn is typed as SignInResource (interface), not SignIn (class extending BaseResource)

‎packages/clerk-js/src/core/resources/__tests__/Client.test.ts‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest';
33

44
import { createSession, createSignIn, createSignUp, createUser } from '@/test/core-fixtures';
55

6+
import { SessionTokenCache } from '../../tokenCache';
67
import { BaseResource, Client } from '../internal';
78

89
const FIXED_DATE = new Date('2025-01-01T00:00:00Z');
@@ -148,6 +149,72 @@ describe('Client Singleton', () => {
148149
});
149150
});
150151

152+
describe('__internal_signOut', () => {
153+
it('returns the response URL and clears sessions while retaining the client', async () => {
154+
const user = createUser({ id: 'user_1' });
155+
const initial: ClientJSON = {
156+
object: 'client',
157+
id: 'client_before',
158+
sessions: [createSession({ id: 'session_1' }, user)],
159+
sign_in: createSignIn({ id: 'sign_in_before' }, user),
160+
sign_up: createSignUp({ id: 'sign_up_before' }),
161+
last_active_session_id: 'session_1',
162+
last_authentication_strategy: 'password',
163+
cookie_expires_at: Date.now() + 30 * 24 * 60 * 60 * 1000,
164+
created_at: Date.now() - 1000,
165+
updated_at: Date.now(),
166+
};
167+
const response = { ...initial, id: 'client_after', sessions: [], last_active_session_id: null };
168+
const request = vi.fn().mockResolvedValue({ response, sign_out_url: 'https://primary.test/sign-out' });
169+
BaseResource._fetch = request;
170+
const clearCache = vi.spyOn(SessionTokenCache, 'clear');
171+
const client = Client.getOrCreateInstance().fromJSON(initial);
172+
const result = await client.__internal_signOut({
173+
redirectUrl: 'https://satellite.test/after?tab=security#settings',
174+
});
175+
176+
expect(request).toHaveBeenCalledWith({
177+
method: 'DELETE',
178+
path: '/client/sessions',
179+
search: { sign_out_redirect_url: 'https://satellite.test/after?tab=security#settings' },
180+
});
181+
expect(result).toEqual({ signOutUrl: 'https://primary.test/sign-out' });
182+
expect(clearCache).toHaveBeenCalledOnce();
183+
expect(client.sessions).toEqual([]);
184+
expect(client.id).toBe('client_after');
185+
expect(client.signIn.id).toBe('sign_in_before');
186+
expect(client.signUp.id).toBe('sign_up_before');
187+
expect(client.lastActiveSessionId).toBeNull();
188+
expect(client.lastAuthenticationStrategy).toBe('password');
189+
expect(client.cookieExpiresAt).toEqual(new Date(initial.cookie_expires_at!));
190+
expect(client.createdAt).toEqual(new Date(initial.created_at!));
191+
expect(client.updatedAt).toEqual(new Date(initial.updated_at!));
192+
clearCache.mockRestore();
193+
});
194+
195+
it.each([null, { response: null }])('accepts a response without a sign-out URL', async response => {
196+
BaseResource._fetch = vi.fn().mockResolvedValue(response);
197+
const result = await Client.getOrCreateInstance().__internal_signOut({
198+
redirectUrl: 'https://satellite.test/',
199+
});
200+
expect(result).toEqual({ signOutUrl: undefined });
201+
});
202+
203+
it('does not reuse the URL from an earlier request', async () => {
204+
BaseResource._fetch = vi
205+
.fn()
206+
.mockResolvedValueOnce({ response: null, sign_out_url: 'https://primary.test/sign-out' })
207+
.mockResolvedValueOnce(null);
208+
const client = Client.getOrCreateInstance();
209+
expect(await client.__internal_signOut({ redirectUrl: 'https://satellite.test/' })).toEqual({
210+
signOutUrl: 'https://primary.test/sign-out',
211+
});
212+
expect(await client.__internal_signOut({ redirectUrl: 'https://satellite.test/' })).toEqual({
213+
signOutUrl: undefined,
214+
});
215+
});
216+
});
217+
151218
it('preserves sign up and sign in identity when fromJSON receives matching ids', () => {
152219
const user = createUser({ first_name: 'John', last_name: 'Doe', id: 'user_1' });
153220
const session = createSession({ id: 'session_1' }, user);

‎packages/shared/src/types/clerk.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -201,6 +201,8 @@ export type SignOutCallback = () => void | Promise<any>;
201201
* Configuration options.
202202
*/
203203
export type SignOutOptions = {
204+
/** @internal */
205+
__internal_satelliteSignOutRedirectUrl?: string;
204206
/**
205207
* Specify a specific session to sign out. Useful for multi-session applications.
206208
*/

‎packages/ui/bundlewatch.config.json‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
{ "path": "./dist/ui.shared.browser.js", "maxSize": "44KB" },
66
{ "path": "./dist/framework*.js", "maxSize": "44KB" },
77
{ "path": "./dist/vendors*.js", "maxSize": "73KB" },
8-
{ "path": "./dist/ui-common*.js", "maxSize": "140KB" },
8+
{ "path": "./dist/ui-common*.js", "maxSize": "141KB" },
99
{ "path": "./dist/signin*.js", "maxSize": "19KB" },
1010
{ "path": "./dist/signup*.js", "maxSize": "13KB" },
1111
{ "path": "./dist/userprofile*.js", "maxSize": "16KB" },

‎packages/ui/src/components/ImpersonationFab/__tests__/ImpersonationFab.test.tsx‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,7 @@ describe('ImpersonationFab', () => {
7777
it('keeps the sign-out action clickable', async () => {
7878
const { fixtures, getByText, userEvent } = await renderDraggableFab();
7979
await userEvent.click(getByText('Sign out'));
80-
expect(fixtures.clerk.signOut).toHaveBeenCalled();
80+
expect(fixtures.clerk.signOut).toHaveBeenCalledExactlyOnceWith(expect.any(Function));
8181
});
8282

8383
it('settles inside the viewport inset when released off-screen', async () => {

0 commit comments

Comments
 (0)