Skip to content
Open
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/tidy-moose-travel.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'@clerk/clerk-js': patch
---

Use the Frontend API for OAuth popup callbacks so popup authentication no longer depends on the Account Portal hostname.
8 changes: 7 additions & 1 deletion packages/clerk-js/src/core/resources/SignIn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1213,13 +1213,15 @@ class SignInFuture implements SignInFutureResource {
}

const routes = { redirectUrl: SignIn.clerk.buildUrlWithAuth(redirectCallbackUrl), actionCompleteRedirectUrl };
let popupState = '';
if (popup) {
const wrappedRoutes = wrapWithPopupRoutes(SignIn.clerk, {
redirectCallbackUrl: routes.redirectUrl,
redirectUrl: actionCompleteRedirectUrl,
});
routes.redirectUrl = wrappedRoutes.redirectCallbackUrl;
routes.actionCompleteRedirectUrl = wrappedRoutes.redirectUrl;
popupState = wrappedRoutes.state;
}

// Reuse the existing sign-in by default so any state already attached to it carries
Expand Down Expand Up @@ -1259,7 +1261,11 @@ class SignInFuture implements SignInFutureResource {

if (status === 'unverified' && externalVerificationRedirectURL) {
if (popup) {
await _futureAuthenticateWithPopup(SignIn.clerk, { popup, externalVerificationRedirectURL });
await _futureAuthenticateWithPopup(SignIn.clerk, {
popup,
externalVerificationRedirectURL,
state: popupState,
});
// Pick up the modified SignIn resource
await this.#resource.reload();
} else {
Expand Down
8 changes: 7 additions & 1 deletion packages/clerk-js/src/core/resources/SignUp.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1074,13 +1074,15 @@ class SignUpFuture implements SignUpFutureResource {
redirectUrl: SignUp.clerk.buildUrlWithAuth(redirectCallbackUrl),
actionCompleteRedirectUrl: redirectUrlComplete,
};
let popupState = '';
if (popup) {
const wrappedRoutes = wrapWithPopupRoutes(SignUp.clerk, {
redirectCallbackUrl: routes.redirectUrl,
redirectUrl: redirectUrlComplete,
});
routes.redirectUrl = wrappedRoutes.redirectCallbackUrl;
routes.actionCompleteRedirectUrl = wrappedRoutes.redirectUrl;
popupState = wrappedRoutes.state;
}

const authenticateFn = () => {
Expand Down Expand Up @@ -1119,7 +1121,11 @@ class SignUpFuture implements SignUpFutureResource {

if (status === 'unverified' && externalVerificationRedirectURL) {
if (popup) {
await _futureAuthenticateWithPopup(SignUp.clerk, { popup, externalVerificationRedirectURL });
await _futureAuthenticateWithPopup(SignUp.clerk, {
popup,
externalVerificationRedirectURL,
state: popupState,
});
// Pick up the modified SignUp resource
await this.#resource.reload();
} else {
Expand Down
19 changes: 17 additions & 2 deletions packages/clerk-js/src/core/resources/__tests__/SignIn.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,14 @@ vi.mock('../../../utils/authenticateWithPopup', async () => {
// Import the mocked function after mocking
import { _futureAuthenticateWithPopup } from '../../../utils/authenticateWithPopup';

const getFapiClient = () => ({
buildUrl: ({ path, search }: { path: string; search?: Record<string, string> }) => {
const url = new URL(`https://clerk.example.com/v1${path}`);
Object.entries(search ?? {}).forEach(([key, value]) => url.searchParams.set(key, value));
return url;
},
});

// Mock the CaptchaChallenge module
vi.mock('../../../utils/captcha/CaptchaChallenge', () => ({
CaptchaChallenge: vi.fn().mockImplementation(function () {
Expand Down Expand Up @@ -2158,6 +2166,7 @@ describe('SignIn', () => {

SignIn.clerk = {
buildUrlWithAuth: vi.fn().mockReturnValue('https://example.com/sso-callback'),
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2211,6 +2220,7 @@ describe('SignIn', () => {

SignIn.clerk = {
buildUrlWithAuth: vi.fn().mockReturnValue('https://example.com/sso-callback'),
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2249,6 +2259,7 @@ describe('SignIn', () => {

SignIn.clerk = {
buildUrlWithAuth: vi.fn().mockReturnValue('https://example.com/sso-callback'),
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2372,6 +2383,7 @@ describe('SignIn', () => {
buildUrlWithAuth: mockBuildUrlWithAuth,
buildUrl: vi.fn().mockImplementation(path => 'https://example.com' + path),
frontendApi: 'clerk.example.com',
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2448,6 +2460,7 @@ describe('SignIn', () => {
buildUrlWithAuth: mockBuildUrlWithAuth,
buildUrl: vi.fn().mockImplementation(path => 'https://example.com' + path),
frontendApi: 'clerk.example.com',
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2528,6 +2541,7 @@ describe('SignIn', () => {
buildUrlWithAuth: mockBuildUrlWithAuth,
buildUrl: vi.fn().mockImplementation(path => 'https://example.com' + path),
frontendApi: 'clerk.example.com',
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand Down Expand Up @@ -2577,6 +2591,7 @@ describe('SignIn', () => {
expect.objectContaining({
popup: mockPopup,
externalVerificationRedirectURL: expect.any(URL),
state: expect.stringMatching(/^[0-9a-f]{64}$/),
}),
);
expect(mockPopup.location.href).toBe('https://sso.example.com/auth');
Expand All @@ -2585,8 +2600,8 @@ describe('SignIn', () => {
expect(mockFetch).toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({
redirectUrl: expect.stringContaining('/popup-callback'),
actionCompleteRedirectUrl: expect.stringContaining('/popup-callback'),
redirectUrl: expect.stringContaining('/popup_auth_callback'),
actionCompleteRedirectUrl: expect.stringContaining('/popup_auth_callback'),
}),
}),
);
Expand Down
17 changes: 14 additions & 3 deletions packages/clerk-js/src/core/resources/__tests__/SignUp.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,14 @@ vi.mock('../../../utils/authenticateWithPopup', async () => {

// Import the mocked function after mocking
import { _futureAuthenticateWithPopup } from '../../../utils/authenticateWithPopup';

const getFapiClient = () => ({
buildUrl: ({ path, search }: { path: string; search?: Record<string, string> }) => {
const url = new URL(`https://clerk.example.com/v1${path}`);
Object.entries(search ?? {}).forEach(([key, value]) => url.searchParams.set(key, value));
return url;
},
});
import { CaptchaChallenge } from '../../../utils/captcha/CaptchaChallenge';

// Mock the CaptchaChallenge module
Expand Down Expand Up @@ -1009,6 +1017,7 @@ describe('SignUp', () => {
buildUrlWithAuth: mockBuildUrlWithAuth,
buildUrl: vi.fn().mockImplementation(path => 'https://example.com' + path),
frontendApi: 'clerk.example.com',
getFapiClient,
__internal_environment: {
displayConfig: {
captchaOauthBypass: [],
Expand All @@ -1031,9 +1040,10 @@ describe('SignUp', () => {
});
BaseResource._fetch = mockFetch;

vi.mocked(_futureAuthenticateWithPopup).mockImplementation(async (_clerk, params) => {
vi.mocked(_futureAuthenticateWithPopup).mockImplementation((_clerk, params) => {
// Simulate the actual behavior of setting popup href
params.popup.location.href = params.externalVerificationRedirectURL.toString();
return Promise.resolve();
});

const signUp = new SignUp();
Expand All @@ -1050,6 +1060,7 @@ describe('SignUp', () => {
expect.objectContaining({
popup: mockPopup,
externalVerificationRedirectURL: expect.any(URL),
state: expect.stringMatching(/^[0-9a-f]{64}$/),
}),
);
expect(mockPopup.location.href).toBe('https://sso.example.com/auth');
Expand All @@ -1058,8 +1069,8 @@ describe('SignUp', () => {
expect(mockFetch).toHaveBeenCalledWith(
expect.objectContaining({
body: expect.objectContaining({
redirectUrl: expect.stringContaining('/popup-callback'),
actionCompleteRedirectUrl: expect.stringContaining('/popup-callback'),
redirectUrl: expect.stringContaining('/popup_auth_callback'),
actionCompleteRedirectUrl: expect.stringContaining('/popup_auth_callback'),
}),
}),
);
Expand Down
141 changes: 141 additions & 0 deletions packages/clerk-js/src/utils/__tests__/authenticateWithPopup.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,141 @@
import { afterEach, describe, expect, it, vi } from 'vitest';

import type { Clerk } from '../../core/clerk';
import { createFapiClient } from '../../core/fapiClient';
import { _authenticateWithPopup, _futureAuthenticateWithPopup, wrapWithPopupRoutes } from '../authenticateWithPopup';

const createClerk = (proxyUrl?: string) => {
const fapiClient = createFapiClient({
frontendApi: 'clerk.example.com',
proxyUrl,
instanceType: 'production',
getSessionId: () => undefined,
});

return {
client: {},
buildUrlWithAuth: vi.fn((url: string) => url),
getFapiClient: () => fapiClient,
} as unknown as Clerk;
};

afterEach(() => {
vi.restoreAllMocks();
});

describe('wrapWithPopupRoutes', () => {
it.each([
[undefined, 'https://clerk.example.com/v1/popup_auth_callback'],
['https://app.example.com/__clerk', 'https://app.example.com/__clerk/v1/popup_auth_callback'],
])('uses the effective FAPI URL when proxyUrl is %s', (proxyUrl, expectedCallbackUrl) => {
const routes = wrapWithPopupRoutes(createClerk(proxyUrl), {
redirectCallbackUrl: 'https://app.example.com/sso-callback',
redirectUrl: 'https://app.example.com/dashboard',
});

const completeUrl = new URL(routes.redirectUrl);
const callbackUrl = new URL(routes.redirectCallbackUrl);

expect(`${completeUrl.origin}${completeUrl.pathname}`).toBe(expectedCallbackUrl);
expect(`${callbackUrl.origin}${callbackUrl.pathname}`).toBe(expectedCallbackUrl);
expect(completeUrl.searchParams.get('state')).toBe(routes.state);
expect(callbackUrl.searchParams.get('state')).toBe(routes.state);
expect(routes.state).toMatch(/^[a-f0-9]{64}$/);
expect(callbackUrl.searchParams.get('return_url')).toContain('https://app.example.com/sso-callback');
});
});

describe('_authenticateWithPopup', () => {
it('only accepts a message from the FAPI origin, expected popup, and generated state', async () => {
const clerk = createClerk();
const popup = { location: { href: '' } } as unknown as Window;
const navigate = vi.fn();
const authenticateMethod = vi.fn().mockResolvedValue(undefined);
Object.assign(clerk, { navigate });

await _authenticateWithPopup(
clerk,
'signIn',
authenticateMethod,
{
popup,
strategy: 'oauth_google',
redirectUrl: 'https://app.example.com/sso-callback',
redirectUrlComplete: 'https://app.example.com/dashboard',
},
vi.fn(),
);

const callbackUrl = new URL(authenticateMethod.mock.calls[0][0].redirectUrl);
const state = callbackUrl.searchParams.get('state');
const returnUrl = callbackUrl.searchParams.get('return_url');

window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://accounts.example.com',
source: popup,
}),
);
expect(navigate).not.toHaveBeenCalled();

window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://clerk.example.com',
source: popup,
}),
);
expect(navigate).toHaveBeenCalledWith(returnUrl);
Comment on lines +73 to +89

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🟡 Minor | ⚡ Quick win

Cover direct popup state and source rejection.

This test only rejects an incorrect origin. Add valid-FAPI-origin events with an incorrect state and incorrect source before the matching event, so regressions in the new _authenticateWithPopup checks cannot permit unintended navigation.

Suggested coverage
+    const otherPopup = { location: { href: '' } } as unknown as Window;
+
+    window.dispatchEvent(
+      new MessageEvent('message', {
+        data: { return_url: returnUrl, state: 'wrong_state' },
+        origin: 'https://clerk.example.com',
+        source: popup,
+      }),
+    );
+    window.dispatchEvent(
+      new MessageEvent('message', {
+        data: { return_url: returnUrl, state },
+        origin: 'https://clerk.example.com',
+        source: otherPopup,
+      }),
+    );
+    expect(navigate).not.toHaveBeenCalled();

As per coding guidelines, “Unit tests are required for all new functionality” and “Verify proper error handling and edge cases.”

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://accounts.example.com',
source: popup,
}),
);
expect(navigate).not.toHaveBeenCalled();
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://clerk.example.com',
source: popup,
}),
);
expect(navigate).toHaveBeenCalledWith(returnUrl);
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://accounts.example.com',
source: popup,
}),
);
expect(navigate).not.toHaveBeenCalled();
const otherPopup = { location: { href: '' } } as unknown as Window;
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state: 'wrong_state' },
origin: 'https://clerk.example.com',
source: popup,
}),
);
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://clerk.example.com',
source: otherPopup,
}),
);
expect(navigate).not.toHaveBeenCalled();
window.dispatchEvent(
new MessageEvent('message', {
data: { return_url: returnUrl, state },
origin: 'https://clerk.example.com',
source: popup,
}),
);
expect(navigate).toHaveBeenCalledWith(returnUrl);
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/clerk-js/src/utils/__tests__/authenticateWithPopup.test.ts` around
lines 73 - 89, Extend the test around _authenticateWithPopup to dispatch
valid-FAPI-origin message events with an incorrect state and an incorrect source
before the matching event. Assert navigate is not called after each rejected
event, then retain the existing matching event and assert navigation occurs with
returnUrl.

Source: Coding guidelines

});
});

describe('_futureAuthenticateWithPopup', () => {
it('only accepts a message from the FAPI origin, expected popup, and expected state', async () => {
const clerk = createClerk('https://app.example.com/__clerk');
const popup = { location: { href: '' } } as unknown as Window;
const otherPopup = { location: { href: '' } } as unknown as Window;
const removeEventListener = vi.spyOn(window, 'removeEventListener');
const authentication = _futureAuthenticateWithPopup(clerk, {
popup,
externalVerificationRedirectURL: new URL('https://oauth.example.com/authorize'),
state: 'expected_state',
});

window.dispatchEvent(
new MessageEvent('message', {
data: { session: 'sess_123', state: 'expected_state' },
origin: 'https://accounts.example.com',
source: popup,
}),
);
window.dispatchEvent(
new MessageEvent('message', {
data: { session: 'sess_123', state: 'expected_state' },
origin: 'https://app.example.com',
source: otherPopup,
}),
);
window.dispatchEvent(
new MessageEvent('message', {
data: { session: 'sess_123', state: 'wrong_state' },
origin: 'https://app.example.com',
source: popup,
}),
);

expect(removeEventListener).not.toHaveBeenCalled();

window.dispatchEvent(
new MessageEvent('message', {
data: { session: 'sess_123', state: 'expected_state' },
origin: 'https://app.example.com',
source: popup,
}),
);

await expect(authentication).resolves.toBeUndefined();
expect(popup.location.href).toBe('https://oauth.example.com/authorize');
expect(removeEventListener).toHaveBeenCalledWith('message', expect.any(Function));
});
});
Loading
Loading