import { ClerkAPIResponseError, ClerkOfflineError, ClerkRuntimeError, EmailLinkErrorCodeStatus, } from '@clerk/shared/error'; import { ERROR_CODES } from '@clerk/shared/internal/clerk-js/constants'; import type { ActiveSessionResource, PendingSessionResource, SignedInSessionResource, SignInJSON, SignUpJSON, TokenResource, } from '@clerk/shared/types'; import { createDeferredPromise } from '@clerk/shared/utils'; import { waitFor } from '@testing-library/react'; import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, test, vi } from 'vitest'; import { mockJwt } from '@/test/core-fixtures'; import { restoreDocument, setDocumentVisibilityState } from '@/test/document-helpers'; import { mockNativeRuntime } from '../../test/utils'; import { Clerk } from '../clerk'; import { eventBus, events } from '../events'; import { ProtectCheckGate } from '../protectCheckGate'; import type { DisplayConfig, Organization } from '../resources/internal'; import { BaseResource, Client, Environment, SignIn, SignUp } from '../resources/internal'; const mockClientFetch = vi.fn(); const mockEnvironmentFetch = vi.fn(() => Promise.resolve({})); vi.mock('../resources/Client'); vi.mock('../resources/Environment'); const { mockCreateClientFromJwt } = vi.hoisted(() => ({ mockCreateClientFromJwt: vi.fn() })); vi.mock('../jwt-client', () => ({ createClientFromJwt: mockCreateClientFromJwt })); const { mockDevBrowser } = vi.hoisted(() => ({ mockDevBrowser: { clear: vi.fn(), setup: vi.fn(), getDevBrowser: vi.fn(() => 'deadbeef'), setDevBrowser: vi.fn(), removeDevBrowser: vi.fn(), refreshCookies: vi.fn(), }, })); vi.mock('../auth/devBrowser', () => ({ createDevBrowser: () => mockDevBrowser, })); Client.getOrCreateInstance = vi.fn().mockImplementation(() => { return { fetch: mockClientFetch }; }); Environment.getInstance = vi.fn().mockImplementation(() => { return { fetch: mockEnvironmentFetch }; }); const oldWindowLocation = window.location; const setWindowQueryParams = (params: Array<[string, string]>) => { // @ts-expect-error - Forcing delete on non-optional property for testing purposes delete window.location; const u = new URL(oldWindowLocation.href); params.forEach(([k, v]) => u.searchParams.append(k, v)); (window.location as any) = u; }; describe('Clerk singleton', () => { // Use a FAPI value for local production instances to avoid triggering the devInit flow during testing const developmentPublishableKey = 'pk_test_Y2xlcmsuYWJjZWYuMTIzNDUuZGV2LmxjbGNsZXJrLmNvbSQ'; const productionPublishableKey = 'pk_live_Y2xlcmsuYWJjZWYuMTIzNDUucHJvZC5sY2xjbGVyay5jb20k'; const mockNavigate = vi.fn((to: string) => Promise.resolve(to)); const mockedLoadOptions = { routerDebug: true, routerPush: mockNavigate, routerReplace: mockNavigate }; const mockDisplayConfig = { signInUrl: 'http://test.host/sign-in', signUpUrl: 'http://test.host/sign-up', userProfileUrl: 'http://test.host/user-profile', homeUrl: 'http://test.host/home', createOrganizationUrl: 'http://test.host/create-organization', organizationProfileUrl: 'http://test.host/organization-profile', } as DisplayConfig; const mockUserSettings = { signUp: { captcha_enabled: false, }, }; let mockWindowLocation; let mockHref: ReturnType; afterAll(() => { Object.defineProperty(global.window, 'location', { value: oldWindowLocation, }); }); beforeEach(() => { mockHref = vi.fn(); mockWindowLocation = { host: 'test.host', hostname: 'test.host', origin: 'http://test.host', get href() { return 'http://test.host'; }, set href(v: string) { mockHref(v); }, }; Object.defineProperty(global.window, 'location', { value: mockWindowLocation }); if (typeof globalThis.document !== 'undefined') { Object.defineProperty(global.window.document, 'hasFocus', { value: () => true, configurable: true }); } const mockAddEventListener = (type: string, callback: (e: any) => void) => { if (type === 'message') { callback({ origin: 'https://' + productionPublishableKey, data: { browserToken: 'hey', }, }); } }; Object.defineProperty(global.window, 'addEventListener', { configurable: true, value: mockAddEventListener, }); mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], }), ); eventBus.off(events.TokenUpdate); }); afterEach(() => mockNavigate.mockReset()); describe('initialize', () => { it('should consider publishableKey readonly', () => { const sut = new Clerk(productionPublishableKey); expect(sut.publishableKey).toEqual(productionPublishableKey); expect(() => { // @ts-expect-error attempt to override getter field sut.publishableKey = 'aloha'; }).toThrowError(/Cannot set property publishableKey of #/); }); it('should throw when publishableKey is invalid', () => { expect(() => { new Clerk('invalidPK'); }).toThrowError(/The publishableKey passed to Clerk is invalid/); }); }); describe('__internal_oauthTransport', () => { it('defaults to null with no getter access errors', () => { const sut = new Clerk(productionPublishableKey); expect(sut.__internal_hasOAuthTransport).toBe(false); expect(sut.__internal_oauthTransport).toBeNull(); }); it('exposes the transport registered via options after load', async () => { const transport = { getRedirectUrl: () => 'myapp://sso-callback', open: async (_url: URL) => ({ callbackUrl: 'myapp://sso-callback' }), }; const sut = new Clerk(productionPublishableKey); await sut.load({ __internal_oauthTransport: transport }); expect(sut.__internal_hasOAuthTransport).toBe(true); expect(sut.__internal_oauthTransport).toBe(transport); }); }); describe('__internal_handleResourceCallback', () => { it('handleGoogleOneTapCallback delegates to __internal_handleResourceCallback', async () => { const clerk = new Clerk(productionPublishableKey); await clerk.load(); const spy = vi.spyOn(clerk, '__internal_handleResourceCallback').mockResolvedValue(undefined); const signInLike = { identifier: 'x' } as any; await clerk.handleGoogleOneTapCallback(signInLike, { signInUrl: '/sign-in' }); expect(spy).toHaveBeenCalledWith(signInLike, { signInUrl: '/sign-in' }, undefined); }); }); describe('.setActive', () => { describe('with `active` session status', () => { const mockSession = { id: '1', remove: vi.fn(), status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), __internal_touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; let eventBusSpy: ReturnType; beforeEach(() => { eventBusSpy = vi.spyOn(eventBus, 'emit'); }); afterEach(() => { mockSession.remove.mockReset(); mockSession.touch.mockReset(); mockSession.__internal_touch.mockReset(); eventBusSpy?.mockRestore(); // cleanup global window pollution (window as any).__internal_onBeforeSetActive = null; (window as any).__internal_onAfterSetActive = null; }); it('does not call session touch on signOut', async () => { mockSession.touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: null }); await waitFor(() => { expect(mockSession.touch).not.toHaveBeenCalled(); expect(eventBusSpy).toHaveBeenCalledWith('token:update', { token: null }); }); }); it('calls session.touch by default', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' }); }); it('mounts OAuthConsent when mounted while navigating to redirectUrl', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], isEligibleForTouch: () => false }), ); const mountComponent = vi.fn(); const mockClerkUICtor = vi.fn(function () { return { ensureMounted: () => Promise.resolve({ mountComponent }) }; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ui: { ClerkUI: mockClerkUICtor } }); const node = document.createElement('div'); sut.navigate = vi.fn(async () => { sut.mountOAuthConsent(node); }); await sut.setActive({ session: mockSession as any as ActiveSessionResource, redirectUrl: '/oauth-consent', }); await waitFor(() => { expect(mountComponent).toHaveBeenCalledWith(expect.objectContaining({ name: 'OAuthConsent', node })); }); }); describe('with `touchSession` set to false', () => { it('calls session.touch by default outside of focus window event', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load({ touchSession: false }); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' }); }); }); it('calls __internal_onBeforeSetActive before session.touch', async () => { mockSession.touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); (window as any).__internal_onBeforeSetActive = () => { expect(mockSession.touch).not.toHaveBeenCalled(); }; const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'select_session' }); }); it('sets __session and __client_uat cookie before calling __internal_onBeforeSetActive', async () => { mockSession.touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); (window as any).__internal_onBeforeSetActive = () => { expect(eventBusSpy).toHaveBeenCalledWith('token:update', { token: mockSession.lastActiveToken }); }; const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); }); it('sets active organization by slug', async () => { const mockSession2 = { id: '1', status, user: { organizationMemberships: [ { id: 'orgmem_id', organization: { id: 'org_id', slug: 'some-org-slug', }, }, ], }, touch: vi.fn(), getToken: vi.fn(), }; mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession2] })); const sut = new Clerk(productionPublishableKey); await sut.load(); mockSession2.touch.mockImplementationOnce(() => { sut.session = mockSession2 as any; return Promise.resolve(); }); mockSession2.getToken.mockImplementation(() => 'mocked-token'); await sut.setActive({ organization: 'some-org-slug' }); await waitFor(() => { expect(mockSession2.touch).toHaveBeenCalledWith({ intent: 'select_org' }); expect(mockSession2.getToken).toHaveBeenCalled(); expect((mockSession2 as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id'); expect(sut.session).toMatchObject(mockSession2); }); }); it('redirects the user to the /v1/client/touch endpoint if the cookie_expires_at is less than 8 days away', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], cookieExpiresAt: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days from now isEligibleForTouch: () => true, buildTouchUrl: () => `https://clerk.example.com/v1/client/touch?redirect_url=${mockWindowLocation.href}/redirect-url-path`, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, redirectUrl: '/redirect-url-path', }); const redirectUrl = new URL((sut.navigate as ReturnType).mock.calls[0][0]); expect(redirectUrl.pathname).toEqual('/v1/client/touch'); expect(redirectUrl.searchParams.get('redirect_url')).toEqual(`${mockWindowLocation.href}/redirect-url-path`); // A second navigate would supersede the touch hop and abort it before it completes. expect(sut.navigate).toHaveBeenCalledTimes(1); }); it('does not redirect the user to the /v1/client/touch endpoint if the cookie_expires_at is more than 8 days away', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], cookieExpiresAt: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000), // 10 days from now isEligibleForTouch: () => false, buildTouchUrl: () => `https://clerk.example.com/v1/client/touch?redirect_url=${mockWindowLocation.href}/redirect-url-path`, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, redirectUrl: '/redirect-url-path', }); expect(sut.navigate).toHaveBeenCalledWith('/redirect-url-path'); }); it('does not redirect the user to the /v1/client/touch endpoint if the cookie_expires_at is not set', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], cookieExpiresAt: null, isEligibleForTouch: () => false, buildTouchUrl: () => `https://clerk.example.com/v1/client/touch?redirect_url=${mockWindowLocation.href}/redirect-url-path`, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, redirectUrl: '/redirect-url-path', }); expect(sut.navigate).toHaveBeenCalledWith('/redirect-url-path'); }); it('calls `navigate`', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const navigate = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate }); expect(mockSession.__internal_touch).toHaveBeenCalledWith({ intent: 'select_session' }); expect(navigate).toHaveBeenCalled(); }); it('passes decorateUrl to the navigate callback', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const navigate = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, navigate }); expect(navigate).toHaveBeenCalledWith( expect.objectContaining({ session: expect.any(Object), decorateUrl: expect.any(Function), }), ); }); it('decorateUrl returns touch URL when isEligibleForTouch is true', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], cookieExpiresAt: new Date(Date.now() + 2 * 24 * 60 * 60 * 1000), // 2 days from now isEligibleForTouch: () => true, buildTouchUrl: ({ redirectUrl }: { redirectUrl: URL }) => `https://clerk.example.com/v1/client/touch?redirect_url=${encodeURIComponent(redirectUrl.href)}`, }), ); let capturedDecorateUrl: ((url: string) => string) | undefined; const navigate = vi.fn(({ decorateUrl }) => { capturedDecorateUrl = decorateUrl; }); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, navigate }); expect(capturedDecorateUrl).toBeDefined(); const decoratedUrl = capturedDecorateUrl!('/dashboard'); // Should return touch URL when ITP fix is needed expect(decoratedUrl).toContain('/v1/client/touch'); expect(decoratedUrl).toContain('redirect_url='); expect(decoratedUrl).toContain('%2Fdashboard'); }); it('decorateUrl returns original URL when isEligibleForTouch is false', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], cookieExpiresAt: new Date(Date.now() + 10 * 24 * 60 * 60 * 1000), // 10 days from now isEligibleForTouch: () => false, buildTouchUrl: ({ redirectUrl }: { redirectUrl: URL }) => `https://clerk.example.com/v1/client/touch?redirect_url=${encodeURIComponent(redirectUrl.href)}`, }), ); let capturedDecorateUrl: ((url: string) => string) | undefined; const navigate = vi.fn(({ decorateUrl }) => { capturedDecorateUrl = decorateUrl; }); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource, navigate }); expect(capturedDecorateUrl).toBeDefined(); const decoratedUrl = capturedDecorateUrl!('/dashboard'); // Should return original URL when ITP fix is not needed expect(decoratedUrl).toBe('/dashboard'); }); mockNativeRuntime(() => { it('calls session.touch in a non-standard browser', async () => { mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load({ standardBrowser: false }); mockSession.touch.mockImplementationOnce(() => { sut.session = mockSession as any; return Promise.resolve(); }); await sut.setActive({ organization: { id: 'org_id' } as Organization }); expect(mockSession.touch).toHaveBeenCalled(); expect((mockSession as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual('org_id'); expect(mockSession.getToken).toHaveBeenCalled(); expect(sut.session).toMatchObject(mockSession); }); }); }); describe('with `pending` session status', () => { const mockSession = { id: '1', remove: vi.fn(), status: 'pending', user: {}, touch: vi.fn(() => Promise.resolve()), __internal_touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, tasks: [{ key: 'choose-organization' }], currentTask: { key: 'choose-organization' }, reload: vi.fn(() => Promise.resolve({ id: '1', status: 'pending', user: {}, tasks: [{ key: 'choose-organization' }], currentTask: { key: 'choose-organization', }, }), ), }; let eventBusSpy; beforeEach(() => { eventBusSpy = vi.spyOn(eventBus, 'emit'); }); afterEach(() => { mockSession.remove.mockReset(); mockSession.touch.mockReset(); mockSession.__internal_touch?.mockReset(); eventBusSpy?.mockRestore(); // cleanup global window pollution (window as any).__internal_onBeforeSetActive = null; (window as any).__internal_onAfterSetActive = null; }); it('calls session.touch by default', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as PendingSessionResource }); expect(mockSession.touch).toHaveBeenCalled(); }); it('does not call __internal_onBeforeSetActive before session.touch', async () => { mockSession.touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const onBeforeSetActive = vi.fn(); (window as any).__internal_onBeforeSetActive = onBeforeSetActive; const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(onBeforeSetActive).not.toHaveBeenCalled(); }); it('does not call __internal_onAfterSetActive after session.touch', async () => { mockSession.touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const onAfterSetActive = vi.fn(); (window as any).__internal_onAfterSetActive = onAfterSetActive; const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(onAfterSetActive).not.toHaveBeenCalled(); }); it('navigate to `taskUrl` option', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load({ taskUrls: { 'choose-organization': '/choose-organization', }, }); await sut.setActive({ session: mockSession as any as PendingSessionResource }); expect(mockSession.__internal_touch).toHaveBeenCalled(); expect(sut.navigate).toHaveBeenCalledWith('/choose-organization'); }); it('calls `navigate`', async () => { mockSession.__internal_touch.mockReturnValue(Promise.resolve()); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const navigate = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as PendingSessionResource, navigate }); expect(mockSession.__internal_touch).toHaveBeenCalled(); expect(navigate).toHaveBeenCalled(); }); }); describe('with force organization selection enabled', () => { const mockSession = { id: '1', remove: vi.fn(), status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; beforeEach(() => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { forceOrganizationSelection: true, }, }), ); }); afterEach(() => { mockSession.remove.mockReset(); mockSession.touch.mockReset(); mockEnvironmentFetch.mockReset(); // cleanup global window pollution (window as any).__internal_onBeforeSetActive = null; (window as any).__internal_onAfterSetActive = null; }); it('does not update session to personal workspace', async () => { const mockSessionWithOrganization = { id: '1', status: 'active', user: { organizationMemberships: [ { id: 'orgmem_id', organization: { id: 'org_id', slug: 'some-org-slug', }, }, ], }, touch: vi.fn(), getToken: vi.fn(), }; mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSessionWithOrganization] })); const sut = new Clerk(productionPublishableKey); await sut.load(); mockSessionWithOrganization.touch.mockImplementationOnce(() => { sut.session = mockSessionWithOrganization as any; return Promise.resolve(); }); mockSessionWithOrganization.getToken.mockImplementation(() => 'mocked-token'); await sut.setActive({ organization: 'some-org-slug' }); await waitFor(() => { expect(mockSessionWithOrganization.touch).toHaveBeenCalled(); expect(mockSessionWithOrganization.getToken).toHaveBeenCalled(); expect((mockSessionWithOrganization as any as ActiveSessionResource)?.lastActiveOrganizationId).toEqual( 'org_id', ); expect(sut.session).toMatchObject(mockSessionWithOrganization); }); await sut.setActive({ organization: null }); expect(sut.session).toMatchObject(mockSessionWithOrganization); }); }); describe('when offline', () => { const mockSession = { id: '1', remove: vi.fn(), status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; let eventBusSpy: ReturnType; beforeEach(() => { eventBusSpy = vi.spyOn(eventBus, 'emit'); }); afterEach(() => { mockSession.remove.mockReset(); mockSession.touch.mockReset(); mockSession.getToken.mockReset(); eventBusSpy?.mockRestore(); }); it('does not emit TokenUpdate with null when getToken throws ClerkOfflineError', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockSession.getToken.mockRejectedValue(new ClerkOfflineError('Network request failed while offline.')); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(eventBusSpy).toHaveBeenCalledWith('token:update', { token: mockSession.lastActiveToken }); const tokenUpdateCalls = eventBusSpy.mock.calls.filter(call => call[0] === 'token:update'); const nullTokenCalls = tokenUpdateCalls.filter(call => call[1]?.token === null); expect(nullTokenCalls.length).toBe(0); }); it('preserves existing auth state when offline during setActive', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockSession.getToken.mockRejectedValue(new ClerkOfflineError('Network request failed while offline.')); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await sut.setActive({ session: mockSession as any as ActiveSessionResource }); expect(sut.session).toBeDefined(); }); it('re-throws non-offline errors from getToken', async () => { mockSession.touch.mockReturnValue(Promise.resolve()); mockSession.getToken.mockRejectedValue(new Error('Some other error')); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); await expect(sut.setActive({ session: mockSession as any as ActiveSessionResource })).rejects.toThrow( 'Some other error', ); }); }); }); describe('.load()', () => { it('clears the stale dev browser before retrying the initial resources', async () => { const callLog: string[] = []; const devBrowserError = Object.assign(new Error('dev browser unauthenticated'), { errors: [{ code: 'dev_browser_unauthenticated' }], status: 401, }); mockDevBrowser.clear.mockImplementationOnce(() => void callLog.push('clearDevBrowser')); mockEnvironmentFetch .mockImplementationOnce(() => { callLog.push('environment'); return Promise.reject(devBrowserError); }) .mockImplementation(() => { callLog.push('environment'); return Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }); }); mockClientFetch.mockImplementation(() => { callLog.push('client'); return Promise.resolve({ signedInSessions: [] }); }); const sut = new Clerk(developmentPublishableKey); await sut.load({ unsafe_disableDevelopmentModeConsoleWarning: true }); expect(callLog).toEqual(['environment', 'client', 'clearDevBrowser', 'environment', 'client']); expect(sut.status).toBe('ready'); }); describe.each(['active', 'pending'] satisfies Array)( 'when session has %s status', status => { const mockSession = { id: '1', status, user: {}, getToken: vi.fn(), lastActiveToken: { getRawString: () => mockJwt }, }; afterEach(() => { // cleanup global window pollution (window as any).__internal_onBeforeSetActive = null; (window as any).__internal_onAfterSetActive = null; }); it('gracefully handles an incorrect value returned from the user provided selectInitialSession', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], }), ); // any is intentional here. We simulate a runtime value that should not exist const mockSelectInitialSession = vi.fn(() => undefined) as any; const sut = new Clerk(productionPublishableKey); await sut.load({ selectInitialSession: mockSelectInitialSession, }); await waitFor(() => { expect(sut.session).not.toBe(undefined); expect(sut.session).toBe(null); }); }); it('updates auth cookie on load from fetched session', async () => { mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); expect(document.cookie).toContain(mockJwt); }); it('updates auth cookie on token:update event', async () => { mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); const token = { jwt: {}, getRawString: () => 'updated-jwt', } as TokenResource; eventBus.emit(events.TokenUpdate, { token }); expect(document.cookie).toContain('updated-jwt'); }); }, ); describe('when the client fetch fails or hangs at load', () => { let startPollSpy: ReturnType; let stopPollSpy: ReturnType; let callLog: string[]; const sessionClient = (session: any) => ({ signedInSessions: [session], lastActiveSessionId: session.id, }); const makeSession = (overrides: Record = {}) => ({ id: 'sess_1', status: 'active', user: {}, getToken: vi.fn(() => Promise.resolve('fresh-token')), clearCache: vi.fn(), ...overrides, }); // `load()` awaits native crypto (cookie suffix) before scheduling the timeout, and that work // is real async the fake clock cannot advance. Yield real event-loop turns until a fake timer // actually exists (or load settles) so slow machines can't exhaust the advance budget early. const realSetTimeout = globalThis.setTimeout.bind(globalThis); const yieldRealEventLoop = () => new Promise(resolve => realSetTimeout(resolve, 0)); const pumpUntilSettled = async (promise: Promise) => { let settled = false; const tracked = promise.then( v => ((settled = true), v), e => ((settled = true), Promise.reject(e)), ); for (let advances = 0; advances < 20 && !settled; ) { if (vi.getTimerCount() === 0) { await yieldRealEventLoop(); continue; } await vi.advanceTimersByTimeAsync(5000); advances++; } await tracked; }; beforeEach(async () => { callLog = []; // Import at runtime (not top-level) so this module does not reorder the // static graph and break the auto-mocked Environment/Client resources. const { AuthCookieService } = await import('../auth/AuthCookieService'); startPollSpy = vi .spyOn(AuthCookieService.prototype, 'startPollingForToken') .mockImplementation(() => void callLog.push('startPoll')); stopPollSpy = vi .spyOn(AuthCookieService.prototype, 'stopPollingForToken') .mockImplementation(() => void callLog.push('stopPoll')); mockClientFetch.mockClear(); mockCreateClientFromJwt.mockReturnValue({ signedInSessions: [], lastActiveSessionId: null }); }); afterEach(() => { startPollSpy.mockRestore(); stopPollSpy.mockRestore(); mockCreateClientFromJwt.mockReset(); vi.useRealTimers(); }); it('fails fast and marks Clerk degraded when the client fetch hangs', async () => { vi.useFakeTimers(); // Only the primary fetch hangs; the background retry must resolve so it can't stall the test. mockClientFetch .mockReturnValueOnce(new Promise(() => {})) .mockResolvedValue({ signedInSessions: [], lastActiveSessionId: null }); const sut = new Clerk(productionPublishableKey); await pumpUntilSettled(sut.load()); expect(sut.status).toBe('degraded'); expect(stopPollSpy).toHaveBeenCalled(); expect(startPollSpy).toHaveBeenCalled(); expect(mockClientFetch.mock.calls[0]?.[0]?.abortSignal?.aborted).toBe(true); }); it('aborts /environment when the environment fetch hangs past the init timeout', async () => { vi.useFakeTimers(); mockEnvironmentFetch.mockReturnValueOnce(new Promise(() => {})); mockClientFetch.mockResolvedValue({ signedInSessions: [], lastActiveSessionId: null }); const sut = new Clerk(productionPublishableKey); await pumpUntilSettled(sut.load()); expect(mockEnvironmentFetch.mock.calls[0]?.[0]?.abortSignal?.aborted).toBe(true); expect(sut.status).toBe('degraded'); }); it('builds the degraded identity from the minted token and falls back to the cookie only if the mint fails', async () => { const stubSession = makeSession(); const freshSession = { id: 'sess_1', status: 'active', user: { id: 'user_fresh' } }; const freshClient = { signedInSessions: [freshSession], lastActiveSessionId: 'sess_1' }; mockClientFetch.mockRejectedValue(new Error('client fetch failed')); mockCreateClientFromJwt.mockReturnValueOnce(sessionClient(stubSession)).mockReturnValueOnce(freshClient); const sut = new Clerk(productionPublishableKey); await sut.load(); expect(mockCreateClientFromJwt).toHaveBeenCalledTimes(2); expect(mockCreateClientFromJwt).toHaveBeenNthCalledWith(2, 'fresh-token'); expect(sut.client).toBe(freshClient); expect(sut.session).toBe(freshSession); expect(sut.status).toBe('degraded'); }); it('clears the token cache and mints without skipCache when the client fetch fails with a session present', async () => { const getToken = vi.fn(() => { callLog.push('getToken'); return Promise.resolve('fresh-token'); }); const clearCache = vi.fn(() => void callLog.push('clearCache')); const session = makeSession({ getToken, clearCache }); mockClientFetch.mockRejectedValue(new Error('client fetch failed')); mockCreateClientFromJwt.mockReturnValue(sessionClient(session)); const sut = new Clerk(productionPublishableKey); await sut.load(); expect(getToken).toHaveBeenCalledWith(); expect(getToken).not.toHaveBeenCalledWith({ skipCache: true }); expect(callLog).toEqual(['startPoll', 'stopPoll', 'clearCache', 'getToken', 'startPoll']); expect(sut.status).toBe('degraded'); }); it('re-clears the token cache before restarting the poller when the recovery mint hangs', async () => { vi.useFakeTimers(); const getToken = vi.fn(() => { callLog.push('getToken'); return new Promise(() => {}); }); const clearCache = vi.fn(() => void callLog.push('clearCache')); const session = makeSession({ getToken, clearCache }); mockClientFetch.mockRejectedValue(new Error('client fetch failed')); mockCreateClientFromJwt.mockReturnValue(sessionClient(session)); const sut = new Clerk(productionPublishableKey); await pumpUntilSettled(sut.load()); expect(callLog).toEqual(['startPoll', 'stopPoll', 'clearCache', 'getToken', 'clearCache', 'startPoll']); expect(sut.status).toBe('degraded'); }); it('renders the empty client without minting when there is no session cookie', async () => { mockClientFetch.mockRejectedValue(new Error('client fetch failed')); const sut = new Clerk(productionPublishableKey); await sut.load(); expect(sut.session).toBeNull(); expect(callLog).toEqual(['startPoll', 'stopPoll', 'startPoll']); expect(sut.status).toBe('degraded'); }); it('rethrows a 4xx client error without entering the mint path', async () => { const err = Object.assign(new Error('bad request'), { status: 400 }); mockClientFetch.mockRejectedValue(err); const sut = new Clerk(productionPublishableKey); await expect(sut.load()).rejects.toBe(err); expect(mockCreateClientFromJwt).not.toHaveBeenCalled(); }); it('re-fetches /client in the background after a degraded load and applies the late response', async () => { vi.useFakeTimers(); const stubSession = makeSession(); const realSession = { id: 'sess_1', status: 'active', user: { id: 'user_real' } }; const realClient = { id: 'client_real', signedInSessions: [realSession], lastActiveSessionId: 'sess_1' }; const refetch = createDeferredPromise(); mockClientFetch.mockRejectedValueOnce(new Error('client fetch failed')).mockReturnValueOnce(refetch.promise); mockCreateClientFromJwt.mockReturnValue(sessionClient(stubSession)); const sut = new Clerk(productionPublishableKey); await pumpUntilSettled(sut.load()); expect(sut.status).toBe('degraded'); expect(mockClientFetch).toHaveBeenCalledTimes(2); // The background retry is not bounded by INITIALIZATION_TIMEOUT_MS. await vi.advanceTimersByTimeAsync(60_000); refetch.resolve(realClient); await vi.advanceTimersByTimeAsync(0); expect(sut.client).toBe(realClient); expect(sut.session).toBe(realSession); }); }); mockNativeRuntime(() => { describe('with cached resources in a non-standard browser', () => { it.each([ ['a network error', new ClerkRuntimeError('Network request failed.', { code: 'network_error' })], ['a 5xx API response', new ClerkAPIResponseError('Bad Gateway', { data: [], status: 502 })], ])('falls back to the cached resources on %s', async (_, error) => { const clientInstance = { fetch: mockClientFetch, signedInSessions: [] }; vi.mocked(Client.getOrCreateInstance) .mockReturnValueOnce(clientInstance as any) .mockReturnValueOnce(clientInstance as any); mockClientFetch.mockRejectedValue(error); const sut = new Clerk(productionPublishableKey); sut.__internal_getCachedResources = vi.fn(() => Promise.resolve({ client: null, environment: null })); await sut.load({ standardBrowser: false }); expect(sut.__internal_getCachedResources).toHaveBeenCalled(); expect(sut.status).toBe('degraded'); }); it('does not fall back to the cached resources on a 4xx API response', async () => { const error = new ClerkAPIResponseError('Bad Request', { data: [], status: 400 }); mockClientFetch.mockRejectedValue(error); const sut = new Clerk(productionPublishableKey); sut.__internal_getCachedResources = vi.fn(() => Promise.resolve({ client: null, environment: null })); await expect(sut.load({ standardBrowser: false })).rejects.toBe(error); expect(sut.__internal_getCachedResources).not.toHaveBeenCalled(); }); }); }); }); describe('updateSessionCookie monotonic backstop', () => { const sessionId = 'sess_active'; // The cookie guard treats an expired current cookie as no baseline, so test // tokens must carry real, non-expired timestamps rather than tiny literals. const T0 = Math.floor(Date.now() / 1000); const createJwtWithOiat = ( iat: number, oiat: number | undefined, opts: { sid?: string; org?: string; ttl?: number } = {}, ): string => { const { sid = sessionId, org, ttl = 60 } = opts; const header: Record = { alg: 'HS256', typ: 'JWT' }; if (oiat !== undefined) { header.oiat = oiat; } const payload: Record = { sid, iat, exp: iat + ttl }; if (org) { payload.org_id = org; } const b64 = (o: object) => btoa(JSON.stringify(o)).replace(/\+/g, '-').replace(/\//g, '_').replace(/=/g, ''); return `${b64(header)}.${b64(payload)}.test-signature`; }; const loadClerkWithSession = async () => { const mockSession = { id: sessionId, status: 'active', user: {}, getToken: vi.fn(), lastActiveToken: { getRawString: () => mockJwt }, }; mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [mockSession] })); const sut = new Clerk(productionPublishableKey); await sut.load(); return sut; }; const emitToken = (raw: string | null) => { eventBus.emit(events.TokenUpdate, { token: raw === null ? null : ({ jwt: {}, getRawString: () => raw } as any), }); }; it('drops a strictly-staler same-context token and keeps the fresher cookie', async () => { await loadClerkWithSession(); const fresh = createJwtWithOiat(T0, 200, { ttl: 600 }); emitToken(fresh); expect(document.cookie).toContain(fresh); const stale = createJwtWithOiat(T0 - 10, 100); emitToken(stale); expect(document.cookie).not.toContain(stale); expect(document.cookie).toContain(fresh); }); it('applies a lower-oiat token when the current cookie is expired (no freshness baseline)', async () => { await loadClerkWithSession(); const expiredFresher = createJwtWithOiat(T0 - 120, 500, { ttl: 60 }); emitToken(expiredFresher); expect(document.cookie).toContain(expiredFresher); const validStaler = createJwtWithOiat(T0, 100); emitToken(validStaler); expect(document.cookie).toContain(validStaler); }); it('applies a fresher same-context token', async () => { await loadClerkWithSession(); const older = createJwtWithOiat(T0, 100); emitToken(older); expect(document.cookie).toContain(older); const newer = createJwtWithOiat(T0 + 10, 200); emitToken(newer); expect(document.cookie).toContain(newer); }); it('applies a token with equal oiat and iat (publish on tie)', async () => { await loadClerkWithSession(); const first = createJwtWithOiat(T0, 100, { ttl: 60 }); emitToken(first); expect(document.cookie).toContain(first); const second = createJwtWithOiat(T0, 100, { ttl: 120 }); emitToken(second); expect(document.cookie).toContain(second); }); it('writes a token for a different session (cross-context cookies are not compared)', async () => { await loadClerkWithSession(); const otherSession = createJwtWithOiat(T0, 200, { sid: 'sess_other' }); emitToken(otherSession); expect(document.cookie).toContain(otherSession); }); it('writes a token for a different organization (cross-context cookies are not compared)', async () => { await loadClerkWithSession(); const otherOrg = createJwtWithOiat(T0, 200, { org: 'org_other' }); emitToken(otherOrg); expect(document.cookie).toContain(otherOrg); }); it('applies a personal-workspace token (no org) for the active personal workspace', async () => { await loadClerkWithSession(); const personal = createJwtWithOiat(T0, 200); emitToken(personal); expect(document.cookie).toContain(personal); }); it('applies an active-context token even when the current cookie is a different session with higher oiat', async () => { const sut = await loadClerkWithSession(); // Plant a different-session, higher-oiat cookie by temporarily making it the active context. (sut.session as any).id = 'sess_other'; const otherContext = createJwtWithOiat(T0 + 20, 999, { sid: 'sess_other' }); emitToken(otherContext); expect(document.cookie).toContain(otherContext); // Restore the active session; a lower-oiat active-context token must still apply, // because the different-session cookie is not a valid freshness baseline. (sut.session as any).id = sessionId; const active = createJwtWithOiat(T0, 100, { sid: sessionId }); emitToken(active); expect(document.cookie).toContain(active); }); it('applies a token without an oiat header (fail open)', async () => { await loadClerkWithSession(); const noOiat = createJwtWithOiat(T0, undefined); emitToken(noOiat); expect(document.cookie).toContain(noOiat); }); it('applies a malformed token (fail open)', async () => { await loadClerkWithSession(); emitToken('garbage.token'); expect(document.cookie).toContain('garbage.token'); }); it('removes the cookie when the token is null', async () => { await loadClerkWithSession(); const fresh = createJwtWithOiat(T0, 200); emitToken(fresh); expect(document.cookie).toContain(fresh); emitToken(null); expect(document.cookie).not.toContain(fresh); }); }); describe('.signOut()', () => { const mockClientDestroy = vi.fn(); const mockClientRemoveSessions = vi.fn(); const mockSession1 = { id: '1', remove: vi.fn(), status: 'active', user: {}, getToken: vi.fn() }; const mockSession2 = { id: '2', remove: vi.fn(), status: 'active', user: {}, getToken: vi.fn() }; const mockSession3 = { id: '3', remove: vi.fn(), status: 'pending', user: {}, getToken: vi.fn() }; // Sign-out consults these to decide whether to route the redirect through // /v1/client/touch. Default to "no refresh needed" so the existing cases // assert against the plain redirect URL. const clientTouchDefaults = { isEligibleForTouch: () => false, buildTouchUrl: () => 'https://clerk.example.com/v1/client/touch', }; beforeEach(() => { mockClientDestroy.mockReset(); mockClientRemoveSessions.mockReset(); mockSession1.remove.mockReset(); mockSession2.remove.mockReset(); mockSession3.remove.mockReset(); }); it('has no effect if called when no sessions exist', async () => { const sut = new Clerk(productionPublishableKey); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], destroy: mockClientDestroy, }), ); await sut.load(); await sut.signOut(); await waitFor(() => { expect(mockClientDestroy).not.toHaveBeenCalled(); expect(mockSession1.remove).not.toHaveBeenCalled(); }); }); it('signs out all sessions if no sessionId is passed and multiple sessions have authenticated status', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1, mockSession2, mockSession3], sessions: [mockSession1, mockSession2, mockSession3], destroy: mockClientDestroy, removeSessions: mockClientRemoveSessions, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut(); await waitFor(() => { expect(mockClientDestroy).not.toHaveBeenCalled(); expect(mockClientRemoveSessions).toHaveBeenCalled(); expect(sut.navigate).toHaveBeenCalledWith('/'); }); }); it.each(['active', 'pending'] satisfies Array)( 'signs out all sessions if no sessionId is passed and only one session has %s status', async status => { mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [{ ...mockSession1, status }], sessions: [{ ...mockSession1, status }], destroy: mockClientDestroy, removeSessions: mockClientRemoveSessions, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut(); await waitFor(() => { expect(mockClientDestroy).not.toHaveBeenCalled(); expect(mockClientRemoveSessions).toHaveBeenCalled(); expect(mockSession1.remove).not.toHaveBeenCalled(); expect(sut.navigate).toHaveBeenCalledWith('/'); }); }, ); it('completes local sign-out when removing sessions fails with an offline network error', async () => { mockClientRemoveSessions.mockRejectedValue( new ClerkRuntimeError('Network request failed.', { code: 'network_error' }), ); mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1], sessions: [mockSession1], destroy: mockClientDestroy, removeSessions: mockClientRemoveSessions, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await expect(sut.signOut()).resolves.toBeUndefined(); expect(sut.session).toBeNull(); expect(sut.navigate).toHaveBeenCalledWith('/'); }); it('rethrows non-network errors when removing sessions during sign-out', async () => { const error = new ClerkRuntimeError('Request failed.', { code: 'unexpected_error' }); mockClientRemoveSessions.mockRejectedValue(error); mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1], sessions: [mockSession1], destroy: mockClientDestroy, removeSessions: mockClientRemoveSessions, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await expect(sut.signOut()).rejects.toBe(error); expect(sut.session).toBeUndefined(); expect(sut.navigate).not.toHaveBeenCalled(); }); it('only removes the session that corresponds to the passed sessionId if it is not the current', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1, mockSession2, mockSession3], sessions: [mockSession1, mockSession2, mockSession3], destroy: mockClientDestroy, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut({ sessionId: '2' }); await waitFor(() => { expect(mockSession2.remove).toHaveBeenCalled(); expect(mockClientDestroy).not.toHaveBeenCalled(); expect(sut.navigate).not.toHaveBeenCalled(); }); }); it('removes and signs out the session that corresponds to the passed sessionId if it is the current', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1, mockSession2, mockSession3], sessions: [mockSession1, mockSession2, mockSession3], destroy: mockClientDestroy, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut({ sessionId: '1' }); await waitFor(() => { expect(mockSession1.remove).toHaveBeenCalled(); expect(mockClientDestroy).not.toHaveBeenCalled(); expect(sut.navigate).toHaveBeenCalledWith('/'); }); }); it('removes and signs out the session and redirects to the provided redirectUrl ', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ ...clientTouchDefaults, signedInSessions: [mockSession1, mockSession2, mockSession3], sessions: [mockSession1, mockSession2, mockSession3], destroy: mockClientDestroy, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut({ sessionId: '1', redirectUrl: '/after-sign-out' }); await waitFor(() => { expect(mockSession1.remove).toHaveBeenCalled(); expect(mockClientDestroy).not.toHaveBeenCalled(); expect(sut.navigate).toHaveBeenCalledWith('/after-sign-out'); }); }); it('routes the redirect through /v1/client/touch when the client cookie is close to expiring', async () => { mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession1], sessions: [mockSession1], destroy: mockClientDestroy, removeSessions: mockClientRemoveSessions, isEligibleForTouch: () => true, // Encodes the nested URL the way the real Client.buildTouchUrl() does, so a // destination carrying its own query or hash survives the round trip. buildTouchUrl: ({ redirectUrl }: { redirectUrl: URL }) => { const touchUrl = new URL('https://clerk.example.com/v1/client/touch'); touchUrl.searchParams.set('redirect_url', redirectUrl.toString()); return touchUrl.toString(); }, }), ); const sut = new Clerk(productionPublishableKey); sut.navigate = vi.fn(); await sut.load(); await sut.signOut({ redirectUrl: '/after-sign-out?tab=security#settings' }); await waitFor(() => { expect(mockClientRemoveSessions).toHaveBeenCalled(); const navigatedTo = new URL((sut.navigate as ReturnType).mock.calls[0][0]); expect(navigatedTo.pathname).toEqual('/v1/client/touch'); // The user still lands on the original destination, via the touch redirect. expect(navigatedTo.searchParams.get('redirect_url')).toEqual( new URL('/after-sign-out?tab=security#settings', mockWindowLocation.href).toString(), ); }); }); }); describe('.navigate(to)', () => { let sut: Clerk; let logSpy; beforeEach(() => { logSpy = vi.spyOn(console, 'log').mockReturnValue(void 0); sut = new Clerk(productionPublishableKey); }); afterEach(() => { logSpy?.mockRestore(); }); it('uses window location if a custom navigate is not defined', async () => { await sut.load(); const toUrl = 'http://test.host/'; await sut.navigate(toUrl); expect(mockHref).toHaveBeenCalledWith(toUrl); expect(logSpy).not.toHaveBeenCalled(); }); it('uses window location if a custom navigate is defined but destination has different origin', async () => { await sut.load(mockedLoadOptions); const toUrl = 'https://www.origindifferent.com/'; await sut.navigate(toUrl); expect(mockHref).toHaveBeenCalledWith(toUrl); }); it('wraps custom navigate method in a promise if provided and it sync', async () => { await sut.load(mockedLoadOptions); const toUrl = 'http://test.host/path#hash'; const res = sut.navigate(toUrl); expect(res.then).toBeDefined(); expect(mockHref).not.toHaveBeenCalled(); expect(mockNavigate.mock.calls[0][0]).toBe('/path#hash'); }); it('logs navigation external navigation when routerDebug is enabled', async () => { await sut.load({ routerDebug: true }); const toUrl = 'http://test.host/'; await sut.navigate(toUrl); expect(mockHref).toHaveBeenCalledWith(toUrl); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith(`Clerk is navigating to: ${toUrl}`); }); it('logs navigation custom navigation when routerDebug is enabled', async () => { await sut.load({ ...mockedLoadOptions, routerDebug: true }); const toUrl = 'http://test.host/path#hash'; const res = sut.navigate(toUrl); expect(res.then).toBeDefined(); expect(mockHref).not.toHaveBeenCalled(); expect(mockNavigate.mock.calls[0][0]).toBe('/path#hash'); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith(`Clerk is navigating to: ${toUrl}`); }); it('validates the protocol of the provided URL', async () => { await sut.load({ ...mockedLoadOptions, allowedRedirectProtocols: ['gg:'] }); // allowed protocol const toUrl = 'gg://some/deeply/nested/path'; await sut.navigate(toUrl); expect(mockNavigate.mock.calls[0][0]).toBe(toUrl); expect(logSpy).toHaveBeenCalledTimes(1); expect(logSpy).toHaveBeenCalledWith(`Clerk is navigating to: ${toUrl}`); mockNavigate.mockReset(); logSpy.mockReset(); // disallowed protocol const badUrl = 'evil://some/deeply/nested/path'; await sut.navigate(badUrl); expect(mockNavigate.mock.calls[0][0]).toBe('/'); expect(logSpy).toHaveBeenCalledTimes(1); }); }); describe('.handleRedirectCallback()', () => { // handleRedirectCallback calls signIn/signUp.reload, which relies on the global fetch instance. We don't actually // need a return value though, so we just mock a resolved promise. const originalFetch = global.fetch; beforeAll(() => { global.fetch = vi.fn().mockResolvedValue({ json: vi.fn().mockResolvedValue({}) }); }); afterAll(() => { global.fetch = originalFetch; }); beforeEach(() => { mockClientFetch.mockReset(); mockEnvironmentFetch.mockReset(); }); describe('with pending session', () => { beforeEach(() => { mockClientFetch.mockReset(); mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { forceOrganizationSelection: true, }, }), ); }); it('navigates to task', async () => { const mockSession = { id: '1', status: 'pending', user: {}, tasks: [{ key: 'choose-organization' }], currentTask: { key: 'choose-organization' }, lastActiveToken: { getRawString: () => 'mocked-token' }, }; const mockResource = { ...mockSession, remove: vi.fn(), touch: vi.fn(() => Promise.resolve()), __internal_touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), reload: vi.fn(() => Promise.resolve(mockSession)), }; mockResource.__internal_touch.mockReturnValueOnce(Promise.resolve()); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockResource], signIn: new SignIn(null), signUp: new SignUp({ status: 'complete', } as any as SignUpJSON), isEligibleForTouch: () => false, }), ); const mockSignUpCreate = vi .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; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/tasks/choose-organization'); }); }); }); it('creates a new user and calls setActive if the user was not found during sso signup', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignUpCreate = vi .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(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata: undefined }); expect(mockSetActive).toHaveBeenCalled(); }); }); it('passes unsafeMetadata to signUp.create during OAuth transfer flow', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignUpCreate = vi .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; const unsafeMetadata = { foo: 'bar', nested: { value: 123 } }; await sut.handleRedirectCallback({ unsafeMetadata }); await waitFor(() => { expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata }); expect(mockSetActive).toHaveBeenCalled(); }); }); it('uses __internal_navigateOnSetActive for completed sign in callbacks', async () => { const sessionId = 'sess_123'; const mockSession = { id: sessionId, currentTask: null }; mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'complete', created_session_id: sessionId, } as any as SignInJSON), signUp: new SignUp(null), }), ); const internalNavigateOnSetActive = vi.fn(async ({ session, redirectUrl, decorateUrl }) => { expect(session).toBe(mockSession); expect(redirectUrl).toBe('http://test.host/after-sign-in'); expect(decorateUrl('/decorated')).toBe('/decorated'); }); const mockSetActive = vi.fn(async ({ navigate }) => navigate({ session: mockSession })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive as any; await sut.handleRedirectCallback({ signInForceRedirectUrl: '/after-sign-in', __internal_navigateOnSetActive: internalNavigateOnSetActive, }); expect(mockSetActive).toHaveBeenCalledWith({ session: sessionId, navigate: expect.any(Function), }); expect(internalNavigateOnSetActive).toHaveBeenCalledTimes(1); expect(mockNavigate).not.toHaveBeenCalled(); }); it('uses __internal_navigateOnSetActive for completed sign up callbacks', async () => { const sessionId = 'sess_123'; const mockSession = { id: sessionId, currentTask: null }; mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'complete', created_session_id: sessionId, } as any as SignUpJSON), }), ); const internalNavigateOnSetActive = vi.fn(async ({ session, redirectUrl, decorateUrl }) => { expect(session).toBe(mockSession); expect(redirectUrl).toBe('http://test.host/after-sign-up'); expect(decorateUrl('/decorated')).toBe('/decorated'); }); const mockSetActive = vi.fn(async ({ navigate }) => navigate({ session: mockSession })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive as any; await sut.handleRedirectCallback({ signUpForceRedirectUrl: '/after-sign-up', __internal_navigateOnSetActive: internalNavigateOnSetActive, }); expect(mockSetActive).toHaveBeenCalledWith({ session: sessionId, navigate: expect.any(Function), }); expect(internalNavigateOnSetActive).toHaveBeenCalledTimes(1); expect(mockNavigate).not.toHaveBeenCalled(); }); it('uses __internal_navigate for intermediate callback navigations instead of window-level navigation', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const internalNavigate = vi.fn().mockResolvedValue(undefined); const mockSignUpCreate = vi .fn() .mockReturnValue(Promise.resolve({ status: 'missing_requirements', missingFields: ['phone_number'] })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signUp.create = mockSignUpCreate; await sut.handleRedirectCallback({ continueSignUpUrl: 'continue', __internal_navigate: internalNavigate, }); await waitFor(() => { expect(internalNavigate).toHaveBeenCalledWith('continue'); }); expect(mockNavigate).not.toHaveBeenCalled(); }); it('passes raw component-relative paths to __internal_navigate on development instances', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const internalNavigate = vi.fn().mockResolvedValue(undefined); const mockSignUpCreate = vi .fn() .mockReturnValue(Promise.resolve({ status: 'missing_requirements', missingFields: ['phone_number'] })); const sut = new Clerk(developmentPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signUp.create = mockSignUpCreate; await sut.__internal_handleResourceCallback(sut.client.signIn, { continueSignUpUrl: 'continue', __internal_navigate: internalNavigate, }); await waitFor(() => { expect(internalNavigate).toHaveBeenCalledWith('continue'); }); expect(mockNavigate).not.toHaveBeenCalled(); }); describe('__internal_resumeAfterProtectCheck', () => { // A verification challenge can interrupt an OAuth callback partway through routing. The // challenge card clears it and hands control back here, from a page that is no longer // the callback route, so the remaining routing has to run rather than start over. const gatedTransferableSignIn = (extra: Record = {}) => new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, ...extra, } as any as SignInJSON); const loadEnvironment = () => mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); it('completes the transfer as a SIGN-UP and activates the created session', async () => { loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: gatedTransferableSignIn(), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignUpCreate = vi .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.__internal_resumeAfterProtectCheck({ continuation: 'transfer_to_sign_up' }); await waitFor(() => { expect(mockSignUpCreate).toHaveBeenCalledTimes(1); expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata: undefined }); expect(mockSetActive).toHaveBeenCalledWith(expect.objectContaining({ session: '123' })); }); }); it('completes the transfer even when the cleared response dropped the transferable marker', async () => { // `SignIn.fromJSON` replaces `firstFactorVerification` wholesale on every write, so the // caller latches the continuation before running the challenge and passes it explicitly. // Re-reading it here would silently fall back to returning the user to sign-in. loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: null, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSignUpCreate = vi .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 = vi.fn(); await sut.__internal_resumeAfterProtectCheck({ continuation: 'transfer_to_sign_up' }); await waitFor(() => expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata: undefined }), ); }); it('does not divert to the sign-up card when a stale gate is on the sign-up resource', async () => { // The sign-in variant below covers the first short-circuit; `resuming` skips a second one // keyed on the SIGN-UP resource, and that is the arm that sends the user to a different // card entirely rather than back to this one. loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: gatedTransferableSignIn(), signUp: new SignUp({ protect_check: { status: 'pending', token: 'stale-signup-token', sdk_url: 'https://example.com/sdk.js' }, } as any), }), ); const mockSignUpCreate = vi .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 = vi.fn(); await sut.__internal_resumeAfterProtectCheck({ continuation: 'transfer_to_sign_up' }); await waitFor(() => expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata: undefined }), ); expect(mockNavigate.mock.calls.some(([to]) => typeof to === 'string' && to.includes('protect-check'))).toBe( false, ); }); it('does not bounce back into the challenge when a stale gate is still on the resource', async () => { // This is the test that proves `resuming` is load-bearing rather than decorative. The // caller IS the challenge card; re-checking the gate here would hand control straight // back to it, or — through the sign-up arm — to the wrong card entirely. loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: gatedTransferableSignIn({ protect_check: { status: 'pending', token: 'stale-token', sdk_url: 'https://example.com/sdk.js' }, }), signUp: new SignUp(null), }), ); const mockSignUpCreate = vi .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 = vi.fn(); await sut.__internal_resumeAfterProtectCheck({ continuation: 'transfer_to_sign_up' }); await waitFor(() => expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true, unsafeMetadata: undefined }), ); expect(mockNavigate.mock.calls.some(([to]) => typeof to === 'string' && to.includes('protect-check'))).toBe( false, ); }); it('still honours transferable: false', async () => { loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: gatedTransferableSignIn(), signUp: new SignUp(null), }), ); const mockSignUpCreate = vi.fn(); 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 = vi.fn(); await sut.__internal_resumeAfterProtectCheck({ continuation: 'transfer_to_sign_up', transferable: false, }); await waitFor(() => expect(mockSignUpCreate).not.toHaveBeenCalled()); }); describe('a sign-up whose external account already belongs to a user', () => { const existingAccountSignUp = (extra: Record = {}) => new SignUp({ status: 'missing_requirements', missing_fields: ['email_address', 'password'], verifications: { external_account: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: null, error: { code: ERROR_CODES.EXTERNAL_ACCOUNT_EXISTS, long_message: 'This external account already exists.', message: 'already exists', }, }, }, external_account: null, ...extra, } as any as SignUpJSON); it('is sent to its challenge by the callback before the transfer runs', async () => { loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: existingAccountSignUp({ missing_fields: ['email_address', 'password', 'protect_check'], protect_check: { status: 'pending', token: 'token', sdk_url: 'https://example.com/sdk.js' }, }), }), ); const mockSignInCreate = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signIn.create = mockSignInCreate; sut.setActive = vi.fn(); await sut.handleRedirectCallback(); await waitFor(() => expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/protect-check')); expect(mockSignInCreate).not.toHaveBeenCalled(); }); it('completes the transfer as a SIGN-IN and activates the created session', async () => { loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: existingAccountSignUp(), }), ); const mockSetActive = vi.fn(); const mockSignInCreate = vi .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.signIn.create = mockSignInCreate; sut.setActive = mockSetActive; await sut.__internal_resumeAfterProtectCheck(); await waitFor(() => { expect(mockSignInCreate).toHaveBeenCalledTimes(1); expect(mockSignInCreate).toHaveBeenCalledWith({ transfer: true }); expect(mockSetActive).toHaveBeenCalledWith(expect.objectContaining({ session: '123' })); }); expect(mockNavigate.mock.calls.some(([to]) => typeof to === 'string' && to.includes('protect-check'))).toBe( false, ); }); it('activates the transferred sign-in when resumed again after the transfer has committed', async () => { loadEnvironment(); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'complete', first_factor_verification: null, second_factor_verification: null, identifier: '', user_data: null, created_session_id: '123', created_user_id: 'user_1', } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignInCreate = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signIn.create = mockSignInCreate; sut.setActive = mockSetActive; await sut.__internal_resumeAfterProtectCheck(); await waitFor(() => { expect(mockSetActive).toHaveBeenCalledWith(expect.objectContaining({ session: '123' })); }); expect(mockSignInCreate).not.toHaveBeenCalled(); }); }); }); it('does not initiate the transfer flow when transferable: false is passed', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignUpCreate = vi .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({ transferable: false }); await waitFor(() => { expect(mockSignUpCreate).not.toHaveBeenCalledWith({ transfer: true }); expect(mockSetActive).not.toHaveBeenCalled(); expect(mockNavigate).toHaveBeenCalledWith('/sign-in', { windowNavigate: expect.any(Function), }); }); }); it('creates a new sign up and navigates to the continue sign-up path if the user was not found during sso signup and there are missing requirements', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, identifier: '', user_data: null, created_session_id: null, created_user_id: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSignUpCreate = vi.fn().mockReturnValue( Promise.resolve( new SignUp({ status: 'missing_requirements', missing_fields: ['phone_number'], } as any as SignUpJSON), ), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signUp.create = mockSignUpCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true }); expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/continue'); }); }); it('signs the user in if the user was found during sign up', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', verifications: { external_account: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: null, error: { code: ERROR_CODES.EXTERNAL_ACCOUNT_EXISTS, long_message: 'This external account already exists.', message: 'already exists', }, }, }, external_account: null, external_account_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: null, error: { code: ERROR_CODES.EXTERNAL_ACCOUNT_EXISTS, long_message: 'This external account already exists.', message: 'already exists', }, }, } as any as SignUpJSON), }), ); const mockSetActive = vi.fn(); const mockSignInCreate = vi .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.signIn.create = mockSignInCreate; sut.setActive = mockSetActive; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockSignInCreate).toHaveBeenCalledWith({ transfer: true }); expect(mockSetActive).toHaveBeenCalled(); }); }); it('signs the user by calling setActive if the user was already signed in during sign up', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: [], verifications: { external_account: { status: 'unverified', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'identifier_already_signed_in', long_message: "You're already signed in", message: "You're already signed in", meta: { session_id: 'sess_1yDceUR8SIKtQ0gIOO8fNsW7nhe', }, }, }, }, } as any as SignUpJSON), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockSetActive).toHaveBeenCalled(); }); }); it('creates a new user and calls setActive in if the user was found during sign in', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: null, error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', }, }, second_factor_verification: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const mockSignUpCreate = vi .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(mockSignUpCreate).toHaveBeenCalledWith({ transfer: true }); expect(mockSetActive).toHaveBeenCalled(); }); }); it('redirects an existing user to the default 2fa page if 2fa is enabled during sign in', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_second_factor', first_factor_verification: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: null, error: null, }, second_factor_verification: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/factor-two'); }); }); it('redirects an existing user to a custom 2fa page if 2fa is enabled and secondFactorUrl is passed during sign in', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_second_factor', first_factor_verification: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: null, error: null, expire_at: 1631777672389, }, second_factor_verification: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ secondFactorUrl: '/custom-2fa', }); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/custom-2fa'); }); }); it('redirects the user to the signInForceRedirectUrl if one was provided', async () => { const sessionId = 'sess_1yDceUR8SIKtQ0gIOO8fNsW7nhe'; const mockSession = { id: sessionId, remove: vi.fn(), status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), __internal_touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ sessions: [mockSession], signedInSessions: [mockSession], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', verifications: { external_account: { status: 'unverified', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'identifier_already_signed_in', long_message: "You're already signed in", message: "You're already signed in", meta: { session_id: sessionId, }, }, }, }, } as any as SignUpJSON), isEligibleForTouch: () => false, }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ signInForceRedirectUrl: '/custom-sign-in', }); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/custom-sign-in'); }); }); it('gives priority to signInForceRedirectUrl if signInForceRedirectUrl and signInFallbackRedirectUrl were provided ', async () => { const sessionId = 'sess_1yDceUR8SIKtQ0gIOO8fNsW7nhe'; const mockSession = { id: sessionId, remove: vi.fn(), status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), __internal_touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ sessions: [mockSession], signedInSessions: [mockSession], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', verifications: { external_account: { status: 'unverified', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'identifier_already_signed_in', long_message: "You're already signed in", message: "You're already signed in", meta: { session_id: sessionId, }, }, }, }, } as any as SignUpJSON), isEligibleForTouch: () => false, }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ signInForceRedirectUrl: '/custom-sign-in', signInFallbackRedirectUrl: '/redirect-to', } as any); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/custom-sign-in'); }); }); it('redirects user to signUp url if there is an external account signup attempt has an error', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', verifications: { external_account: { status: 'unverified', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'external_account_not_found', long_message: 'The External Account was not found.', message: 'Invalid external account', meta: { session_id: 'sess_1yDceUR8SIKtQ0gIOO8fNsW7nhe', }, }, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up'); }); }); it('redirects user to signUp url if there is an external account signup error even if missing requirements', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: { code: 'not_allowed_to_sign_up', long_message: 'You cannot sign up with test@clerk.com since this is a restricted application.', message: 'Not allowed to sign up', meta: { session_id: 'sess_1yDceUR8SIKtQ0gIOO8fNsW7nhe', }, }, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up'); }); }); it('redirects user to the continue sign-up url if the external account was verified but there are still missing requirements', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['last_name'], verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/continue'); }); }); it('redirects user to factor-one to choose between multiple enterprise connections', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', supported_first_factors: [ { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_1', enterprise_connection_name: 'A' }, { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_2', enterprise_connection_name: 'B' }, ], } as unknown as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/factor-one'); }); }); it('redirects user to sign-in when a single bare enterprise_sso factor needs the first factor', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', supported_first_factors: [{ strategy: 'enterprise_sso' }], } as unknown as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in'); }); }); it('redirects user to the enterprise connections url if the sign-up is missing enterprise_sso', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['enterprise_sso'], verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/enterprise-connections'); }); }); it('builds the enterprise connections url from the signUpUrl param when provided', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['enterprise_sso'], verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ signUpUrl: '/custom-sign-up' }); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/custom-sign-up#/enterprise-connections'); }); }); it('completes a sign-up callback instead of resuming a pending enterprise connection sign-in', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', supported_first_factors: [ { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_1', enterprise_connection_name: 'A' }, { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_2', enterprise_connection_name: 'B' }, ], } as unknown as SignInJSON), signUp: new SignUp({ status: 'complete', missing_fields: [], created_session_id: 'sess_123', verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockSetActive).toHaveBeenCalledWith(expect.objectContaining({ session: 'sess_123' })); }); expect(mockNavigate).not.toHaveBeenCalledWith('/sign-in#/factor-one'); }); it('continues a sign-up callback instead of resuming a pending enterprise connection sign-in', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', supported_first_factors: [ { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_1', enterprise_connection_name: 'A' }, { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_2', enterprise_connection_name: 'B' }, ], } as unknown as SignInJSON), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['first_name'], created_session_id: null, verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/continue'); }); }); it('does not resume a pending enterprise connection sign-in on a sign-up callback', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', supported_first_factors: [ { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_1', enterprise_connection_name: 'A' }, { strategy: 'enterprise_sso', enterprise_connection_id: 'ec_2', enterprise_connection_name: 'B' }, ], } as unknown as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ reloadResource: 'signUp' }); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in'); }); }); it('redirects user to the enterpriseConnectionsUrl param if the sign-up is missing enterprise_sso', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['enterprise_sso'], created_session_id: null, verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback({ enterpriseConnectionsUrl: '/custom-chooser' }); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/custom-chooser'); }); }); it('redirects a transferred sign-up missing enterprise_sso to the enterprise connections url', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_identifier', first_factor_verification: { status: 'transferable', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSignUpCreate = vi .fn() .mockReturnValue(Promise.resolve({ status: 'missing_requirements', missingFields: ['enterprise_sso'] })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signUp.create = mockSignUpCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/enterprise-connections'); }); }); it('redirects user to the protect-check url before the enterprise connections url if the sign-up is protect-gated', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: ['protect_check', 'enterprise_sso'], verifications: { external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/protect-check'); }); }); it('redirects user to the verify-email-address url if the external account has unverified email and there are no missing requirements', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: [], unverified_fields: ['email_address'], verifications: { email_address: { status: 'unverified', strategy: 'from_oauth_google', next_action: 'needs_attempt', }, external_account: { status: 'verified', strategy: 'oauth_google', external_verification_redirect_url: '', error: null, }, }, } as any as SignUpJSON), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up#/verify-email-address'); }); }); it('redirects user to factor-one, if the email is claimed, but the external account has an unverified email', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', } as unknown as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/factor-one'); }); }); it('redirects user to factor-one, if we are doing a account transfer and the external account has an unverified email', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: [], unverified_fields: ['email_address'], verifications: { external_account: { status: 'transferable', error: { code: ERROR_CODES.EXTERNAL_ACCOUNT_EXISTS, }, }, }, } as unknown as SignUpJSON), }), ); const mockSignInCreate = vi.fn().mockReturnValue(Promise.resolve({ status: 'needs_first_factor' })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signIn.create = mockSignInCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/factor-one'); }); }); it('redirects to sign-up if an oauth flow fails due to the user being locked', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn(null), signUp: new SignUp({ status: 'missing_requirements', missing_fields: [], unverified_fields: ['email_address'], verifications: { external_account: { status: 'unverified', error: { error: { code: 'user_locked', long_message: 'Your account is locked. Please contact yolo@swag.com for more information.', message: 'Account locked', }, }, }, }, } as unknown as SignUpJSON), }), ); const mockSignUpCreate = vi.fn().mockReturnValue( Promise.resolve( new SignUp({ status: 'missing_requirements', missing_fields: ['phone_number'], } as any as SignUpJSON), ), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signUp.create = mockSignUpCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-up'); }); }); it('redirects to sign-in if an oauth flows fails due to the user being locked', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_first_factor', first_factor_verification: { status: 'unverified', strategy: 'oauth_google', external_verification_redirect_url: null, error: { code: 'user_locked', long_message: 'Your account is locked. Please contact yolo@swag.com for more information.', message: 'Account locked', }, expire_at: 1631777672389, }, second_factor_verification: null, } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSignInCreate = vi.fn().mockReturnValue(Promise.resolve({ status: 'needs_first_factor' })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signIn.create = mockSignInCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in'); }); }); it('redirects user to reset-password, if the user is required to set a new password', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_new_password', } as unknown as SignInJSON), signUp: new SignUp(null), }), ); const mockSignInCreate = vi.fn().mockReturnValue(Promise.resolve({ status: 'needs_new_password' })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); if (!sut.client) { fail('we should always have a client'); } sut.client.signIn.create = mockSignInCreate; await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/reset-password'); }); }); it('does not route a sign-up callback into a stale sign-in protect_check gate', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); // An abandoned sign-in keeps serializing its pending protect_check on the client. const staleSignIn = new SignIn({ status: 'needs_protect_check', identifier: 'user@example.com', first_factor_verification: null, second_factor_verification: null, user_data: null, created_session_id: null, created_user_id: null, protect_check: { status: 'pending', token: 'stale-token', sdk_url: 'https://example.com/sdk.js' }, } as any as SignInJSON); const completeSignUp = new SignUp({ status: 'complete', created_session_id: 'sess_signup' } as any as SignUpJSON); // The intent-driven reload at the top of the handler is a no-op here; keep the state stable. (staleSignIn as any).reload = vi.fn().mockResolvedValue(staleSignIn); (completeSignUp as any).reload = vi.fn().mockResolvedValue(completeSignUp); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: staleSignIn, signUp: completeSignUp, }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await sut.handleRedirectCallback({ reloadResource: 'signUp' }); await waitFor(() => { // Completes the sign-up rather than routing into the stale sign-in's challenge. expect(mockSetActive).toHaveBeenCalled(); expect(mockNavigate).not.toHaveBeenCalledWith('/sign-in#/protect-check'); }); }); it('routes a sign-in callback to the protect-check gate', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, onWindowLocationHost: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], signIn: new SignIn({ status: 'needs_protect_check', identifier: 'user@example.com', first_factor_verification: null, second_factor_verification: null, user_data: null, created_session_id: null, created_user_id: null, protect_check: { status: 'pending', token: 'fresh-token', sdk_url: 'https://example.com/sdk.js' }, } as any as SignInJSON), signUp: new SignUp(null), }), ); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await sut.handleRedirectCallback(); await waitFor(() => { expect(mockNavigate.mock.calls[0][0]).toBe('/sign-in#/protect-check'); }); }); }); describe('.handleEmailLinkVerification()', () => { beforeEach(() => { mockClientFetch.mockReset(); mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); }); it('completes the sign in flow if a session was created on this client', async () => { const createdSessionId = 'sess_123'; setWindowQueryParams([ ['__clerk_status', 'verified'], ['__clerk_created_session', createdSessionId], ]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [{ id: createdSessionId }], signIn: new SignIn({ status: 'completed', } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; const redirectUrlComplete = '/redirect-to'; await sut.handleEmailLinkVerification({ redirectUrlComplete }); await waitFor(() => { expect(mockSetActive).toHaveBeenCalledWith({ session: createdSessionId, redirectUrl: redirectUrlComplete, }); }); }); it("continues to redirectUrl for sign in that's not completed", async () => { setWindowQueryParams([['__clerk_status', 'verified']]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signIn: new SignIn({ status: 'needs_second_factor', } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; const redirectUrl = '/2fa'; sut.handleEmailLinkVerification({ redirectUrl }); await waitFor(() => { expect(mockSetActive).not.toHaveBeenCalled(); expect(mockNavigate.mock.calls[0][0]).toBe(redirectUrl); }); }); it('completes the sign up flow if a session was created on this client', async () => { const createdSessionId = 'sess_123'; setWindowQueryParams([ ['__clerk_status', 'verified'], ['__clerk_created_session', createdSessionId], ]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [{ id: createdSessionId }], signUp: new SignUp({ status: 'completed', } as any as SignUpJSON), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; const redirectUrlComplete = '/redirect-to'; await sut.handleEmailLinkVerification({ redirectUrlComplete }); await waitFor(() => { expect(mockSetActive).toHaveBeenCalledWith({ session: createdSessionId, redirectUrl: redirectUrlComplete, }); }); }); it("continues the sign up flow for a sign up that's not completed", async () => { setWindowQueryParams([['__clerk_status', 'verified']]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signUp: new SignUp({ status: 'missing_requirements', } as any as SignUpJSON), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; const redirectUrl = '/next-up'; sut.handleEmailLinkVerification({ redirectUrl }); await waitFor(() => { expect(mockSetActive).not.toHaveBeenCalled(); expect(mockNavigate.mock.calls[0][0]).toBe(redirectUrl); }); }); it('throws an error for expired verification status parameter', async () => { setWindowQueryParams([['__clerk_status', 'expired']]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signUp: new SignUp(null), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await expect(async () => { await sut.handleEmailLinkVerification({}); }).rejects.toThrow(EmailLinkErrorCodeStatus.Expired); expect(mockSetActive).not.toHaveBeenCalled(); }); it('throws an error for failed verification status parameter', async () => { setWindowQueryParams([['__clerk_status', 'failed']]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signUp: new SignUp(null), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await expect(async () => { await sut.handleEmailLinkVerification({}); }).rejects.toThrow(EmailLinkErrorCodeStatus.Failed); expect(mockSetActive).not.toHaveBeenCalled(); }); it('runs a callback when verified on other device', async () => { setWindowQueryParams([ ['__clerk_status', 'verified'], ['__clerk_created_session', 'sess_123'], ]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signUp: new SignUp(null), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; const res = { ping: 'ping' }; const cb = () => { res.ping = 'pong'; }; await sut.handleEmailLinkVerification({ onVerifiedOnOtherDevice: cb }); expect(res.ping).toEqual('pong'); expect(mockSetActive).not.toHaveBeenCalled(); }); it('throws an error with no status query parameter', async () => { setWindowQueryParams([['__clerk_created_session', 'sess_123']]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [], signUp: new SignUp(null), signIn: new SignIn(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await expect(async () => { await sut.handleEmailLinkVerification({}); }).rejects.toThrow(EmailLinkErrorCodeStatus.Failed); expect(mockSetActive).not.toHaveBeenCalled(); }); it('throws an error for invalid status query parameter', async () => { setWindowQueryParams([ ['__clerk_status', 'whatever'], ['__clerk_created_session', 'sess_123'], ]); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], sessions: [{ id: 'sess_123' }], signIn: new SignIn({ status: 'completed', } as any as SignInJSON), signUp: new SignUp(null), }), ); const mockSetActive = vi.fn(); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); sut.setActive = mockSetActive; await expect(async () => { await sut.handleEmailLinkVerification({}); }).rejects.toThrow(EmailLinkErrorCodeStatus.Failed); expect(mockSetActive).not.toHaveBeenCalled(); }); }); /** * TODO: * 1) Write better test names for this.domain and this.isSatellite * 2) Write test for when to throw errors in proxy url and multi-domain prod * 3) Write test the mimic sync/link in prod */ describe('Clerk().isSatellite and Clerk().domain getters', () => { beforeEach(() => { mockClientFetch.mockReset(); mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [] })); mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: {}, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); }); it('domain is string, isSatellite is true', async () => { const sut = new Clerk(productionPublishableKey, { domain: 'example.com', }); await sut.load({ isSatellite: true, }); expect(sut.domain).toBe('clerk.example.com'); expect(sut.isSatellite).toBe(true); }); it('domain is string, isSatellite is function returning true', async () => { const sut = new Clerk(productionPublishableKey, { domain: 'example.com', }); await sut.load({ isSatellite: url => url.host === 'test.host', }); expect(sut.domain).toBe('clerk.example.com'); expect(sut.isSatellite).toBe(true); }); it('domain is string with scheme and clerk prefix, isSatellite is true', async () => { const sut = new Clerk(productionPublishableKey, { domain: 'https://clerk.example.com', }); await sut.load({ isSatellite: true, }); expect(sut.domain).toBe('clerk.example.com'); expect(sut.isSatellite).toBe(true); }); it('domain is function that returns the url of the website, isSatellite is true', async () => { const sut = new Clerk(productionPublishableKey, { domain: url => url.href.replace(/\/$/, ''), }); await sut.load({ isSatellite: true, }); expect(sut.domain).toBe('clerk.test.host'); expect(sut.isSatellite).toBe(true); }); }); describe('Clerk multi-domain', () => { describe('when development satellite', () => { it('fapiClient should not use Clerk.domain as its baseUrl', async () => { const sut = new Clerk(developmentPublishableKey, { domain: 'satellite.dev', }); await sut.load({ isSatellite: true, signInUrl: 'https://primary.dev/sign-in', }); expect(sut.getFapiClient().buildUrl({ path: '/me' }).href).toContain(`https://${sut.frontendApi}/v1/me`); }); }); describe('when production satellite', () => { test('fapiClient should use Clerk.domain as its baseUrl', async () => { const sut = new Clerk(productionPublishableKey, { domain: 'satellite.com', }); await sut.load({ isSatellite: true, }); expect(sut.getFapiClient().buildUrl({ path: '/me' }).href).toContain('https://clerk.satellite.com/v1/me'); }); mockNativeRuntime(() => { test('fapiClient should use Clerk.domain as its baseUrl in non-browser runtimes', async () => { const sut = new Clerk(productionPublishableKey, { domain: 'satellite.com', }); await sut.load({ isSatellite: true, }); expect(sut.getFapiClient().buildUrl({ path: '/me' }).href).toContain('https://satellite.com/v1/me'); }); }); }); }); describe('proxyUrl', () => { describe('when proxyUrl is set', () => { test('fapiClient should use Clerk.proxyUrl as its baseUrl', async () => { const sut = new Clerk(productionPublishableKey, { proxyUrl: 'https://proxy.com/api/__clerk', }); await sut.load({}); expect(sut.getFapiClient().buildUrl({ path: '/me' }).href).toContain('https://proxy.com/api/__clerk/v1/me'); }); mockNativeRuntime(() => { test('fapiClient should use Clerk.proxyUrl as its baseUrl in non-browser runtimes', async () => { const sut = new Clerk(productionPublishableKey, { proxyUrl: 'https://proxy.com/api/__clerk', }); await sut.load({}); expect(sut.getFapiClient().buildUrl({ path: '/me' }).href).toContain('https://proxy.com/api/__clerk/v1/me'); }); }); }); describe('auto-detection for eligible hosts', () => { const originalLocation = window.location; afterEach(() => { Object.defineProperty(window, 'location', { value: originalLocation, writable: true, }); }); test('auto-derives proxyUrl for production instances on eligible hosts', () => { Object.defineProperty(window, 'location', { value: { ...originalLocation, hostname: 'myapp-abc123.vercel.app', origin: 'https://myapp-abc123.vercel.app', href: 'https://myapp-abc123.vercel.app/dashboard', }, writable: true, }); const sut = new Clerk(productionPublishableKey); expect(sut.proxyUrl).toBe('https://myapp-abc123.vercel.app/__clerk'); }); test('does NOT auto-derive proxyUrl for development instances on eligible hosts', () => { Object.defineProperty(window, 'location', { value: { ...originalLocation, hostname: 'myapp-abc123.vercel.app', origin: 'https://myapp-abc123.vercel.app', href: 'https://myapp-abc123.vercel.app/dashboard', }, writable: true, }); const sut = new Clerk(developmentPublishableKey); expect(sut.proxyUrl).toBe(''); }); test('does NOT auto-derive proxyUrl for ineligible domains', () => { const sut = new Clerk(productionPublishableKey); expect(sut.proxyUrl).toBe(''); }); test('explicit proxyUrl takes precedence over auto-detection', () => { Object.defineProperty(window, 'location', { value: { ...originalLocation, hostname: 'myapp-abc123.vercel.app', origin: 'https://myapp-abc123.vercel.app', href: 'https://myapp-abc123.vercel.app/dashboard', }, writable: true, }); const sut = new Clerk(productionPublishableKey, { proxyUrl: 'https://custom-proxy.example.com/__clerk', }); expect(sut.proxyUrl).toBe('https://custom-proxy.example.com/__clerk'); }); test('explicit domain skips auto-detection', () => { Object.defineProperty(window, 'location', { value: { ...originalLocation, hostname: 'myapp-abc123.vercel.app', origin: 'https://myapp-abc123.vercel.app', href: 'https://myapp-abc123.vercel.app/dashboard', }, writable: true, }); const sut = new Clerk(productionPublishableKey, { domain: 'clerk.myapp.com', }); expect(sut.proxyUrl).toBe(''); }); }); }); describe('buildUrlWithAuth', () => { it('builds an absolute url from a relative url in development', async () => { const sut = new Clerk(developmentPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('foo'); expect(url).toBe('http://test.host/foo'); }); it('returns what was passed when in production', async () => { const sut = new Clerk(productionPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('foo'); expect(url).toBe('foo'); }); it('uses the hash to propagate the dev browser by default on dev', async () => { const sut = new Clerk(developmentPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('https://example.com/some-path'); expect(url).toBe('https://example.com/some-path?__clerk_db_jwt=deadbeef'); }); it('uses the query param to propagate the dev browser if specified by option on dev', async () => { const sut = new Clerk(developmentPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('https://example.com/some-path'); expect(url).toBe('https://example.com/some-path?__clerk_db_jwt=deadbeef'); }); it('uses the query param to propagate the dev browser to Account Portal pages on dev - non-kima', async () => { const sut = new Clerk(developmentPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('https://accounts.abcef.12345.dev.lclclerk.com'); expect(url).toBe('https://accounts.abcef.12345.dev.lclclerk.com/?__clerk_db_jwt=deadbeef'); }); it('uses the query param to propagate the dev browser to Account Portal pages on dev - kima', async () => { const sut = new Clerk(developmentPublishableKey); await sut.load(); const url = sut.buildUrlWithAuth('https://rested-anemone-14.accounts.dev'); expect(url).toBe('https://rested-anemone-14.accounts.dev/?__clerk_db_jwt=deadbeef'); }); }); describe('Organizations', () => { it('getOrganization', async () => { // @ts-expect-error - Mocking a protected method BaseResource._fetch = vi.fn().mockResolvedValue({}); const sut = new Clerk(developmentPublishableKey); await sut.getOrganization('org_id'); // @ts-expect-error - Mocking a protected method expect(BaseResource._fetch).toHaveBeenCalledWith({ method: 'GET', path: '/organizations/org_id', }); }); }); describe('updateClient', () => { afterEach(() => { // cleanup global window pollution (window as any).__internal_onBeforeSetActive = null; (window as any).__internal_onAfterSetActive = null; }); it('runs server revalidation hooks when session transitions from `active` to `pending`', async () => { const mockOnBeforeSetActive = vi.fn().mockReturnValue(Promise.resolve()); const mockOnAfterSetActive = vi.fn().mockReturnValue(Promise.resolve()); (window as any).__internal_onBeforeSetActive = mockOnBeforeSetActive; (window as any).__internal_onAfterSetActive = mockOnAfterSetActive; const mockActiveSession = { id: 'session_1', status: 'active', user: { id: 'user_1' }, lastActiveToken: { getRawString: () => 'token_1' }, }; const mockPendingSession = { id: 'session_1', status: 'pending', user: { id: 'user_1' }, lastActiveToken: { getRawString: () => 'token_1' }, }; const mockInitialClient = { sessions: [mockActiveSession], signedInSessions: [mockActiveSession], lastActiveSessionId: 'session_1', }; const mockUpdatedClient = { sessions: [mockPendingSession], signedInSessions: [mockPendingSession], lastActiveSessionId: 'session_1', }; const sut = new Clerk(productionPublishableKey); // Manually set the initial client and session state to simulate active session // without going through load() or setActive() sut.updateClient(mockInitialClient as any); // Verify we start with an active session expect(sut.session?.status).toBe('active'); // Call updateClient with the new client that has pending session sut.updateClient(mockUpdatedClient as any); // Verify hooks were called await waitFor(() => { expect(mockOnAfterSetActive).toHaveBeenCalledTimes(1); }); }); it('does not emit to listeners when __internal_dangerouslySkipEmit is true', () => { const mockSession = { id: 'session_1', status: 'active', user: { id: 'user_1' }, lastActiveToken: { getRawString: () => 'token_1' }, }; const mockClient = { sessions: [mockSession], signedInSessions: [mockSession], lastActiveSessionId: 'session_1', }; const sut = new Clerk(productionPublishableKey); sut.updateClient(mockClient as any); const listener = vi.fn(); const unsubscribe = sut.addListener(listener, { skipInitialEmit: true }); listener.mockClear(); sut.updateClient(mockClient as any, { __internal_dangerouslySkipEmit: true }); unsubscribe(); expect(listener).not.toHaveBeenCalled(); }); }); describe('__internal_attemptToEnableEnvironmentSetting', () => { afterEach(() => { mockEnvironmentFetch.mockReset(); mockClientFetch.mockReset(); }); describe('for organizations', () => { it('does not open prompt if organizations is enabled in development', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { enabled: true, }, }), ); const sut = new Clerk(productionPublishableKey); const __internal_openEnableOrganizationsPromptSpy = vi.fn(); sut.__internal_openEnableOrganizationsPrompt = __internal_openEnableOrganizationsPromptSpy; await sut.load(); const result = await sut.__internal_attemptToEnableEnvironmentSetting({ for: 'organizations', caller: 'OrganizationSwitcher', }); expect(result?.isEnabled).toBe(true); expect(__internal_openEnableOrganizationsPromptSpy).not.toHaveBeenCalled(); }); it('does not open prompt if organizations is enabled in production', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => true, isDevelopmentOrStaging: () => true, organizationSettings: { enabled: true, }, }), ); const sut = new Clerk(productionPublishableKey); const __internal_openEnableOrganizationsPromptSpy = vi.fn(); sut.__internal_openEnableOrganizationsPrompt = __internal_openEnableOrganizationsPromptSpy; await sut.load(); const result = await sut.__internal_attemptToEnableEnvironmentSetting({ for: 'organizations', caller: 'OrganizationSwitcher', }); expect(result?.isEnabled).toBe(true); expect(__internal_openEnableOrganizationsPromptSpy).not.toHaveBeenCalled(); }); it('opens prompt if organizations is disabled in development', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { enabled: false, }, }), ); const sut = new Clerk(developmentPublishableKey); const __internal_openEnableOrganizationsPromptSpy = vi.fn(); sut.__internal_openEnableOrganizationsPrompt = __internal_openEnableOrganizationsPromptSpy; await sut.load(); const result = await sut.__internal_attemptToEnableEnvironmentSetting({ for: 'organizations', caller: 'OrganizationSwitcher', }); expect(result?.isEnabled).toBe(false); expect(__internal_openEnableOrganizationsPromptSpy).toHaveBeenCalled(); }); it('does not open prompt if organizations is disabled in production', async () => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { enabled: false, }, }), ); const sut = new Clerk(productionPublishableKey); const __internal_openEnableOrganizationsPromptSpy = vi.fn(); sut.__internal_openEnableOrganizationsPrompt = __internal_openEnableOrganizationsPromptSpy; await sut.load(); const result = await sut.__internal_attemptToEnableEnvironmentSetting({ for: 'organizations', caller: 'OrganizationSwitcher', }); expect(result?.isEnabled).toBe(false); expect(__internal_openEnableOrganizationsPromptSpy).not.toHaveBeenCalled(); }); // Handles case where environment gets enabled via BAPI, but it gets cached and the user is redirected to the choose-organization task // The enable org prompt should not appear in the task screen since orgs have already been enabled it('does not open prompt if organizations is disabled in development and session has choose-organization task', async () => { const mockSession = { id: '1', remove: vi.fn(), status: 'pending', user: {}, touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, tasks: [{ key: 'choose-organization' }], currentTask: { key: 'choose-organization' }, reload: vi.fn(() => Promise.resolve({ id: '1', status: 'pending', user: {}, tasks: [{ key: 'choose-organization' }], currentTask: { key: 'choose-organization', }, }), ), }; mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => false, isDevelopmentOrStaging: () => true, organizationSettings: { enabled: false, }, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], }), ); const sut = new Clerk(developmentPublishableKey); const __internal_openEnableOrganizationsPromptSpy = vi.fn(); sut.__internal_openEnableOrganizationsPrompt = __internal_openEnableOrganizationsPromptSpy; await sut.load(); const result = await sut.__internal_attemptToEnableEnvironmentSetting({ for: 'organizations', caller: 'OrganizationSwitcher', }); // Contains the organization task, so the prompt should not be opened expect(result?.isEnabled).toBe(true); expect(__internal_openEnableOrganizationsPromptSpy).not.toHaveBeenCalled(); }); }); }); describe('protect check modal', () => { beforeEach(() => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => true, isDevelopmentOrStaging: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], }), ); }); const gatedSignIn = () => ({ protectCheck: { status: 'pending', token: 'tok', sdkUrl: 'https://p.example.com/sdk.js' }, }); it('resolves at once when Clerk was loaded without UI components', async () => { const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); await expect(sut.__internal_openProtectCheckModal({ resource: gatedSignIn() as any })).resolves.toBeUndefined(); }); it('resolves at once and leaves the gate when the UI predates the Protect modal', async () => { const openModal = vi.fn(); const mockClerkUICtor = vi.fn(function () { return { ensureMounted: () => Promise.resolve({ openModal, closeModal: vi.fn() }) }; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ...mockedLoadOptions, ui: { ClerkUI: mockClerkUICtor } }); const resource = gatedSignIn() as any; await expect(sut.__internal_openProtectCheckModal({ resource })).resolves.toBeUndefined(); expect(openModal).not.toHaveBeenCalled(); expect(resource.protectCheck).not.toBeNull(); }); it('closes the modal and rejects with the error the modal reports', async () => { const openProtectCheckModal = vi.fn(); const closeModal = vi.fn(); const mockClerkUICtor = vi.fn(function () { return { ensureMounted: () => Promise.resolve({ openProtectCheckModal, closeModal }) }; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ...mockedLoadOptions, ui: { ClerkUI: mockClerkUICtor } }); const blocked = new Error('blocked'); const pending = sut.__internal_openProtectCheckModal({ resource: gatedSignIn() as any }); await vi.waitFor(() => expect(openProtectCheckModal).toHaveBeenCalled()); openProtectCheckModal.mock.calls[0][0].onFailed(blocked); await expect(pending).rejects.toBe(blocked); expect(closeModal).toHaveBeenCalledWith('protectCheck'); }); const loadWithClient = async (client: { signIn: Record; signUp: Record }) => { mockClientFetch.mockReturnValue(Promise.resolve({ signedInSessions: [], ...client })); const sut = new Clerk(productionPublishableKey); await sut.load(mockedLoadOptions); return sut; }; it('resolves gates the client carries on its sign-in and sign-up', async () => { const resolve = vi.spyOn(ProtectCheckGate.prototype, 'resolve').mockResolvedValue(undefined); const sut = await loadWithClient({ signIn: gatedSignIn(), signUp: gatedSignIn() }); await sut.__internal_resolvePendingProtectCheck(); expect(resolve).toHaveBeenCalledWith(sut, sut.client?.signIn); expect(resolve).toHaveBeenCalledWith(sut, sut.client?.signUp); resolve.mockRestore(); }); it('leaves every gate alone once the sign-in is complete', async () => { const resolve = vi.spyOn(ProtectCheckGate.prototype, 'resolve').mockResolvedValue(undefined); const sut = await loadWithClient({ signIn: { status: 'complete' }, signUp: gatedSignIn() }); await sut.__internal_resolvePendingProtectCheck(); expect(resolve).not.toHaveBeenCalled(); resolve.mockRestore(); }); it('resolves only the sign-up gate when the callback is a sign-up', async () => { const resolve = vi.spyOn(ProtectCheckGate.prototype, 'resolve').mockResolvedValue(undefined); const sut = await loadWithClient({ signIn: gatedSignIn(), signUp: gatedSignIn() }); await sut.__internal_resolvePendingProtectCheck('signUp'); expect(resolve).toHaveBeenCalledTimes(1); expect(resolve).toHaveBeenCalledWith(sut, sut.client?.signUp); resolve.mockRestore(); }); it('reports a failed gate on the resource that carries it and rejects', async () => { const blocked = new Error('blocked'); const resolve = vi .spyOn(ProtectCheckGate.prototype, 'resolve') .mockResolvedValueOnce(undefined) .mockRejectedValueOnce(blocked); const sut = await loadWithClient({ signIn: gatedSignIn(), signUp: gatedSignIn() }); const emit = vi.spyOn(eventBus, 'emit'); await expect(sut.__internal_resolvePendingProtectCheck()).rejects.toBe(blocked); expect(emit).toHaveBeenCalledTimes(1); expect(emit).toHaveBeenCalledWith(events.ResourceError, { resource: sut.client?.signUp, error: blocked }); emit.mockRestore(); resolve.mockRestore(); }); }); describe('ui.ClerkUI option', () => { beforeEach(() => { mockEnvironmentFetch.mockReturnValue( Promise.resolve({ userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => false, isProduction: () => true, isDevelopmentOrStaging: () => false, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [], }), ); }); it('uses ui.ClerkUI when provided', async () => { const mockClerkUIInstance = { mount: vi.fn() }; const mockClerkUICtor = vi.fn(function () { return mockClerkUIInstance; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ...mockedLoadOptions, ui: { ClerkUI: mockClerkUICtor }, }); expect(mockClerkUICtor).toHaveBeenCalled(); }); it('supports legacy clerkUICtor option for backwards compatibility', async () => { const mockClerkUIInstance = { mount: vi.fn() }; const mockClerkUICtor = vi.fn(function () { return mockClerkUIInstance; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ...mockedLoadOptions, clerkUICtor: mockClerkUICtor, } as any); expect(mockClerkUICtor).toHaveBeenCalled(); }); it('supports legacy clerkUiCtor option for backwards compatibility', async () => { const mockClerkUIInstance = { mount: vi.fn() }; const mockClerkUICtor = vi.fn(function () { return mockClerkUIInstance; }); const sut = new Clerk(productionPublishableKey); await sut.load({ ...mockedLoadOptions, clerkUiCtor: mockClerkUICtor, } as any); expect(mockClerkUICtor).toHaveBeenCalled(); }); }); describe('page focus session touch', () => { const windowListeners = new Map void>>(); const firePageFocus = () => { for (const listener of windowListeners.get('focus') ?? []) { listener(new Event('focus')); } }; const mockSession = { id: 'sess_1', status: 'active', user: {}, touch: vi.fn(() => Promise.resolve()), getToken: vi.fn(), lastActiveToken: { getRawString: () => 'mocked-token' }, }; beforeEach(() => { windowListeners.clear(); const recordWindowListener = (type: string, callback: (e: any) => void) => { const listeners = windowListeners.get(type) ?? []; listeners.push(callback); windowListeners.set(type, listeners); if (type === 'message') { callback({ origin: 'https://' + productionPublishableKey, data: { browserToken: 'hey', }, }); } }; Object.defineProperty(global.window, 'addEventListener', { configurable: true, value: recordWindowListener, }); mockSession.touch.mockReset(); mockSession.touch.mockResolvedValue(undefined); setDocumentVisibilityState('visible'); mockEnvironmentFetch.mockReturnValue( Promise.resolve({ authConfig: { singleSessionMode: true }, userSettings: mockUserSettings, displayConfig: mockDisplayConfig, isSingleSession: () => true, isProduction: () => false, isDevelopmentOrStaging: () => true, }), ); mockClientFetch.mockReturnValue( Promise.resolve({ signedInSessions: [mockSession], lastActiveSessionId: mockSession.id, }), ); }); afterEach(() => { restoreDocument(); }); it('does not surface a failed focus touch as an unhandled rejection', async () => { const unhandled: unknown[] = []; const onUnhandledRejection = (reason: unknown) => { unhandled.push(reason); }; process.on('unhandledRejection', onUnhandledRejection); try { mockSession.touch.mockRejectedValue( new Error( 'ClerkJS: Network error at "https://clerk.example.com/v1/client/sessions/sess_1/touch" - TypeError: NetworkError when attempting to fetch resource. Please try again.', ), ); const sut = new Clerk(productionPublishableKey); await sut.load(); firePageFocus(); expect(mockSession.touch).toHaveBeenCalledWith({ intent: 'focus' }); await new Promise(resolve => setTimeout(resolve, 0)); expect(unhandled).toEqual([]); } finally { process.off('unhandledRejection', onUnhandledRejection); } }); it('still handles an unauthenticated focus touch', async () => { const sut = new Clerk(productionPublishableKey); await sut.load(); const handleUnauthenticated = vi.spyOn(sut, 'handleUnauthenticated').mockResolvedValue(undefined); mockSession.touch.mockRejectedValue({ status: 401 }); firePageFocus(); await waitFor(() => { expect(handleUnauthenticated).toHaveBeenCalled(); }); }); it('does not touch the session on focus when touchSession is false', async () => { const sut = new Clerk(productionPublishableKey); await sut.load({ touchSession: false }); firePageFocus(); expect(mockSession.touch).not.toHaveBeenCalled(); }); }); });