Skip to content

Commit cb76aa2

Browse files
author
Jacek Radko
authored
fix(clerk-js): validate window navigation protocols and honor allowedRedirectProtocols (#8961)
1 parent 497774b commit cb76aa2

17 files changed

Lines changed: 481 additions & 25 deletions

File tree

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'@clerk/clerk-js': patch
3+
'@clerk/react': patch
4+
'@clerk/shared': patch
5+
'@clerk/ui': patch
6+
---
7+
8+
Fix missing redirect URL protocol validation for Clerk UI browser navigations, including the multi-session add-account flow.
9+
10+
Internal browser navigations now consistently honor configured redirect protocols and fail closed across mixed ClerkJS/UI bundle versions.

‎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": "549KB" },
44
{ "path": "./dist/clerk.browser.js", "maxSize": "74KB" },
5-
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "115KB" },
5+
{ "path": "./dist/clerk.legacy.browser.js", "maxSize": "116KB" },
66
{ "path": "./dist/clerk.no-rhc.js", "maxSize": "316KB" },
7-
{ "path": "./dist/clerk.native.js", "maxSize": "73KB" },
7+
{ "path": "./dist/clerk.native.js", "maxSize": "74KB" },
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/clerk.ts‎

Lines changed: 18 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1916,7 +1916,7 @@ export class Clerk implements ClerkInterface {
19161916

19171917
if (customNavigate) {
19181918
debugLogger.info(`Clerk is navigating to: ${to}`);
1919-
return await customNavigate(to, { windowNavigate });
1919+
return await customNavigate(to, { windowNavigate: this.__internal_windowNavigate });
19201920
}
19211921

19221922
// No window.location and no custom router - can't navigate
@@ -1955,13 +1955,13 @@ export class Clerk implements ClerkInterface {
19551955

19561956
// Custom protocol URLs have an origin value of 'null'. In many cases, this indicates deep-linking and we want to ensure the customNavigate function is used if available.
19571957
if ((toURL.origin !== 'null' && toURL.origin !== window.location.origin) || !customNavigate) {
1958-
windowNavigate(toURL);
1958+
this.__internal_windowNavigate(toURL);
19591959
return;
19601960
}
19611961

19621962
const metadata = {
19631963
...(options?.metadata ? { __internal_metadata: options?.metadata } : {}),
1964-
windowNavigate,
1964+
windowNavigate: this.__internal_windowNavigate,
19651965
};
19661966
// React router only wants the path, search or hash portion.
19671967
return await customNavigate(stripOrigin(toURL), metadata);
@@ -3578,6 +3578,21 @@ export class Clerk implements ClerkInterface {
35783578
return allowedProtocols;
35793579
}
35803580

3581+
/**
3582+
* Primary `window.location.href` navigation chokepoint for `@clerk/clerk-js` and `@clerk/ui`.
3583+
* By default the resolved URL is validated against the customer-supplied
3584+
* `allowedRedirectProtocols` option (the static `ALLOWED_PROTOCOLS` ∪ the customer extension),
3585+
* so internal callers honor customer protocols automatically.
3586+
*
3587+
* Pass `useStaticAllowlistOnly: true` to opt out of the customer extension when a call site
3588+
* must reject any protocol the customer added. There is no current internal consumer of the
3589+
* opt-out; it exists for future security-critical paths.
3590+
*/
3591+
public __internal_windowNavigate = (to: URL | string, opts?: { useStaticAllowlistOnly?: boolean }): void => {
3592+
const allowedProtocols = opts?.useStaticAllowlistOnly ? ALLOWED_PROTOCOLS : this.#allowedRedirectProtocols;
3593+
windowNavigate(to, { allowedProtocols });
3594+
};
3595+
35813596
#isLoaded(): this is LoadedClerk {
35823597
return this.client !== undefined;
35833598
}

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@ import {
77
} from '@clerk/shared/internal/clerk-js/passkeys';
88
import { createValidatePassword } from '@clerk/shared/internal/clerk-js/passwords/password';
99
import { getClerkQueryParam } from '@clerk/shared/internal/clerk-js/queryParams';
10-
import { windowNavigate } from '@clerk/shared/internal/clerk-js/windowNavigate';
1110
import { Poller } from '@clerk/shared/poller';
1211
import type {
1312
AttemptFirstFactorParams,
@@ -392,7 +391,7 @@ export class SignIn extends BaseResource implements SignInResource {
392391
});
393392
}
394393

395-
return this.authenticateWithRedirectOrPopup(params, windowNavigate);
394+
return this.authenticateWithRedirectOrPopup(params, SignIn.clerk.__internal_windowNavigate);
396395
};
397396

398397
public authenticateWithPopup = async (params: AuthenticateWithPopupParams): Promise<void> => {
@@ -1199,7 +1198,7 @@ class SignInFuture implements SignInFutureResource {
11991198
// Pick up the modified SignIn resource
12001199
await this.#resource.reload();
12011200
} else {
1202-
windowNavigate(externalVerificationRedirectURL);
1201+
SignIn.clerk.__internal_windowNavigate(externalVerificationRedirectURL);
12031202
}
12041203
}
12051204
});

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

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
import { inBrowser } from '@clerk/shared/browser';
22
import { type ClerkError, ClerkRuntimeError, isCaptchaError, isClerkAPIResponseError } from '@clerk/shared/error';
33
import { createValidatePassword } from '@clerk/shared/internal/clerk-js/passwords/password';
4-
import { windowNavigate } from '@clerk/shared/internal/clerk-js/windowNavigate';
54
import { Poller } from '@clerk/shared/poller';
65
import type {
76
AttemptEmailAddressVerificationParams,
@@ -462,7 +461,7 @@ export class SignUp extends BaseResource implements SignUpResource {
462461
});
463462
}
464463

465-
return this.authenticateWithRedirectOrPopup(params, windowNavigate);
464+
return this.authenticateWithRedirectOrPopup(params, SignUp.clerk.__internal_windowNavigate);
466465
};
467466

468467
public authenticateWithPopup = async (
@@ -1082,7 +1081,7 @@ class SignUpFuture implements SignUpFutureResource {
10821081
// Pick up the modified SignUp resource
10831082
await this.#resource.reload();
10841083
} else {
1085-
windowNavigate(externalVerificationRedirectURL);
1084+
SignUp.clerk.__internal_windowNavigate(externalVerificationRedirectURL);
10861085
}
10871086
}
10881087
});

‎packages/react/src/__tests__/isomorphicClerk.test.ts‎

Lines changed: 90 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,4 +434,94 @@ describe('isomorphicClerk', () => {
434434
);
435435
});
436436
});
437+
438+
describe('__internal_windowNavigate', () => {
439+
let originalLocation: Location;
440+
let hrefSetter: ReturnType<typeof vi.fn>;
441+
let warnSpy: ReturnType<typeof vi.spyOn>;
442+
443+
beforeEach(() => {
444+
originalLocation = window.location;
445+
hrefSetter = vi.fn();
446+
Object.defineProperty(window, 'location', {
447+
configurable: true,
448+
value: new Proxy(
449+
{ href: 'https://example.com/' },
450+
{
451+
set: (target, prop, value) => {
452+
if (prop === 'href') {
453+
hrefSetter(value);
454+
}
455+
(target as any)[prop] = value;
456+
return true;
457+
},
458+
},
459+
),
460+
});
461+
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
462+
});
463+
464+
afterEach(() => {
465+
Object.defineProperty(window, 'location', { configurable: true, value: originalLocation });
466+
warnSpy.mockRestore();
467+
});
468+
469+
it('delegates to clerk-js when the navigation chokepoint is available', () => {
470+
const navigate = vi.fn();
471+
const isomorphicClerk = new IsomorphicClerk({ publishableKey: 'pk_test_XXX' });
472+
(isomorphicClerk as any).clerkjs = { __internal_windowNavigate: navigate };
473+
474+
isomorphicClerk.__internal_windowNavigate('/sign-in', { useStaticAllowlistOnly: true });
475+
476+
expect(navigate).toHaveBeenCalledWith('/sign-in', { useStaticAllowlistOnly: true });
477+
expect(hrefSetter).not.toHaveBeenCalled();
478+
});
479+
480+
it('falls back to navigation when clerk-js is older and lacks the chokepoint', () => {
481+
const isomorphicClerk = new IsomorphicClerk({ publishableKey: 'pk_test_XXX' });
482+
// An older clerk-js that does not expose __internal_windowNavigate.
483+
(isomorphicClerk as any).clerkjs = {};
484+
485+
isomorphicClerk.__internal_windowNavigate('/sign-in');
486+
487+
expect(hrefSetter).toHaveBeenCalledWith('https://example.com/sign-in');
488+
expect(warnSpy).not.toHaveBeenCalled();
489+
});
490+
491+
it('fallback honors the customer-supplied allowedRedirectProtocols option', () => {
492+
const isomorphicClerk = new IsomorphicClerk({
493+
publishableKey: 'pk_test_XXX',
494+
allowedRedirectProtocols: ['slack:'],
495+
});
496+
(isomorphicClerk as any).clerkjs = {};
497+
498+
isomorphicClerk.__internal_windowNavigate('slack://channel/123');
499+
500+
expect(hrefSetter).toHaveBeenCalledWith('slack://channel/123');
501+
expect(warnSpy).not.toHaveBeenCalled();
502+
});
503+
504+
it('fallback fails closed for disallowed protocols', () => {
505+
const isomorphicClerk = new IsomorphicClerk({ publishableKey: 'pk_test_XXX' });
506+
(isomorphicClerk as any).clerkjs = {};
507+
508+
isomorphicClerk.__internal_windowNavigate('javascript:alert(1)');
509+
510+
expect(hrefSetter).not.toHaveBeenCalled();
511+
expect(warnSpy).toHaveBeenCalledTimes(1);
512+
});
513+
514+
it('fallback ignores customer protocols when useStaticAllowlistOnly is set', () => {
515+
const isomorphicClerk = new IsomorphicClerk({
516+
publishableKey: 'pk_test_XXX',
517+
allowedRedirectProtocols: ['slack:'],
518+
});
519+
(isomorphicClerk as any).clerkjs = {};
520+
521+
isomorphicClerk.__internal_windowNavigate('slack://channel/123', { useStaticAllowlistOnly: true });
522+
523+
expect(hrefSetter).not.toHaveBeenCalled();
524+
expect(warnSpy).toHaveBeenCalledTimes(1);
525+
});
526+
});
437527
});

‎packages/react/src/isomorphicClerk.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { inBrowser } from '@clerk/shared/browser';
22
import { clerkEvents, createClerkEventBus } from '@clerk/shared/clerkEventBus';
3+
import { ALLOWED_PROTOCOLS, windowNavigate } from '@clerk/shared/internal/clerk-js/windowNavigate';
34
import { loadClerkJSScript, loadClerkUIScript } from '@clerk/shared/loadClerkJsScript';
45
import type {
56
__internal_AttemptToEnableEnvironmentSettingParams,
@@ -265,6 +266,25 @@ export class IsomorphicClerk implements IsomorphicLoadedClerk {
265266
return this.clerkjs?.__internal_getOption ? this.clerkjs?.__internal_getOption(key) : this.options[key];
266267
}
267268

269+
public __internal_windowNavigate: Clerk['__internal_windowNavigate'] = (to, opts) => {
270+
const clerkjs = this.clerkjs;
271+
if (typeof clerkjs?.__internal_windowNavigate === 'function') {
272+
clerkjs.__internal_windowNavigate(to, opts);
273+
return;
274+
}
275+
276+
// Older clerk-js lacks this navigation chokepoint, so delegating would silently no-op. Fall back to
277+
// the shared helper (browser-only, it touches window.location) so newer @clerk/ui still navigates and
278+
// rejects disallowed protocols on an older clerk-js, honoring allowedRedirectProtocols unless opted out.
279+
if (!inBrowser()) {
280+
return;
281+
}
282+
const allowedProtocols = opts?.useStaticAllowlistOnly
283+
? ALLOWED_PROTOCOLS
284+
: [...ALLOWED_PROTOCOLS, ...(this.options.allowedRedirectProtocols ?? [])];
285+
windowNavigate(to, { allowedProtocols });
286+
};
287+
268288
constructor(options: IsomorphicClerkOptions) {
269289
this.#publishableKey = options?.publishableKey;
270290
this.#proxyUrl = options?.proxyUrl;
Lines changed: 132 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,132 @@
1+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
2+
3+
import { ALLOWED_PROTOCOLS, CLERK_BEFORE_UNLOAD_EVENT, windowNavigate } from '../windowNavigate';
4+
5+
describe('windowNavigate', () => {
6+
let originalLocation: Location;
7+
let hrefSetter: ReturnType<typeof vi.fn>;
8+
let warnSpy: ReturnType<typeof vi.spyOn>;
9+
let eventSpy: ReturnType<typeof vi.fn>;
10+
11+
beforeEach(() => {
12+
originalLocation = window.location;
13+
hrefSetter = vi.fn();
14+
Object.defineProperty(window, 'location', {
15+
configurable: true,
16+
value: new Proxy(
17+
{ href: 'https://example.com/' },
18+
{
19+
set: (target, prop, value) => {
20+
if (prop === 'href') {
21+
hrefSetter(value);
22+
(target as any).href = value;
23+
return true;
24+
}
25+
(target as any)[prop] = value;
26+
return true;
27+
},
28+
},
29+
),
30+
});
31+
warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
32+
eventSpy = vi.fn();
33+
window.addEventListener(CLERK_BEFORE_UNLOAD_EVENT, eventSpy);
34+
});
35+
36+
afterEach(() => {
37+
window.removeEventListener(CLERK_BEFORE_UNLOAD_EVENT, eventSpy);
38+
Object.defineProperty(window, 'location', {
39+
configurable: true,
40+
value: originalLocation,
41+
});
42+
warnSpy.mockRestore();
43+
});
44+
45+
it.each([
46+
['absolute https URL', 'https://example.com/dashboard'],
47+
['absolute http URL', 'http://example.com/dashboard'],
48+
['relative path', '/sign-in'],
49+
['wails protocol', 'wails://app/route'],
50+
['chrome-extension protocol', 'chrome-extension://abc/route'],
51+
])('navigates to %s', (_label, to) => {
52+
windowNavigate(to);
53+
expect(hrefSetter).toHaveBeenCalledTimes(1);
54+
expect(eventSpy).toHaveBeenCalledTimes(1);
55+
expect(warnSpy).not.toHaveBeenCalled();
56+
});
57+
58+
it.each([
59+
['javascript', 'javascript:alert(1)'],
60+
['data', 'data:text/html,<script>alert(1)</script>'],
61+
['file', 'file:///etc/passwd'],
62+
['vbscript', 'vbscript:msgbox(1)'],
63+
['mixed-case JavaScript', 'JavaScript:alert(1)'],
64+
['upper-case JAVASCRIPT', 'JAVASCRIPT:alert(1)'],
65+
['leading-whitespace javascript', ' javascript:alert(1)'],
66+
['leading-tab javascript', '\tjavascript:alert(1)'],
67+
['leading-newline javascript', '\njavascript:alert(1)'],
68+
])('blocks %s: protocol and does not navigate', (_label, to) => {
69+
windowNavigate(to);
70+
expect(hrefSetter).not.toHaveBeenCalled();
71+
expect(eventSpy).not.toHaveBeenCalled();
72+
expect(warnSpy).toHaveBeenCalledTimes(1);
73+
});
74+
75+
it('blocks javascript: URLs that the URL parser normalizes via the base URL', () => {
76+
windowNavigate('javascript:alert(location.origin)//');
77+
expect(hrefSetter).not.toHaveBeenCalled();
78+
expect(eventSpy).not.toHaveBeenCalled();
79+
expect(warnSpy).toHaveBeenCalledTimes(1);
80+
});
81+
82+
it.each([
83+
['scheme-relative //host', '//evil.example/path'],
84+
['scheme-relative ///host', '///evil.example/path'],
85+
['backslash \\\\host', '\\\\evil.example\\path'],
86+
['mixed /\\host', '/\\evil.example/path'],
87+
['mixed \\/host', '\\/evil.example/path'],
88+
['leading-whitespace scheme-relative', ' //evil.example/path'],
89+
['leading-tab scheme-relative', '\t//evil.example/path'],
90+
// Control characters the URL parser strips but `trim()` does not: each still resolves
91+
// scheme-relative against the base origin, so the guard must normalize before testing.
92+
['interior-tab scheme-relative', '/\t/evil.example/path'],
93+
['interior-newline scheme-relative', '/\n/evil.example/path'],
94+
['interior-cr scheme-relative', '/\r/evil.example/path'],
95+
['interior-tab backslash', '\\\t\\evil.example/path'],
96+
['leading-null scheme-relative', '\x00//evil.example/path'],
97+
['leading-c0-controls scheme-relative', '\x01\x02//evil.example/path'],
98+
])('blocks %s and does not navigate', (_label, to) => {
99+
windowNavigate(to);
100+
expect(hrefSetter).not.toHaveBeenCalled();
101+
expect(eventSpy).not.toHaveBeenCalled();
102+
expect(warnSpy).toHaveBeenCalledTimes(1);
103+
});
104+
105+
it('still rejects scheme-relative URLs when an extended allowlist is supplied', () => {
106+
windowNavigate('//evil.example/path', {
107+
allowedProtocols: [...ALLOWED_PROTOCOLS, 'slack:'],
108+
});
109+
expect(hrefSetter).not.toHaveBeenCalled();
110+
expect(eventSpy).not.toHaveBeenCalled();
111+
expect(warnSpy).toHaveBeenCalledTimes(1);
112+
});
113+
114+
it('honors a caller-supplied extended allowlist for custom protocols', () => {
115+
windowNavigate('slack://channel/123', {
116+
allowedProtocols: [...ALLOWED_PROTOCOLS, 'slack:'],
117+
});
118+
expect(hrefSetter).toHaveBeenCalledTimes(1);
119+
expect(hrefSetter).toHaveBeenCalledWith('slack://channel/123');
120+
expect(eventSpy).toHaveBeenCalledTimes(1);
121+
expect(warnSpy).not.toHaveBeenCalled();
122+
});
123+
124+
it('still rejects disallowed protocols when an extended allowlist is supplied', () => {
125+
windowNavigate('javascript:alert(1)', {
126+
allowedProtocols: [...ALLOWED_PROTOCOLS, 'slack:'],
127+
});
128+
expect(hrefSetter).not.toHaveBeenCalled();
129+
expect(eventSpy).not.toHaveBeenCalled();
130+
expect(warnSpy).toHaveBeenCalledTimes(1);
131+
});
132+
});

0 commit comments

Comments
 (0)