Skip to content

The open alternative to Salesforce, designed for AI.

Reload the enterprise validity token in the server process (#26449)

Mariedd6c74c09bcf
diff --git a/packages/twenty-server/src/engine/core-modules/auth/guards/enterprise-features-enabled.guard.ts b/packages/twenty-server/src/engine/core-modules/auth/guards/enterprise-features-enabled.guard.ts
index 30a38a09c8f..6b006daaee9 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/guards/enterprise-features-enabled.guard.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/guards/enterprise-features-enabled.guard.ts
@@ -20,9 +20,9 @@ export class EnterpriseFeaturesEnabledGuard implements CanActivate {
private readonly enterprisePlanService: EnterprisePlanService,
) {}
- canActivate(context: ExecutionContext): boolean {
+ async canActivate(context: ExecutionContext): Promise<boolean> {
try {
- if (!this.enterprisePlanService.isValid()) {
+ if (!(await this.enterprisePlanService.isValidWithFreshToken())) {
throw new AuthException(
'Enterprise features are not enabled',
AuthExceptionCode.ENTERPRISE_VALIDITY_TOKEN_NOT_VALID,
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-interval.constant.ts
new file mode 100644
index 00000000000..dab1e9eef0a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-interval.constant.ts
@@ -0,0 +1,3 @@
+/* @license Enterprise */
+
+export const ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS = 15 * 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-retry-interval.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-retry-interval.constant.ts
new file mode 100644
index 00000000000..c6d74ae66f8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-retry-interval.constant.ts
@@ -0,0 +1,3 @@
+/* @license Enterprise */
+
+export const ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS = 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
index 4819328f9f0..4dbd1818439 100644
--- a/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
@@ -29,6 +29,7 @@ import {
type EnterpriseLicenseInfo,
type EnterpriseValidityPayload,
} from 'src/engine/core-modules/enterprise/types/organization-key-payload.type';
+import { isValidityTokenReloadDue } from 'src/engine/core-modules/enterprise/utils/is-validity-token-reload-due.util';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
import {
ConfigVariableException,
@@ -45,6 +46,9 @@ export class EnterprisePlanService implements OnModuleInit {
private cachedValidityPayload: EnterpriseValidityPayload | null = null;
private cachedKeyPayload: EnterpriseKeyPayload | null = null;
private lastRefreshRejectionCode: string | null = null;
+ private lastValidityTokenLoadStartedAt: number | null = null;
+ private didLastValidityTokenLoadFail = false;
+ private validityTokenRevocationCount = 0;
static readonly ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER_CODE =
'ENTERPRISE_KEY_BOUND_TO_ANOTHER_SERVER';
@@ -84,6 +88,10 @@ export class EnterprisePlanService implements OnModuleInit {
}
private async loadValidityToken(): Promise<void> {
+ this.lastValidityTokenLoadStartedAt = Date.now();
+
+ const revocationCountAtLoadStart = this.validityTokenRevocationCount;
+
try {
const dbToken = await this.appTokenRepository.findOne({
where: {
@@ -95,6 +103,12 @@ export class EnterprisePlanService implements OnModuleInit {
order: { createdAt: 'DESC' },
});
+ this.didLastValidityTokenLoadFail = false;
+
+ if (revocationCountAtLoadStart !== this.validityTokenRevocationCount) {
+ return;
+ }
+
const tokenValue =
dbToken?.value ??
this.twentyConfigService.get('ENTERPRISE_VALIDITY_TOKEN');
@@ -113,10 +127,11 @@ export class EnterprisePlanService implements OnModuleInit {
this.cachedValidityPayload = null;
}
} catch (error) {
+ this.didLastValidityTokenLoadFail = true;
+
this.logger.warn(
- `Failed to load validity token: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ `Failed to load validity token: ${error instanceof Error ? error.message : 'Unknown error'}. Keeping the token in hand.`,
);
- this.cachedValidityPayload = null;
}
}
@@ -156,14 +171,50 @@ export class EnterprisePlanService implements OnModuleInit {
return isDefined(this.cachedKeyPayload);
}
+ private reloadValidityTokenIfStale(): void {
+ const isReloadDue = isValidityTokenReloadDue({
+ lastLoadStartedAt: this.lastValidityTokenLoadStartedAt,
+ didLastLoadFail: this.didLastValidityTokenLoadFail,
+ now: Date.now(),
+ });
+
+ if (!isReloadDue) {
+ return;
+ }
+
+ void this.loadValidityToken();
+ }
+
+ private isCachedValidityPayloadValid(): boolean {
+ if (!isDefined(this.cachedValidityPayload)) {
+ return false;
+ }
+
+ return this.cachedValidityPayload.exp > Math.floor(Date.now() / 1000);
+ }
+
hasValidEnterpriseValidityToken(): boolean {
- if (isDefined(this.cachedValidityPayload)) {
- const now = Math.floor(Date.now() / 1000);
+ this.reloadValidityTokenIfStale();
+
+ return this.isCachedValidityPayloadValid();
+ }
- return this.cachedValidityPayload.exp > now;
+ async isValidWithFreshToken(): Promise<boolean> {
+ if (this.isCachedValidityPayloadValid()) {
+ return true;
}
- return false;
+ if (
+ isValidityTokenReloadDue({
+ lastLoadStartedAt: this.lastValidityTokenLoadStartedAt,
+ didLastLoadFail: this.didLastValidityTokenLoadFail,
+ now: Date.now(),
+ })
+ ) {
+ await this.loadValidityToken();
+ }
+
+ return this.isCachedValidityPayloadValid();
}
isValid(): boolean {
@@ -179,10 +230,8 @@ export class EnterprisePlanService implements OnModuleInit {
await this.loadValidityToken();
if (isDefined(this.cachedValidityPayload)) {
- const now = Math.floor(Date.now() / 1000);
-
return {
- isValid: this.cachedValidityPayload.exp > now,
+ isValid: this.isCachedValidityPayloadValid(),
licensee: this.cachedKeyPayload?.licensee ?? null,
expiresAt: new Date(this.cachedValidityPayload.exp * 1000),
subscriptionId: this.cachedValidityPayload.sub,
@@ -221,6 +270,7 @@ export class EnterprisePlanService implements OnModuleInit {
}
private async revokeStoredValidityToken(): Promise<void> {
+ this.validityTokenRevocationCount += 1;
this.cachedValidityPayload = null;
try {
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/is-validity-token-reload-due.util.spec.ts b/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/is-validity-token-reload-due.util.spec.ts
new file mode 100644
index 00000000000..65fc70804e9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/utils/__tests__/is-validity-token-reload-due.util.spec.ts
@@ -0,0 +1,62 @@
+/* @license Enterprise */
+
+import { ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-interval.constant';
+import { ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-retry-interval.constant';
+import { isValidityTokenReloadDue } from 'src/engine/core-modules/enterprise/utils/is-validity-token-reload-due.util';
+
+describe('isValidityTokenReloadDue', () => {
+ const NOW = 1_700_000_000_000;
+
+ it('is due before anything has been read', () => {
+ expect(
+ isValidityTokenReloadDue({
+ lastLoadStartedAt: null,
+ didLastLoadFail: false,
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it('is not due while the token in hand is younger than the interval', () => {
+ expect(
+ isValidityTokenReloadDue({
+ lastLoadStartedAt:
+ NOW - ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS + 1,
+ didLastLoadFail: false,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+
+ it('is due once the interval has elapsed', () => {
+ expect(
+ isValidityTokenReloadDue({
+ lastLoadStartedAt: NOW - ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS,
+ didLastLoadFail: false,
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it('is due on the retry interval after a read that failed', () => {
+ expect(
+ isValidityTokenReloadDue({
+ lastLoadStartedAt:
+ NOW - ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS,
+ didLastLoadFail: true,
+ now: NOW,
+ }),
+ ).toBe(true);
+ });
+
+ it('is not due right after a read that failed', () => {
+ expect(
+ isValidityTokenReloadDue({
+ lastLoadStartedAt:
+ NOW - ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS + 1,
+ didLastLoadFail: true,
+ now: NOW,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/utils/is-validity-token-reload-due.util.ts b/packages/twenty-server/src/engine/core-modules/enterprise/utils/is-validity-token-reload-due.util.ts
new file mode 100644
index 00000000000..90e74bbccc8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/utils/is-validity-token-reload-due.util.ts
@@ -0,0 +1,28 @@
+/* @license Enterprise */
+
+import { isDefined } from 'twenty-shared/utils';
+
+import { ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-interval.constant';
+import { ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS } from 'src/engine/core-modules/enterprise/constants/enterprise-validity-token-reload-retry-interval.constant';
+
+type IsValidityTokenReloadDueArgs = {
+ lastLoadStartedAt: number | null;
+ didLastLoadFail: boolean;
+ now: number;
+};
+
+export const isValidityTokenReloadDue = ({
+ lastLoadStartedAt,
+ didLastLoadFail,
+ now,
+}: IsValidityTokenReloadDueArgs): boolean => {
+ if (!isDefined(lastLoadStartedAt)) {
+ return true;
+ }
+
+ const reloadInterval = didLastLoadFail
+ ? ENTERPRISE_VALIDITY_TOKEN_RELOAD_RETRY_INTERVAL_MS
+ : ENTERPRISE_VALIDITY_TOKEN_RELOAD_INTERVAL_MS;
+
+ return now - lastLoadStartedAt >= reloadInterval;
+};