The open alternative to Salesforce, designed for AI.
TypeScript crmcrm-systemcustomergood-first-issuegraphqlhacktoberfestjavascriptmarketingmonoreponestjsopen-sourcepostgresqlreactreactjssalestypescriptweb
Remove the legacy token-pair credential from the front (#25070)
Félix Malfaitb6223f729865
diff --git a/packages/twenty-front/.storybook/preview.tsx b/packages/twenty-front/.storybook/preview.tsxindex 6410bc1dec6..6b94e4fea3f 100644--- a/packages/twenty-front/.storybook/preview.tsx+++ b/packages/twenty-front/.storybook/preview.tsx@@ -39,7 +39,6 @@ import { messages as enMessages } from '../src/locales/generated/en';i18n.load({ [SOURCE_LOCALE]: enMessages });i18n.activate(SOURCE_LOCALE);-import { mockedUserJWT } from '~/testing/mock-data/jwt';// oxlint-disable-next-line no-restricted-importsimport { ClickOutsideListenerContext } from '../src/modules/ui/utilities/pointer-event/contexts/ClickOutsideListenerContext';@@ -160,9 +159,6 @@ const preview: Preview = {order: ['UI', 'Modules', 'Pages'],},},- cookie: {- tokenPair: `{%22accessOrWorkspaceAgnosticToken%22:{%22token%22:%22${mockedUserJWT}%22%2C%22expiresAt%22:%222023-07-18T15:06:40.704Z%22%2C%22__typename%22:%22AuthToken%22}%2C%22refreshToken%22:{%22token%22:%22${mockedUserJWT}%22%2C%22expiresAt%22:%222023-10-15T15:06:41.558Z%22%2C%22__typename%22:%22AuthToken%22}%2C%22__typename%22:%22AuthTokenPair%22}`,- },},};diff --git a/packages/twenty-front/src/index.tsx b/packages/twenty-front/src/index.tsxindex 23c414a6221..c074b9352a4 100644--- a/packages/twenty-front/src/index.tsx+++ b/packages/twenty-front/src/index.tsx@@ -2,7 +2,6 @@ import ReactDOM from 'react-dom/client';import { App } from '@/app/components/App';import '@/app/utils/setupMonacoEnvironment';-import { migrateTokenPairCookieToLocalStorage } from '@/auth/utils/migrateTokenPairCookieToLocalStorage';import { hydrateMetadataStore } from '@/metadata-store/storage/metadataStoreStorage';import '@fontsource/dm-mono/400.css';import '@fontsource/dm-mono/500.css';@@ -16,10 +15,6 @@ import 'twenty-ui/theme-light.css';import 'twenty-ui/theme-dark.css';import './index.css';-// TODO: REMOVE this after 2026-12-12 — temporary migration of tokenPair from the-// legacy cookie to localStorage (legacy cookie has a 180-day expiry).-migrateTokenPairCookieToLocalStorage();-const renderApp = () => {const root = ReactDOM.createRoot(document.getElementById('root') ?? document.body,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 d436bf558d5..1df6cbef516 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@@ -7,13 +7,6 @@ import { useApolloFactory } from '@/apollo/hooks/useApolloFactory';enableFetchMocks();-jest.mock('@/apollo/utils/getTokenPair', () => ({- getTokenPair: jest.fn().mockReturnValue({- accessOrWorkspaceAgnosticToken: { token: 'testAccessToken', expiresAt: '' },- refreshToken: { token: 'testRefreshToken', expiresAt: '' },- }),-}));-const mockNavigate = jest.fn();jest.mock('react-router-dom', () => {diff --git a/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts b/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.tsindex f6c623a33c9..5afae3e40d1 100644--- a/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts+++ b/packages/twenty-front/src/modules/apollo/hooks/useApolloFactory.ts@@ -11,7 +11,6 @@ import { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMembeimport { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { returnToPathState } from '@/auth/states/returnToPathState';import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';-import { tokenPairState } from '@/auth/states/tokenPairState';import { appVersionState } from '@/client-config/states/appVersionState';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';@@ -28,7 +27,6 @@ export const useApolloFactory = (options: Partial<Options> = {}) => {const apolloRef = useRef<ApolloFactory | null>(null);const navigate = useNavigate();- const setTokenPair = useSetAtomState(tokenPairState);const setIsCookieAuthActive = useSetAtomState(isCookieAuthActiveState);const [currentWorkspace, setCurrentWorkspace] = useAtomState(currentWorkspaceState,@@ -68,11 +66,7 @@ export const useApolloFactory = (options: Partial<Options> = {}) => {currentWorkspaceMember: currentWorkspaceMember,currentWorkspace: currentWorkspace,appVersion,- onTokenPairChange: (tokenPair) => {- setTokenPair(tokenPair);- },onUnauthenticatedError: () => {- setTokenPair(null);setIsCookieAuthActive(false);setCurrentUser(null);setCurrentWorkspaceMember(null);@@ -115,7 +109,6 @@ export const useApolloFactory = (options: Partial<Options> = {}) => {return apolloRef.current.getClient();// oxlint-disable-next-line react-hooks/exhaustive-deps}, [- setTokenPair,setCurrentUser,setCurrentWorkspaceMember,setCurrentWorkspace,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 63bf9ab7296..c93803ad803 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,53 +3,22 @@ import { CombinedGraphQLErrors } from '@apollo/client/errors';import fetchMock, { enableFetchMocks } from 'jest-fetch-mock';import { ApolloFactory, type Options } from '@/apollo/services/apollo.factory';-import { getTokenPair } from '@/apollo/utils/getTokenPair';-import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';-import { renewToken } from '@/auth/services/AuthService';import { CUSTOM_WORKSPACE_APPLICATION_MOCK } from '@/object-metadata/hooks/__tests__/constants/CustomWorkspaceApplicationMock.test.constant';import {AUTO_SELECT_FAST_MODEL_ID,AUTO_SELECT_SMART_MODEL_ID,} from 'twenty-shared/constants';import {- type AuthTokenPair,WorkspaceActivationStatus,WorkspaceDiscoverability,} from '~/generated-metadata/graphql';enableFetchMocks();-jest.mock('@/auth/services/AuthService', () => {- const initialAuthService = jest.requireActual('@/auth/services/AuthService');- return {- ...initialAuthService,- renewToken: jest.fn(),- };-});--jest.mock('@/apollo/utils/getTokenPair', () => ({- getTokenPair: jest.fn(),-}));-jest.mock('~/utils/sleep', () => ({sleep: jest.fn().mockResolvedValue(undefined),}));-const CURRENT_TOKEN_PAIR: AuthTokenPair = {- accessOrWorkspaceAgnosticToken: { token: 'testAccessToken', expiresAt: '' },- refreshToken: { token: 'testRefreshToken', expiresAt: '' },-};--const RENEWED_TOKEN_PAIR: AuthTokenPair = {- accessOrWorkspaceAgnosticToken: { token: 'newAccessToken', expiresAt: '' },- refreshToken: { token: 'newRefreshToken', expiresAt: '' },-};--// Mirrors persistence: a replay re-reads the pair renewal just stored, so the-// mock must move with it or an assertion on the replay header proves nothing.-let storedTokenPair: AuthTokenPair | undefined = CURRENT_TOKEN_PAIR;-const UNAUTHENTICATED_RESPONSE = JSON.stringify({data: {},errors: [{ extensions: { code: 'UNAUTHENTICATED' } }],@@ -68,9 +37,6 @@ const PERMISSION_DENIED_RESPONSE = JSON.stringify({const mockOnError = jest.fn();const mockOnNetworkError = jest.fn();const mockOnPayloadTooLarge = jest.fn();-const mockOnTokenPairChange = jest.fn((tokenPair: AuthTokenPair) => {- storedTokenPair = tokenPair;-});const mockOnUnauthenticatedError = jest.fn();const mockWorkspaceMember = {@@ -134,7 +100,6 @@ const createMockOptions = (): Options => ({onError: mockOnError,onNetworkError: mockOnNetworkError,onPayloadTooLarge: mockOnPayloadTooLarge,- onTokenPairChange: mockOnTokenPairChange,onUnauthenticatedError: mockOnUnauthenticatedError,appVersion: '1.0.0',});@@ -173,13 +138,6 @@ describe('ApolloFactory', () => {beforeEach(() => {jest.clearAllMocks();fetchMock.resetMocks();- jest.mocked(renewToken).mockReset().mockResolvedValue(RENEWED_TOKEN_PAIR);- storedTokenPair = CURRENT_TOKEN_PAIR;- jest- .mocked(getTokenPair)- .mockReset()- .mockImplementation(() => storedTokenPair);- jotaiStore.set(isCookieAuthActiveState.atom, false);});it('should create an instance of ApolloFactory', () => {@@ -267,7 +225,7 @@ describe('ApolloFactory', () => {}}, 10000);- it('should call renewToken when encountering any error', async () => {+ it('should call onNetworkError when the request itself fails', async () => {fetchMock.mockReject(() => Promise.reject({ message: 'Unknown error' }));try {@@ -314,158 +272,50 @@ describe('ApolloFactory', () => {}}, 10000);- it('should renew tokens and replay the operation when the access token is rejected', async () => {- fetchMock.mockResponses(- UNAUTHENTICATED_RESPONSE,- JSON.stringify({ data: { trackAnalytics: { success: true } } }),+ // fetch normalises header names, so assert case-insensitively rather than+ // depending on the casing the mock happens to expose.+ const readHeader = (+ headers: Record<string, string>,+ name: string,+ ): string | undefined =>+ Object.entries(headers).find(+ ([key]) => key.toLowerCase() === name.toLowerCase(),+ )?.[1];++ it('should not attach an Authorization header', async () => {+ fetchMock.mockResponse(() =>+ Promise.resolve({ body: JSON.stringify({ data: {} }) }),);await makeRequest();- expect(renewToken).toHaveBeenCalledTimes(1);- expect(mockOnTokenPairChange).toHaveBeenCalledWith(RENEWED_TOKEN_PAIR);- expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();- });+ const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<+ string,+ string+ >;- it('should trigger unauthenticated error when the server rejects the refresh token', async () => {- fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);- jest.mocked(renewToken).mockRejectedValue(- new CombinedGraphQLErrors({- errors: [- {- message: 'This refresh token has been revoked.',- extensions: { code: 'FORBIDDEN' },- },- ],- }),- );-- await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);-- expect(renewToken).toHaveBeenCalledTimes(1);- expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);- expect(mockOnTokenPairChange).not.toHaveBeenCalled();+ expect(readHeader(headers, 'authorization')).toBeUndefined();+ // Version-mismatch detection must keep working without one.+ expect(readHeader(headers, 'X-App-Version')).toBe('1.0.0');});- it('should keep the session when token renewal fails on a network error', async () => {+ // The session cookie is issued and refreshed server-side, so a rejection is+ // 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);- jest.mocked(renewToken).mockRejectedValue(new Error('Failed to fetch'));await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);- expect(renewToken).toHaveBeenCalledTimes(4);- expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();- expect(mockOnTokenPairChange).not.toHaveBeenCalled();+ expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);});- it('should keep the session when token renewal fails on a server error', async () => {- fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);- jest.mocked(renewToken).mockRejectedValue(- new CombinedGraphQLErrors({- errors: [- {- message: 'Internal server error',- extensions: { code: 'INTERNAL_SERVER_ERROR' },- },- ],- }),- );+ it('should leave a permission denial alone', async () => {+ fetchMock.mockResponse(PERMISSION_DENIED_RESPONSE);await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);- expect(renewToken).toHaveBeenCalledTimes(1);+ expect(fetchMock).toHaveBeenCalledTimes(1);expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();- expect(mockOnTokenPairChange).not.toHaveBeenCalled();- });-- it('should trigger unauthenticated error without renewing when the stored pair has no refresh token', async () => {- jest.mocked(getTokenPair).mockReturnValue({- accessOrWorkspaceAgnosticToken: {- token: 'testAccessToken',- expiresAt: '',- },- } as unknown as AuthTokenPair);- fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);-- await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);-- expect(renewToken).not.toHaveBeenCalled();- expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);- });- describe('cookie auth', () => {- const setCookieAuthActive = () =>- jotaiStore.set(isCookieAuthActiveState.atom, true);-- // fetch normalises header names, so assert case-insensitively rather than- // depending on the casing the mock happens to expose.- const readHeader = (- headers: Record<string, string>,- name: string,- ): string | undefined =>- Object.entries(headers).find(- ([key]) => key.toLowerCase() === name.toLowerCase(),- )?.[1];-- // A pair still exists between sign-in and the boot effect's switch, and- // across the impersonation exchange. Sending it would take precedence over- // the session cookie server-side and bypass the CSRF origin check.- it('should not attach the Bearer header while cookie auth is active', async () => {- setCookieAuthActive();- fetchMock.mockResponse(() =>- Promise.resolve({ body: JSON.stringify({ data: {} }) }),- );-- await makeRequest();-- const headers = fetchMock.mock.calls[0]?.[1]?.headers as Record<- string,- string- >;-- expect(readHeader(headers, 'authorization')).toBeUndefined();- // Version-mismatch detection must keep working in cookie-auth mode.- expect(readHeader(headers, 'X-App-Version')).toBe('1.0.0');- });-- it('should leave a permission denial alone', async () => {- setCookieAuthActive();- fetchMock.mockResponse(PERMISSION_DENIED_RESPONSE);-- await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);-- expect(fetchMock).toHaveBeenCalledTimes(1);- expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);- expect(mockOnUnauthenticatedError).not.toHaveBeenCalled();- });-- // CookieSessionBootEffect can switch to cookie auth while a renewal is in- // flight. Publishing that renewal would put the refresh token back for- // good, since the boot effect only probes while cookie auth is inactive.- it('should not restore the token pair when it is cleared mid-renewal', async () => {- jest.mocked(renewToken).mockImplementation(async () => {- storedTokenPair = undefined;- setCookieAuthActive();-- return RENEWED_TOKEN_PAIR;- });- fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);-- await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);-- expect(renewToken).toHaveBeenCalled();- expect(mockOnTokenPairChange).not.toHaveBeenCalled();- });-- it('should sign out on an unauthenticated response, with no pair to fall back to', async () => {- setCookieAuthActive();- storedTokenPair = undefined;- fetchMock.mockResponse(UNAUTHENTICATED_RESPONSE);-- await expect(makeRequest()).rejects.toBeInstanceOf(CombinedGraphQLErrors);-- expect(renewToken).not.toHaveBeenCalled();- expect(mockOnUnauthenticatedError).toHaveBeenCalledTimes(1);- expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);- });});});diff --git a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts b/packages/twenty-front/src/modules/apollo/services/apollo.factory.tsindex d7e6a94fe20..843da31f4a5 100644--- a/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts+++ b/packages/twenty-front/src/modules/apollo/services/apollo.factory.ts@@ -7,21 +7,15 @@ import {import { setContext } from '@apollo/client/link/context';import { ErrorLink } from '@apollo/client/link/error';import { RetryLink } from '@apollo/client/link/retry';-import { from, switchMap, throwError } from 'rxjs';import { RestLink } from 'apollo-link-rest';import UploadHttpLink from 'apollo-upload-client/UploadHttpLink.mjs';-import { renewToken } from '@/auth/services/AuthService';import { type CurrentWorkspaceMember } from '@/auth/states/currentWorkspaceMemberState';import { type CurrentWorkspace } from '@/auth/states/currentWorkspaceState';-import { type AuthTokenPair } from '~/generated-metadata/graphql';import { logDebug } from '~/utils/logDebug';-import { retryWithBackoff } from '~/utils/retryWithBackoff';import { REST_API_BASE_URL } from '@/apollo/constant/rest-api-base-url';import { type ApolloManager } from '@/apollo/types/apolloManager.interface';-import { getIsCookieAuthActive } from '@/apollo/utils/getIsCookieAuthActive';-import { getTokenPair } from '@/apollo/utils/getTokenPair';import { isUnauthenticatedGraphQLError } from '@/apollo/utils/isUnauthenticatedGraphQLError';import { loggerLink } from '@/apollo/utils/loggerLink';import { StreamingRestLink } from '@/apollo/utils/streamingRestLink';@@ -35,35 +29,9 @@ import {} from 'graphql';import isEmpty from 'lodash.isempty';import { getGenericOperationName, isDefined } from 'twenty-shared/utils';-import { REACT_APP_SERVER_BASE_URL } from '~/config';-import { isUndefinedOrNull } from '~/utils/isUndefinedOrNull';const logger = loggerLink(() => 'Twenty');-// Shared across all ApolloFactory instances so concurrent-// UNAUTHENTICATED errors from /graphql and /metadata clients-// deduplicate into a single renewal request.-let renewalPromise: Promise<boolean> | null = null;--const TOKEN_RENEWAL_MAX_RETRIES = 3;-const TOKEN_RENEWAL_RETRY_DELAY_MS = 1000;--// Error codes returned by the renewToken mutation when the server-// definitively rejects the refresh token (expired, revoked or unknown).-const TOKEN_RENEWAL_REJECTION_CODES = [- 'UNAUTHENTICATED',- 'FORBIDDEN',- 'BAD_USER_INPUT',-];--const isTokenRenewalRejection = (error: unknown): boolean =>- CombinedGraphQLErrors.is(error) &&- error.errors.some((graphQLError) =>- TOKEN_RENEWAL_REJECTION_CODES.includes(- graphQLError.extensions?.code as string,- ),- );-export interface Options {uri: string;cache: ApolloClient.Options['cache'];@@ -72,7 +40,6 @@ export interface Options {devtools?: { enabled?: boolean };onError?: (err: readonly GraphQLFormattedError[] | undefined) => void;onNetworkError?: (err: Error | ServerParseError | ServerError) => void;- onTokenPairChange?: (tokenPair: AuthTokenPair) => void;onUnauthenticatedError?: () => void;onAppVersionMismatch?: (message: string) => void;onPayloadTooLarge?: (message: string) => void;@@ -98,7 +65,6 @@ export class ApolloFactory implements ApolloManager {devtools,onError: onErrorCb,onNetworkError,- onTokenPairChange,onUnauthenticatedError,onAppVersionMismatch,onPayloadTooLarge,@@ -129,40 +95,13 @@ export class ApolloFactory implements ApolloManager {credentials: 'include',});- const authLink = setContext(async (_, { headers, skipAuthToken }) => {- const tokenPair = getTokenPair();-+ const authLink = setContext(async (_, { headers }) => {const locale = this.currentWorkspaceMember?.locale ?? i18n.locale;- // A pair can still be present while cookie auth is active: sign-in and- // the impersonation exchange both store one before the cookie takes- // over. It must not be sent. Bearer takes precedence over the session- // cookie server-side, so attaching it would keep the cookie unused and- // bypass the CSRF origin check.- if (- isUndefinedOrNull(tokenPair) ||- skipAuthToken === true ||- getIsCookieAuthActive()- ) {- return {- headers: {- ...headers,- ...optionHeaders,- 'x-locale': locale,- ...(isDefined(this.appVersion) && {- 'X-App-Version': this.appVersion,- }),- },- };- }-- const token = tokenPair.accessOrWorkspaceAgnosticToken?.token;-return {headers: {...headers,...optionHeaders,- authorization: token ? `Bearer ${token}` : '','x-locale': locale,...(isDefined(this.appVersion) && {'X-App-Version': this.appVersion,@@ -177,9 +116,15 @@ export class ApolloFactory implements ApolloManager {},attempts: {max: 2,- retryIf: (error) => {+ retryIf: (error, operation) => {// oxlint-disable-next-line no-consoleconsole.log('retryIf error from retryLink', error);+ // A retry is a fresh request seconds later, so it carries whatever+ // cookie exists by then rather than the one that was current when+ // the operation was issued. See PendingServerSignOutEffect.+ if (operation.getContext().skipRetry === true) {+ return false;+ }if (this.isAuthenticationError(error)) {return false;}@@ -191,83 +136,6 @@ export class ApolloFactory implements ApolloManager {},});- const attemptTokenRenewal = async (): Promise<void> => {- const graphqlUri = `${REACT_APP_SERVER_BASE_URL}/metadata`;- const refreshTokenSnapshot = getTokenPair()?.refreshToken?.token;-- const tokens = await retryWithBackoff(- () => renewToken(graphqlUri, getTokenPair()),- {- maxRetries: TOKEN_RENEWAL_MAX_RETRIES,- baseDelayMs: TOKEN_RENEWAL_RETRY_DELAY_MS,- shouldRetry: (error) =>- !CombinedGraphQLErrors.is(error) && isDefined(getTokenPair()),- },- );-- // Same snapshot guard as ensureTokenRenewed. CookieSessionBootEffect- // can clear the pair while this is in flight, and publishing anyway- // would put a fresh refresh token back in localStorage for good: the- // boot effect only probes while cookie auth is inactive, so it never- // clears it again.- if (- isDefined(tokens) &&- getTokenPair()?.refreshToken?.token === refreshTokenSnapshot- ) {- onTokenPairChange?.(tokens);- }- };-- const handleTokenRenewal = (- operation: ApolloLink.Operation,- forward: ApolloLink.ForwardFunction,- error: ErrorLike,- ) => {- // Renewing and replaying a deliberately headerless operation (the cookie- // session probe) could loop, so it must fail as-is.- if (operation.getContext().skipAuthToken === true) {- return throwError(() => error);- }-- if (!getTokenPair()?.refreshToken?.token) {- onUnauthenticatedError?.();-- return throwError(() => error);- }-- if (!renewalPromise) {- renewalPromise = attemptTokenRenewal()- .then(() => true)- .catch((renewalError) => {- if (isTokenRenewalRejection(renewalError)) {- // oxlint-disable-next-line no-console- console.log(- 'Refresh token rejected by the server, triggering unauthenticated error',- renewalError,- );- onUnauthenticatedError?.();- } else {- // oxlint-disable-next-line no-console- console.log(- 'Token renewal failed transiently, keeping session for retry',- renewalError,- );- }-- return false;- })- .finally(() => {- renewalPromise = null;- });- }-- return from(renewalPromise).pipe(- switchMap((succeeded) =>- succeeded ? forward(operation) : throwError(() => error),- ),- );- };-const sendToSentry = ({graphQLError,operation,@@ -326,14 +194,14 @@ export class ApolloFactory implements ApolloManager {});};- const errorLink = new ErrorLink(({ error, operation, forward }) => {+ const errorLink = new ErrorLink(({ error, operation }) => {if (CombinedGraphQLErrors.is(error)) {onErrorCb?.(error.errors);for (const graphQLError of error.errors) {if (isUnauthenticatedGraphQLError(graphQLError)) {- // oxlint-disable-next-line no-console- console.log('Unauthenticated, triggering token renewal');- return handleTokenRenewal(operation, forward, error);+ onUnauthenticatedError?.();++ return;}switch (graphQLError?.extensions?.code) {@@ -372,11 +240,9 @@ export class ApolloFactory implements ApolloManager {this.isRestOperation(operation) &&this.isAuthenticationError(error)) {- // oxlint-disable-next-line no-console- console.log(- 'Authentication error, triggering token renewal from errorLink',- );- return handleTokenRenewal(operation, forward, error);+ onUnauthenticatedError?.();++ return;}if (this.isPayloadTooLargeError(error)) {diff --git a/packages/twenty-front/src/modules/apollo/utils/__tests__/getTokenPair.test.ts b/packages/twenty-front/src/modules/apollo/utils/__tests__/getTokenPair.test.tsdeleted file mode 100644index d3a1756039b..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/__tests__/getTokenPair.test.ts+++ /dev/null@@ -1,241 +0,0 @@-import { getTokenPair } from '@/apollo/utils/getTokenPair';-import { TOKEN_PAIR_LOCAL_STORAGE_KEY } from '@/auth/states/tokenPairState';--describe('getTokenPair', () => {- let getItemSpy: jest.SpyInstance;- let removeItemSpy: jest.SpyInstance;-- beforeEach(() => {- getItemSpy = jest.spyOn(Storage.prototype, 'getItem');- removeItemSpy = jest.spyOn(Storage.prototype, 'removeItem');- });-- afterEach(() => {- jest.restoreAllMocks();- });-- describe('when tokenPair is not stored', () => {- it('should return undefined when nothing is stored', () => {- getItemSpy.mockReturnValue(null);-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(getItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });- });-- describe('when stored tokenPair has invalid JSON', () => {- it('should remove the item and return undefined for malformed JSON', () => {- getItemSpy.mockReturnValue('invalid-json');-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined for partial JSON', () => {- getItemSpy.mockReturnValue('{"incomplete":');-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });- });-- describe('when stored tokenPair has invalid structure', () => {- it('should remove the item and return undefined when tokenPair is null', () => {- getItemSpy.mockReturnValue('null');-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined when tokenPair is not an object', () => {- getItemSpy.mockReturnValue('"string-value"');-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined when accessOrWorkspaceAgnosticToken is missing', () => {- const invalidTokenPair = {- refreshToken: { token: 'refresh-token' },- };- getItemSpy.mockReturnValue(JSON.stringify(invalidTokenPair));-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined when accessOrWorkspaceAgnosticToken is not an object', () => {- const invalidTokenPair = {- accessOrWorkspaceAgnosticToken: 'not-an-object',- refreshToken: { token: 'refresh-token' },- };- getItemSpy.mockReturnValue(JSON.stringify(invalidTokenPair));-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined when token is missing', () => {- const invalidTokenPair = {- accessOrWorkspaceAgnosticToken: {- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: { token: 'refresh-token' },- };- getItemSpy.mockReturnValue(JSON.stringify(invalidTokenPair));-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should remove the item and return undefined when token is not a string', () => {- const invalidTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 123,- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: { token: 'refresh-token' },- };- getItemSpy.mockReturnValue(JSON.stringify(invalidTokenPair));-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);- });-- it('should accept empty string token as valid', () => {- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: '',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: { token: 'refresh-token' },- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(removeItemSpy).not.toHaveBeenCalled();- });- });-- describe('when stored tokenPair has valid structure', () => {- it('should return valid tokenPair with all required fields', () => {- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'valid-access-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'valid-refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(removeItemSpy).not.toHaveBeenCalled();- });-- it('should return valid tokenPair with minimal required fields', () => {- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'minimal-access-token',- },- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(removeItemSpy).not.toHaveBeenCalled();- });-- it('should return valid tokenPair with extra fields', () => {- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'access-token-with-extras',- expiresAt: '2024-01-01T00:00:00Z',- extraField: 'extra-value',- },- refreshToken: {- token: 'refresh-token',- },- additionalField: 'additional-value',- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(removeItemSpy).not.toHaveBeenCalled();- });- });-- describe('edge cases', () => {- it('should handle JSON parsing error gracefully', () => {- getItemSpy.mockReturnValue('{"valid": "json"');- const originalParse = JSON.parse;- JSON.parse = jest.fn(() => {- throw new SyntaxError('Unexpected end of JSON input');- });-- const result = getTokenPair();-- expect(result).toBeUndefined();- expect(removeItemSpy).toHaveBeenCalledWith(TOKEN_PAIR_LOCAL_STORAGE_KEY);-- JSON.parse = originalParse;- });-- it('should handle very long token strings', () => {- const longToken = 'a'.repeat(10000);- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: longToken,- },- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(result?.accessOrWorkspaceAgnosticToken.token).toHaveLength(10000);- });-- it('should handle unicode characters in token', () => {- const unicodeToken = 'token-with-unicode-🚀-characters-∑';- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: unicodeToken,- },- };- getItemSpy.mockReturnValue(JSON.stringify(validTokenPair));-- const result = getTokenPair();-- expect(result).toEqual(validTokenPair);- expect(result?.accessOrWorkspaceAgnosticToken.token).toBe(unicodeToken);- });- });-});diff --git a/packages/twenty-front/src/modules/apollo/utils/__tests__/hasTokenPair.test.ts b/packages/twenty-front/src/modules/apollo/utils/__tests__/hasTokenPair.test.tsdeleted file mode 100644index d2425dd9b44..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/__tests__/hasTokenPair.test.ts+++ /dev/null@@ -1,177 +0,0 @@-import { getTokenPair } from '@/apollo/utils/getTokenPair';-import { hasTokenPair } from '@/apollo/utils/hasTokenPair';--jest.mock('../getTokenPair');--const mockGetTokenPair = getTokenPair as jest.MockedFunction<- typeof getTokenPair->;--describe('hasTokenPair', () => {- beforeEach(() => {- jest.clearAllMocks();- });-- describe('when getTokenPair returns a valid token pair', () => {- it('should return true for a complete valid token pair', () => {- const validTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'valid-access-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'valid-refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(validTokenPair);-- const result = hasTokenPair();-- expect(result).toBe(true);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });-- it('should return true for a minimal valid token pair', () => {- const minimalTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'minimal-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(minimalTokenPair);-- const result = hasTokenPair();-- expect(result).toBe(true);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });-- it('should return true even if token pair has extra fields', () => {- const tokenPairWithExtras = {- accessOrWorkspaceAgnosticToken: {- token: 'access-token',- expiresAt: '2024-01-01T00:00:00Z',- customField: 'custom-value',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- extraField: 'extra-value',- };- mockGetTokenPair.mockReturnValue(tokenPairWithExtras);-- const result = hasTokenPair();-- expect(result).toBe(true);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });- });-- describe('when getTokenPair returns undefined', () => {- it('should return false when no token pair exists', () => {- mockGetTokenPair.mockReturnValue(undefined);-- const result = hasTokenPair();-- expect(result).toBe(false);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });- });-- describe('validation behavior', () => {- it('should rely on getTokenPair for all validation logic', () => {- mockGetTokenPair.mockReturnValue(undefined);-- hasTokenPair();-- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);-- mockGetTokenPair.mockClear();- const validToken = {- accessOrWorkspaceAgnosticToken: {- token: 'valid-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(validToken);-- const result = hasTokenPair();-- expect(result).toBe(true);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });-- it('should not perform additional validation beyond getTokenPair', () => {- const tokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'any-token-that-getTokenPair-considers-valid',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(tokenPair);-- const result = hasTokenPair();-- expect(result).toBe(true);- expect(mockGetTokenPair).toHaveBeenCalledTimes(1);- });- });-- describe('multiple calls', () => {- it('should call getTokenPair on each invocation', () => {- const tokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'test-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(tokenPair);-- hasTokenPair();- hasTokenPair();- hasTokenPair();-- expect(mockGetTokenPair).toHaveBeenCalledTimes(3);- });-- it('should return consistent results for consistent getTokenPair results', () => {- const tokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'consistent-token',- expiresAt: '2024-01-01T00:00:00Z',- },- refreshToken: {- token: 'refresh-token',- expiresAt: '2024-01-02T00:00:00Z',- },- };- mockGetTokenPair.mockReturnValue(tokenPair);-- const result1 = hasTokenPair();- const result2 = hasTokenPair();- const result3 = hasTokenPair();-- expect(result1).toBe(true);- expect(result2).toBe(true);- expect(result3).toBe(true);- });- });-});diff --git a/packages/twenty-front/src/modules/apollo/utils/getIsCookieAuthActive.ts b/packages/twenty-front/src/modules/apollo/utils/getIsCookieAuthActive.tsdeleted file mode 100644index 3b9ba6fa211..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/getIsCookieAuthActive.ts+++ /dev/null@@ -1,13 +0,0 @@-import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';--// Read straight off the store rather than through a subscription because the-// Apollo links run per request and must see the value synchronously, before-// the render a React subscription would wait for.-export const getIsCookieAuthActive = (): boolean => {- try {- return jotaiStore.get(isCookieAuthActiveState.atom) === true;- } catch {- return false;- }-};diff --git a/packages/twenty-front/src/modules/apollo/utils/getTokenPair.ts b/packages/twenty-front/src/modules/apollo/utils/getTokenPair.tsdeleted file mode 100644index e25b1cc1b0d..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/getTokenPair.ts+++ /dev/null@@ -1,26 +0,0 @@-import { isDefined } from 'twenty-shared/utils';-import { TOKEN_PAIR_LOCAL_STORAGE_KEY } from '@/auth/states/tokenPairState';-import { type AuthTokenPair } from '~/generated-metadata/graphql';-import { isValidAuthTokenPair } from './isValidAuthTokenPair';--export const getTokenPair = (): AuthTokenPair | undefined => {- const stringTokenPair = localStorage.getItem(TOKEN_PAIR_LOCAL_STORAGE_KEY);-- if (!isDefined(stringTokenPair)) {- return undefined;- }-- try {- const parsedTokenPair = JSON.parse(stringTokenPair);-- if (!isValidAuthTokenPair(parsedTokenPair)) {- localStorage.removeItem(TOKEN_PAIR_LOCAL_STORAGE_KEY);- return undefined;- }-- return parsedTokenPair;- } catch {- localStorage.removeItem(TOKEN_PAIR_LOCAL_STORAGE_KEY);- return undefined;- }-};diff --git a/packages/twenty-front/src/modules/apollo/utils/hasTokenPair.ts b/packages/twenty-front/src/modules/apollo/utils/hasTokenPair.tsdeleted file mode 100644index 04f697e9099..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/hasTokenPair.ts+++ /dev/null@@ -1,7 +0,0 @@-import { getTokenPair } from '@/apollo/utils/getTokenPair';-import { isDefined } from 'twenty-shared/utils';--export const hasTokenPair = () => {- const tokenPair = getTokenPair();- return isDefined(tokenPair);-};diff --git a/packages/twenty-front/src/modules/apollo/utils/isValidAuthTokenPair.ts b/packages/twenty-front/src/modules/apollo/utils/isValidAuthTokenPair.tsdeleted file mode 100644index f9d742bb933..00000000000--- a/packages/twenty-front/src/modules/apollo/utils/isValidAuthTokenPair.ts+++ /dev/null@@ -1,13 +0,0 @@-import { type AuthTokenPair } from '~/generated-metadata/graphql';--export const isValidAuthTokenPair = (- tokenPair: any,-): tokenPair is AuthTokenPair => {- return (- tokenPair &&- typeof tokenPair === 'object' &&- tokenPair.accessOrWorkspaceAgnosticToken &&- typeof tokenPair.accessOrWorkspaceAgnosticToken === 'object' &&- typeof tokenPair.accessOrWorkspaceAgnosticToken.token === 'string'- );-};diff --git a/packages/twenty-front/src/modules/app/components/SharedAppProviders.tsx b/packages/twenty-front/src/modules/app/components/SharedAppProviders.tsxindex 0367e44de5e..650bb2010d3 100644--- a/packages/twenty-front/src/modules/app/components/SharedAppProviders.tsx+++ b/packages/twenty-front/src/modules/app/components/SharedAppProviders.tsx@@ -1,7 +1,7 @@import { type PropsWithChildren } from 'react';import { ApolloProvider } from '@/apollo/components/ApolloProvider';-import { CookieSessionBootEffect } from '@/auth/effect-components/CookieSessionBootEffect';+import { PendingServerSignOutEffect } from '@/auth/effect-components/PendingServerSignOutEffect';import { ClientConfigProvider } from '@/client-config/components/ClientConfigProvider';import { ClientConfigProviderEffect } from '@/client-config/components/ClientConfigProviderEffect';import { BaseThemeProvider } from '@/ui/theme/components/BaseThemeProvider';@@ -13,7 +13,7 @@ export const SharedAppProviders = ({ children }: SharedAppProvidersProps) => {<ApolloProvider><BaseThemeProvider><ClientConfigProviderEffect />- <CookieSessionBootEffect />+ <PendingServerSignOutEffect /><ClientConfigProvider>{children}</ClientConfigProvider></BaseThemeProvider></ApolloProvider>diff --git a/packages/twenty-front/src/modules/app/components/__tests__/DomainShell.test.tsx b/packages/twenty-front/src/modules/app/components/__tests__/DomainShell.test.tsxindex 5475fe06ca6..2941668a4aa 100644--- a/packages/twenty-front/src/modules/app/components/__tests__/DomainShell.test.tsx+++ b/packages/twenty-front/src/modules/app/components/__tests__/DomainShell.test.tsx@@ -23,8 +23,8 @@ jest.mock('@/client-config/components/ClientConfigProviderEffect', () => ({ClientConfigProviderEffect: () => null,}));-jest.mock('@/auth/effect-components/CookieSessionBootEffect', () => ({- CookieSessionBootEffect: () => null,+jest.mock('@/auth/effect-components/PendingServerSignOutEffect', () => ({+ PendingServerSignOutEffect: () => null,}));jest.mock('@/client-config/components/ClientConfigProvider', () => ({diff --git a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsxindex ab73b77eca4..a9da94512cb 100644--- a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx+++ b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyEmail.test.tsx@@ -8,7 +8,6 @@ import { AppPath } from 'twenty-shared/types';import { ThemeProvider } from 'twenty-ui/theme-constants';import { VerifyEmail } from '@/auth/components/VerifyEmail';-import { tokenPairState } from '@/auth/states/tokenPairState';import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';import {jotaiStore,@@ -90,17 +89,6 @@ const renderVerifyEmail = (initialEntry: string) =></JotaiProvider>,);-const staleTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'stale-access-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },- refreshToken: {- token: 'stale-refresh-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },-};-describe('VerifyEmail', () => {beforeEach(() => {jest.clearAllMocks();@@ -183,21 +171,4 @@ describe('VerifyEmail', () => {});expect(redirectToWorkspaceDomainMock).not.toHaveBeenCalled();});-- it('keeps the token pair when redirecting to another workspace domain', async () => {- isOnAWorkspaceValue = true;- jotaiStore.set(tokenPairState.atom, staleTokenPair);- verifyEmailAndGetLoginTokenMock.mockResolvedValue({- loginToken: { token: 'login-token' },- workspaceUrls: { subdomainUrl: 'https://foo.twenty.com/' },- });-- renderVerifyEmail(VERIFY_EMAIL_URL);-- await waitFor(() => {- expect(redirectToWorkspaceDomainMock).toHaveBeenCalled();- });- expect(jotaiStore.get(tokenPairState.atom)).toEqual(staleTokenPair);- expect(verifyLoginTokenMock).not.toHaveBeenCalled();- });});diff --git a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyLoginTokenEffect.test.tsx b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyLoginTokenEffect.test.tsxindex 95ea0d34d35..694dec50d0c 100644--- a/packages/twenty-front/src/modules/auth/components/__tests__/VerifyLoginTokenEffect.test.tsx+++ b/packages/twenty-front/src/modules/auth/components/__tests__/VerifyLoginTokenEffect.test.tsx@@ -5,7 +5,6 @@ import { MemoryRouter } from 'react-router-dom';import { AppPath } from 'twenty-shared/types';import { VerifyLoginTokenEffect } from '@/auth/components/VerifyLoginTokenEffect';-import { tokenPairState } from '@/auth/states/tokenPairState';import {jotaiStore,resetJotaiStore,@@ -22,17 +21,6 @@ jest.mock('~/hooks/useNavigateApp', () => ({useNavigateApp: () => navigateMock,}));-const staleTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'stale-access-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },- refreshToken: {- token: 'stale-refresh-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },-};-const renderEffect = (initialEntry: string) =>render(<JotaiProvider store={jotaiStore}>@@ -60,7 +48,7 @@ describe('VerifyLoginTokenEffect', () => {expect(verifyLoginTokenMock).toHaveBeenCalledTimes(1);});- it('navigates to sign in up when neither login token nor token pair is present', async () => {+ it('navigates to sign in up when no login token is present', async () => {renderEffect('/verify');await waitFor(() => {@@ -68,14 +56,4 @@ describe('VerifyLoginTokenEffect', () => {});expect(verifyLoginTokenMock).not.toHaveBeenCalled();});-- it('keeps the existing token pair when arriving without a login token', () => {- jotaiStore.set(tokenPairState.atom, staleTokenPair);-- renderEffect('/verify');-- expect(jotaiStore.get(tokenPairState.atom)).toEqual(staleTokenPair);- expect(navigateMock).not.toHaveBeenCalled();- expect(verifyLoginTokenMock).not.toHaveBeenCalled();- });});diff --git a/packages/twenty-front/src/modules/auth/effect-components/CookieSessionBootEffect.tsx b/packages/twenty-front/src/modules/auth/effect-components/CookieSessionBootEffect.tsxdeleted file mode 100644index 115466ccb9f..00000000000--- a/packages/twenty-front/src/modules/auth/effect-components/CookieSessionBootEffect.tsx+++ /dev/null@@ -1,143 +0,0 @@-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { useApolloClient } from '@apollo/client/react';-import { useStore } from 'jotai';-import { useEffect, useRef } from 'react';-import { isDefined } from 'twenty-shared/utils';--import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { ensureTokenRenewed } from '@/auth/utils/ensureTokenRenewed';-import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';-import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-import {- GetCurrentUserDocument,- SignOutDocument,-} from '~/generated-metadata/graphql';--type CookieSessionProbeResult =- | 'authenticated'- | 'unauthenticated'- | 'unreachable';--// The probe deliberately sends no credential, so it has to recognise every-// shape that refusal takes. A credential-less request is UNAUTHENTICATED on a-// current server but FORBIDDEN on one predating the guard change, and guards-// that throw before the code is attached surface a bare "Unauthorized".-const AUTH_REFUSAL_CODES = new Set(['UNAUTHENTICATED', 'FORBIDDEN']);--const isAuthRefusal = (error: unknown): boolean =>- CombinedGraphQLErrors.is(error) &&- error.errors.some(- (graphQLError) =>- AUTH_REFUSAL_CODES.has(String(graphQLError.extensions?.code)) ||- graphQLError.message === 'Unauthorized',- );--// Migrates the client from the localStorage token pair onto the httpOnly-// session cookie. Clients without a cookie get one through a single token-// renewal, which the server sets on renewToken, then switch on the next probe.-export const CookieSessionBootEffect = () => {- const apolloClient = useApolloClient();- const store = useStore();- const { isLoadedOnce } = useAtomStateValue(clientConfigApiStatusState);- const [isCookieAuthActive, setIsCookieAuthActive] = useAtomState(- isCookieAuthActiveState,- );- const [tokenPair, setTokenPair] = useAtomState(tokenPairState);- // oxlint-disable-next-line twenty/no-state-useref- const hasProbeRunRef = useRef(false);-- useEffect(() => {- const probeCookieSession = async (): Promise<CookieSessionProbeResult> => {- try {- const result = await apolloClient.query({- query: GetCurrentUserDocument,- fetchPolicy: 'network-only',- context: { skipAuthToken: true },- });-- return isDefined(result.data?.currentUser)- ? 'authenticated'- : 'unauthenticated';- } catch (error) {- return isAuthRefusal(error) ? 'unauthenticated' : 'unreachable';- }- };-- const switchToCookieAuth = () => {- setIsCookieAuthActive(true);- setTokenPair(null);- };-- const attemptCookieSessionBoot = async (): Promise<boolean> => {- const probeResult = await probeCookieSession();-- if (probeResult === 'authenticated') {- switchToCookieAuth();-- return true;- }-- if (probeResult === 'unreachable') {- return false;- }-- if (!isDefined(tokenPair?.refreshToken?.token)) {- return true;- }-- if (!(await ensureTokenRenewed(store))) {- return false;- }-- const probeResultAfterRenewal = await probeCookieSession();-- if (probeResultAfterRenewal === 'authenticated') {- switchToCookieAuth();-- return true;- }-- return probeResultAfterRenewal === 'unauthenticated';- };-- const runCookieSessionBoot = async () => {- if (!isLoadedOnce) {- return;- }-- if (store.get(isPendingServerSignOutState.atom)) {- try {- await apolloClient.mutate({ mutation: SignOutDocument });- store.set(isPendingServerSignOutState.atom, false);- } catch {}-- return;- }-- if (isCookieAuthActive || hasProbeRunRef.current) {- return;- }-- hasProbeRunRef.current = true;-- if (!(await attemptCookieSessionBoot())) {- hasProbeRunRef.current = false;- }- };-- void runCookieSessionBoot();- }, [- apolloClient,- isCookieAuthActive,- isLoadedOnce,- setIsCookieAuthActive,- setTokenPair,- store,- tokenPair,- ]);-- return null;-};diff --git a/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx b/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsxnew file mode 100644index 00000000000..042f7e9aedd--- /dev/null+++ b/packages/twenty-front/src/modules/auth/effect-components/PendingServerSignOutEffect.tsx@@ -0,0 +1,47 @@+import { useApolloClient } from '@apollo/client/react';+import { useStore } from 'jotai';+import { useEffect } from 'react';++import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';+import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';+import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';+import { SignOutDocument } from '~/generated-metadata/graphql';++// A signOut that never reached the server leaves the httpOnly cookie alive, and+// only the server can revoke it, so the next boot has to retry.+export const PendingServerSignOutEffect = () => {+ const apolloClient = useApolloClient();+ const store = useStore();+ const { isLoadedOnce } = useAtomStateValue(clientConfigApiStatusState);++ useEffect(() => {+ const retryPendingServerSignOut = async () => {+ if (!isLoadedOnce || !store.get(isPendingServerSignOutState.atom)) {+ return;+ }++ // Signing out now would revoke the session that sign-in just established.+ if (store.get(isCookieAuthActiveState.atom)) {+ store.set(isPendingServerSignOutState.atom, false);++ return;+ }++ try {+ // Never retried: a retry is issued seconds later and carries whatever+ // cookie exists by then, so it would revoke a session established in+ // the meantime. A failure waits for the next boot instead.+ await apolloClient.mutate({+ mutation: SignOutDocument,+ context: { skipRetry: true },+ });+ store.set(isPendingServerSignOutState.atom, false);+ } catch {}+ };++ void retryPendingServerSignOut();+ }, [apolloClient, isLoadedOnce, store]);++ return null;+};diff --git a/packages/twenty-front/src/modules/auth/effect-components/__tests__/CookieSessionBootEffect.test.tsx b/packages/twenty-front/src/modules/auth/effect-components/__tests__/CookieSessionBootEffect.test.tsxdeleted file mode 100644index 7150d731c65..00000000000--- a/packages/twenty-front/src/modules/auth/effect-components/__tests__/CookieSessionBootEffect.test.tsx+++ /dev/null@@ -1,142 +0,0 @@-import { CombinedGraphQLErrors } from '@apollo/client/errors';-import { renderHook, waitFor } from '@testing-library/react';-import { Provider as JotaiProvider, createStore } from 'jotai';-import { type ReactNode } from 'react';--import { CookieSessionBootEffect } from '@/auth/effect-components/CookieSessionBootEffect';-import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';--const mockQuery = jest.fn();-const mockEnsureTokenRenewed = jest.fn();--jest.mock('@apollo/client/react', () => ({- useApolloClient: () => ({- query: mockQuery,- mutate: jest.fn(),- }),-}));--jest.mock('@/auth/utils/ensureTokenRenewed', () => ({- ensureTokenRenewed: (...args: unknown[]) => mockEnsureTokenRenewed(...args),-}));--const buildTokenPair = () => ({- accessOrWorkspaceAgnosticToken: {- token: 'access',- expiresAt: new Date(Date.now() + 60_000).toISOString(),- },- refreshToken: {- token: 'refresh',- expiresAt: new Date(Date.now() + 600_000).toISOString(),- },-});--// A request carrying no credential is refused as FORBIDDEN, not UNAUTHENTICATED.-const buildForbiddenError = () =>- new CombinedGraphQLErrors({- data: null,- errors: [- {- message: 'Forbidden resource',- extensions: { code: 'FORBIDDEN' },- },- ],- });--const renderBootEffect = () => {- const store = createStore();-- store.set(clientConfigApiStatusState.atom, {- isLoadedOnce: true,- isLoading: false,- isErrored: false,- isSaved: false,- });- store.set(isCookieAuthActiveState.atom, false);- store.set(tokenPairState.atom, buildTokenPair());-- renderHook(() => CookieSessionBootEffect(), {- wrapper: ({ children }: { children: ReactNode }) => (- <JotaiProvider store={store}>{children}</JotaiProvider>- ),- });-- return store;-};--describe('CookieSessionBootEffect', () => {- beforeEach(() => {- jest.clearAllMocks();- mockEnsureTokenRenewed.mockResolvedValue(true);- });-- it('should renew once so the server can set the cookie when the probe is refused', async () => {- mockQuery- .mockRejectedValueOnce(buildForbiddenError())- .mockResolvedValueOnce({ data: { currentUser: { id: 'user-id' } } });-- const store = renderBootEffect();-- await waitFor(() => {- expect(mockEnsureTokenRenewed).toHaveBeenCalledTimes(1);- });-- await waitFor(() => {- expect(store.get(isCookieAuthActiveState.atom)).toBe(true);- });-- expect(store.get(tokenPairState.atom)).toBeNull();- });-- it('should stay retryable when the probe fails for an unrelated reason', async () => {- mockQuery.mockRejectedValue(- new CombinedGraphQLErrors({- data: null,- errors: [- {- message: 'Something broke in a resolver',- extensions: { code: 'INTERNAL_SERVER_ERROR' },- },- ],- }),- );-- const store = renderBootEffect();-- await waitFor(() => {- expect(mockQuery).toHaveBeenCalled();- });-- expect(mockEnsureTokenRenewed).not.toHaveBeenCalled();- expect(store.get(isCookieAuthActiveState.atom)).toBe(false);- expect(store.get(tokenPairState.atom)).not.toBeNull();- });-- it('should not renew when the server cannot be reached', async () => {- mockQuery.mockRejectedValue(new Error('Network request failed'));-- const store = renderBootEffect();-- await waitFor(() => {- expect(mockQuery).toHaveBeenCalled();- });-- expect(mockEnsureTokenRenewed).not.toHaveBeenCalled();- expect(store.get(isCookieAuthActiveState.atom)).toBe(false);- });-- it('should switch straight over when the cookie already authenticates', async () => {- mockQuery.mockResolvedValue({ data: { currentUser: { id: 'user-id' } } });-- const store = renderBootEffect();-- await waitFor(() => {- expect(store.get(isCookieAuthActiveState.atom)).toBe(true);- });-- expect(store.get(tokenPairState.atom)).toBeNull();- expect(mockEnsureTokenRenewed).not.toHaveBeenCalled();- });-});diff --git a/packages/twenty-front/src/modules/auth/effect-components/__tests__/PendingServerSignOutEffect.test.tsx b/packages/twenty-front/src/modules/auth/effect-components/__tests__/PendingServerSignOutEffect.test.tsxnew file mode 100644index 00000000000..8ec1bfe423b--- /dev/null+++ b/packages/twenty-front/src/modules/auth/effect-components/__tests__/PendingServerSignOutEffect.test.tsx@@ -0,0 +1,102 @@+import { renderHook, waitFor } from '@testing-library/react';+import { Provider as JotaiProvider, createStore } from 'jotai';+import { type ReactNode } from 'react';++import { PendingServerSignOutEffect } from '@/auth/effect-components/PendingServerSignOutEffect';+import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';+import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';+import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';++const mockMutate = jest.fn();++jest.mock('@apollo/client/react', () => ({+ useApolloClient: () => ({ mutate: mockMutate }),+}));++const renderEffect = ({+ isLoadedOnce = true,+ isPendingServerSignOut = true,+ isCookieAuthActive = false,+}: {+ isLoadedOnce?: boolean;+ isPendingServerSignOut?: boolean;+ isCookieAuthActive?: boolean;+} = {}) => {+ const store = createStore();++ store.set(clientConfigApiStatusState.atom, {+ isLoadedOnce,+ isLoading: false,+ isErrored: false,+ isSaved: false,+ });+ store.set(isPendingServerSignOutState.atom, isPendingServerSignOut);+ store.set(isCookieAuthActiveState.atom, isCookieAuthActive);++ renderHook(() => PendingServerSignOutEffect(), {+ wrapper: ({ children }: { children: ReactNode }) => (+ <JotaiProvider store={store}>{children}</JotaiProvider>+ ),+ });++ return store;+};++describe('PendingServerSignOutEffect', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockMutate.mockResolvedValue({ data: { signOut: true } });+ });++ it('should revoke the session left behind by a sign out that never reached the server', async () => {+ const store = renderEffect();++ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));+ await waitFor(() =>+ expect(store.get(isPendingServerSignOutState.atom)).toBe(false),+ );+ });++ it('should keep the retry pending when the server is still unreachable', async () => {+ mockMutate.mockRejectedValue(new Error('Network error'));++ const store = renderEffect();++ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));+ expect(store.get(isPendingServerSignOutState.atom)).toBe(true);+ });++ // A retry is issued seconds later and carries whatever cookie exists by then,+ // so it would revoke a session established in the meantime.+ it('should not let the sign out be retried', async () => {+ renderEffect();++ await waitFor(() => expect(mockMutate).toHaveBeenCalledTimes(1));+ expect(mockMutate).toHaveBeenCalledWith(+ expect.objectContaining({ context: { skipRetry: true } }),+ );+ });++ // The pending sign-out is stale once a new session exists; firing it would+ // revoke the session the user just got.+ it('should drop the pending sign out when a session is already active', async () => {+ const store = renderEffect({ isCookieAuthActive: true });++ await waitFor(() =>+ expect(store.get(isPendingServerSignOutState.atom)).toBe(false),+ );+ expect(mockMutate).not.toHaveBeenCalled();+ });++ it('should not sign out a session the user never asked to end', async () => {+ renderEffect({ isPendingServerSignOut: false });++ await waitFor(() => expect(mockMutate).not.toHaveBeenCalled());+ });++ it('should wait for the api before retrying', async () => {+ renderEffect({ isLoadedOnce: false });++ await waitFor(() => expect(mockMutate).not.toHaveBeenCalled());+ });+});diff --git a/packages/twenty-front/src/modules/auth/hooks/__tests__/useIsLogged.test.ts b/packages/twenty-front/src/modules/auth/hooks/__tests__/useIsLogged.test.tsindex 1b97263ab82..919dc75f7ec 100644--- a/packages/twenty-front/src/modules/auth/hooks/__tests__/useIsLogged.test.ts+++ b/packages/twenty-front/src/modules/auth/hooks/__tests__/useIsLogged.test.ts@@ -2,62 +2,33 @@ import { act, renderHook } from '@testing-library/react';import { useIsLogged } from '@/auth/hooks/useIsLogged';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';const renderHooks = () => {- const { result } = renderHook(() => {- const isLogged = useIsLogged();- const setTokenPair = useSetAtomState(tokenPairState);- const setIsCookieAuthActive = useSetAtomState(isCookieAuthActiveState);-- return {- isLogged,- setTokenPair,- setIsCookieAuthActive,- };- });+ const { result } = renderHook(() => ({+ isLogged: useIsLogged(),+ setIsCookieAuthActive: useSetAtomState(isCookieAuthActiveState),+ }));return { result };};describe('useIsLogged', () => {- it('should be true when a token pair is present', async () => {+ it('should follow the cookie session', async () => {const { result } = renderHooks();expect(result.current.isLogged).toBe(false);await act(async () => {- result.current.setTokenPair({- accessOrWorkspaceAgnosticToken: {- expiresAt: '',- token: 'testToken',- },- refreshToken: {- expiresAt: '',- token: 'testToken',- },- });+ result.current.setIsCookieAuthActive(true);});expect(result.current.isLogged).toBe(true);await act(async () => {- result.current.setTokenPair(null);+ result.current.setIsCookieAuthActive(false);});expect(result.current.isLogged).toBe(false);});-- it('should be true when cookie auth is active without a token pair', async () => {- const { result } = renderHooks();-- expect(result.current.isLogged).toBe(false);-- await act(async () => {- result.current.setIsCookieAuthActive(true);- });-- expect(result.current.isLogged).toBe(true);- });});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 fe5963227bd..679c8eee091 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@@ -2,8 +2,8 @@ import { renderHook } from '@testing-library/react';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 { tokenPairState } from '@/auth/states/tokenPairState';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import {jotaiStore,@@ -29,17 +29,6 @@ const renderHooks = () => {return { result };};-const staleTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'stale-access-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },- refreshToken: {- token: 'stale-refresh-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },-};-const freshTokenPair = {accessOrWorkspaceAgnosticToken: {token: 'fresh-access-token',@@ -70,24 +59,13 @@ describe('useRedeemSSOExchangeToken', () => {});});- it('should store the redeemed token pair', async () => {- const { result } = renderHooks();-- await result.current.redeemSSOExchangeToken('sso-exchange-token');-- expect(mockGetAuthTokensFromSSOExchangeToken).toHaveBeenCalledWith({- variables: { ssoExchangeToken: 'sso-exchange-token' },- });- expect(jotaiStore.get(tokenPairState.atom)).toEqual(freshTokenPair);- });-- it('should clear the existing token pair before exchanging', async () => {- jotaiStore.set(tokenPairState.atom, staleTokenPair);-- const tokenPairsAtExchangeTime: unknown[] = [];+ it('should disable the redirect effect while exchanging and restore it after', async () => {+ const redirectFlagsAtExchangeTime: unknown[] = [];mockGetAuthTokensFromSSOExchangeToken.mockImplementation(() => {- tokenPairsAtExchangeTime.push(jotaiStore.get(tokenPairState.atom));+ redirectFlagsAtExchangeTime.push(+ jotaiStore.get(isAppEffectRedirectEnabledState.atom),+ );return Promise.resolve({data: { getAuthTokensFromSSOExchangeToken: { tokens: freshTokenPair } },@@ -98,31 +76,33 @@ describe('useRedeemSSOExchangeToken', () => {await result.current.redeemSSOExchangeToken('sso-exchange-token');- expect(tokenPairsAtExchangeTime).toEqual([null]);+ expect(redirectFlagsAtExchangeTime).toEqual([false]);+ expect(jotaiStore.get(isAppEffectRedirectEnabledState.atom)).toBe(true);});- it('should disable the redirect effect while exchanging and restore it after', async () => {- const redirectFlagsAtExchangeTime: unknown[] = [];+ // The cookie is httpOnly, so nothing else can tell the client it is now+ // signed in; without this the user stays on the sign-in flow.+ it('should mark the session active once the exchange succeeds', async () => {+ const { result } = renderHooks();- mockGetAuthTokensFromSSOExchangeToken.mockImplementation(() => {- redirectFlagsAtExchangeTime.push(- jotaiStore.get(isAppEffectRedirectEnabledState.atom),- );+ await result.current.redeemSSOExchangeToken('sso-exchange-token');- return Promise.resolve({- data: { getAuthTokensFromSSOExchangeToken: { tokens: freshTokenPair } },- });- });+ expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(true);+ });++ it('should leave the session inactive when the exchange fails', async () => {+ mockGetAuthTokensFromSSOExchangeToken.mockRejectedValueOnce(+ new Error('Invalid SSO exchange token'),+ );const { result } = renderHooks();await result.current.redeemSSOExchangeToken('sso-exchange-token');- expect(redirectFlagsAtExchangeTime).toEqual([false]);- expect(jotaiStore.get(isAppEffectRedirectEnabledState.atom)).toBe(true);+ expect(jotaiStore.get(isCookieAuthActiveState.atom)).toBe(false);});- it('should snackbar and leave no token pair when redemption fails', async () => {+ it('should snackbar when redemption fails', async () => {mockGetAuthTokensFromSSOExchangeToken.mockRejectedValueOnce(new Error('Invalid SSO exchange token'),);@@ -134,7 +114,6 @@ describe('useRedeemSSOExchangeToken', () => {expect(mockEnqueueErrorSnackBar).toHaveBeenCalledWith({message: 'Invalid SSO exchange token',});- expect(jotaiStore.get(tokenPairState.atom)).toBeNull();expect(jotaiStore.get(isAppEffectRedirectEnabledState.atom)).toBe(true);});});diff --git a/packages/twenty-front/src/modules/auth/hooks/__tests__/useVerifyLogin.test.ts b/packages/twenty-front/src/modules/auth/hooks/__tests__/useVerifyLogin.test.tsindex e9204aef008..6f682c8002a 100644--- a/packages/twenty-front/src/modules/auth/hooks/__tests__/useVerifyLogin.test.ts+++ b/packages/twenty-front/src/modules/auth/hooks/__tests__/useVerifyLogin.test.ts@@ -8,7 +8,6 @@ import { AppPath } from 'twenty-shared/types';import { useNavigateApp } from '~/hooks/useNavigateApp';import { useAuth } from '@/auth/hooks/useAuth';import { useVerifyLogin } from '@/auth/hooks/useVerifyLogin';-import { tokenPairState } from '@/auth/states/tokenPairState';import {jotaiStore,resetJotaiStore,@@ -42,17 +41,6 @@ const renderHooks = () => {return { result };};-const staleTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'stale-access-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },- refreshToken: {- token: 'stale-refresh-token',- expiresAt: '2020-01-01T00:00:00.000Z',- },-};-describe('useVerifyLogin', () => {const mockGetAuthTokensFromLoginToken = jest.fn();const mockEnqueueErrorSnackBar = jest.fn();@@ -82,20 +70,6 @@ describe('useVerifyLogin', () => {expect(mockGetAuthTokensFromLoginToken).toHaveBeenCalledWith('test-token');});- it('should clear the existing token pair before exchanging the login token', async () => {- jotaiStore.set(tokenPairState.atom, staleTokenPair);- const tokenPairsAtExchangeTime: unknown[] = [];- mockGetAuthTokensFromLoginToken.mockImplementation(() => {- tokenPairsAtExchangeTime.push(jotaiStore.get(tokenPairState.atom));- });-- const { result } = renderHooks();-- await result.current.verifyLoginToken('test-token');-- expect(tokenPairsAtExchangeTime).toEqual([null]);- });-it('should handle verification error', async () => {const error = new Error('Verification failed');mockGetAuthTokensFromLoginToken.mockRejectedValueOnce(error);diff --git a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts b/packages/twenty-front/src/modules/auth/hooks/useAuth.tsindex 312cabc7087..7790aa45f13 100644--- a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts@@ -9,7 +9,6 @@ import { AppPath } from 'twenty-shared/types';import { REACT_APP_SERVER_BASE_URL } from '~/config';import {type AuthToken,- type AuthTokenPair,CheckUserExistsDocument,GetAuthTokensFromLoginTokenDocument,GetAuthTokensFromOtpDocument,@@ -23,6 +22,7 @@ import {VerifyEmailAndGetWorkspaceAgnosticTokenDocument,} from '~/generated-metadata/graphql';+import { useMarkSessionActive } from '@/auth/hooks/useMarkSessionActive';import { currentUserState } from '@/auth/states/currentUserState';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';@@ -30,7 +30,6 @@ import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceStaimport { currentWorkspaceMemberState } from '@/auth/states/currentWorkspaceMemberState';import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';import { returnToPathState } from '@/auth/states/returnToPathState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { clearSessionLocalStorageKeys } from '@/auth/utils/clearSessionLocalStorageKeys';import { broadcastSignOutToOtherTabs } from '@/auth/utils/crossTabSignOut';import { isValidReturnToPath } from '@/auth/utils/isValidReturnToPath';@@ -67,7 +66,7 @@ import { useStore } from 'jotai';export const useAuth = () => {const store = useStore();- const setTokenPair = useSetAtomState(tokenPairState);+ const markSessionActive = useMarkSessionActive();const setLoginToken = useSetAtomState(loginTokenState);const setIsAppEffectRedirectEnabled = useSetAtomState(isAppEffectRedirectEnabledState,@@ -122,7 +121,6 @@ export const useAuth = () => {// racing it to the sign-in page once the session is cleared.store.set(isAppEffectRedirectEnabledState.atom, false);sessionStorage.clear();- store.set(tokenPairState.atom, null);store.set(isCookieAuthActiveState.atom, false);store.set(currentUserState.atom, null);store.set(currentWorkspaceState.atom, null);@@ -133,14 +131,6 @@ export const useAuth = () => {window.location.assign(AppPath.SignInUp);}, [store, setLastAuthenticateWorkspaceDomain]);- const handleSetAuthTokens = useCallback(- (tokens: AuthTokenPair) => {- setTokenPair(tokens);- store.set(isPendingServerSignOutState.atom, false);- },- [setTokenPair, store],- );-const navigateAfterMultiWorkspaceSignInUp = useCallback(async (availableWorkspaces: Parameters<typeof countAvailableWorkspaces>[0],@@ -267,7 +257,7 @@ export const useAuth = () => {throw new Error('No workspace agnostic token in result');}- handleSetAuthTokens(data.verifyEmailAndGetWorkspaceAgnosticToken.tokens);+ markSessionActive();const { user } = await loadCurrentUser();@@ -278,7 +268,7 @@ export const useAuth = () => {},[verifyEmailAndGetWorkspaceAgnosticToken,- handleSetAuthTokens,+ markSessionActive,loadCurrentUser,navigateAfterMultiWorkspaceSignInUp,],@@ -291,19 +281,16 @@ export const useAuth = () => {[setLoginToken],);- const handleLoadWorkspaceAfterAuthentication = useCallback(- async (authTokens: AuthTokenPair) => {- handleSetAuthTokens(authTokens);- setIsAppEffectRedirectEnabled(false);+ const handleLoadWorkspaceAfterAuthentication = useCallback(async () => {+ markSessionActive();+ setIsAppEffectRedirectEnabled(false);- try {- await loadCurrentUser();- } finally {- setIsAppEffectRedirectEnabled(true);- }- },- [loadCurrentUser, handleSetAuthTokens, setIsAppEffectRedirectEnabled],- );+ try {+ await loadCurrentUser();+ } finally {+ setIsAppEffectRedirectEnabled(true);+ }+ }, [loadCurrentUser, markSessionActive, setIsAppEffectRedirectEnabled]);const handleGetAuthTokensFromLoginToken = useCallback(async (loginToken: string) => {@@ -323,9 +310,7 @@ export const useAuth = () => {throw new Error('No getAuthTokensFromLoginToken result');}- await handleLoadWorkspaceAfterAuthentication(- getAuthTokensResult.data.getAuthTokensFromLoginToken.tokens,- );+ await handleLoadWorkspaceAfterAuthentication();} catch (error) {if (isGraphqlErrorOfType(@@ -367,8 +352,8 @@ export const useAuth = () => {async (email: string, password: string, captchaToken?: string) => {await signIn({variables: { email, password, captchaToken },- onCompleted: async (data) => {- handleSetAuthTokens(data.signIn.tokens);+ onCompleted: async () => {+ markSessionActive();const { user } = await loadCurrentUser();await navigateAfterMultiWorkspaceSignInUp(@@ -387,7 +372,7 @@ export const useAuth = () => {});},[- handleSetAuthTokens,+ markSessionActive,signIn,loadCurrentUser,setSearchParams,@@ -421,7 +406,7 @@ export const useAuth = () => {throw new Error('No signUp result');}- handleSetAuthTokens(signUpResult.data.signUp.tokens);+ markSessionActive();const { user } = await loadCurrentUser();@@ -433,7 +418,7 @@ export const useAuth = () => {[isEmailVerificationRequired,setSearchParams,- handleSetAuthTokens,+ markSessionActive,signUp,loadCurrentUser,setSignInUpStep,@@ -454,16 +439,11 @@ export const useAuth = () => {);const handleSignOut = useCallback(async () => {- // Before clearSession: it needs the refresh token, and the navigation there- // kills in-flight requests.+ // Before clearSession, whose navigation kills in-flight requests.store.set(isPendingServerSignOutState.atom, true);try {- await signOutMutation({- variables: {- refreshToken: store.get(tokenPairState.atom)?.refreshToken?.token,- },- });+ await signOutMutation();store.set(isPendingServerSignOutState.atom, false);} catch {}@@ -638,9 +618,7 @@ export const useAuth = () => {throw new Error('No getAuthTokensFromOTP result');}- await handleLoadWorkspaceAfterAuthentication(- getAuthTokensFromOtpResult.data.getAuthTokensFromOTP.tokens,- );+ await handleLoadWorkspaceAfterAuthentication();},[getAuthTokensFromOtp, origin, handleLoadWorkspaceAfterAuthentication],);diff --git a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.tsindex 06689c30546..27d9c1fc3c7 100644--- a/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useImpersonationSession.ts@@ -4,23 +4,18 @@ import { useCallback } from 'react';import { useAuth } from '@/auth/hooks/useAuth';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { clearSessionLocalStorageKeys } from '@/auth/utils/clearSessionLocalStorageKeys';-import {- type AuthTokenPair,- StopImpersonationDocument,-} from '~/generated-metadata/graphql';+import { StopImpersonationDocument } from '~/generated-metadata/graphql';const IMPERSONATION_SESSION_KEY = 'impersonation_original_session';type StoredImpersonationSession = {- tokenPair?: AuthTokenPair;returnPath: string;};-// Token swaps without a full reload would require enumerating every-// user-scoped atom, localStorage entry, and Apollo cache key — brittle and-// silently broken every time a new piece of user state is added. Instead,+// Session swaps without a full reload would require enumerating every+// user-scoped atom, localStorage entry, and Apollo cache key — brittle, and+// silently broken every time a new piece of user state is added.const reloadWithSession = (returnPath: string) => {window.location.assign(returnPath);};@@ -32,15 +27,10 @@ export const useImpersonationSession = () => {const startImpersonating = useCallback(async (loginToken: string, returnPath?: string) => {- const currentTokenPair = store.get(tokenPairState.atom);- const isCookieAuthActive = store.get(isCookieAuthActiveState.atom);const targetPath = returnPath ?? window.location.pathname;- if (currentTokenPair || isCookieAuthActive) {- const session: StoredImpersonationSession = {- ...(currentTokenPair ? { tokenPair: currentTokenPair } : {}),- returnPath: targetPath,- };+ if (store.get(isCookieAuthActiveState.atom)) {+ const session: StoredImpersonationSession = { returnPath: targetPath };sessionStorage.setItem(IMPERSONATION_SESSION_KEY,@@ -55,12 +45,6 @@ export const useImpersonationSession = () => {throw error;}- if (isCookieAuthActive) {- // Drop the token pair the exchange also returned, so the cookie it set stays- // the only credential.- store.set(tokenPairState.atom, null);- }-clearSessionLocalStorageKeys();reloadWithSession(targetPath);},@@ -69,67 +53,30 @@ export const useImpersonationSession = () => {const stopImpersonating = useCallback(async () => {const raw = sessionStorage.getItem(IMPERSONATION_SESSION_KEY);- const isCookieAuthActive = store.get(isCookieAuthActiveState.atom);-- if (isCookieAuthActive) {- let returnPath = window.location.pathname;-- if (raw !== null) {- sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);- try {- returnPath = (JSON.parse(raw) as StoredImpersonationSession)- .returnPath;- } catch {}- }+ let returnPath = window.location.pathname;+ if (raw !== null) {+ sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);try {- const { data } = await stopImpersonationMutation();-- if (data?.stopImpersonation.canRestoreImpersonatorSession === true) {- store.set(tokenPairState.atom, null);- clearSessionLocalStorageKeys();- reloadWithSession(returnPath);-- return;- }+ returnPath = (JSON.parse(raw) as StoredImpersonationSession).returnPath;} catch {}-- // Cross-workspace: the admin session on its own origin was never replaced.- window.close();- await signOut();-- return;- }-- if (raw === null) {- // Cross-workspace tab opened via redirect — no stored admin session- // to restore. Close the tab; fall back to sign out if the browser- // blocks window.close().- window.close();- await signOut();- return;}- let session: StoredImpersonationSession;try {- session = JSON.parse(raw);- } catch {- sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);- await signOut();- return;- }+ const { data } = await stopImpersonationMutation();- if (!session.tokenPair) {- sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);- await signOut();- return;- }+ if (data?.stopImpersonation.canRestoreImpersonatorSession === true) {+ clearSessionLocalStorageKeys();+ reloadWithSession(returnPath);++ return;+ }+ } catch {}- sessionStorage.removeItem(IMPERSONATION_SESSION_KEY);- store.set(tokenPairState.atom, session.tokenPair);- clearSessionLocalStorageKeys();- reloadWithSession(session.returnPath);- }, [store, signOut, stopImpersonationMutation]);+ // Cross-workspace: the admin session on its own origin was never replaced.+ window.close();+ await signOut();+ }, [signOut, stopImpersonationMutation]);const hasStoredSession = useCallback(() => {return sessionStorage.getItem(IMPERSONATION_SESSION_KEY) !== null;diff --git a/packages/twenty-front/src/modules/auth/hooks/useIsLogged.ts b/packages/twenty-front/src/modules/auth/hooks/useIsLogged.tsindex 51a05117ebc..527a79274c5 100644--- a/packages/twenty-front/src/modules/auth/hooks/useIsLogged.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useIsLogged.ts@@ -1,10 +1,5 @@import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';-export const useIsLogged = (): boolean => {- const [tokenPair] = useAtomState(tokenPairState);- const [isCookieAuthActive] = useAtomState(isCookieAuthActiveState);-- return !!tokenPair || isCookieAuthActive;-};+export const useIsLogged = (): boolean =>+ useAtomStateValue(isCookieAuthActiveState);diff --git a/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.tsnew file mode 100644index 00000000000..60d42ffa8e8--- /dev/null+++ b/packages/twenty-front/src/modules/auth/hooks/useMarkSessionActive.ts@@ -0,0 +1,17 @@+import { useStore } from 'jotai';+import { useCallback } from 'react';++import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';+import { isPendingServerSignOutState } from '@/auth/states/isPendingServerSignOutState';++// 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+// now exists. Missing this leaves useIsLogged false on an authenticated client.+export const useMarkSessionActive = () => {+ const store = useStore();++ return useCallback(() => {+ store.set(isCookieAuthActiveState.atom, true);+ store.set(isPendingServerSignOutState.atom, false);+ }, [store]);+};diff --git a/packages/twenty-front/src/modules/auth/hooks/useRedeemSSOExchangeToken.ts b/packages/twenty-front/src/modules/auth/hooks/useRedeemSSOExchangeToken.tsindex 06959dd2ec5..847691d2b28 100644--- a/packages/twenty-front/src/modules/auth/hooks/useRedeemSSOExchangeToken.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useRedeemSSOExchangeToken.ts@@ -1,5 +1,5 @@import { isAppEffectRedirectEnabledState } from '@/app/states/isAppEffectRedirectEnabledState';-import { tokenPairState } from '@/auth/states/tokenPairState';+import { useMarkSessionActive } from '@/auth/hooks/useMarkSessionActive';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { CombinedGraphQLErrors } from '@apollo/client/errors';@@ -10,7 +10,7 @@ import { GetAuthTokensFromSsoExchangeTokenDocument } from '~/generated-metadata/export const useRedeemSSOExchangeToken = () => {const { enqueueErrorSnackBar } = useSnackBar();- const setTokenPair = useSetAtomState(tokenPairState);+ const markSessionActive = useMarkSessionActive();const setIsAppEffectRedirectEnabled = useSetAtomState(isAppEffectRedirectEnabledState,);@@ -20,10 +20,9 @@ export const useRedeemSSOExchangeToken = () => {const redeemSSOExchangeToken = useCallback(async (ssoExchangeToken: string) => {- // Keeps PageChangeEffect from consuming returnToPath mid token swap, and- // drops any stale pair so the resume waits for the one being redeemed+ // Keeps PageChangeEffect from consuming returnToPath while the server+ // swaps the session cookiesetIsAppEffectRedirectEnabled(false);- setTokenPair(null);try {const { data } = await getAuthTokensFromSSOExchangeToken({@@ -34,7 +33,7 @@ export const useRedeemSSOExchangeToken = () => {throw new Error('No getAuthTokensFromSSOExchangeToken result');}- setTokenPair(data.getAuthTokensFromSSOExchangeToken.tokens);+ markSessionActive();} catch (error: unknown) {enqueueErrorSnackBar(CombinedGraphQLErrors.is(error)@@ -47,7 +46,7 @@ export const useRedeemSSOExchangeToken = () => {},[getAuthTokensFromSSOExchangeToken,- setTokenPair,+ markSessionActive,setIsAppEffectRedirectEnabled,enqueueErrorSnackBar,],diff --git a/packages/twenty-front/src/modules/auth/hooks/useVerifyLogin.ts b/packages/twenty-front/src/modules/auth/hooks/useVerifyLogin.tsindex 7346f212894..6bed3288114 100644--- a/packages/twenty-front/src/modules/auth/hooks/useVerifyLogin.ts+++ b/packages/twenty-front/src/modules/auth/hooks/useVerifyLogin.ts@@ -1,6 +1,5 @@import { isAppEffectRedirectEnabledState } from '@/app/states/isAppEffectRedirectEnabledState';import { useAuth } from '@/auth/hooks/useAuth';-import { tokenPairState } from '@/auth/states/tokenPairState';import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { useLingui } from '@lingui/react/macro';@@ -10,7 +9,6 @@ import { useNavigateApp } from '~/hooks/useNavigateApp';export const useVerifyLogin = () => {const { enqueueErrorSnackBar } = useSnackBar();const navigate = useNavigateApp();- const setTokenPair = useSetAtomState(tokenPairState);const setIsAppEffectRedirectEnabled = useSetAtomState(isAppEffectRedirectEnabledState,);@@ -20,7 +18,6 @@ export const useVerifyLogin = () => {const verifyLoginToken = async (loginToken: string) => {// Keeps PageChangeEffect from consuming returnToPath mid token swapsetIsAppEffectRedirectEnabled(false);- setTokenPair(null);try {await getAuthTokensFromLoginToken(loginToken);} catch {diff --git a/packages/twenty-front/src/modules/auth/services/AuthService.ts b/packages/twenty-front/src/modules/auth/services/AuthService.tsdeleted file mode 100644index fe423a4ed94..00000000000--- a/packages/twenty-front/src/modules/auth/services/AuthService.ts+++ /dev/null@@ -1,61 +0,0 @@-import {- ApolloClient,- ApolloLink,- HttpLink,- InMemoryCache,-} from '@apollo/client';--import { loggerLink } from '@/apollo/utils/loggerLink';-import {- type AuthTokenPair,- RenewTokenDocument,- type RenewTokenMutation,- type RenewTokenMutationVariables,-} from '~/generated-metadata/graphql';-import { isUndefinedOrNull } from '~/utils/isUndefinedOrNull';--const isDebugMode = process.env.IS_DEBUG_MODE === 'true';--const logger = loggerLink(() => 'Twenty-Refresh');--const renewTokenMutation = async (- uri: string | undefined,- refreshToken: string,-) => {- const httpLink = new HttpLink({ uri, credentials: 'include' });-- const client = new ApolloClient({- link: ApolloLink.from([...(isDebugMode ? [logger] : []), httpLink]),- cache: new InMemoryCache({}),- });-- const result = await client.mutate<- RenewTokenMutation,- RenewTokenMutationVariables- >({- mutation: RenewTokenDocument,- variables: {- appToken: refreshToken,- },- fetchPolicy: 'network-only',- });-- if (isUndefinedOrNull(result.data)) {- throw new Error('Token renewal returned empty data');- }-- return result.data;-};--export const renewToken = async (- uri: string | undefined,- tokenPair: AuthTokenPair | undefined | null,-) => {- if (!tokenPair) {- throw new Error('Refresh token is not defined');- }-- const data = await renewTokenMutation(uri, tokenPair.refreshToken.token);-- return data?.renewToken.tokens;-};diff --git a/packages/twenty-front/src/modules/auth/services/__tests__/AuthService.test.ts b/packages/twenty-front/src/modules/auth/services/__tests__/AuthService.test.tsdeleted file mode 100644index adf838c49c1..00000000000--- a/packages/twenty-front/src/modules/auth/services/__tests__/AuthService.test.ts+++ /dev/null@@ -1,52 +0,0 @@-import { enableFetchMocks } from 'jest-fetch-mock';-import { act } from 'react';--import { renewToken } from '@/auth/services/AuthService';--enableFetchMocks();--const tokens = {- accessOrWorkspaceAgnosticToken: {- token: 'accessToken',- expiresAt: 'expiresAt',- },- refreshToken: {- token: 'refreshToken',- expiresAt: 'expiresAt',- },-};--describe('AuthService', () => {- it('should renewToken', async () => {- fetchMock.mockResponse(() =>- Promise.resolve({- body: JSON.stringify({- data: { renewToken: { tokens } },- }),- }),- );- await act(async () => {- const res = await renewToken('http://localhost:3000', tokens);- expect(res).toEqual(tokens);- });- });-- it('should send credentials so the renewal response can set the session cookie', async () => {- fetchMock.mockResponse(() =>- Promise.resolve({- body: JSON.stringify({- data: { renewToken: { tokens } },- }),- }),- );-- await act(async () => {- await renewToken('http://localhost:3000', tokens);- });-- expect(fetchMock).toHaveBeenCalledWith(- expect.any(String),- expect.objectContaining({ credentials: 'include' }),- );- });-});diff --git a/packages/twenty-front/src/modules/auth/states/isImpersonatingState.ts b/packages/twenty-front/src/modules/auth/states/isImpersonatingState.tsindex 683072fb10a..952a67ccb29 100644--- a/packages/twenty-front/src/modules/auth/states/isImpersonatingState.ts+++ b/packages/twenty-front/src/modules/auth/states/isImpersonatingState.ts@@ -1,27 +1,7 @@-import { jwtDecode } from 'jwt-decode';-import { isDefined } from 'twenty-shared/utils';-import { currentUserWorkspaceState } from '@/auth/states/currentUserWorkspaceState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { createAtomSelector } from '@/ui/utilities/state/jotai/utils/createAtomSelector';export const isImpersonatingState = createAtomSelector<boolean>({key: 'isImpersonatingState',- get: ({ get }) => {- const tokenPair = get(tokenPairState);-- if (isDefined(tokenPair?.accessOrWorkspaceAgnosticToken?.token)) {- try {- const decodedToken = jwtDecode<{ isImpersonating: boolean }>(- tokenPair.accessOrWorkspaceAgnosticToken.token,- );-- return decodedToken?.isImpersonating ?? false;- } catch {- return false;- }- }-- return get(currentUserWorkspaceState)?.isImpersonating === true;- },+ get: ({ get }) => get(currentUserWorkspaceState)?.isImpersonating === true,});diff --git a/packages/twenty-front/src/modules/auth/states/tokenPairState.ts b/packages/twenty-front/src/modules/auth/states/tokenPairState.tsdeleted file mode 100644index 8e17915b864..00000000000--- a/packages/twenty-front/src/modules/auth/states/tokenPairState.ts+++ /dev/null@@ -1,13 +0,0 @@-import { isValidAuthTokenPair } from '@/apollo/utils/isValidAuthTokenPair';-import { createAtomState } from '@/ui/utilities/state/jotai/utils/createAtomState';-import { type AuthTokenPair } from '~/generated-metadata/graphql';--export const TOKEN_PAIR_LOCAL_STORAGE_KEY = 'tokenPairState';--export const tokenPairState = createAtomState<AuthTokenPair | null>({- key: TOKEN_PAIR_LOCAL_STORAGE_KEY,- defaultValue: null,- useLocalStorage: true,- localStorageOptions: { getOnInit: true },- validateInitFn: (payload) => isValidAuthTokenPair(payload),-});diff --git a/packages/twenty-front/src/modules/auth/utils/ensureTokenRenewed.ts b/packages/twenty-front/src/modules/auth/utils/ensureTokenRenewed.tsdeleted file mode 100644index 465bc9621b7..00000000000--- a/packages/twenty-front/src/modules/auth/utils/ensureTokenRenewed.ts+++ /dev/null@@ -1,60 +0,0 @@-import { renewToken } from '@/auth/services/AuthService';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { type createStore } from 'jotai';-import { isDefined } from 'twenty-shared/utils';-import { REACT_APP_SERVER_BASE_URL } from '~/config';-import { retryWithBackoff } from '~/utils/retryWithBackoff';--const TOKEN_RENEWAL_MAX_RETRIES = 3;-const TOKEN_RENEWAL_RETRY_DELAY_MS = 1000;--let renewalPromise: Promise<boolean> | null = null;--export const ensureTokenRenewed = (- store: ReturnType<typeof createStore>,-): Promise<boolean> => {- if (isDefined(renewalPromise)) {- return renewalPromise;- }-- const tokenPair = store.get(tokenPairState.atom);-- if (!isDefined(tokenPair?.refreshToken?.token)) {- return Promise.resolve(false);- }-- const refreshTokenSnapshot = tokenPair.refreshToken.token;-- renewalPromise = retryWithBackoff(- () =>- renewToken(- `${REACT_APP_SERVER_BASE_URL}/metadata`,- store.get(tokenPairState.atom),- ),- {- maxRetries: TOKEN_RENEWAL_MAX_RETRIES,- baseDelayMs: TOKEN_RENEWAL_RETRY_DELAY_MS,- shouldRetry: () => isDefined(store.get(tokenPairState.atom)),- },- )- .then((tokens) => {- if (!isDefined(tokens)) return true;-- const currentPair = store.get(tokenPairState.atom);-- if (- isDefined(currentPair) &&- currentPair.refreshToken.token === refreshTokenSnapshot- ) {- store.set(tokenPairState.atom, tokens);- }-- return true;- })- .catch(() => false)- .finally(() => {- renewalPromise = null;- });-- return renewalPromise;-};diff --git a/packages/twenty-front/src/modules/auth/utils/migrateTokenPairCookieToLocalStorage.ts b/packages/twenty-front/src/modules/auth/utils/migrateTokenPairCookieToLocalStorage.tsdeleted file mode 100644index e7a81805f94..00000000000--- a/packages/twenty-front/src/modules/auth/utils/migrateTokenPairCookieToLocalStorage.ts+++ /dev/null@@ -1,29 +0,0 @@-import { isDefined } from 'twenty-shared/utils';-import { TOKEN_PAIR_LOCAL_STORAGE_KEY } from '@/auth/states/tokenPairState';-import { cookieStorage } from '~/utils/cookie-storage';--const LEGACY_TOKEN_PAIR_COOKIE_KEY = 'tokenPair';--export const migrateTokenPairCookieToLocalStorage = () => {- try {- const legacyCookieValue = cookieStorage.getItem(- LEGACY_TOKEN_PAIR_COOKIE_KEY,- );-- if (!isDefined(legacyCookieValue)) {- return;- }-- const existingLocalStorageValue = localStorage.getItem(- TOKEN_PAIR_LOCAL_STORAGE_KEY,- );-- if (!isDefined(existingLocalStorageValue)) {- localStorage.setItem(TOKEN_PAIR_LOCAL_STORAGE_KEY, legacyCookieValue);- }-- cookieStorage.removeItem(LEGACY_TOKEN_PAIR_COOKIE_KEY);- } catch {- // noop- }-};diff --git a/packages/twenty-front/src/modules/onboarding/hooks/__tests__/useOnboardingStatus.test.ts b/packages/twenty-front/src/modules/onboarding/hooks/__tests__/useOnboardingStatus.test.tsindex 214e72e8f1e..af57a4a22bf 100644--- a/packages/twenty-front/src/modules/onboarding/hooks/__tests__/useOnboardingStatus.test.ts+++ b/packages/twenty-front/src/modules/onboarding/hooks/__tests__/useOnboardingStatus.test.ts@@ -5,19 +5,12 @@ import {type CurrentUser,currentUserState,} from '@/auth/states/currentUserState';-import { tokenPairState } from '@/auth/states/tokenPairState';+import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';import { jotaiStore } from '@/ui/utilities/state/jotai/jotaiStore';import { useOnboardingStatus } from '@/onboarding/hooks/useOnboardingStatus';import { OnboardingStatus } from '~/generated-metadata/graphql';-const tokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'accessToken',- expiresAt: 'expiresAt',- },- refreshToken: { token: 'refreshToken', expiresAt: 'expiresAt' },-};const currentUser = {id: '1',onboardingStatus: null,@@ -31,12 +24,12 @@ const renderHooks = () => {() => {const onboardingStatus = useOnboardingStatus();const setCurrentUser = useSetAtomState(currentUserState);- const setTokenPair = useSetAtomState(tokenPairState);+ const setIsCookieAuthActive = useSetAtomState(isCookieAuthActiveState);return {onboardingStatus,setCurrentUser,- setTokenPair,+ setIsCookieAuthActive,};},{@@ -55,10 +48,10 @@ describe('useOnboardingStatus', () => {Object.values(OnboardingStatus).forEach((onboardingStatus) => {it(`should return "${onboardingStatus}"`, async () => {const { result } = renderHooks();- const { setTokenPair, setCurrentUser } = result.current;+ const { setIsCookieAuthActive, setCurrentUser } = result.current;act(() => {- setTokenPair(tokenPair);+ setIsCookieAuthActive(true);setCurrentUser({...currentUser,onboardingStatus,diff --git a/packages/twenty-front/src/modules/sse-db-event/components/SSEClientEffect.tsx b/packages/twenty-front/src/modules/sse-db-event/components/SSEClientEffect.tsxindex 091043d3658..cd25fa35002 100644--- a/packages/twenty-front/src/modules/sse-db-event/components/SSEClientEffect.tsx+++ b/packages/twenty-front/src/modules/sse-db-event/components/SSEClientEffect.tsx@@ -1,6 +1,4 @@import { useIsLogged } from '@/auth/hooks/useIsLogged';-import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { useListenToBrowserEvent } from '@/browser-event/hooks/useListenToBrowserEvent';import { dispatchBrowserEvent } from '@/browser-event/utils/dispatchBrowserEvent';import { useResyncMetadataStore } from '@/metadata-store/hooks/useResyncMetadataStore';@@ -10,7 +8,6 @@ import { useHandleSseClientConnectionRetry } from '@/sse-db-event/hooks/useHandlimport { activeQueryListenersState } from '@/sse-db-event/states/activeQueryListenersState';import { sseClientState } from '@/sse-db-event/states/sseClientState';import { useAtomState } from '@/ui/utilities/state/jotai/hooks/useAtomState';-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';import { isNonEmptyArray } from '@sniptt/guards';import { createClient } from 'graphql-sse';import { useCallback, useEffect } from 'react';@@ -23,7 +20,6 @@ export const SSEClientEffect = () => {const store = useStore();const isLogged = useIsLogged();const [sseClient, setSseClient] = useAtomState(sseClientState);- const tokenPair = useAtomStateValue(tokenPairState);const { resyncMetadataStore } = useResyncMetadataStore();const debouncedResyncMetadataStore = useDebouncedCallback(@@ -62,23 +58,6 @@ export const SSEClientEffect = () => {const newSseClient = createClient({url: `${REACT_APP_SERVER_BASE_URL}/metadata`,credentials: 'include',- headers: (): Record<string, string> => {- // Same rule as the Apollo auth link: a pair can still be present- // while cookie auth is active, and must not be sent. The server- // prefers Bearer over the session cookie, so attaching a token- // nothing refreshes any more authenticates the stream with a- // credential that expires and never recovers.- if (store.get(isCookieAuthActiveState.atom)) {- return {};- }-- const currentTokenPair = store.get(tokenPairState.atom);- const token = currentTokenPair?.accessOrWorkspaceAgnosticToken?.token;-- return {- Authorization: token ? `Bearer ${token}` : '',- };- },on: {connected: handleSSEClientConnected,},@@ -95,7 +74,6 @@ export const SSEClientEffect = () => {setSseClient,sseClient,store,- tokenPair,handleSseClientConnectionRetry,]);diff --git a/packages/twenty-front/src/modules/sse-db-event/components/__tests__/SSEClientEffect.test.tsx b/packages/twenty-front/src/modules/sse-db-event/components/__tests__/SSEClientEffect.test.tsxindex 6bfffe03e24..36aeaf17ae5 100644--- a/packages/twenty-front/src/modules/sse-db-event/components/__tests__/SSEClientEffect.test.tsx+++ b/packages/twenty-front/src/modules/sse-db-event/components/__tests__/SSEClientEffect.test.tsx@@ -4,10 +4,8 @@ import { createStore, Provider } from 'jotai';import { createElement } from 'react';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';import { SSEClientEffect } from '@/sse-db-event/components/SSEClientEffect';import { REACT_APP_SERVER_BASE_URL } from '~/config';-import { type AuthTokenPair } from '~/generated-metadata/graphql';const createClientMock = jest.fn();@@ -27,41 +25,18 @@ jest.mock('@/metadata-store/hooks/useResyncMetadataStore', () => ({useResyncMetadataStore: () => ({ resyncMetadataStore: jest.fn() }),}));-const TOKEN_PAIR: AuthTokenPair = {- accessOrWorkspaceAgnosticToken: {- token: 'access-token',- expiresAt: new Date().toISOString(),- },- refreshToken: {- token: 'refresh-token',- expiresAt: new Date().toISOString(),- },-};--const renderWithAuthMode = (isCookieAuthActive: boolean) => {+const renderSseClient = () => {const store = createStore();- store.set(tokenPairState.atom, TOKEN_PAIR);- store.set(isCookieAuthActiveState.atom, isCookieAuthActive);+ store.set(isCookieAuthActiveState.atom, true);render(createElement(Provider, { store }, createElement(SSEClientEffect, null)),);- // Asserted here rather than per-case: a second client would mean the effect- // reconnected, and the stream's credential handling only makes sense against- // the rest of the options it was created with.expect(createClientMock).toHaveBeenCalledTimes(1);- const options = createClientMock.mock.calls[0]?.[0] as ClientOptions;-- expect(options).toMatchObject({- url: `${REACT_APP_SERVER_BASE_URL}/metadata`,- credentials: 'include',- retryAttempts: Infinity,- });-- return options.headers as () => Record<string, string>;+ return createClientMock.mock.calls[0]?.[0] as ClientOptions;};describe('SSEClientEffect', () => {@@ -69,17 +44,16 @@ describe('SSEClientEffect', () => {jest.clearAllMocks();});- it('should attach the Bearer header when the client authenticates by token', () => {- const headers = renderWithAuthMode(false);-- expect(headers()).toEqual({ Authorization: 'Bearer access-token' });- });-- // The server prefers Bearer over the session cookie, so a dormant token here- // would authenticate the stream with a credential nothing refreshes.- it('should not attach the Bearer header while cookie auth is active', () => {- const headers = renderWithAuthMode(true);-- expect(headers()).toEqual({});+ // The session cookie travels with the request, so the stream needs no header+ // of its own.+ it('should authenticate the stream with the session cookie alone', () => {+ const options = renderSseClient();++ expect(options).toMatchObject({+ url: `${REACT_APP_SERVER_BASE_URL}/metadata`,+ credentials: 'include',+ retryAttempts: Infinity,+ });+ expect(options.headers).toBeUndefined();});});diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.tsindex a0f2f415e06..d50aef878b3 100644--- a/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/__tests__/useHandleSseClientConnectionRetry.test.ts@@ -5,8 +5,6 @@ import { createElement, type ReactNode } from 'react';import { isDefined } from 'twenty-shared/utils';import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { type AuthTokenPair } from '~/generated-metadata/graphql';import { shouldDestroyEventStreamState } from '@/sse-db-event/states/shouldDestroyEventStreamState';import { sseClientState } from '@/sse-db-event/states/sseClientState';import { useHandleSseClientConnectionRetry } from '@/sse-db-event/hooks/useHandleSseClientConnectionRetry';@@ -15,23 +13,6 @@ jest.mock('~/utils/sleep', () => ({sleep: jest.fn().mockResolvedValue(undefined),}));-const ensureTokenRenewedMock = jest.fn();--jest.mock('@/auth/utils/ensureTokenRenewed', () => ({- ensureTokenRenewed: (...args: unknown[]) => ensureTokenRenewedMock(...args),-}));--const buildTokenPair = (expiresAt: Date): AuthTokenPair => ({- accessOrWorkspaceAgnosticToken: {- token: 'access-token',- expiresAt: expiresAt.toISOString(),- },- refreshToken: {- token: 'refresh-token',- expiresAt: expiresAt.toISOString(),- },-});-// The hook only ever calls dispose, but the atom holds a full Client, so the// unused members are stubbed rather than cast away.const buildSseClient = (dispose: () => void): Client => ({@@ -42,10 +23,8 @@ const buildSseClient = (dispose: () => void): Client => ({const setupStore = ({isCookieAuthActive,- tokenPair,}: {isCookieAuthActive: boolean;- tokenPair: AuthTokenPair | null;}) => {const store = createStore();const dispose = jest.fn();@@ -53,7 +32,6 @@ const setupStore = ({store.set(sseClientState.atom, buildSseClient(dispose));store.set(shouldDestroyEventStreamState.atom, false);store.set(isCookieAuthActiveState.atom, isCookieAuthActive);- store.set(tokenPairState.atom, tokenPair);const wrapper = ({ children }: { children: ReactNode }) =>createElement(Provider, { store }, children);@@ -72,13 +50,11 @@ const wasStreamDestroyed = (store: ReturnType<typeof createStore>) =>describe('useHandleSseClientConnectionRetry', () => {beforeEach(() => {jest.clearAllMocks();- ensureTokenRenewedMock.mockResolvedValue(true);});it('should stop retrying when a cookie-mode client has been signed out', async () => {const { store, dispose, result } = setupStore({isCookieAuthActive: false,- tokenPair: null,});await act(() => result.current.handleSseClientConnectionRetry(0));@@ -90,20 +66,17 @@ describe('useHandleSseClientConnectionRetry', () => {it('should keep retrying a live cookie session that has no token pair', async () => {const { store, dispose, result } = setupStore({isCookieAuthActive: true,- tokenPair: null,});await act(() => result.current.handleSseClientConnectionRetry(0));expect(dispose).not.toHaveBeenCalled();expect(wasStreamDestroyed(store)).toBe(false);- expect(ensureTokenRenewedMock).not.toHaveBeenCalled();});it('should stop retrying past the attempt cap regardless of credential', async () => {const { store, dispose, result } = setupStore({isCookieAuthActive: true,- tokenPair: null,});await act(() => result.current.handleSseClientConnectionRetry(11));@@ -111,33 +84,4 @@ describe('useHandleSseClientConnectionRetry', () => {expect(dispose).toHaveBeenCalledTimes(1);expect(wasStreamDestroyed(store)).toBe(true);});-- it('should renew an expired token in token mode and stop when renewal fails', async () => {- ensureTokenRenewedMock.mockResolvedValue(false);-- const { store, dispose, result } = setupStore({- isCookieAuthActive: false,- tokenPair: buildTokenPair(new Date(Date.now() - 1000)),- });-- await act(() => result.current.handleSseClientConnectionRetry(0));-- expect(ensureTokenRenewedMock).toHaveBeenCalledTimes(1);- expect(ensureTokenRenewedMock).toHaveBeenCalledWith(store);- expect(dispose).toHaveBeenCalledTimes(1);- expect(wasStreamDestroyed(store)).toBe(true);- });-- it('should keep retrying in token mode while the token is still valid', async () => {- const { store, dispose, result } = setupStore({- isCookieAuthActive: false,- tokenPair: buildTokenPair(new Date(Date.now() + 60_000)),- });-- await act(() => result.current.handleSseClientConnectionRetry(0));-- expect(ensureTokenRenewedMock).not.toHaveBeenCalled();- expect(dispose).not.toHaveBeenCalled();- expect(wasStreamDestroyed(store)).toBe(false);- });});diff --git a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.tsindex 8f0223b4461..81367d1fbe0 100644--- a/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts+++ b/packages/twenty-front/src/modules/sse-db-event/hooks/useHandleSseClientConnectionRetry.ts@@ -1,6 +1,4 @@import { isCookieAuthActiveState } from '@/auth/states/isCookieAuthActiveState';-import { tokenPairState } from '@/auth/states/tokenPairState';-import { ensureTokenRenewed } from '@/auth/utils/ensureTokenRenewed';import { SSE_CONNECTION_RETRY_MAX_WAIT_TIME_IN_MS } from '@/sse-db-event/constants/SseConnectionRetryMaxWaitTimeInMs';import { SSE_CONNECTION_RETRY_WAIT_TIME_IN_MS_FOR_DEV_MODE } from '@/sse-db-event/constants/SseConnectionRetryWaitTimeInMsForDevMode';import { SSE_CONNECTION_RETRY_WAIT_TIME_IN_MS_TO_AVOID_RACE_CONDITIONS } from '@/sse-db-event/constants/SseConnectionRetryWaitTimeInMsToAvoidRaceConditions';@@ -23,12 +21,11 @@ const destroyStream = async (store.set(sseClientState.atom, null);};-// The session cookie is httpOnly, so a cookie-mode client cannot inspect its own-// credential. clearSession drops both credentials together, so their joint-// absence is what "signed out" looks like from here.+// The session cookie is httpOnly, so the client cannot inspect its own+// credential; clearSession dropping this flag is what "signed out" looks like+// from here.const hasCredential = (store: ReturnType<typeof useStore>): boolean =>- store.get(isCookieAuthActiveState.atom) ||- isDefined(store.get(tokenPairState.atom)?.accessOrWorkspaceAgnosticToken);+ store.get(isCookieAuthActiveState.atom);export const useHandleSseClientConnectionRetry = () => {const store = useStore();@@ -57,24 +54,6 @@ export const useHandleSseClientConnectionRetry = () => {return;}- if (!store.get(isCookieAuthActiveState.atom)) {- const accessToken = store.get(- tokenPairState.atom,- )?.accessOrWorkspaceAgnosticToken;-- if (- isDefined(accessToken) &&- new Date(accessToken.expiresAt) <= new Date()- ) {- const renewed = await ensureTokenRenewed(store);-- if (!renewed) {- await destroyStream(store, sseClient);- return;- }- }- }-const randomWaitTimeInMsToSpaceAllClientsReconnection = Math.round(Math.random() * SSE_CONNECTION_RETRY_MAX_WAIT_TIME_IN_MS,);diff --git a/packages/twenty-front/src/pages/auth/PasswordReset.tsx b/packages/twenty-front/src/pages/auth/PasswordReset.tsxindex 5d1fe28d840..d4ac85e9114 100644--- a/packages/twenty-front/src/pages/auth/PasswordReset.tsx+++ b/packages/twenty-front/src/pages/auth/PasswordReset.tsx@@ -115,7 +115,6 @@ export const PasswordReset = () => {token: passwordResetToken ?? '',},skip: !passwordResetToken || isTokenValid,- context: { skipAuthToken: true },},);@@ -143,9 +142,6 @@ export const PasswordReset = () => {const [updatePasswordViaToken, { loading: isUpdatingPassword }] = useMutation(UpdatePasswordViaResetTokenDocument,- {- context: { skipAuthToken: true },- },);const { signInWithCredentialsInWorkspace, signInWithCredentials } = useAuth();