Skip to content

The open alternative to Salesforce, designed for AI.

fix(server): refresh app connection access tokens using provider expires_in (#28446) (#29173)

Apoorv A Sddcddd468847
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-callback.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-callback.ts
index 457e3306435..c94b07ead9e 100644
--- a/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-callback.ts
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/linkedin-callback.ts
@@ -20,7 +20,9 @@ export const linkedinCallbackHandler = async ({
if (isNonEmptyString(errorTitle)) {
throw new Error(
- isNonEmptyString(errorDetail) ? `${errorTitle}: ${errorDetail}` : errorTitle,
+ isNonEmptyString(errorDetail)
+ ? `${errorTitle}: ${errorDetail}`
+ : errorTitle,
);
}
diff --git a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/map-unipile-message-to-ingest-message.util.test.ts b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/map-unipile-message-to-ingest-message.util.test.ts
index 5beba7353e8..253d19b37bf 100644
--- a/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/map-unipile-message-to-ingest-message.util.test.ts
+++ b/packages/twenty-apps/public/linkedin/src/logic-functions/utils/__tests__/map-unipile-message-to-ingest-message.util.test.ts
@@ -5,7 +5,9 @@ import { type UnipileMessage } from 'src/unipile/types/unipile-message.type';
const CHANNEL_HANDLE = 'linkedin.com/in/me';
-const buildMessage = (overrides: Partial<UnipileMessage> = {}): UnipileMessage => ({
+const buildMessage = (
+ overrides: Partial<UnipileMessage> = {},
+): UnipileMessage => ({
id: 'message-1',
chat_id: 'chat-1',
sender_id: 'ACoGRACE',
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793357800472-add-access-token-expires-at-to-connected-account.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793357800472-add-access-token-expires-at-to-connected-account.ts
new file mode 100644
index 00000000000..760c7805f18
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793357800472-add-access-token-expires-at-to-connected-account.ts
@@ -0,0 +1,21 @@
+import { type QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { type FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.54.0', 1793357800472)
+export class AddAccessTokenExpiresAtToConnectedAccountFastInstanceCommand
+ implements FastInstanceCommand
+{
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" ADD "accessTokenExpiresAt" TIMESTAMP WITH TIME ZONE',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" DROP COLUMN "accessTokenExpiresAt"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/add-access-token-expires-at-to-connected-account-upgrade-command-name.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/add-access-token-expires-at-to-connected-account-upgrade-command-name.constant.ts
new file mode 100644
index 00000000000..1f49da8e63f
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-54/add-access-token-expires-at-to-connected-account-upgrade-command-name.constant.ts
@@ -0,0 +1,2 @@
+export const ADD_ACCESS_TOKEN_EXPIRES_AT_TO_CONNECTED_ACCOUNT_UPGRADE_COMMAND_NAME =
+ '2.54.0_AddAccessTokenExpiresAtToConnectedAccountFastInstanceCommand_1793357800472';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 041e27222a6..0e46e5c49f6 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -270,6 +270,7 @@ import { PurgeSoftDeletedAgentsSlowInstanceCommand } from 'src/database/commands
import { AddGeolocationToUserSessionFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793274494191-add-geolocation-to-user-session';
import { AddWorkspaceChatAssistantModesFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793280483473-add-workspace-chat-assistant-modes';
import { AddRelatedRecordPathTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793291361887-add-related-record-path-table';
+import { AddAccessTokenExpiresAtToConnectedAccountFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-54/2-54-instance-command-fast-1793357800472-add-access-token-expires-at-to-connected-account';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -542,4 +543,5 @@ export const INSTANCE_COMMANDS = [
AddGeolocationToUserSessionFastInstanceCommand,
AddWorkspaceChatAssistantModesFastInstanceCommand,
AddRelatedRecordPathTableFastInstanceCommand,
+ AddAccessTokenExpiresAtToConnectedAccountFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts
index 7f56e34dfad..283e9eebde8 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-connected-account.service.ts
@@ -25,6 +25,7 @@ type ConnectedAccountCredentials = {
accessToken: PlaintextString | null;
refreshToken: PlaintextString | null;
scopes: string[] | null;
+ accessTokenExpiresAt?: Date | null;
};
@Injectable()
@@ -130,6 +131,7 @@ export class ConnectionProviderConnectedAccountService {
}),
scopes: credentials.scopes,
lastCredentialsRefreshedAt: new Date(),
+ accessTokenExpiresAt: credentials.accessTokenExpiresAt ?? null,
}),
...(isDefined(handle) && { handle }),
authFailedAt: null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
index 1917e65a3c2..24349a6fe51 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
@@ -171,6 +171,7 @@ export class ConnectionProviderOAuthFlowService {
accessToken: tokenResponse.accessToken,
refreshToken: tokenResponse.refreshToken,
scopes: tokenResponse.scopes ?? provider.oauthConfig.scopes,
+ accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
},
handle,
identifiedAccount,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/refresh/services/app-oauth-refresh-tokens.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/refresh/services/app-oauth-refresh-tokens.service.ts
index 9bbb8425a02..efac07bc8b1 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/refresh/services/app-oauth-refresh-tokens.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/refresh/services/app-oauth-refresh-tokens.service.ts
@@ -58,6 +58,7 @@ export class AppOAuthRefreshAccessTokenService {
refreshToken: isDefined(tokenResponse.refreshToken)
? tokenResponse.refreshToken
: refreshToken,
+ accessTokenExpiresAt: tokenResponse.accessTokenExpiresAt,
};
} catch (error) {
this.logger.warn(
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/token-exchange-response.type.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/token-exchange-response.type.ts
index b0e83900c3a..01417eeaa81 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/token-exchange-response.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/types/token-exchange-response.type.ts
@@ -5,4 +5,5 @@ export type TokenExchangeResponse = {
refreshToken: PlaintextString | null;
idToken: PlaintextString | null;
scopes: string[] | null;
+ accessTokenExpiresAt: Date | null;
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/exchange-code-for-token.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/exchange-code-for-token.util.spec.ts
index 008cafbb999..c8ea7dcb53d 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/exchange-code-for-token.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/exchange-code-for-token.util.spec.ts
@@ -44,6 +44,7 @@ describe('exchangeCodeForToken', () => {
refreshToken: 'lin_refresh',
idToken: null,
scopes: ['read', 'write'],
+ accessTokenExpiresAt: expect.any(Date),
});
const init = (
@@ -143,6 +144,7 @@ describe('exchangeRefreshTokenForToken', () => {
refreshToken: 'new_refresh',
idToken: null,
scopes: null,
+ accessTokenExpiresAt: null,
});
const init = (
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-token-response.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-token-response.util.spec.ts
new file mode 100644
index 00000000000..fec4c545cfc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-token-response.util.spec.ts
@@ -0,0 +1,72 @@
+import * as jwt from 'jsonwebtoken';
+
+import { parseTokenResponse } from 'src/engine/core-modules/application/connection-provider/utils/parse-token-response.util';
+
+describe('parseTokenResponse', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.setSystemTime(new Date('2026-01-01T00:00:00.000Z'));
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('computes accessTokenExpiresAt from numeric expires_in', () => {
+ const result = parseTokenResponse({
+ access_token: 'valid-access-token',
+ refresh_token: 'valid-refresh-token',
+ expires_in: 300,
+ scope: 'read write',
+ });
+
+ expect(result.accessToken).toBe('valid-access-token');
+ expect(result.refreshToken).toBe('valid-refresh-token');
+ expect(result.scopes).toEqual(['read', 'write']);
+ expect(result.accessTokenExpiresAt).toEqual(
+ new Date('2026-01-01T00:05:00.000Z'),
+ );
+ });
+
+ it('computes accessTokenExpiresAt from string expires_in', () => {
+ const result = parseTokenResponse({
+ access_token: 'valid-access-token',
+ expires_in: '3600',
+ });
+
+ expect(result.accessTokenExpiresAt).toEqual(
+ new Date('2026-01-01T01:00:00.000Z'),
+ );
+ });
+
+ it('extracts accessTokenExpiresAt from JWT exp claim when expires_in is omitted', () => {
+ const expSeconds = Math.floor(
+ new Date('2026-01-01T00:15:00.000Z').getTime() / 1000,
+ );
+ const token = jwt.sign({ exp: expSeconds }, 'secret');
+
+ const result = parseTokenResponse({
+ access_token: token,
+ });
+
+ expect(result.accessTokenExpiresAt).toEqual(
+ new Date('2026-01-01T00:15:00.000Z'),
+ );
+ });
+
+ it('leaves accessTokenExpiresAt as null when neither expires_in nor JWT exp claim is present', () => {
+ const result = parseTokenResponse({
+ access_token: 'opaque-token-without-expiry',
+ });
+
+ expect(result.accessTokenExpiresAt).toBeNull();
+ });
+
+ it('throws when access_token is missing', () => {
+ expect(() =>
+ parseTokenResponse({
+ refresh_token: 'only-refresh',
+ }),
+ ).toThrow('Token endpoint did not return an access_token');
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-access-token-expires-at.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-access-token-expires-at.util.ts
new file mode 100644
index 00000000000..213ea10ccb2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-access-token-expires-at.util.ts
@@ -0,0 +1,27 @@
+import { isNumber } from '@sniptt/guards';
+import { addSeconds, fromUnixTime } from 'date-fns';
+import { isDefined } from 'twenty-shared/utils';
+
+import { parseExpiresInSeconds } from 'src/engine/core-modules/application/connection-provider/utils/parse-expires-in-seconds.util';
+import { decodeJwtPayload } from 'src/engine/core-modules/jwt/utils/decode-jwt-payload.util';
+import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+
+export const parseAccessTokenExpiresAt = (
+ expiresIn: unknown,
+ accessToken: PlaintextString,
+): Date | null => {
+ const expiresInSeconds = parseExpiresInSeconds(expiresIn);
+
+ if (isDefined(expiresInSeconds)) {
+ return addSeconds(new Date(), expiresInSeconds);
+ }
+
+ const expirationEpochSeconds = decodeJwtPayload<{ exp?: unknown }>(
+ accessToken,
+ )?.exp;
+
+ return isNumber(expirationEpochSeconds) &&
+ Number.isFinite(expirationEpochSeconds)
+ ? fromUnixTime(expirationEpochSeconds)
+ : null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-expires-in-seconds.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-expires-in-seconds.util.ts
new file mode 100644
index 00000000000..b5c8fc3c0cb
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-expires-in-seconds.util.ts
@@ -0,0 +1,13 @@
+import { isNonEmptyString, isNumber } from '@sniptt/guards';
+
+export const parseExpiresInSeconds = (expiresIn: unknown): number | null => {
+ if (!isNumber(expiresIn) && !isNonEmptyString(expiresIn)) {
+ return null;
+ }
+
+ const expiresInSeconds = Number(expiresIn);
+
+ return Number.isFinite(expiresInSeconds) && expiresInSeconds > 0
+ ? expiresInSeconds
+ : null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-token-response.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-token-response.util.ts
index 8a240213a6e..4fa5f1ca891 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-token-response.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-token-response.util.ts
@@ -1,33 +1,34 @@
+import { isNonEmptyString } from '@sniptt/guards';
+
import { type TokenExchangeResponse } from 'src/engine/core-modules/application/connection-provider/types/token-exchange-response.type';
+import { parseAccessTokenExpiresAt } from 'src/engine/core-modules/application/connection-provider/utils/parse-access-token-expires-at.util';
import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
export const parseTokenResponse = (
json: Record<string, unknown>,
): TokenExchangeResponse => {
- const accessToken =
- typeof json.access_token === 'string'
- ? (json.access_token as PlaintextString)
- : null;
-
- if (!accessToken) {
+ if (!isNonEmptyString(json.access_token)) {
throw new Error(
`Token endpoint did not return an access_token. Response keys: ${Object.keys(json).join(', ')}`,
);
}
+ const accessToken = json.access_token as PlaintextString;
+
return {
accessToken,
- refreshToken:
- typeof json.refresh_token === 'string'
- ? (json.refresh_token as PlaintextString)
- : null,
- idToken:
- typeof json.id_token === 'string'
- ? (json.id_token as PlaintextString)
- : null,
- scopes:
- typeof json.scope === 'string'
- ? json.scope.split(/[\s,]+/).filter(Boolean)
- : null,
+ refreshToken: isNonEmptyString(json.refresh_token)
+ ? (json.refresh_token as PlaintextString)
+ : null,
+ idToken: isNonEmptyString(json.id_token)
+ ? (json.id_token as PlaintextString)
+ : null,
+ scopes: isNonEmptyString(json.scope)
+ ? json.scope.split(/[\s,]+/).filter(Boolean)
+ : null,
+ accessTokenExpiresAt: parseAccessTokenExpiresAt(
+ json.expires_in,
+ accessToken,
+ ),
};
};
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
index cfe94b9e8c5..ca68208ccc4 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
@@ -16,6 +16,7 @@ import { type ConnectedAccountProvider } from 'twenty-shared/types';
import { ApplicationEntity } from 'src/engine/core-modules/application/application.entity';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { ADD_ACCESS_TOKEN_EXPIRES_AT_TO_CONNECTED_ACCOUNT_UPGRADE_COMMAND_NAME } from 'src/database/commands/upgrade-version-command/2-54/add-access-token-expires-at-to-connected-account-upgrade-command-name.constant';
import { type EncryptedImapSmtpCaldavParams } from 'src/engine/core-modules/imap-smtp-caldav-connection/types/imap-smtp-caldav-connection.type';
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
@@ -76,6 +77,13 @@ export class ConnectedAccountEntity extends WorkspaceRelatedEntity {
@Column({ type: 'timestamptz', nullable: true })
lastCredentialsRefreshedAt: Date | null;
+ @Column({ type: 'timestamptz', nullable: true })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ ADD_ACCESS_TOKEN_EXPIRES_AT_TO_CONNECTED_ACCOUNT_UPGRADE_COMMAND_NAME,
+ })
+ accessTokenExpiresAt: Date | null;
+
@Column({ type: 'timestamptz', nullable: true })
authFailedAt: Date | null;
diff --git a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
index 9db87f311c0..540a40319be 100644
--- a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/services/connected-account-refresh-tokens.service.ts
@@ -1,6 +1,7 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { isBefore } from 'date-fns';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { assertUnreachable, isDefined } from 'twenty-shared/utils';
import { Repository } from 'typeorm';
@@ -16,11 +17,13 @@ import {
import { ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
import { GoogleApiRefreshAccessTokenService } from 'src/modules/connected-account/refresh-tokens-manager/drivers/google/services/google-api-refresh-tokens.service';
import { MicrosoftApiRefreshAccessTokenService } from 'src/modules/connected-account/refresh-tokens-manager/drivers/microsoft/services/microsoft-api-refresh-tokens.service';
+import { computeAccessTokenRefreshAt } from 'src/modules/connected-account/refresh-tokens-manager/utils/compute-access-token-refresh-at.util';
// Encrypted and plaintext shapes are modeled separately so they cannot be mixed (#20819)
export type ConnectedAccountPlaintextTokens = {
accessToken: PlaintextString;
refreshToken: PlaintextString | null;
+ accessTokenExpiresAt?: Date | null;
};
export type ConnectedAccountEncryptedTokens = {
@@ -30,8 +33,6 @@ export type ConnectedAccountEncryptedTokens = {
export type ConnectedAccountTokens = ConnectedAccountEncryptedTokens;
-const CONNECTED_ACCOUNT_ACCESS_TOKEN_EXPIRATION = 1000 * 60 * 60;
-
@Injectable()
export class ConnectedAccountRefreshTokensService {
private readonly logger = new Logger(
@@ -131,6 +132,7 @@ export class ConnectedAccountRefreshTokensService {
accessToken: encryptedAccessToken,
refreshToken: reEncryptedRefreshToken,
lastCredentialsRefreshedAt: new Date(),
+ accessTokenExpiresAt: plaintextTokens.accessTokenExpiresAt ?? null,
},
);
@@ -159,15 +161,13 @@ export class ConnectedAccountRefreshTokensService {
return false;
}
- const BUFFER_TIME = 5 * 60 * 1000;
-
- const tokenExpirationTime =
- CONNECTED_ACCOUNT_ACCESS_TOKEN_EXPIRATION - BUFFER_TIME;
+ const now = new Date();
+ const accessTokenRefreshAt = computeAccessTokenRefreshAt({
+ accessTokenIssuedAt: connectedAccount.lastCredentialsRefreshedAt,
+ accessTokenExpiresAt: connectedAccount.accessTokenExpiresAt,
+ });
- return (
- connectedAccount.lastCredentialsRefreshedAt >
- new Date(Date.now() - tokenExpirationTime)
- );
+ return isBefore(now, accessTokenRefreshAt);
}
case ConnectedAccountProvider.IMAP_SMTP_CALDAV:
case ConnectedAccountProvider.OIDC:
diff --git a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/__tests__/compute-access-token-refresh-at.util.spec.ts b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/__tests__/compute-access-token-refresh-at.util.spec.ts
new file mode 100644
index 00000000000..ee7e353fced
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/__tests__/compute-access-token-refresh-at.util.spec.ts
@@ -0,0 +1,32 @@
+import { computeAccessTokenRefreshAt } from 'src/modules/connected-account/refresh-tokens-manager/utils/compute-access-token-refresh-at.util';
+
+const accessTokenIssuedAt = new Date('2026-01-01T12:00:00.000Z');
+
+describe('computeAccessTokenRefreshAt', () => {
+ it('refreshes 55 minutes after issue when the provider sent no lifetime, as Google and Microsoft accounts always do', () => {
+ expect(
+ computeAccessTokenRefreshAt({
+ accessTokenIssuedAt,
+ accessTokenExpiresAt: null,
+ }),
+ ).toEqual(new Date('2026-01-01T12:55:00.000Z'));
+ });
+
+ it('refreshes a 5-minute token 30 seconds before it expires', () => {
+ expect(
+ computeAccessTokenRefreshAt({
+ accessTokenIssuedAt,
+ accessTokenExpiresAt: new Date('2026-01-01T12:05:00.000Z'),
+ }),
+ ).toEqual(new Date('2026-01-01T12:04:30.000Z'));
+ });
+
+ it('caps the refresh margin at 5 minutes for long-lived tokens', () => {
+ expect(
+ computeAccessTokenRefreshAt({
+ accessTokenIssuedAt,
+ accessTokenExpiresAt: new Date('2026-01-01T14:00:00.000Z'),
+ }),
+ ).toEqual(new Date('2026-01-01T13:55:00.000Z'));
+ });
+});
diff --git a/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/compute-access-token-refresh-at.util.ts b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/compute-access-token-refresh-at.util.ts
new file mode 100644
index 00000000000..28ef1f2cbd2
--- /dev/null
+++ b/packages/twenty-server/src/modules/connected-account/refresh-tokens-manager/utils/compute-access-token-refresh-at.util.ts
@@ -0,0 +1,29 @@
+import {
+ addMilliseconds,
+ differenceInMilliseconds,
+ subMilliseconds,
+} from 'date-fns';
+
+const DEFAULT_ACCESS_TOKEN_LIFETIME_MS = 60 * 60 * 1000;
+const MAX_REFRESH_MARGIN_MS = 5 * 60 * 1000;
+const REFRESH_MARGIN_LIFETIME_RATIO = 0.1;
+
+export const computeAccessTokenRefreshAt = ({
+ accessTokenIssuedAt,
+ accessTokenExpiresAt,
+}: {
+ accessTokenIssuedAt: Date;
+ accessTokenExpiresAt: Date | null;
+}): Date => {
+ const expiresAt =
+ accessTokenExpiresAt ??
+ addMilliseconds(accessTokenIssuedAt, DEFAULT_ACCESS_TOKEN_LIFETIME_MS);
+
+ const refreshMarginMs = Math.min(
+ MAX_REFRESH_MARGIN_MS,
+ differenceInMilliseconds(expiresAt, accessTokenIssuedAt) *
+ REFRESH_MARGIN_LIFETIME_RATIO,
+ );
+
+ return subMilliseconds(expiresAt, refreshMarginMs);
+};