The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
[codex] Ignore stale authentication errors after session changes (#25510)
Félix Malfaitcb0339ff639c
diff --git a/packages/twenty-front/src/modules/apollo/hooks/__tests__/useApolloFactory.test.tsx b/packages/twenty-front/src/modules/apollo/hooks/__tests__/useApolloFactory.test.tsxindex 1df6cbef516..ee8bc909095 100644--- a/packages/twenty-front/src/modules/apollo/hooks/__tests__/useApolloFactory.test.tsx+++ b/packages/twenty-front/src/modules/apollo/hooks/__tests__/useApolloFactory.test.tsx@@ -1,9 +1,13 @@import { gql } from '@apollo/client';+import { CombinedGraphQLErrors } from '@apollo/client/errors';import { act, renderHook } from '@testing-library/react';import fetchMock, { enableFetchMocks } from 'jest-fetch-mock';import { MemoryRouter, useLocation } from 'react-router-dom';import { SnackBarComponentInstanceContext } from '@/ui/feedback/snack-bar-manager/contexts/SnackBarComponentInstanceContext';import { useApolloFactory } from '@/apollo/hooks/useApolloFactory';+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';+import { getSessionGeneration } from '@/auth/utils/getSessionGeneration';+import { rotateSessionGeneration } from '@/auth/utils/rotateSessionGeneration';enableFetchMocks();@@ -32,6 +36,12 @@ const Wrapper = ({ children }: { children: React.ReactNode }) => ();describe('useApolloFactory', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ fetchMock.resetMocks();+ clearSessionGeneration();+ });+it('should work as expected', () => {const { result } = renderHook(() => useApolloFactory(), {wrapper: Wrapper,@@ -46,6 +56,12 @@ describe('useApolloFactory', () => {});it('should navigate to /welcome on unauthenticated error', async () => {+ expect.assertions(6);++ rotateSessionGeneration();++ expect(getSessionGeneration()).not.toBeNull();+const errors = [{extensions: {@@ -65,7 +81,10 @@ describe('useApolloFactory', () => {const { result } = renderHook(() => {const location = useLocation();- return { factory: useApolloFactory(), location };+ return {+ factory: useApolloFactory(),+ location,+ };},{wrapper: Wrapper,@@ -74,6 +93,8 @@ describe('useApolloFactory', () => {expect(result.current.location.pathname).toBe('/opportunities');+ let mutationError: unknown;+try {await act(async () => {await result.current.factory.mutate({@@ -87,10 +108,12 @@ describe('useApolloFactory', () => {});});} catch (error) {- expect(error).toBeDefined();-- expect(mockNavigate).toHaveBeenCalled();- expect(mockNavigate).toHaveBeenCalledWith('/welcome');+ mutationError = error;}++ expect(mutationError).toBeInstanceOf(CombinedGraphQLErrors);+ expect(getSessionGeneration()).toBeNull();+ expect(mockNavigate).toHaveBeenCalled();+ expect(mockNavigate).toHaveBeenCalledWith('/welcome');});});diff --git a/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts b/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.tsindex 5afae3e40d1..946ca567590 100644--- a/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts+++ b/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts@@ -10,6 +10,7 @@ import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceStaimport { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { returnToPathState } from '@/auth/states/returnToPathState';+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';import { appVersionState } from '@/client-config/states/appVersionState';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';@@ -67,6 +68,7 @@ export const useApolloFactory = (options: Partial<Options> = {}) => {currentWorkspace: currentWorkspace,appVersion,onUnauthenticatedError: () => {+ clearSessionGeneration();setIsCookieAuthActive(false);setCurrentUser(null);setCurrentWorkspaceMember(null);diff --git a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.tsindex c93803ad803..77bbaaf095b 100644--- a/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts+++ b/packages/twenty-front/src/modules/apollo/services/__tests__/apollo.factory.test.ts@@ -3,6 +3,9 @@ import { CombinedGraphQLErrors } from '@apollo/client/errors';import fetchMock, { enableFetchMocks } from 'jest-fetch-mock';import { ApolloFactory, type Options } from '@/apollo/services/apollo.factory';+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';+import { getSessionGeneration } from '@/auth/utils/getSessionGeneration';+import { rotateSessionGeneration } from '@/auth/utils/rotateSessionGeneration';import { CUSTOM_WORKSPACE_APPLICATION_MOCK } from '@/object-metadata/hooks/__tests__/constants/CustomWorkspaceApplicationMock.test.constant';import {AUTO_SELECT_FAST_MODEL_ID,@@ -138,6 +141,7 @@ describe('ApolloFactory', () => {beforeEach(() => {jest.clearAllMocks();fetchMock.resetMocks();+ clearSessionGeneration();});it('should create an instance of ApolloFactory', () => {@@ -303,13 +307,51 @@ describe('ApolloFactory', () => {// the end of the session rather than something the client can retry.it('should sign out on an unauthenticated response', async () => {fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);+ mockOnUnauthenticatedError.mockImplementation(clearSessionGeneration);+ rotateSessionGeneration();++ expect(getSessionGeneration()).not.toBeNull();await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);+ expect(getSessionGeneration()).toBeNull();expect(fetchMock).toHaveBeenCalledTimes(1);});+ it('should ignore an unauthenticated response from an older session', async () => {+ let markRequestStarted!: () => void;+ const requestStarted = new Promise<void>((resolve) => {+ markRequestStarted = resolve;+ });+ let releaseResponse!: (response: { body: string }) => void;+ const pendingResponse = new Promise<{ body: string }>((resolve) => {+ releaseResponse = resolve;+ });++ fetchMock.mockResponse(() => {+ markRequestStarted();++ return pendingResponse;+ });++ rotateSessionGeneration();+ const requestSessionGeneration = getSessionGeneration();+ const request = makeRequest();++ expect(requestSessionGeneration).not.toBeNull();++ await requestStarted;+ rotateSessionGeneration();++ expect(getSessionGeneration()).not.toBe(requestSessionGeneration);++ releaseResponse({ body: UNAUTHENTICATED_RESPONSE });++ await expect(request).rejects.toBeInstanceOf(CombinedGraphQLErrors);+ expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();+ });+it('should leave a permission denial alone', async () => {fetchMock.mockResponse(PERMISSION_DENIED_RESPONSE);diff --git a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts b/packages/twenty-front/src/modules/apollo/services/apollo.factory.tsindex 843da31f4a5..ef971e02240 100644--- a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts+++ b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts@@ -12,6 +12,7 @@ import UploadHttpLink from 'apollo-upload-client/UploadHttpLink.mjs';import { type CurrentWorkspaceMember } from '@/auth/states/currentWorkspaceMemberState';import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';+import { getSessionGeneration } from '@/auth/utils/getSessionGeneration';import { logDebug } from '~/utils/logDebug';import { REST_API_BASE_URL } from '@/apollo/constant/rest-api-base-url';@@ -99,6 +100,7 @@ export class ApolloFactory implements ApolloManager {const locale = this.currentWorkspaceMember?.locale ?? i18n.locale;return {+ sessionGeneration: getSessionGeneration(),headers: {...headers,...optionHeaders,@@ -195,11 +197,20 @@ export class ApolloFactory implements ApolloManager {};const errorLink = new ErrorLink(({ error, operation }) => {+ const requestSessionGeneration =+ operation.getContext().sessionGeneration;+ // Missing context must keep sign-out behavior if the link chain changes.+ const isResponseFromCurrentSession =+ requestSessionGeneration === undefined ||+ requestSessionGeneration === getSessionGeneration();+if (CombinedGraphQLErrors.is(error)) {onErrorCb?.(error.errors);for (const graphQLError of error.errors) {if (isUnauthenticatedGraphQLError(graphQLError)) {- onUnauthenticatedError?.();+ if (isResponseFromCurrentSession) {+ onUnauthenticatedError?.();+ }return;}@@ -240,7 +251,9 @@ export class ApolloFactory implements ApolloManager {this.isRestOperation(operation) &&this.isAuthenticationError(error)) {- onUnauthenticatedError?.();+ if (isResponseFromCurrentSession) {+ onUnauthenticatedError?.();+ }return;}diff --git a/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts b/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.tsindex 8925f83f574..69482ca5b01 100644--- a/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts+++ b/packages/twenty-front/src/modules/auth/hooks/__tests__/useRedeemSsoExchangeToken.test.ts@@ -4,6 +4,8 @@ import { Provider as JotaiProvider } from 'jotai';import { isAppEffectRedirectEnabledState } from '@/app/states/isAppEffectRedirectEnabledState';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';import { useRedeemSsoExchangeToken } from '@/auth/hooks/useRedeemSsoExchangeToken';+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';+import { getSessionGeneration } from '@/auth/utils/getSessionGeneration';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import {jotaiStore,@@ -46,6 +48,7 @@ describe('useRedeemSsoExchangeToken', () => {beforeEach(() => {jest.clearAllMocks();localStorage.clear();+ clearSessionGeneration();resetJotaiStore();(useSnackBar as jest.Mock).mockReturnValue({@@ -88,6 +91,7 @@ describe('useRedeemSsoExchangeToken', () => {await result.current.redeemSsoExchangeToken('sso-exchange-token');expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);+ expect(getSessionGeneration()).not.toBeNull();});it('should leave the session inactive when the exchange fails', async () => {@@ -100,6 +104,7 @@ describe('useRedeemSsoExchangeToken', () => {await result.current.redeemSsoExchangeToken('sso-exchange-token');expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(false);+ expect(getSessionGeneration()).toBeNull();});it('should snackbar when redemption fails', async () => {diff --git a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts b/packages/twenty-front/src/modules/auth/hooks/useAuth.tsindex 7790aa45f13..1fd5856c1b0 100644--- a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts@@ -32,6 +32,7 @@ import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { returnToPathState } from '@/auth/states/returnToPathState';import { clearSessionLocalStorageKeys } from '@/auth/utils/clearSessionLocalStorageKeys';import { broadcastSignOutToOtherTabs } from '@/auth/utils/crossTabSignOut';+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';import { isNonEmptyString } from '@sniptt/guards';import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';@@ -126,6 +127,7 @@ export const useAuth = () => {store.set(currentWorkspaceState.atom, null);store.set(currentWorkspaceMemberState.atom, null);store.set(currentUserWorkspaceState.atom, null);+ clearSessionGeneration();clearSessionLocalStorageKeys();setLastAuthenticateWorkspaceDomain(null);window.location.assign(AppPath.SignInUp);diff --git a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.tsindex 27d9c1fc3c7..c0b2c33cbe4 100644--- a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts@@ -3,6 +3,7 @@ import { useStore } from 'jotai';import { useCallback } from 'react';import { useAuth } from '@/auth/hooks/useAuth';+import { useMarkSessionActive } from '@/auth/hooks/useMarkSessionActive';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';import { clearSessionLocalStorageKeys } from '@/auth/utils/clearSessionLocalStorageKeys';import { StopImpersonationDocument } from '~/generated-metadata/graphql';@@ -23,6 +24,7 @@ const reloadWithSession = (returnPath: string) => {export const useImpersonationSession = () => {const store = useStore();const { getAuthTokensFromLoginToken, signOut } = useAuth();+ const markSessionActive = useMarkSessionActive();const [stopImpersonationMutation] = useMutation(StopImpersonationDocument);const startImpersonating = useCallback(@@ -66,6 +68,7 @@ export const useImpersonationSession = () => {const { data } = await stopImpersonationMutation();if (data?.stopImpersonation.canRestoreImpersonatorSession === true) {+ markSessionActive();clearSessionLocalStorageKeys();reloadWithSession(returnPath);@@ -76,7 +79,7 @@ export const useImpersonationSession = () => {// Cross-workspace: the admin session on its own origin was never replaced.window.close();await signOut();- }, [signOut, stopImpersonationMutation]);+ }, [markSessionActive, signOut, stopImpersonationMutation]);const hasStoredSession = useCallback(() => {return sessionStorage.getItem(IMPERSONATION_SESSION_KEY) !== null;diff --git a/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.tsindex 60d42ffa8e8..a172a4617fc 100644--- a/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts@@ -3,6 +3,7 @@ import { useCallback } from 'react';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';+import { rotateSessionGeneration } from '@/auth/utils/rotateSessionGeneration';// The auth mutations set the session cookie server-side, which the client// cannot read, so every flow that authenticates has to record that a session@@ -11,6 +12,7 @@ export const useMarkSessionActive = () => {const store = useStore();return useCallback(() => {+ rotateSessionGeneration();store.set(isCookieAuthActiveState.atom, true);store.set(isPendingServerSignOutState.atom, false);}, [store]);diff --git a/packages/twenty-front/src/modules/auth/utils/__tests__/sessionGeneration.test.ts b/packages/twenty-front/src/modules/auth/utils/__tests__/sessionGeneration.test.tsnew file mode 100644index 00000000000..356f9d731a6--- /dev/null+++ b/packages/twenty-front/src/modules/auth/utils/__tests__/sessionGeneration.test.ts@@ -0,0 +1,59 @@+import { clearSessionGeneration } from '@/auth/utils/clearSessionGeneration';+import { getSessionGeneration } from '@/auth/utils/getSessionGeneration';+import { rotateSessionGeneration } from '@/auth/utils/rotateSessionGeneration';++describe('sessionGeneration', () => {+ beforeEach(() => {+ clearSessionGeneration();+ });++ afterEach(() => {+ jest.restoreAllMocks();+ clearSessionGeneration();+ });++ it('should rotate and clear the session generation', () => {+ rotateSessionGeneration();+ const firstGeneration = getSessionGeneration();++ rotateSessionGeneration();++ expect(firstGeneration).not.toBeNull();+ expect(getSessionGeneration()).not.toBe(firstGeneration);++ clearSessionGeneration();++ expect(getSessionGeneration()).toBeNull();+ });++ it('should keep an in-memory generation when storage is unavailable', () => {+ jest.spyOn(Storage.prototype, 'getItem').mockImplementation(() => {+ throw new Error('Storage is unavailable');+ });+ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('Storage is unavailable');+ });++ rotateSessionGeneration();+ const firstGeneration = getSessionGeneration();++ rotateSessionGeneration();++ expect(firstGeneration).not.toBeNull();+ expect(getSessionGeneration()).not.toBe(firstGeneration);+ });++ it('should not replace an unpersisted generation with a stale stored one', () => {+ rotateSessionGeneration();+ const persistedGeneration = getSessionGeneration();++ jest.spyOn(Storage.prototype, 'setItem').mockImplementation(() => {+ throw new Error('Storage is read-only');+ });++ rotateSessionGeneration();++ expect(getSessionGeneration()).not.toBeNull();+ expect(getSessionGeneration()).not.toBe(persistedGeneration);+ });+});diff --git a/packages/twenty-front/src/modules/auth/utils/clearSessionGeneration.ts b/packages/twenty-front/src/modules/auth/utils/clearSessionGeneration.tsnew file mode 100644index 00000000000..31589a22d8f--- /dev/null+++ b/packages/twenty-front/src/modules/auth/utils/clearSessionGeneration.ts@@ -0,0 +1,4 @@+import { sessionGenerationStore } from '@/auth/utils/sessionGenerationStore';++export const clearSessionGeneration = (): void =>+ sessionGenerationStore.clear();diff --git a/packages/twenty-front/src/modules/auth/utils/getSessionGeneration.ts b/packages/twenty-front/src/modules/auth/utils/getSessionGeneration.tsnew file mode 100644index 00000000000..b9d36803fc6--- /dev/null+++ b/packages/twenty-front/src/modules/auth/utils/getSessionGeneration.ts@@ -0,0 +1,4 @@+import { sessionGenerationStore } from '@/auth/utils/sessionGenerationStore';++export const getSessionGeneration = (): string | null =>+ sessionGenerationStore.get();diff --git a/packages/twenty-front/src/modules/auth/utils/rotateSessionGeneration.ts b/packages/twenty-front/src/modules/auth/utils/rotateSessionGeneration.tsnew file mode 100644index 00000000000..8bb09a72f46--- /dev/null+++ b/packages/twenty-front/src/modules/auth/utils/rotateSessionGeneration.ts@@ -0,0 +1,4 @@+import { sessionGenerationStore } from '@/auth/utils/sessionGenerationStore';++export const rotateSessionGeneration = (): void =>+ sessionGenerationStore.rotate();diff --git a/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts b/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.tsnew file mode 100644index 00000000000..043d2bac530--- /dev/null+++ b/packages/twenty-front/src/modules/auth/utils/sessionGenerationStore.ts@@ -0,0 +1,51 @@+import { v4 as uuidv4 } from 'uuid';++const SESSION_GENERATION_LOCAL_STORAGE_KEY = 'authSessionGeneration';++class SessionGenerationStore {+ private inMemorySessionGeneration: string | null = null;+ private hasUnpersistedSessionGeneration = false;++ get(): string | null {+ if (this.hasUnpersistedSessionGeneration) {+ return this.inMemorySessionGeneration;+ }++ try {+ // Direct reads observe another tab's rotation immediately; persisted Jotai+ // state only reads storage when the atom initializes.+ this.inMemorySessionGeneration = localStorage.getItem(+ SESSION_GENERATION_LOCAL_STORAGE_KEY,+ );+ } catch {}++ return this.inMemorySessionGeneration;+ }++ rotate(): void {+ this.inMemorySessionGeneration = uuidv4();++ try {+ localStorage.setItem(+ SESSION_GENERATION_LOCAL_STORAGE_KEY,+ this.inMemorySessionGeneration,+ );+ this.hasUnpersistedSessionGeneration = false;+ } catch {+ this.hasUnpersistedSessionGeneration = true;+ }+ }++ clear(): void {+ this.inMemorySessionGeneration = null;++ try {+ localStorage.removeItem(SESSION_GENERATION_LOCAL_STORAGE_KEY);+ this.hasUnpersistedSessionGeneration = false;+ } catch {+ this.hasUnpersistedSessionGeneration = true;+ }+ }+}++export const sessionGenerationStore = new SessionGenerationStore();