Skip to content

The open alternative to Salesforce, designed for AI.

Billing for self-hosts (#18075)

Mariec1da7be6d782
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 7cb42f737fa..bcdfe78e5ab 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -1597,6 +1597,24 @@ export enum EngineComponentKey {
USE_AS_DRAFT_WORKFLOW_VERSION = 'USE_AS_DRAFT_WORKFLOW_VERSION'
}
+export type EnterpriseLicenseInfoDto = {
+ __typename?: 'EnterpriseLicenseInfoDTO';
+ expiresAt?: Maybe<Scalars['DateTime']>;
+ isValid: Scalars['Boolean'];
+ licensee?: Maybe<Scalars['String']>;
+ subscriptionId?: Maybe<Scalars['String']>;
+};
+
+export type EnterpriseSubscriptionStatusDto = {
+ __typename?: 'EnterpriseSubscriptionStatusDTO';
+ cancelAt?: Maybe<Scalars['DateTime']>;
+ currentPeriodEnd?: Maybe<Scalars['DateTime']>;
+ expiresAt?: Maybe<Scalars['DateTime']>;
+ isCancellationScheduled: Scalars['Boolean'];
+ licensee?: Maybe<Scalars['String']>;
+ status: Scalars['String'];
+};
+
export type EventLogDateRangeInput = {
end?: InputMaybe<Scalars['DateTime']>;
start?: InputMaybe<Scalars['DateTime']>;
@@ -2483,6 +2501,7 @@ export type Mutation = {
initiateOTPProvisioningForAuthenticatedUser: InitiateTwoFactorAuthenticationProvisioning;
installApplication: Scalars['Boolean'];
installMarketplaceApp: Scalars['Boolean'];
+ refreshEnterpriseValidityToken: Scalars['Boolean'];
removeQueryFromEventStream: Scalars['Boolean'];
removeRoleFromAgent: Scalars['Boolean'];
renewApplicationToken: ApplicationTokenPair;
@@ -2497,6 +2516,7 @@ export type Mutation = {
saveImapSmtpCaldavAccount: ImapSmtpCaldavConnectionSuccess;
sendInvitations: SendInvitations;
setAdminAiModelEnabled: Scalars['Boolean'];
+ setEnterpriseKey: EnterpriseLicenseInfoDto;
setMeteredSubscriptionPrice: BillingUpdate;
signIn: AvailableWorkspacesAndAccessTokens;
signUp: AvailableWorkspacesAndAccessTokens;
@@ -3160,6 +3180,11 @@ export type MutationSetAdminAiModelEnabledArgs = {
};
+export type MutationSetEnterpriseKeyArgs = {
+ enterpriseKey: Scalars['String'];
+};
+
+
export type MutationSetMeteredSubscriptionPriceArgs = {
priceId: Scalars['String'];
};
@@ -3975,6 +4000,9 @@ export type Query = {
commandMenuItems: Array<CommandMenuItem>;
currentUser: User;
currentWorkspace: Workspace;
+ enterpriseCheckoutSession?: Maybe<Scalars['String']>;
+ enterprisePortalSession?: Maybe<Scalars['String']>;
+ enterpriseSubscriptionStatus?: Maybe<EnterpriseSubscriptionStatusDto>;
eventLogs: EventLogQueryResult;
field: Field;
fields: FieldConnection;
@@ -4117,6 +4145,16 @@ export type QueryCommandMenuItemArgs = {
};
+export type QueryEnterpriseCheckoutSessionArgs = {
+ billingInterval?: InputMaybe<Scalars['String']>;
+};
+
+
+export type QueryEnterprisePortalSessionArgs = {
+ returnUrlPath?: InputMaybe<Scalars['String']>;
+};
+
+
export type QueryEventLogsArgs = {
input: EventLogQueryInput;
};
@@ -5543,6 +5581,8 @@ export type Workspace = {
fastModel: Scalars['String'];
featureFlags?: Maybe<Array<FeatureFlag>>;
hasValidEnterpriseKey: Scalars['Boolean'];
+ hasValidEnterpriseValidityToken: Scalars['Boolean'];
+ hasValidSignedEnterpriseKey: Scalars['Boolean'];
id: Scalars['UUID'];
inviteHash?: Maybe<Scalars['String']>;
isCustomDomainEnabled: Scalars['Boolean'];
@@ -6823,6 +6863,37 @@ export type GetEmailingDomainsQueryVariables = Exact<{ [key: string]: never; }>;
export type GetEmailingDomainsQuery = { __typename?: 'Query', getEmailingDomains: Array<{ __typename?: 'EmailingDomain', id: string, domain: string, driver: EmailingDomainDriver, status: EmailingDomainStatus, verifiedAt?: string | null, createdAt: string, updatedAt: string, verificationRecords?: Array<{ __typename?: 'VerificationRecord', type: string, key: string, value: string, priority?: number | null }> | null }> };
+export type RefreshEnterpriseValidityTokenMutationVariables = Exact<{ [key: string]: never; }>;
+
+
+export type RefreshEnterpriseValidityTokenMutation = { __typename?: 'Mutation', refreshEnterpriseValidityToken: boolean };
+
+export type SetEnterpriseKeyMutationVariables = Exact<{
+ enterpriseKey: Scalars['String'];
+}>;
+
+
+export type SetEnterpriseKeyMutation = { __typename?: 'Mutation', setEnterpriseKey: { __typename?: 'EnterpriseLicenseInfoDTO', isValid: boolean, licensee?: string | null, expiresAt?: string | null, subscriptionId?: string | null } };
+
+export type EnterpriseCheckoutSessionQueryVariables = Exact<{
+ billingInterval?: InputMaybe<Scalars['String']>;
+}>;
+
+
+export type EnterpriseCheckoutSessionQuery = { __typename?: 'Query', enterpriseCheckoutSession?: string | null };
+
+export type EnterprisePortalSessionQueryVariables = Exact<{
+ returnUrlPath?: InputMaybe<Scalars['String']>;
+}>;
+
+
+export type EnterprisePortalSessionQuery = { __typename?: 'Query', enterprisePortalSession?: string | null };
+
+export type EnterpriseSubscriptionStatusQueryVariables = Exact<{ [key: string]: never; }>;
+
+
+export type EnterpriseSubscriptionStatusQuery = { __typename?: 'Query', enterpriseSubscriptionStatus?: { __typename?: 'EnterpriseSubscriptionStatusDTO', status: string, licensee?: string | null, expiresAt?: string | null, cancelAt?: string | null, currentPeriodEnd?: string | null, isCancellationScheduled: boolean } | null };
+
export type UpdateLabPublicFeatureFlagMutationVariables = Exact<{
input: UpdateLabPublicFeatureFlagInput;
}>;
@@ -6991,7 +7062,7 @@ export type BillingSubscriptionFragmentFragment = { __typename?: 'BillingSubscri
export type CurrentBillingSubscriptionFragmentFragment = { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null };
-export type UserQueryFragmentFragment = { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidEnterpriseKey: boolean, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, fastModel: string, smartModel: string, aiAdditionalInstructions?: string | null, autoEnableNewAiModels: boolean, disabledAiModelIds?: Array<string> | null, enabledAiModelIds?: Array<string> | null, useRecommendedModels: boolean, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
+export type UserQueryFragmentFragment = { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidEnterpriseKey: boolean, hasValidSignedEnterpriseKey: boolean, hasValidEnterpriseValidityToken: boolean, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, fastModel: string, smartModel: string, aiAdditionalInstructions?: string | null, autoEnableNewAiModels: boolean, disabledAiModelIds?: Array<string> | null, enabledAiModelIds?: Array<string> | null, useRecommendedModels: boolean, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } };
export type WorkspaceUrlsFragmentFragment = { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null };
@@ -7010,7 +7081,7 @@ export type DeleteUserWorkspaceMutation = { __typename?: 'Mutation', deleteUserF
export type GetCurrentUserQueryVariables = Exact<{ [key: string]: never; }>;
-export type GetCurrentUserQuery = { __typename?: 'Query', currentUser: { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidEnterpriseKey: boolean, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, fastModel: string, smartModel: string, aiAdditionalInstructions?: string | null, autoEnableNewAiModels: boolean, disabledAiModelIds?: Array<string> | null, enabledAiModelIds?: Array<string> | null, useRecommendedModels: boolean, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
+export type GetCurrentUserQuery = { __typename?: 'Query', currentUser: { __typename?: 'User', id: string, firstName: string, lastName: string, email: string, hasPassword: boolean, canAccessFullAdminPanel: boolean, canImpersonate: boolean, supportUserHash?: string | null, onboardingStatus?: OnboardingStatus | null, userVars?: any | null, workspaceMember?: { __typename?: 'WorkspaceMember', id: string, colorScheme: string, avatarUrl?: string | null, locale?: string | null, userEmail: string, userWorkspaceId?: string | null, timeZone?: string | null, dateFormat?: WorkspaceMemberDateFormatEnum | null, timeFormat?: WorkspaceMemberTimeFormatEnum | null, calendarStartDay?: number | null, numberFormat?: WorkspaceMemberNumberFormatEnum | null, name: { __typename?: 'FullName', firstName: string, lastName: string } } | null, workspaceMembers?: Array<{ __typename?: 'WorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, userWorkspaceId?: string | null, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, deletedWorkspaceMembers?: Array<{ __typename?: 'DeletedWorkspaceMember', id: string, avatarUrl?: string | null, userEmail: string, name: { __typename?: 'FullName', firstName: string, lastName: string } }> | null, currentUserWorkspace?: { __typename?: 'UserWorkspace', id: string, permissionFlags?: Array<PermissionFlagType> | null, objectsPermissions?: Array<{ __typename?: 'ObjectPermission', objectMetadataId: string, canReadObjectRecords?: boolean | null, canUpdateObjectRecords?: boolean | null, canSoftDeleteObjectRecords?: boolean | null, canDestroyObjectRecords?: boolean | null, restrictedFields?: any | null, rowLevelPermissionPredicates?: Array<{ __typename?: 'RowLevelPermissionPredicate', id: string, fieldMetadataId: string, objectMetadataId: string, operand: RowLevelPermissionPredicateOperand, subFieldName?: string | null, workspaceMemberFieldMetadataId?: string | null, workspaceMemberSubFieldName?: string | null, rowLevelPermissionPredicateGroupId?: string | null, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, value?: any | null }> | null, rowLevelPermissionPredicateGroups?: Array<{ __typename?: 'RowLevelPermissionPredicateGroup', id: string, parentRowLevelPermissionPredicateGroupId?: string | null, logicalOperator: RowLevelPermissionPredicateGroupLogicalOperator, positionInRowLevelPermissionPredicateGroup?: number | null, roleId: string, objectMetadataId: string }> | null }> | null, twoFactorAuthenticationMethodSummary?: Array<{ __typename?: 'TwoFactorAuthenticationMethodSummary', twoFactorAuthenticationMethodId: string, status: string, strategy: string }> | null } | null, currentWorkspace?: { __typename?: 'Workspace', id: string, displayName?: string | null, logo?: string | null, inviteHash?: string | null, allowImpersonation: boolean, activationStatus: WorkspaceActivationStatus, isPublicInviteLinkEnabled: boolean, isGoogleAuthEnabled: boolean, isMicrosoftAuthEnabled: boolean, isPasswordAuthEnabled: boolean, isGoogleAuthBypassEnabled: boolean, isMicrosoftAuthBypassEnabled: boolean, isPasswordAuthBypassEnabled: boolean, subdomain: string, customDomain?: string | null, hasValidEnterpriseKey: boolean, hasValidSignedEnterpriseKey: boolean, hasValidEnterpriseValidityToken: boolean, isCustomDomainEnabled: boolean, metadataVersion: number, workspaceMembersCount?: number | null, fastModel: string, smartModel: string, aiAdditionalInstructions?: string | null, autoEnableNewAiModels: boolean, disabledAiModelIds?: Array<string> | null, enabledAiModelIds?: Array<string> | null, useRecommendedModels: boolean, isTwoFactorAuthenticationEnforced: boolean, trashRetentionDays: number, eventLogRetentionDays: number, editableProfileFields?: Array<string> | null, workspaceCustomApplication?: { __typename?: 'Application', id: string } | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, featureFlags?: Array<{ __typename?: 'FeatureFlag', key: FeatureFlagKey, value: boolean }> | null, currentBillingSubscription?: { __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, interval?: SubscriptionInterval | null, metadata: any, currentPeriodEnd?: string | null, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }>, billingSubscriptionItems?: Array<{ __typename?: 'BillingSubscriptionItem', id: string, hasReachedCurrentPeriodCap: boolean, quantity?: number | null, stripePriceId: string, billingProduct: { __typename?: 'BillingLicensedProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } | { __typename?: 'BillingMeteredProduct', name: string, description: string, images?: Array<string> | null, metadata: { __typename?: 'BillingProductMetadata', productKey: BillingProductKey, planKey: BillingPlanKey, priceUsageBased: BillingUsageType } } }> | null } | null, billingSubscriptions: Array<{ __typename?: 'BillingSubscription', id: string, status: SubscriptionStatus, metadata: any, phases: Array<{ __typename?: 'BillingSubscriptionSchedulePhase', start_date: number, end_date: number, items: Array<{ __typename?: 'BillingSubscriptionSchedulePhaseItem', price: string, quantity?: number | null }> }> }>, billingEntitlements: Array<{ __typename?: 'BillingEntitlement', key: BillingEntitlementKey, value: boolean }>, defaultRole?: { __typename?: 'Role', id: string, label: string, description?: string | null, icon?: string | null, canUpdateAllSettings: boolean, canAccessAllTools: boolean, isEditable: boolean, canReadAllObjectRecords: boolean, canUpdateAllObjectRecords: boolean, canSoftDeleteAllObjectRecords: boolean, canDestroyAllObjectRecords: boolean, canBeAssignedToUsers: boolean, canBeAssignedToAgents: boolean, canBeAssignedToApiKeys: boolean } | null } | null, availableWorkspaces: { __typename?: 'AvailableWorkspaces', availableWorkspacesForSignIn: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }>, availableWorkspacesForSignUp: Array<{ __typename?: 'AvailableWorkspace', id: string, displayName?: string | null, loginToken?: string | null, inviteHash?: string | null, personalInviteToken?: string | null, logo?: string | null, workspaceUrls: { __typename?: 'WorkspaceUrls', subdomainUrl: string, customUrl?: string | null }, sso: Array<{ __typename?: 'SSOConnection', type: IdentityProviderType, id: string, issuer: string, name: string, status: SsoIdentityProviderStatus }> }> } } };
export type ViewFieldFragmentFragment = { __typename?: 'CoreViewField', id: string, fieldMetadataId: string, viewId: string, isVisible: boolean, position: number, size: number, aggregateOperation?: AggregateOperations | null, createdAt: string, updatedAt: string, deletedAt?: string | null };
@@ -8329,6 +8400,8 @@ export const UserQueryFragmentFragmentDoc = gql`
subdomain
customDomain
hasValidEnterpriseKey
+ hasValidSignedEnterpriseKey
+ hasValidEnterpriseValidityToken
workspaceCustomApplication {
id
}
@@ -14525,6 +14598,177 @@ export function useGetEmailingDomainsLazyQuery(baseOptions?: Apollo.LazyQueryHoo
export type GetEmailingDomainsQueryHookResult = ReturnType<typeof useGetEmailingDomainsQuery>;
export type GetEmailingDomainsLazyQueryHookResult = ReturnType<typeof useGetEmailingDomainsLazyQuery>;
export type GetEmailingDomainsQueryResult = Apollo.QueryResult<GetEmailingDomainsQuery, GetEmailingDomainsQueryVariables>;
+export const RefreshEnterpriseValidityTokenDocument = gql`
+ mutation RefreshEnterpriseValidityToken {
+ refreshEnterpriseValidityToken
+}
+ `;
+export type RefreshEnterpriseValidityTokenMutationFn = Apollo.MutationFunction<RefreshEnterpriseValidityTokenMutation, RefreshEnterpriseValidityTokenMutationVariables>;
+
+/**
+ * __useRefreshEnterpriseValidityTokenMutation__
+ *
+ * To run a mutation, you first call `useRefreshEnterpriseValidityTokenMutation` within a React component and pass it any options that fit your needs.
+ * When your component renders, `useRefreshEnterpriseValidityTokenMutation` returns a tuple that includes:
+ * - A mutate function that you can call at any time to execute the mutation
+ * - An object with fields that represent the current status of the mutation's execution
+ *
+ * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
+ *
+ * @example
+ * const [refreshEnterpriseValidityTokenMutation, { data, loading, error }] = useRefreshEnterpriseValidityTokenMutation({
+ * variables: {
+ * },
+ * });
+ */
+export function useRefreshEnterpriseValidityTokenMutation(baseOptions?: Apollo.MutationHookOptions<RefreshEnterpriseValidityTokenMutation, RefreshEnterpriseValidityTokenMutationVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useMutation<RefreshEnterpriseValidityTokenMutation, RefreshEnterpriseValidityTokenMutationVariables>(RefreshEnterpriseValidityTokenDocument, options);
+ }
+export type RefreshEnterpriseValidityTokenMutationHookResult = ReturnType<typeof useRefreshEnterpriseValidityTokenMutation>;
+export type RefreshEnterpriseValidityTokenMutationResult = Apollo.MutationResult<RefreshEnterpriseValidityTokenMutation>;
+export type RefreshEnterpriseValidityTokenMutationOptions = Apollo.BaseMutationOptions<RefreshEnterpriseValidityTokenMutation, RefreshEnterpriseValidityTokenMutationVariables>;
+export const SetEnterpriseKeyDocument = gql`
+ mutation SetEnterpriseKey($enterpriseKey: String!) {
+ setEnterpriseKey(enterpriseKey: $enterpriseKey) {
+ isValid
+ licensee
+ expiresAt
+ subscriptionId
+ }
+}
+ `;
+export type SetEnterpriseKeyMutationFn = Apollo.MutationFunction<SetEnterpriseKeyMutation, SetEnterpriseKeyMutationVariables>;
+
+/**
+ * __useSetEnterpriseKeyMutation__
+ *
+ * To run a mutation, you first call `useSetEnterpriseKeyMutation` within a React component and pass it any options that fit your needs.
+ * When your component renders, `useSetEnterpriseKeyMutation` returns a tuple that includes:
+ * - A mutate function that you can call at any time to execute the mutation
+ * - An object with fields that represent the current status of the mutation's execution
+ *
+ * @param baseOptions options that will be passed into the mutation, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options-2;
+ *
+ * @example
+ * const [setEnterpriseKeyMutation, { data, loading, error }] = useSetEnterpriseKeyMutation({
+ * variables: {
+ * enterpriseKey: // value for 'enterpriseKey'
+ * },
+ * });
+ */
+export function useSetEnterpriseKeyMutation(baseOptions?: Apollo.MutationHookOptions<SetEnterpriseKeyMutation, SetEnterpriseKeyMutationVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useMutation<SetEnterpriseKeyMutation, SetEnterpriseKeyMutationVariables>(SetEnterpriseKeyDocument, options);
+ }
+export type SetEnterpriseKeyMutationHookResult = ReturnType<typeof useSetEnterpriseKeyMutation>;
+export type SetEnterpriseKeyMutationResult = Apollo.MutationResult<SetEnterpriseKeyMutation>;
+export type SetEnterpriseKeyMutationOptions = Apollo.BaseMutationOptions<SetEnterpriseKeyMutation, SetEnterpriseKeyMutationVariables>;
+export const EnterpriseCheckoutSessionDocument = gql`
+ query EnterpriseCheckoutSession($billingInterval: String) {
+ enterpriseCheckoutSession(billingInterval: $billingInterval)
+}
+ `;
+
+/**
+ * __useEnterpriseCheckoutSessionQuery__
+ *
+ * To run a query within a React component, call `useEnterpriseCheckoutSessionQuery` and pass it any options that fit your needs.
+ * When your component renders, `useEnterpriseCheckoutSessionQuery` returns an object from Apollo Client that contains loading, error, and data properties
+ * you can use to render your UI.
+ *
+ * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
+ *
+ * @example
+ * const { data, loading, error } = useEnterpriseCheckoutSessionQuery({
+ * variables: {
+ * billingInterval: // value for 'billingInterval'
+ * },
+ * });
+ */
+export function useEnterpriseCheckoutSessionQuery(baseOptions?: Apollo.QueryHookOptions<EnterpriseCheckoutSessionQuery, EnterpriseCheckoutSessionQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useQuery<EnterpriseCheckoutSessionQuery, EnterpriseCheckoutSessionQueryVariables>(EnterpriseCheckoutSessionDocument, options);
+ }
+export function useEnterpriseCheckoutSessionLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<EnterpriseCheckoutSessionQuery, EnterpriseCheckoutSessionQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useLazyQuery<EnterpriseCheckoutSessionQuery, EnterpriseCheckoutSessionQueryVariables>(EnterpriseCheckoutSessionDocument, options);
+ }
+export type EnterpriseCheckoutSessionQueryHookResult = ReturnType<typeof useEnterpriseCheckoutSessionQuery>;
+export type EnterpriseCheckoutSessionLazyQueryHookResult = ReturnType<typeof useEnterpriseCheckoutSessionLazyQuery>;
+export type EnterpriseCheckoutSessionQueryResult = Apollo.QueryResult<EnterpriseCheckoutSessionQuery, EnterpriseCheckoutSessionQueryVariables>;
+export const EnterprisePortalSessionDocument = gql`
+ query EnterprisePortalSession($returnUrlPath: String) {
+ enterprisePortalSession(returnUrlPath: $returnUrlPath)
+}
+ `;
+
+/**
+ * __useEnterprisePortalSessionQuery__
+ *
+ * To run a query within a React component, call `useEnterprisePortalSessionQuery` and pass it any options that fit your needs.
+ * When your component renders, `useEnterprisePortalSessionQuery` returns an object from Apollo Client that contains loading, error, and data properties
+ * you can use to render your UI.
+ *
+ * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
+ *
+ * @example
+ * const { data, loading, error } = useEnterprisePortalSessionQuery({
+ * variables: {
+ * returnUrlPath: // value for 'returnUrlPath'
+ * },
+ * });
+ */
+export function useEnterprisePortalSessionQuery(baseOptions?: Apollo.QueryHookOptions<EnterprisePortalSessionQuery, EnterprisePortalSessionQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useQuery<EnterprisePortalSessionQuery, EnterprisePortalSessionQueryVariables>(EnterprisePortalSessionDocument, options);
+ }
+export function useEnterprisePortalSessionLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<EnterprisePortalSessionQuery, EnterprisePortalSessionQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useLazyQuery<EnterprisePortalSessionQuery, EnterprisePortalSessionQueryVariables>(EnterprisePortalSessionDocument, options);
+ }
+export type EnterprisePortalSessionQueryHookResult = ReturnType<typeof useEnterprisePortalSessionQuery>;
+export type EnterprisePortalSessionLazyQueryHookResult = ReturnType<typeof useEnterprisePortalSessionLazyQuery>;
+export type EnterprisePortalSessionQueryResult = Apollo.QueryResult<EnterprisePortalSessionQuery, EnterprisePortalSessionQueryVariables>;
+export const EnterpriseSubscriptionStatusDocument = gql`
+ query EnterpriseSubscriptionStatus {
+ enterpriseSubscriptionStatus {
+ status
+ licensee
+ expiresAt
+ cancelAt
+ currentPeriodEnd
+ isCancellationScheduled
+ }
+}
+ `;
+
+/**
+ * __useEnterpriseSubscriptionStatusQuery__
+ *
+ * To run a query within a React component, call `useEnterpriseSubscriptionStatusQuery` and pass it any options that fit your needs.
+ * When your component renders, `useEnterpriseSubscriptionStatusQuery` returns an object from Apollo Client that contains loading, error, and data properties
+ * you can use to render your UI.
+ *
+ * @param baseOptions options that will be passed into the query, supported options are listed on: https://www.apollographql.com/docs/react/api/react-hooks/#options;
+ *
+ * @example
+ * const { data, loading, error } = useEnterpriseSubscriptionStatusQuery({
+ * variables: {
+ * },
+ * });
+ */
+export function useEnterpriseSubscriptionStatusQuery(baseOptions?: Apollo.QueryHookOptions<EnterpriseSubscriptionStatusQuery, EnterpriseSubscriptionStatusQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useQuery<EnterpriseSubscriptionStatusQuery, EnterpriseSubscriptionStatusQueryVariables>(EnterpriseSubscriptionStatusDocument, options);
+ }
+export function useEnterpriseSubscriptionStatusLazyQuery(baseOptions?: Apollo.LazyQueryHookOptions<EnterpriseSubscriptionStatusQuery, EnterpriseSubscriptionStatusQueryVariables>) {
+ const options = {...defaultOptions, ...baseOptions}
+ return Apollo.useLazyQuery<EnterpriseSubscriptionStatusQuery, EnterpriseSubscriptionStatusQueryVariables>(EnterpriseSubscriptionStatusDocument, options);
+ }
+export type EnterpriseSubscriptionStatusQueryHookResult = ReturnType<typeof useEnterpriseSubscriptionStatusQuery>;
+export type EnterpriseSubscriptionStatusLazyQueryHookResult = ReturnType<typeof useEnterpriseSubscriptionStatusLazyQuery>;
+export type EnterpriseSubscriptionStatusQueryResult = Apollo.QueryResult<EnterpriseSubscriptionStatusQuery, EnterpriseSubscriptionStatusQueryVariables>;
export const UpdateLabPublicFeatureFlagDocument = gql`
mutation UpdateLabPublicFeatureFlag($input: UpdateLabPublicFeatureFlagInput!) {
updateLabPublicFeatureFlag(input: $input) {
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.ts
index 2ab887ee2cd..4ac58703266 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
@@ -58,6 +58,9 @@ const mockWorkspace = {
isPasswordAuthBypassEnabled: false,
isMicrosoftAuthBypassEnabled: false,
hasValidEnterpriseKey: false,
+ hasActivatedAndValidEnterpriseKey: false,
+ hasValidSignedEnterpriseKey: false,
+ hasValidEnterpriseValidityToken: false,
subdomain: 'test',
customDomain: 'test.com',
workspaceUrls: {
diff --git a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
index 8a940c97cfa..0f33609edb0 100644
--- a/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
+++ b/packages/twenty-front/src/modules/app/components/SettingsRoutes.tsx
@@ -1,10 +1,11 @@
import { lazy, Suspense } from 'react';
-import { Route, Routes } from 'react-router-dom';
+import { Navigate, Route, Routes } from 'react-router-dom';
import { SettingsProtectedRouteWrapper } from '@/settings/components/SettingsProtectedRouteWrapper';
import { SettingsSkeletonLoader } from '@/settings/components/SettingsSkeletonLoader';
import { SettingPublicDomain } from '@/settings/domains/components/SettingPublicDomain';
import { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath } from 'twenty-shared/utils';
import {
FeatureFlagKey,
PermissionFlagType,
@@ -662,6 +663,15 @@ export const SettingsRoutes = ({ isAdminPageEnabled }: SettingsRoutesProps) => (
{isAdminPageEnabled && (
<>
<Route path={SettingsPath.AdminPanel} element={<SettingsAdmin />} />
+ <Route
+ path={SettingsPath.Enterprise}
+ element={
+ <Navigate
+ to={getSettingsPath(SettingsPath.AdminPanelEnterprise)}
+ replace
+ />
+ }
+ />
<Route
path={SettingsPath.AdminPanelIndicatorHealthStatus}
element={<SettingsAdminIndicatorHealthStatus />}
diff --git a/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts b/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
index 9f3067bba89..9b70764f3ed 100644
--- a/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
+++ b/packages/twenty-front/src/modules/auth/states/currentWorkspaceState.ts
@@ -27,6 +27,8 @@ export type CurrentWorkspace = Pick<
| 'isPasswordAuthBypassEnabled'
| 'isCustomDomainEnabled'
| 'hasValidEnterpriseKey'
+ | 'hasValidSignedEnterpriseKey'
+ | 'hasValidEnterpriseValidityToken'
| 'subdomain'
| 'customDomain'
| 'workspaceUrls'
diff --git a/packages/twenty-front/src/modules/information-banner/components/InformationBanner.tsx b/packages/twenty-front/src/modules/information-banner/components/InformationBanner.tsx
index 57dce27f327..d4ced55118d 100644
--- a/packages/twenty-front/src/modules/information-banner/components/InformationBanner.tsx
+++ b/packages/twenty-front/src/modules/information-banner/components/InformationBanner.tsx
@@ -15,7 +15,6 @@ import { themeCssVariables } from 'twenty-ui/theme-constants';
const StyledText = styled.div`
overflow: hidden;
text-overflow: ellipsis;
- white-space: nowrap;
`;
const StyledCloseButtonContainer = styled.div`
diff --git a/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx b/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
index aaa5492fef8..265752ce51d 100644
--- a/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
+++ b/packages/twenty-front/src/modules/information-banner/components/InformationBannerWrapper.tsx
@@ -6,6 +6,7 @@ import { InformationBannerBillingSubscriptionPaused } from '@/information-banner
import { InformationBannerEndTrialPeriod } from '@/information-banner/components/billing/InformationBannerEndTrialPeriod';
import { InformationBannerFailPaymentInfo } from '@/information-banner/components/billing/InformationBannerFailPaymentInfo';
import { InformationBannerNoBillingSubscription } from '@/information-banner/components/billing/InformationBannerNoBillingSubscription';
+import { InformationBannerLegacyEnterpriseKey } from '@/information-banner/components/enterprise/InformationBannerLegacyEnterpriseKey';
import { InformationBannerReconnectAccountEmailAliases } from '@/information-banner/components/reconnect-account/InformationBannerReconnectAccountEmailAliases';
import { InformationBannerReconnectAccountInsufficientPermissions } from '@/information-banner/components/reconnect-account/InformationBannerReconnectAccountInsufficientPermissions';
import { usePermissionFlagMap } from '@/settings/roles/hooks/usePermissionFlagMap';
@@ -52,6 +53,7 @@ export const InformationBannerWrapper = () => {
return (
<StyledInformationBannerWrapper>
+ <InformationBannerLegacyEnterpriseKey />
{isAccountSyncEnabled && (
<InformationBannerReconnectAccountInsufficientPermissions />
)}
diff --git a/packages/twenty-front/src/modules/information-banner/components/enterprise/InformationBannerLegacyEnterpriseKey.tsx b/packages/twenty-front/src/modules/information-banner/components/enterprise/InformationBannerLegacyEnterpriseKey.tsx
new file mode 100644
index 00000000000..f2f2d81cc4c
--- /dev/null
+++ b/packages/twenty-front/src/modules/information-banner/components/enterprise/InformationBannerLegacyEnterpriseKey.tsx
@@ -0,0 +1,45 @@
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { InformationBanner } from '@/information-banner/components/InformationBanner';
+import { informationBannerIsOpenComponentState } from '@/information-banner/states/informationBannerIsOpenComponentState';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useSetAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useSetAtomComponentState';
+import { useLingui } from '@lingui/react/macro';
+import { useNavigate } from 'react-router-dom';
+import { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath } from 'twenty-shared/utils';
+import { IconKey } from 'twenty-ui/display';
+
+const COMPONENT_INSTANCE_ID = 'information-banner-legacy-enterprise-key';
+
+export const InformationBannerLegacyEnterpriseKey = () => {
+ const { t } = useLingui();
+ const navigate = useNavigate();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
+
+ const setInformationBannerIsOpen = useSetAtomComponentState(
+ informationBannerIsOpenComponentState,
+ COMPONENT_INSTANCE_ID,
+ );
+
+ const hasLegacyKey =
+ currentWorkspace?.hasValidEnterpriseKey === true &&
+ currentWorkspace?.hasValidSignedEnterpriseKey !== true;
+
+ if (!hasLegacyKey) {
+ return null;
+ }
+
+ return (
+ <InformationBanner
+ componentInstanceId={COMPONENT_INSTANCE_ID}
+ variant="default"
+ message={t`Your enterprise key format is deprecated. Please activate a new key to keep enterprise features.`}
+ buttonTitle={t`Activate`}
+ buttonIcon={IconKey}
+ buttonOnClick={() =>
+ navigate(getSettingsPath(SettingsPath.AdminPanelEnterprise))
+ }
+ onClose={() => setInformationBannerIsOpen(false)}
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/object-metadata/hooks/__mocks__/useFieldMetadataItem.ts b/packages/twenty-front/src/modules/object-metadata/hooks/__mocks__/useFieldMetadataItem.ts
index aa1701e8e87..5dd088d6305 100644
--- a/packages/twenty-front/src/modules/object-metadata/hooks/__mocks__/useFieldMetadataItem.ts
+++ b/packages/twenty-front/src/modules/object-metadata/hooks/__mocks__/useFieldMetadataItem.ts
@@ -181,6 +181,8 @@ export const responseData = {
activationStatus: 'active',
isPublicInviteLinkEnabled: false,
hasValidEnterpriseKey: false,
+ hasValidSignedEnterpriseKey: false,
+ hasValidEnterpriseValidityToken: false,
isGoogleAuthEnabled: true,
isMicrosoftAuthEnabled: false,
isPasswordAuthEnabled: true,
diff --git a/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromObjectMetadata.test.ts b/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromObjectMetadata.test.ts
index 95fa2f72730..a9f28316bb6 100644
--- a/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromObjectMetadata.test.ts
+++ b/packages/twenty-front/src/modules/object-metadata/hooks/__tests__/useColumnDefinitionsFromObjectMetadata.test.ts
@@ -33,6 +33,8 @@ describe('useColumnDefinitionsFromObjectMetadata', () => {
subdomain: 'test',
activationStatus: WorkspaceActivationStatus.ACTIVE,
hasValidEnterpriseKey: false,
+ hasValidSignedEnterpriseKey: false,
+ hasValidEnterpriseValidityToken: false,
metadataVersion: 1,
isPublicInviteLinkEnabled: false,
isGoogleAuthEnabled: true,
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminContent.tsx
index 7ca51933284..b4ae97cc4e0 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminContent.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminContent.tsx
@@ -1,23 +1,27 @@
import { currentUserState } from '@/auth/states/currentUserState';
+import { billingState } from '@/client-config/states/billingState';
import { SettingsAdminTabContent } from '@/settings/admin-panel/components/SettingsAdminTabContent';
import { SETTINGS_ADMIN_TABS } from '@/settings/admin-panel/constants/SettingsAdminTabs';
import { SETTINGS_ADMIN_TABS_ID } from '@/settings/admin-panel/constants/SettingsAdminTabsId';
import { TabList } from '@/ui/layout/tab-list/components/TabList';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
import { t } from '@lingui/core/macro';
import {
IconApps,
IconHeart,
+ IconKey,
IconSettings2,
IconSparkles,
IconVariable,
} from 'twenty-ui/display';
-import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
export const SettingsAdminContent = () => {
const currentUser = useAtomStateValue(currentUserState);
+ const billing = useAtomStateValue(billingState);
const canAccessFullAdminPanel = currentUser?.canAccessFullAdminPanel;
const canImpersonate = currentUser?.canImpersonate;
+ const isBillingEnabled = billing?.isBillingEnabled;
const tabs = [
{
id: SETTINGS_ADMIN_TABS.GENERAL,
@@ -49,6 +53,16 @@ export const SettingsAdminContent = () => {
Icon: IconHeart,
disabled: !canAccessFullAdminPanel,
},
+ ...(!isBillingEnabled
+ ? [
+ {
+ id: SETTINGS_ADMIN_TABS.ENTERPRISE,
+ title: t`Enterprise`,
+ Icon: IconKey,
+ disabled: !canAccessFullAdminPanel && !canImpersonate,
+ },
+ ]
+ : []),
];
return (
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTabContent.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTabContent.tsx
index 2063680883d..884d479c3fb 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTabContent.tsx
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTabContent.tsx
@@ -5,9 +5,16 @@ import { SettingsAdminConfigVariables } from '@/settings/admin-panel/config-vari
import { SETTINGS_ADMIN_TABS } from '@/settings/admin-panel/constants/SettingsAdminTabs';
import { SETTINGS_ADMIN_TABS_ID } from '@/settings/admin-panel/constants/SettingsAdminTabsId';
import { SettingsAdminHealthStatus } from '@/settings/admin-panel/health-status/components/SettingsAdminHealthStatus';
+import { SettingsSkeletonLoader } from '@/settings/components/SettingsSkeletonLoader';
import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';
import { useAtomComponentStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomComponentStateValue';
+import { lazy, Suspense } from 'react';
+const SettingsEnterprise = lazy(() =>
+ import('~/pages/settings/enterprise/SettingsEnterprise').then((module) => ({
+ default: module.SettingsEnterprise,
+ })),
+);
export const SettingsAdminTabContent = () => {
const activeTabId = useAtomComponentStateValue(
activeTabIdComponentState,
@@ -25,6 +32,12 @@ export const SettingsAdminTabContent = () => {
return <SettingsAdminConfigVariables />;
case SETTINGS_ADMIN_TABS.HEALTH_STATUS:
return <SettingsAdminHealthStatus />;
+ case SETTINGS_ADMIN_TABS.ENTERPRISE:
+ return (
+ <Suspense fallback={<SettingsSkeletonLoader />}>
+ <SettingsEnterprise isAdminPanelTab />
+ </Suspense>
+ );
default:
return null;
}
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminTabs.ts b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminTabs.ts
index 3cf4c9d64a4..d8e5d2b60f0 100644
--- a/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminTabs.ts
+++ b/packages/twenty-front/src/modules/settings/admin-panel/constants/SettingsAdminTabs.ts
@@ -4,4 +4,5 @@ export const SETTINGS_ADMIN_TABS = {
AI: 'ai',
CONFIG_VARIABLES: 'config-variables',
HEALTH_STATUS: 'health-status',
+ ENTERPRISE: 'enterprise',
};
diff --git a/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
new file mode 100644
index 00000000000..b0ec5ec5836
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/components/EnterprisePlanModal.tsx
@@ -0,0 +1,178 @@
+import { SubTitle } from '@/auth/components/SubTitle';
+import { Title } from '@/auth/components/Title';
+import { SubscriptionBenefit } from '@/billing/components/SubscriptionBenefit';
+import { ENTERPRISE_CHECKOUT_SESSION } from '@/settings/enterprise/graphql/queries/enterpriseCheckoutSession';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { ModalStatefulWrapper } from '@/ui/layout/modal/components/ModalStatefulWrapper';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { useLazyQuery } from '@apollo/client';
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { useState } from 'react';
+import { Loader } from 'twenty-ui/feedback';
+import { CardPicker, MainButton } from 'twenty-ui/input';
+import { ModalContent } from 'twenty-ui/layout';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+export const ENTERPRISE_PLAN_MODAL_ID = 'enterprise-plan-modal';
+
+type BillingInterval = 'monthly' | 'yearly';
+
+const MONTHLY_PRICE = 25;
+const YEARLY_PRICE = 19;
+
+const StyledSubscriptionContainer = styled.div`
+ background-color: ${themeCssVariables.background.secondary};
+ border: 1px solid ${themeCssVariables.border.color.medium};
+ border-radius: ${themeCssVariables.border.radius.md};
+ display: flex;
+ flex-direction: column;
+ margin: ${themeCssVariables.spacing[8]} 0 ${themeCssVariables.spacing[2]};
+ width: 100%;
+`;
+
+const StyledPriceContainer = styled.div`
+ align-items: center;
+ border-bottom: 1px solid ${themeCssVariables.border.color.light};
+ display: flex;
+ flex-direction: column;
+ margin: ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[3]} 0
+ ${themeCssVariables.spacing[4]};
+ padding-bottom: ${themeCssVariables.spacing[3]};
+`;
+
+const StyledPrice = styled.span`
+ color: ${themeCssVariables.font.color.primary};
+ font-size: ${themeCssVariables.font.size.xxl};
+ font-weight: ${themeCssVariables.font.weight.semiBold};
+ margin-bottom: ${themeCssVariables.spacing[1]};
+`;
+
+const StyledPriceUnit = styled.span`
+ color: ${themeCssVariables.font.color.light};
+ font-size: ${themeCssVariables.font.size.md};
+ font-weight: ${themeCssVariables.font.weight.medium};
+`;
+
+const StyledBenefitsContainer = styled.div`
+ box-sizing: border-box;
+ display: flex;
+ flex-direction: column;
+ gap: 16px;
+ padding: ${themeCssVariables.spacing[4]} ${themeCssVariables.spacing[3]};
+ width: 100%;
+`;
+
+const StyledIntervalContainer = styled.div`
+ display: flex;
+ flex-direction: row;
+ gap: ${themeCssVariables.spacing[2]};
+ margin-bottom: ${themeCssVariables.spacing[8]};
+ width: 100%;
+`;
+
+const StyledIntervalTitle = styled.div`
+ color: ${themeCssVariables.font.color.secondary};
+ font-size: ${themeCssVariables.font.size.md};
+`;
+
+export const EnterprisePlanModal = () => {
+ const { t } = useLingui();
+ const { closeModal } = useModal();
+ const { enqueueErrorSnackBar } = useSnackBar();
+ const [selectedInterval, setSelectedInterval] =
+ useState<BillingInterval>('monthly');
+ const [isLoading, setIsLoading] = useState(false);
+
+ const [fetchCheckoutSession] = useLazyQuery(ENTERPRISE_CHECKOUT_SESSION);
+
+ const benefits = [
+ t`SSO (SAML / OIDC)`,
+ t`Row-level security`,
+ t`Audit logs`,
+ t`Custom objects`,
+ t`API & Webhooks`,
+ ];
+
+ const price = selectedInterval === 'monthly' ? MONTHLY_PRICE : YEARLY_PRICE;
+ const priceUnit =
+ selectedInterval === 'monthly'
+ ? t`seat / month`
+ : t`seat / month - billed yearly`;
+
+ const handleContinue = async () => {
+ setIsLoading(true);
+
+ try {
+ const { data } = await fetchCheckoutSession({
+ variables: { billingInterval: selectedInterval },
+ });
+
+ const checkoutUrl = data?.enterpriseCheckoutSession;
+
+ if (checkoutUrl !== null && checkoutUrl !== undefined) {
+ window.open(checkoutUrl, '_blank', 'noopener');
+ closeModal(ENTERPRISE_PLAN_MODAL_ID);
+ } else {
+ enqueueErrorSnackBar({
+ message: t`Could not open Stripe. Please contact support.`,
+ });
+ }
+ } catch {
+ enqueueErrorSnackBar({
+ message: t`Error opening Stripe`,
+ });
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ return (
+ <ModalStatefulWrapper
+ modalInstanceId={ENTERPRISE_PLAN_MODAL_ID}
+ size="small"
+ padding="none"
+ isClosable
+ >
+ <ModalContent isVerticallyCentered>
+ <Title noMarginTop>{t`Get Enterprise`}</Title>
+ <SubTitle>{t`Enjoy a 30-day free trial`}</SubTitle>
+
+ <StyledSubscriptionContainer>
+ <StyledPriceContainer>
+ <StyledPrice>{`$${price}`}</StyledPrice>
+ <StyledPriceUnit>{priceUnit}</StyledPriceUnit>
+ </StyledPriceContainer>
+ <StyledBenefitsContainer>
+ {benefits.map((benefit) => (
+ <SubscriptionBenefit key={benefit}>{benefit}</SubscriptionBenefit>
+ ))}
+ </StyledBenefitsContainer>
+ </StyledSubscriptionContainer>
+
+ <StyledIntervalContainer>
+ <CardPicker
+ checked={selectedInterval === 'monthly'}
+ handleChange={() => setSelectedInterval('monthly')}
+ >
+ <StyledIntervalTitle>{t`Monthly subscription`}</StyledIntervalTitle>
+ </CardPicker>
+ <CardPicker
+ checked={selectedInterval === 'yearly'}
+ handleChange={() => setSelectedInterval('yearly')}
+ >
+ <StyledIntervalTitle>{t`Yearly subscription`}</StyledIntervalTitle>
+ </CardPicker>
+ </StyledIntervalContainer>
+
+ <MainButton
+ title={t`Continue`}
+ onClick={handleContinue}
+ width={200}
+ Icon={() => isLoading && <Loader />}
+ disabled={isLoading}
+ />
+ </ModalContent>
+ </ModalStatefulWrapper>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/refreshEnterpriseValidityToken.ts b/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/refreshEnterpriseValidityToken.ts
new file mode 100644
index 00000000000..41c05fa7690
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/refreshEnterpriseValidityToken.ts
@@ -0,0 +1,7 @@
+import { gql } from '@apollo/client';
+
+export const REFRESH_ENTERPRISE_VALIDITY_TOKEN = gql`
+ mutation RefreshEnterpriseValidityToken {
+ refreshEnterpriseValidityToken
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/setEnterpriseKey.ts b/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/setEnterpriseKey.ts
new file mode 100644
index 00000000000..4603befb694
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/graphql/mutations/setEnterpriseKey.ts
@@ -0,0 +1,12 @@
+import { gql } from '@apollo/client';
+
+export const SET_ENTERPRISE_KEY = gql`
+ mutation SetEnterpriseKey($enterpriseKey: String!) {
+ setEnterpriseKey(enterpriseKey: $enterpriseKey) {
+ isValid
+ licensee
+ expiresAt
+ subscriptionId
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseCheckoutSession.ts b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseCheckoutSession.ts
new file mode 100644
index 00000000000..9eee1314932
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseCheckoutSession.ts
@@ -0,0 +1,7 @@
+import { gql } from '@apollo/client';
+
+export const ENTERPRISE_CHECKOUT_SESSION = gql`
+ query EnterpriseCheckoutSession($billingInterval: String) {
+ enterpriseCheckoutSession(billingInterval: $billingInterval)
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterprisePortalSession.ts b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterprisePortalSession.ts
new file mode 100644
index 00000000000..51180557a9b
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterprisePortalSession.ts
@@ -0,0 +1,7 @@
+import { gql } from '@apollo/client';
+
+export const ENTERPRISE_PORTAL_SESSION = gql`
+ query EnterprisePortalSession($returnUrlPath: String) {
+ enterprisePortalSession(returnUrlPath: $returnUrlPath)
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseSubscriptionStatus.ts b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseSubscriptionStatus.ts
new file mode 100644
index 00000000000..709bed3d153
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/enterprise/graphql/queries/enterpriseSubscriptionStatus.ts
@@ -0,0 +1,14 @@
+import { gql } from '@apollo/client';
+
+export const ENTERPRISE_SUBSCRIPTION_STATUS = gql`
+ query EnterpriseSubscriptionStatus {
+ enterpriseSubscriptionStatus {
+ status
+ licensee
+ expiresAt
+ cancelAt
+ currentPeriodEnd
+ isCancellationScheduled
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/record-level-permissions/components/SettingsRolePermissionsObjectLevelRecordLevelSection.tsx b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/record-level-permissions/components/SettingsRolePermissionsObjectLevelRecordLevelSection.tsx
index 258dacaf888..b555ca6d41b 100644
--- a/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/record-level-permissions/components/SettingsRolePermissionsObjectLevelRecordLevelSection.tsx
+++ b/packages/twenty-front/src/modules/settings/roles/role-permissions/object-level-permissions/record-level-permissions/components/SettingsRolePermissionsObjectLevelRecordLevelSection.tsx
@@ -17,7 +17,6 @@ import { useNavigateSettings } from '~/hooks/useNavigateSettings';
const StyledContent = styled.div`
padding-bottom: ${themeCssVariables.spacing[2]};
- padding-top: ${themeCssVariables.spacing[4]};
`;
const StyledCardContainer = styled.div`
@@ -70,18 +69,22 @@ export const SettingsRolePermissionsObjectLevelRecordLevelSection = ({
<SettingsOptionCardContentButton
Icon={IconLock}
title={t`Upgrade to access`}
- description={t`This feature is part of the Organization Plan`}
+ description={t`This feature is part of the Enterprise Plan`}
Button={
- isBillingEnabled && (
- <Button
- title={t`Upgrade`}
- variant="primary"
- accent="blue"
- size="small"
- Icon={IconArrowUp}
- onClick={() => navigateSettings(SettingsPath.Billing)}
- />
- )
+ <Button
+ title={t`Upgrade`}
+ variant="primary"
+ accent="blue"
+ size="small"
+ Icon={IconArrowUp}
+ onClick={() =>
+ navigateSettings(
+ isBillingEnabled
+ ? SettingsPath.Billing
+ : SettingsPath.AdminPanelEnterprise,
+ )
+ }
+ />
}
/>
</Card>
diff --git a/packages/twenty-front/src/modules/ui/layout/tab-list/components/TabList.tsx b/packages/twenty-front/src/modules/ui/layout/tab-list/components/TabList.tsx
index 1812ea6ab25..531f5089496 100644
--- a/packages/twenty-front/src/modules/ui/layout/tab-list/components/TabList.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/tab-list/components/TabList.tsx
@@ -1,18 +1,17 @@
import { useCloseDropdown } from '@/ui/layout/dropdown/hooks/useCloseDropdown';
+import { TabListHiddenMeasurements } from '@/ui/layout/tab-list/components/TabListHiddenMeasurements';
import { TAB_LIST_GAP } from '@/ui/layout/tab-list/constants/TabListGap';
import { TAB_LIST_HEIGHT } from '@/ui/layout/tab-list/constants/TabListHeight';
+import { useTabListMeasurements } from '@/ui/layout/tab-list/hooks/useTabListMeasurements';
import { activeTabIdComponentState } from '@/ui/layout/tab-list/states/activeTabIdComponentState';
import { TabListComponentInstanceContext } from '@/ui/layout/tab-list/states/contexts/TabListComponentInstanceContext';
import { type TabListProps } from '@/ui/layout/tab-list/types/TabListProps';
import { NodeDimension } from '@/ui/utilities/dimensions/components/NodeDimension';
-import { TabListHiddenMeasurements } from '@/ui/layout/tab-list/components/TabListHiddenMeasurements';
-import { useTabListMeasurements } from '@/ui/layout/tab-list/hooks/useTabListMeasurements';
import { useAtomComponentState } from '@/ui/utilities/state/jotai/hooks/useAtomComponentState';
import { styled } from '@linaria/react';
import { useCallback, useEffect, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { TabButton } from 'twenty-ui/input';
-import { themeCssVariables } from 'twenty-ui/theme-constants';
import { TabListDropdown } from './TabListDropdown';
import { TabListFromUrlOptionalEffect } from './TabListFromUrlOptionalEffect';
@@ -23,16 +22,6 @@ const StyledContainer = styled.div`
position: relative;
user-select: none;
width: 100%;
-
- &::after {
- background-color: ${themeCssVariables.border.color.light};
- bottom: 0;
- content: '';
- height: 1px;
- left: 0;
- position: absolute;
- right: 0;
- }
`;
const StyledDropdownContainer = styled.div`
diff --git a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
index 1e112a1748c..3d990ec4893 100644
--- a/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
+++ b/packages/twenty-front/src/modules/users/graphql/fragments/userQueryFragment.ts
@@ -61,6 +61,8 @@ export const USER_QUERY_FRAGMENT = gql`
subdomain
customDomain
hasValidEnterpriseKey
+ hasValidSignedEnterpriseKey
+ hasValidEnterpriseValidityToken
workspaceCustomApplication {
id
}
diff --git a/packages/twenty-front/src/pages/settings/enterprise/SettingsEnterprise.tsx b/packages/twenty-front/src/pages/settings/enterprise/SettingsEnterprise.tsx
new file mode 100644
index 00000000000..3d342aa83bf
--- /dev/null
+++ b/packages/twenty-front/src/pages/settings/enterprise/SettingsEnterprise.tsx
@@ -0,0 +1,682 @@
+import { Trans, useLingui } from '@lingui/react/macro';
+import { useCallback, useEffect, useState } from 'react';
+
+import { currentWorkspaceState } from '@/auth/states/currentWorkspaceState';
+import { SubscriptionInfoContainer } from '@/billing/components/SubscriptionInfoContainer';
+import { SubscriptionInfoRowContainer } from '@/billing/components/internal/SubscriptionInfoRowContainer';
+import { SettingsPageContainer } from '@/settings/components/SettingsPageContainer';
+import {
+ ENTERPRISE_PLAN_MODAL_ID,
+ EnterprisePlanModal,
+} from '@/settings/enterprise/components/EnterprisePlanModal';
+import { REFRESH_ENTERPRISE_VALIDITY_TOKEN } from '@/settings/enterprise/graphql/mutations/refreshEnterpriseValidityToken';
+import { SET_ENTERPRISE_KEY } from '@/settings/enterprise/graphql/mutations/setEnterpriseKey';
+import { ENTERPRISE_PORTAL_SESSION } from '@/settings/enterprise/graphql/queries/enterprisePortalSession';
+import { ENTERPRISE_SUBSCRIPTION_STATUS } from '@/settings/enterprise/graphql/queries/enterpriseSubscriptionStatus';
+import { useSnackBar } from '@/ui/feedback/snack-bar-manager/hooks/useSnackBar';
+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
+import { useModal } from '@/ui/layout/modal/hooks/useModal';
+import { SubMenuTopBarContainer } from '@/ui/layout/page/components/SubMenuTopBarContainer';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useLoadCurrentUser } from '@/users/hooks/useLoadCurrentUser';
+import { ApolloError, useLazyQuery, useMutation } from '@apollo/client';
+import { styled } from '@linaria/react';
+import { SettingsPath } from 'twenty-shared/types';
+import { getSettingsPath, isDefined } from 'twenty-shared/utils';
+import {
+ H2Title,
+ IconCalendarRepeat,
+ IconCheck,
+ IconCircleX,
+ IconCreditCard,
+ IconKey,
+ IconUser,
+} from 'twenty-ui/display';
+import { Button } from 'twenty-ui/input';
+import { Section } from 'twenty-ui/layout';
+import { themeCssVariables } from 'twenty-ui/theme-constants';
+
+type SettingsEnterpriseProps = {
+ isAdminPanelTab?: boolean;
+};
+
+type SubscriptionStatus = {
+ status: string | null;
+ licensee: string | null;
+ expiresAt: string | null;
+ cancelAt: string | null;
+ currentPeriodEnd: string | null;
+ isCancellationScheduled: boolean;
+};
+
+const StyledStatusDot = styled.div<{ isActive: boolean }>`
+ background-color: ${({ isActive }) =>
+ isActive ? themeCssVariables.color.green : themeCssVariables.color.red};
+ border-radius: 50%;
+ height: 8px;
+ width: 8px;
+`;
+
+const StyledStatusContainer = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledCancellationNotice = styled.div`
+ color: ${themeCssVariables.font.color.danger};
+ font-size: ${themeCssVariables.font.size.sm};
+ margin-top: ${themeCssVariables.spacing[3]};
+`;
+
+const StyledInputContainer = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+ width: 100%;
+`;
+
+const StyledInputWrapper = styled.div`
+ flex: 1;
+ min-width: 0;
+`;
+
+const StyledActivateButtonWrapper = styled.div`
+ flex-shrink: 0;
+`;
+
+const StyledSpacer = styled.div`
+ height: ${themeCssVariables.spacing[4]};
+`;
+
+export const SettingsEnterprise = ({
+ isAdminPanelTab = false,
+}: SettingsEnterpriseProps = {}) => {
+ const { t } = useLingui();
+ const currentWorkspace = useAtomStateValue(currentWorkspaceState);
+ const [enterpriseKey, setEnterpriseKey] = useState('');
+ const [isActivating, setIsActivating] = useState(false);
+ const [setEnterpriseKeyMutation] = useMutation(SET_ENTERPRISE_KEY);
+ const [refreshValidityTokenMutation] = useMutation(
+ REFRESH_ENTERPRISE_VALIDITY_TOKEN,
+ );
+ const [fetchPortalSession] = useLazyQuery(ENTERPRISE_PORTAL_SESSION);
+ const [isRefreshingToken, setIsRefreshingToken] = useState(false);
+ const { openModal } = useModal();
+ const { enqueueErrorSnackBar, enqueueSuccessSnackBar } = useSnackBar();
+ const { loadCurrentUser } = useLoadCurrentUser();
+
+ const hasSignedEnterpriseKey =
+ currentWorkspace?.hasValidSignedEnterpriseKey === true;
+ const hasValidityToken =
+ currentWorkspace?.hasValidEnterpriseValidityToken === true;
+
+ const hasOrphanedValidityToken = hasValidityToken && !hasSignedEnterpriseKey;
+
+ const [fetchSubscriptionStatus] = useLazyQuery(
+ ENTERPRISE_SUBSCRIPTION_STATUS,
+ { fetchPolicy: 'network-only' },
+ );
+
+ const [subscriptionStatus, setSubscriptionStatus] =
+ useState<SubscriptionStatus | null>(null);
+ const [isStatusLoaded, setIsStatusLoaded] = useState(false);
+
+ useEffect(() => {
+ if (!hasSignedEnterpriseKey) {
+ setIsStatusLoaded(true);
+
+ return;
+ }
+
+ const loadStatus = async () => {
+ const { data } = await fetchSubscriptionStatus();
+
+ setSubscriptionStatus(data?.enterpriseSubscriptionStatus ?? null);
+ setIsStatusLoaded(true);
+ };
+
+ loadStatus();
+ }, [hasSignedEnterpriseKey, fetchSubscriptionStatus]);
+
+ const stripeStatus = subscriptionStatus?.status ?? null;
+
+ const isSubscriptionActiveOrTrialing =
+ stripeStatus === 'active' || stripeStatus === 'trialing';
+ const isCancelScheduled =
+ subscriptionStatus?.isCancellationScheduled === true;
+ const isCanceled = stripeStatus === 'canceled';
+ const isPastDue = stripeStatus === 'past_due' || stripeStatus === 'unpaid';
+ const isIncomplete =
+ stripeStatus === 'incomplete' || stripeStatus === 'incomplete_expired';
+
+ const licensee = subscriptionStatus?.licensee ?? null;
+ const expiresAt = subscriptionStatus?.expiresAt
+ ? new Date(subscriptionStatus.expiresAt)
+ : null;
+
+ const cancelAt = isDefined(subscriptionStatus?.cancelAt)
+ ? new Date(subscriptionStatus.cancelAt)
+ : null;
+
+ const cancelAtDate =
+ isCancelScheduled && isDefined(cancelAt)
+ ? cancelAt.toLocaleDateString()
+ : '';
+
+ const cancellationMessage =
+ isCancelScheduled && isDefined(cancelAt)
+ ? t`Your enterprise features will remain active until ${cancelAtDate}.`
+ : null;
+
+ const handleActivate = useCallback(async () => {
+ if (!enterpriseKey.trim()) return;
+
+ setIsActivating(true);
+
+ try {
+ const result = await setEnterpriseKeyMutation({
+ variables: { enterpriseKey: enterpriseKey.trim() },
+ });
+
+ if (result.data?.setEnterpriseKey.isValid === true) {
+ enqueueSuccessSnackBar({
+ message: t`Enterprise license activated successfully`,
+ });
+ setEnterpriseKey('');
+ const { data: statusData } = await fetchSubscriptionStatus();
+
+ setSubscriptionStatus(statusData?.enterpriseSubscriptionStatus ?? null);
+ await loadCurrentUser();
+ } else {
+ enqueueErrorSnackBar({
+ message: t`Failed to activate enterprise license. Please check your key or contact support.`,
+ });
+ }
+ } catch (error) {
+ const subCode =
+ error instanceof ApolloError
+ ? error.graphQLErrors?.[0]?.extensions?.subCode
+ : undefined;
+
+ if (subCode === 'CONFIG_VARIABLES_IN_DB_DISABLED') {
+ enqueueErrorSnackBar({
+ apolloError: error as ApolloError,
+ options: { duration: 10000 },
+ });
+ } else {
+ enqueueErrorSnackBar({
+ message: t`Error activating enterprise license`,
+ });
+ }
+ } finally {
+ setIsActivating(false);
+ }
+ }, [
+ enterpriseKey,
+ setEnterpriseKeyMutation,
+ enqueueErrorSnackBar,
+ enqueueSuccessSnackBar,
+ fetchSubscriptionStatus,
+ loadCurrentUser,
+ t,
+ ]);
+
+ const returnUrlPath = isAdminPanelTab
+ ? getSettingsPath(SettingsPath.AdminPanelEnterprise)
+ : getSettingsPath(SettingsPath.Enterprise);
+
+ const openBillingPortal = useCallback(async () => {
+ try {
+ const { data } = await fetchPortalSession({
+ variables: { returnUrlPath },
+ });
+
+ const portalUrl = data?.enterprisePortalSession;
+
+ if (portalUrl !== null && portalUrl !== undefined) {
+ window.open(portalUrl, '_blank', 'noopener');
+ } else {
+ enqueueErrorSnackBar({
+ message: t`Could not open billing portal. Please check your enterprise key is present, or contact support.`,
+ });
+ }
+ } catch {
+ enqueueErrorSnackBar({
+ message: t`Error opening billing portal`,
+ });
+ }
+ }, [fetchPortalSession, enqueueErrorSnackBar, t, returnUrlPath]);
+
+ const openCheckoutModal = useCallback(() => {
+ openModal(ENTERPRISE_PLAN_MODAL_ID);
+ }, [openModal]);
+
+ const handleRefreshValidityToken = useCallback(async () => {
+ setIsRefreshingToken(true);
+
+ try {
+ const { data } = await refreshValidityTokenMutation();
+
+ if (data?.refreshEnterpriseValidityToken === true) {
+ enqueueSuccessSnackBar({
+ message: t`Validity token refreshed successfully`,
+ });
+ await loadCurrentUser();
+ } else {
+ enqueueErrorSnackBar({
+ message: t`Could not refresh validity token. Please contact support.`,
+ });
+ }
+ } catch {
+ enqueueErrorSnackBar({
+ message: t`Error refreshing validity token. Please contact support.`,
+ });
+ } finally {
+ setIsRefreshingToken(false);
+ }
+ }, [
+ refreshValidityTokenMutation,
+ enqueueSuccessSnackBar,
+ enqueueErrorSnackBar,
+ loadCurrentUser,
+ t,
+ ]);
+
+ const activateKeySection = (
+ <Section>
+ <H2Title
+ title={t`Activate Enterprise Key`}
+ description={t`Paste your enterprise key below to activate`}
+ />
+ <StyledInputContainer>
+ <StyledInputWrapper>
+ <SettingsTextInput
+ instanceId="enterprise-key-input"
+ value={enterpriseKey}
+ onChange={(value) => setEnterpriseKey(value)}
+ placeholder={t`Paste your enterprise key here`}
+ fullWidth
+ onInputEnter={handleActivate}
+ />
+ </StyledInputWrapper>
+ <StyledActivateButtonWrapper>
+ <Button
+ Icon={IconKey}
+ title={isActivating ? t`Activating...` : t`Activate`}
+ variant="secondary"
+ accent="blue"
+ onClick={handleActivate}
+ disabled={isActivating || !enterpriseKey.trim()}
+ />
+ </StyledActivateButtonWrapper>
+ </StyledInputContainer>
+ </Section>
+ );
+
+ const renderContent = () => {
+ if (!isStatusLoaded) {
+ return null;
+ }
+
+ if (hasOrphanedValidityToken) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={t`Your enterprise features are active but your enterprise key is missing or invalid. This may be expected, but if not, please set a valid signed enterprise key to manage your subscription, or contact support.`}
+ />
+ <Button
+ Icon={IconKey}
+ title={t`Get Enterprise Key`}
+ variant="secondary"
+ onClick={openCheckoutModal}
+ />
+ </Section>
+ {activateKeySection}
+ </>
+ );
+ }
+
+ if (!hasSignedEnterpriseKey) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Get Enterprise`}
+ description={t`Unlock enterprise features like SSO, row-level security, and audit logs.`}
+ />
+ <Button
+ Icon={IconKey}
+ title={t`Get Enterprise Key`}
+ variant="secondary"
+ onClick={openCheckoutModal}
+ />
+ </Section>
+ {activateKeySection}
+ </>
+ );
+ }
+
+ if (isSubscriptionActiveOrTrialing && !hasValidityToken) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={t`Your subscription is active but your validity token is invalid or has expired. Try reloading it or contact support.`}
+ />
+ <Button
+ Icon={IconKey}
+ title={
+ isRefreshingToken ? t`Reloading...` : t`Reload validity token`
+ }
+ variant="secondary"
+ accent="blue"
+ onClick={handleRefreshValidityToken}
+ disabled={isRefreshingToken}
+ />
+ <StyledSpacer />
+ <SubscriptionInfoContainer>
+ <SubscriptionInfoRowContainer
+ label={t`Status`}
+ Icon={IconCheck}
+ currentValue={
+ <StyledStatusContainer>
+ <StyledStatusDot isActive={true} />
+ {stripeStatus === 'trialing' ? (
+ <Trans>Trial</Trans>
+ ) : (
+ <Trans>Active</Trans>
+ )}
+ </StyledStatusContainer>
+ }
+ />
+ {licensee && (
+ <SubscriptionInfoRowContainer
+ label={t`Licensee`}
+ Icon={IconUser}
+ currentValue={licensee}
+ />
+ )}
+ {expiresAt && (
+ <SubscriptionInfoRowContainer
+ label={t`Valid until`}
+ Icon={IconCalendarRepeat}
+ currentValue={new Date(expiresAt).toLocaleDateString()}
+ />
+ )}
+ </SubscriptionInfoContainer>
+ </Section>
+ <Section>
+ <H2Title
+ title={t`Manage billing information`}
+ description={t`Edit payment method, see your invoices and more`}
+ />
+ <Button
+ Icon={IconCreditCard}
+ title={t`View billing details`}
+ variant="secondary"
+ onClick={openBillingPortal}
+ />
+ </Section>
+ </>
+ );
+ }
+
+ if (isSubscriptionActiveOrTrialing) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={
+ isCancelScheduled
+ ? t`Your subscription is scheduled for cancellation`
+ : t`Your enterprise features are active`
+ }
+ />
+ <SubscriptionInfoContainer>
+ <SubscriptionInfoRowContainer
+ label={t`Status`}
+ Icon={IconCheck}
+ currentValue={
+ <StyledStatusContainer>
+ <StyledStatusDot isActive={!isCancelScheduled} />
+ {isCancelScheduled ? (
+ <Trans>Cancelling</Trans>
+ ) : stripeStatus === 'trialing' ? (
+ <Trans>Trial</Trans>
+ ) : (
+ <Trans>Active</Trans>
+ )}
+ </StyledStatusContainer>
+ }
+ />
+ {licensee && (
+ <SubscriptionInfoRowContainer
+ label={t`Licensee`}
+ Icon={IconUser}
+ currentValue={licensee}
+ />
+ )}
+ {expiresAt && (
+ <SubscriptionInfoRowContainer
+ label={isCancelScheduled ? t`Cancels on` : t`Valid until`}
+ Icon={IconCalendarRepeat}
+ currentValue={new Date(expiresAt).toLocaleDateString()}
+ />
+ )}
+ </SubscriptionInfoContainer>
+ {cancellationMessage && (
+ <StyledCancellationNotice>
+ {cancellationMessage}
+ </StyledCancellationNotice>
+ )}
+ </Section>
+ <Section>
+ <H2Title
+ title={t`Manage billing information`}
+ description={t`Edit payment method, see your invoices and more`}
+ />
+ <Button
+ Icon={IconCreditCard}
+ title={t`View billing details`}
+ variant="secondary"
+ onClick={openBillingPortal}
+ />
+ </Section>
+ {!isCancelScheduled && (
+ <Section>
+ <H2Title
+ title={t`Cancel your subscription`}
+ description={t`Your enterprise features will be disabled`}
+ />
+ <Button
+ Icon={IconCircleX}
+ title={t`Cancel Plan`}
+ variant="secondary"
+ accent="danger"
+ onClick={openBillingPortal}
+ />
+ </Section>
+ )}
+ </>
+ );
+ }
+
+ if (isCanceled) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={t`Your enterprise subscription has been canceled.`}
+ />
+ <SubscriptionInfoContainer>
+ <SubscriptionInfoRowContainer
+ label={t`Status`}
+ Icon={IconCheck}
+ currentValue={
+ <StyledStatusContainer>
+ <StyledStatusDot isActive={false} />
+ <Trans>Canceled</Trans>
+ </StyledStatusContainer>
+ }
+ />
+ <SubscriptionInfoRowContainer
+ label={t`Billing history`}
+ Icon={IconCreditCard}
+ currentValue={
+ <Button
+ title={t`View invoices`}
+ variant="secondary"
+ size="small"
+ onClick={openBillingPortal}
+ />
+ }
+ />
+ </SubscriptionInfoContainer>
+ </Section>
+ <Section>
+ <H2Title
+ title={t`Get Enterprise`}
+ description={t`Start a new enterprise subscription to re-enable enterprise features.`}
+ />
+ <Button
+ Icon={IconKey}
+ title={t`Get Enterprise Key`}
+ variant="secondary"
+ onClick={openCheckoutModal}
+ />
+ </Section>
+ {activateKeySection}
+ </>
+ );
+ }
+
+ if (isPastDue) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={t`There is a payment issue with your subscription. Please update your payment method.`}
+ />
+ <SubscriptionInfoContainer>
+ <SubscriptionInfoRowContainer
+ label={t`Status`}
+ Icon={IconCheck}
+ currentValue={
+ <StyledStatusContainer>
+ <StyledStatusDot isActive={false} />
+ <Trans>Payment issue</Trans>
+ </StyledStatusContainer>
+ }
+ />
+ </SubscriptionInfoContainer>
+ </Section>
+ <Section>
+ <H2Title
+ title={t`Update payment method`}
+ description={t`Fix the payment issue to keep your enterprise features active.`}
+ />
+ <Button
+ Icon={IconCreditCard}
+ title={t`Go to billing portal`}
+ variant="secondary"
+ accent="blue"
+ onClick={openBillingPortal}
+ />
+ </Section>
+ </>
+ );
+ }
+
+ if (isIncomplete) {
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={t`Your subscription setup was not completed.`}
+ />
+ <SubscriptionInfoContainer>
+ <SubscriptionInfoRowContainer
+ label={t`Status`}
+ Icon={IconCheck}
+ currentValue={
+ <StyledStatusContainer>
+ <StyledStatusDot isActive={false} />
+ <Trans>Incomplete</Trans>
+ </StyledStatusContainer>
+ }
+ />
+ </SubscriptionInfoContainer>
+ </Section>
+ <Section>
+ <H2Title
+ title={t`Get Enterprise`}
+ description={t`Start a new enterprise subscription.`}
+ />
+ <Button
+ Icon={IconKey}
+ title={t`Get Enterprise Key`}
+ variant="secondary"
+ onClick={openCheckoutModal}
+ />
+ </Section>
+ {activateKeySection}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <Section>
+ <H2Title
+ title={t`Enterprise License`}
+ description={(() => {
+ const statusLabel = stripeStatus ?? 'unknown';
+
+ return t`Your subscription status is: ${statusLabel}`;
+ })()}
+ />
+ <Button
+ Icon={IconCreditCard}
+ title={t`Go to billing portal`}
+ variant="secondary"
+ onClick={openBillingPortal}
+ />
+ </Section>
+ {activateKeySection}
+ </>
+ );
+ };
+
+ const innerContent = (
+ <>
+ <EnterprisePlanModal />
+ {renderContent()}
+ </>
+ );
+
+ if (isAdminPanelTab) {
+ return innerContent;
+ }
+
+ return (
+ <SubMenuTopBarContainer
+ title={t`Enterprise`}
+ links={[
+ {
+ children: <Trans>Workspace</Trans>,
+ href: getSettingsPath(SettingsPath.Workspace),
+ },
+ { children: <Trans>Enterprise</Trans> },
+ ]}
+ >
+ <SettingsPageContainer>{innerContent}</SettingsPageContainer>
+ </SubMenuTopBarContainer>
+ );
+};
diff --git a/packages/twenty-front/src/testing/mock-data/users.ts b/packages/twenty-front/src/testing/mock-data/users.ts
index 521c8350366..30c7ecd4579 100644
--- a/packages/twenty-front/src/testing/mock-data/users.ts
+++ b/packages/twenty-front/src/testing/mock-data/users.ts
@@ -68,6 +68,8 @@ export const mockCurrentWorkspace = {
allowImpersonation: true,
activationStatus: WorkspaceActivationStatus.ACTIVE,
hasValidEnterpriseKey: false,
+ hasValidSignedEnterpriseKey: false,
+ hasValidEnterpriseValidityToken: false,
isGoogleAuthEnabled: true,
isPasswordAuthEnabled: true,
isMicrosoftAuthEnabled: false,
diff --git a/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql b/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
index 2b67d4d18a0..22d81ba146e 100644
--- a/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
+++ b/packages/twenty-sdk/src/clients/generated/metadata/schema.graphql
@@ -805,6 +805,8 @@ type Workspace {
currentBillingSubscription: BillingSubscription
billingEntitlements: [BillingEntitlement!]!
hasValidEnterpriseKey: Boolean!
+ hasValidSignedEnterpriseKey: Boolean!
+ hasValidEnterpriseValidityToken: Boolean!
workspaceUrls: WorkspaceUrls!
workspaceCustomApplicationId: String!
}
@@ -1454,6 +1456,22 @@ type BillingUpdate {
billingSubscriptions: [BillingSubscription!]!
}
+type EnterpriseLicenseInfoDTO {
+ isValid: Boolean!
+ licensee: String
+ expiresAt: DateTime
+ subscriptionId: String
+}
+
+type EnterpriseSubscriptionStatusDTO {
+ status: String!
+ licensee: String
+ expiresAt: DateTime
+ cancelAt: DateTime
+ currentPeriodEnd: DateTime
+ isCancellationScheduled: Boolean!
+}
+
type OnboardingStepSuccess {
"""Boolean that confirms query was dispatched"""
success: Boolean!
@@ -2859,6 +2877,9 @@ type Query {
billingPortalSession(returnUrlPath: String): BillingSession!
listPlans: [BillingPlan!]!
getMeteredProductsUsage: [BillingMeteredProductUsage!]!
+ enterprisePortalSession(returnUrlPath: String): String
+ enterpriseCheckoutSession(billingInterval: String): String
+ enterpriseSubscriptionStatus: EnterpriseSubscriptionStatusDTO
navigationMenuItems: [NavigationMenuItem!]!
navigationMenuItem(id: UUID!): NavigationMenuItem
apiKeys: [ApiKey!]!
@@ -3119,6 +3140,8 @@ type Mutation {
setMeteredSubscriptionPrice(priceId: String!): BillingUpdate!
endSubscriptionTrialPeriod: BillingEndTrialPeriod!
cancelSwitchMeteredPrice: BillingUpdate!
+ refreshEnterpriseValidityToken: Boolean!
+ setEnterpriseKey(enterpriseKey: String!): EnterpriseLicenseInfoDTO!
createNavigationMenuItem(input: CreateNavigationMenuItemInput!): NavigationMenuItem!
updateNavigationMenuItem(input: UpdateOneNavigationMenuItemInput!): NavigationMenuItem!
deleteNavigationMenuItem(id: UUID!): NavigationMenuItem!
diff --git a/packages/twenty-sdk/src/clients/generated/metadata/schema.ts b/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
index 0a047bfe777..e43131bbb4d 100644
--- a/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
+++ b/packages/twenty-sdk/src/clients/generated/metadata/schema.ts
@@ -589,6 +589,8 @@ export interface Workspace {
currentBillingSubscription?: BillingSubscription
billingEntitlements: BillingEntitlement[]
hasValidEnterpriseKey: Scalars['Boolean']
+ hasValidSignedEnterpriseKey: Scalars['Boolean']
+ hasValidEnterpriseValidityToken: Scalars['Boolean']
workspaceUrls: WorkspaceUrls
workspaceCustomApplicationId: Scalars['String']
__typename: 'Workspace'
@@ -1170,6 +1172,24 @@ export interface BillingUpdate {
__typename: 'BillingUpdate'
}
+export interface EnterpriseLicenseInfoDTO {
+ isValid: Scalars['Boolean']
+ licensee?: Scalars['String']
+ expiresAt?: Scalars['DateTime']
+ subscriptionId?: Scalars['String']
+ __typename: 'EnterpriseLicenseInfoDTO'
+}
+
+export interface EnterpriseSubscriptionStatusDTO {
+ status: Scalars['String']
+ licensee?: Scalars['String']
+ expiresAt?: Scalars['DateTime']
+ cancelAt?: Scalars['DateTime']
+ currentPeriodEnd?: Scalars['DateTime']
+ isCancellationScheduled: Scalars['Boolean']
+ __typename: 'EnterpriseSubscriptionStatusDTO'
+}
+
export interface OnboardingStepSuccess {
/** Boolean that confirms query was dispatched */
success: Scalars['Boolean']
@@ -2542,6 +2562,9 @@ export interface Query {
billingPortalSession: BillingSession
listPlans: BillingPlan[]
getMeteredProductsUsage: BillingMeteredProductUsage[]
+ enterprisePortalSession?: Scalars['String']
+ enterpriseCheckoutSession?: Scalars['String']
+ enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTO
navigationMenuItems: NavigationMenuItem[]
navigationMenuItem?: NavigationMenuItem
apiKeys: ApiKey[]
@@ -2692,6 +2715,8 @@ export interface Mutation {
setMeteredSubscriptionPrice: BillingUpdate
endSubscriptionTrialPeriod: BillingEndTrialPeriod
cancelSwitchMeteredPrice: BillingUpdate
+ refreshEnterpriseValidityToken: Scalars['Boolean']
+ setEnterpriseKey: EnterpriseLicenseInfoDTO
createNavigationMenuItem: NavigationMenuItem
updateNavigationMenuItem: NavigationMenuItem
deleteNavigationMenuItem: NavigationMenuItem
@@ -3432,6 +3457,8 @@ export interface WorkspaceGenqlSelection{
currentBillingSubscription?: BillingSubscriptionGenqlSelection
billingEntitlements?: BillingEntitlementGenqlSelection
hasValidEnterpriseKey?: boolean | number
+ hasValidSignedEnterpriseKey?: boolean | number
+ hasValidEnterpriseValidityToken?: boolean | number
workspaceUrls?: WorkspaceUrlsGenqlSelection
workspaceCustomApplicationId?: boolean | number
__typename?: boolean | number
@@ -4042,6 +4069,26 @@ export interface BillingUpdateGenqlSelection{
__scalar?: boolean | number
}
+export interface EnterpriseLicenseInfoDTOGenqlSelection{
+ isValid?: boolean | number
+ licensee?: boolean | number
+ expiresAt?: boolean | number
+ subscriptionId?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface EnterpriseSubscriptionStatusDTOGenqlSelection{
+ status?: boolean | number
+ licensee?: boolean | number
+ expiresAt?: boolean | number
+ cancelAt?: boolean | number
+ currentPeriodEnd?: boolean | number
+ isCancellationScheduled?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface OnboardingStepSuccessGenqlSelection{
/** Boolean that confirms query was dispatched */
success?: boolean | number
@@ -5530,6 +5577,9 @@ export interface QueryGenqlSelection{
billingPortalSession?: (BillingSessionGenqlSelection & { __args?: {returnUrlPath?: (Scalars['String'] | null)} })
listPlans?: BillingPlanGenqlSelection
getMeteredProductsUsage?: BillingMeteredProductUsageGenqlSelection
+ enterprisePortalSession?: { __args: {returnUrlPath?: (Scalars['String'] | null)} } | boolean | number
+ enterpriseCheckoutSession?: { __args: {billingInterval?: (Scalars['String'] | null)} } | boolean | number
+ enterpriseSubscriptionStatus?: EnterpriseSubscriptionStatusDTOGenqlSelection
navigationMenuItems?: NavigationMenuItemGenqlSelection
navigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })
apiKeys?: ApiKeyGenqlSelection
@@ -5711,6 +5761,8 @@ export interface MutationGenqlSelection{
setMeteredSubscriptionPrice?: (BillingUpdateGenqlSelection & { __args: {priceId: Scalars['String']} })
endSubscriptionTrialPeriod?: BillingEndTrialPeriodGenqlSelection
cancelSwitchMeteredPrice?: BillingUpdateGenqlSelection
+ refreshEnterpriseValidityToken?: boolean | number
+ setEnterpriseKey?: (EnterpriseLicenseInfoDTOGenqlSelection & { __args: {enterpriseKey: Scalars['String']} })
createNavigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {input: CreateNavigationMenuItemInput} })
updateNavigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {input: UpdateOneNavigationMenuItemInput} })
deleteNavigationMenuItem?: (NavigationMenuItemGenqlSelection & { __args: {id: Scalars['UUID']} })
@@ -6883,6 +6935,22 @@ export interface LogicFunctionLogsInput {applicationId?: (Scalars['UUID'] | null
+ const EnterpriseLicenseInfoDTO_possibleTypes: string[] = ['EnterpriseLicenseInfoDTO']
+ export const isEnterpriseLicenseInfoDTO = (obj?: { __typename?: any } | null): obj is EnterpriseLicenseInfoDTO => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseLicenseInfoDTO"')
+ return EnterpriseLicenseInfoDTO_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const EnterpriseSubscriptionStatusDTO_possibleTypes: string[] = ['EnterpriseSubscriptionStatusDTO']
+ export const isEnterpriseSubscriptionStatusDTO = (obj?: { __typename?: any } | null): obj is EnterpriseSubscriptionStatusDTO => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isEnterpriseSubscriptionStatusDTO"')
+ return EnterpriseSubscriptionStatusDTO_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const OnboardingStepSuccess_possibleTypes: string[] = ['OnboardingStepSuccess']
export const isOnboardingStepSuccess = (obj?: { __typename?: any } | null): obj is OnboardingStepSuccess => {
if (!obj?.__typename) throw new Error('__typename is missing in "isOnboardingStepSuccess"')
diff --git a/packages/twenty-sdk/src/clients/generated/metadata/types.ts b/packages/twenty-sdk/src/clients/generated/metadata/types.ts
index 95121bfcad6..f9bdf228eee 100644
--- a/packages/twenty-sdk/src/clients/generated/metadata/types.ts
+++ b/packages/twenty-sdk/src/clients/generated/metadata/types.ts
@@ -45,37 +45,37 @@ export default {
128,
130,
138,
- 152,
- 153,
- 158,
- 162,
- 181,
- 216,
- 224,
- 225,
- 238,
- 239,
- 244,
- 247,
- 253,
- 254,
+ 154,
+ 155,
+ 160,
+ 164,
+ 183,
+ 218,
+ 226,
+ 227,
+ 240,
+ 241,
+ 246,
+ 249,
+ 255,
256,
- 261,
- 266,
- 267,
- 279,
- 295,
- 296,
- 319,
- 326,
- 327,
+ 258,
+ 263,
+ 268,
+ 269,
+ 281,
+ 297,
+ 298,
+ 321,
328,
+ 329,
330,
- 339,
- 398,
- 449,
- 450,
- 451
+ 332,
+ 341,
+ 400,
+ 451,
+ 452,
+ 453
],
"types": {
"BillingProductDTO": {
@@ -779,10 +779,10 @@ export default {
3
],
"relation": [
- 180
+ 182
],
"morphRelations": [
- 180
+ 182
],
"object": [
46
@@ -841,7 +841,7 @@ export default {
36
],
"objectMetadata": [
- 173,
+ 175,
{
"paging": [
39,
@@ -854,7 +854,7 @@ export default {
}
],
"indexFieldMetadatas": [
- 171,
+ 173,
{
"paging": [
39,
@@ -1096,7 +1096,7 @@ export default {
37
],
"fields": [
- 178,
+ 180,
{
"paging": [
39,
@@ -1109,7 +1109,7 @@ export default {
}
],
"indexMetadatas": [
- 176,
+ 178,
{
"paging": [
39,
@@ -1684,7 +1684,7 @@ export default {
49
],
"featureFlags": [
- 161
+ 163
],
"billingSubscriptions": [
137
@@ -1693,13 +1693,19 @@ export default {
137
],
"billingEntitlements": [
- 157
+ 159
],
"hasValidEnterpriseKey": [
6
],
+ "hasValidSignedEnterpriseKey": [
+ 6
+ ],
+ "hasValidEnterpriseValidityToken": [
+ 6
+ ],
"workspaceUrls": [
- 150
+ 152
],
"workspaceCustomApplicationId": [
1
@@ -1791,7 +1797,7 @@ export default {
20
],
"deletedWorkspaceMembers": [
- 156
+ 158
],
"hasPassword": [
6
@@ -1803,7 +1809,7 @@ export default {
17
],
"availableWorkspaces": [
- 155
+ 157
],
"__typename": [
1
@@ -2947,6 +2953,46 @@ export default {
1
]
},
+ "EnterpriseLicenseInfoDTO": {
+ "isValid": [
+ 6
+ ],
+ "licensee": [
+ 1
+ ],
+ "expiresAt": [
+ 4
+ ],
+ "subscriptionId": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "EnterpriseSubscriptionStatusDTO": {
+ "status": [
+ 1
+ ],
+ "licensee": [
+ 1
+ ],
+ "expiresAt": [
+ 4
+ ],
+ "cancelAt": [
+ 4
+ ],
+ "currentPeriodEnd": [
+ 4
+ ],
+ "isCancellationScheduled": [
+ 6
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"OnboardingStepSuccess": {
"success": [
6
@@ -3017,7 +3063,7 @@ export default {
1
],
"result": [
- 147
+ 149
],
"__typename": [
1
@@ -3044,7 +3090,7 @@ export default {
},
"SSOConnection": {
"type": [
- 152
+ 154
],
"id": [
3
@@ -3056,7 +3102,7 @@ export default {
1
],
"status": [
- 153
+ 155
],
"__typename": [
1
@@ -3081,13 +3127,13 @@ export default {
1
],
"workspaceUrls": [
- 150
+ 152
],
"logo": [
1
],
"sso": [
- 151
+ 153
],
"__typename": [
1
@@ -3095,10 +3141,10 @@ export default {
},
"AvailableWorkspaces": {
"availableWorkspacesForSignIn": [
- 154
+ 156
],
"availableWorkspacesForSignUp": [
- 154
+ 156
],
"__typename": [
1
@@ -3126,7 +3172,7 @@ export default {
},
"BillingEntitlement": {
"key": [
- 158
+ 160
],
"value": [
6
@@ -3164,7 +3210,7 @@ export default {
1
],
"records": [
- 159
+ 161
],
"__typename": [
1
@@ -3172,7 +3218,7 @@ export default {
},
"FeatureFlag": {
"key": [
- 162
+ 164
],
"value": [
6
@@ -3190,10 +3236,10 @@ export default {
1
],
"type": [
- 152
+ 154
],
"status": [
- 153
+ 155
],
"issuer": [
1
@@ -3204,7 +3250,7 @@ export default {
},
"AuthProviders": {
"sso": [
- 163
+ 165
],
"google": [
6
@@ -3241,10 +3287,10 @@ export default {
3
],
"authProviders": [
- 164
+ 166
],
"authBypassProviders": [
- 165
+ 167
],
"logo": [
1
@@ -3253,7 +3299,7 @@ export default {
1
],
"workspaceUrls": [
- 150
+ 152
],
"__typename": [
1
@@ -3289,10 +3335,10 @@ export default {
},
"IndexConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 167
+ 169
],
"__typename": [
1
@@ -3311,10 +3357,10 @@ export default {
},
"IndexIndexFieldMetadatasConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 170
+ 172
],
"__typename": [
1
@@ -3333,10 +3379,10 @@ export default {
},
"IndexObjectMetadataConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 172
+ 174
],
"__typename": [
1
@@ -3355,10 +3401,10 @@ export default {
},
"ObjectConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 172
+ 174
],
"__typename": [
1
@@ -3366,10 +3412,10 @@ export default {
},
"ObjectIndexMetadatasConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 167
+ 169
],
"__typename": [
1
@@ -3388,10 +3434,10 @@ export default {
},
"ObjectFieldsConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 177
+ 179
],
"__typename": [
1
@@ -3410,7 +3456,7 @@ export default {
},
"Relation": {
"type": [
- 181
+ 183
],
"sourceObjectMetadata": [
46
@@ -3431,10 +3477,10 @@ export default {
"RelationType": {},
"FieldConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 177
+ 179
],
"__typename": [
1
@@ -3459,7 +3505,7 @@ export default {
1
],
"versionDistribution": [
- 183
+ 185
],
"__typename": [
1
@@ -3517,7 +3563,7 @@ export default {
3
],
"type": [
- 152
+ 154
],
"issuer": [
1
@@ -3526,7 +3572,7 @@ export default {
1
],
"status": [
- 153
+ 155
],
"__typename": [
1
@@ -3545,7 +3591,7 @@ export default {
},
"FindAvailableSSOIDP": {
"type": [
- 152
+ 154
],
"id": [
3
@@ -3557,10 +3603,10 @@ export default {
1
],
"status": [
- 153
+ 155
],
"workspace": [
- 190
+ 192
],
"__typename": [
1
@@ -3571,7 +3617,7 @@ export default {
3
],
"type": [
- 152
+ 154
],
"issuer": [
1
@@ -3580,7 +3626,7 @@ export default {
1
],
"status": [
- 153
+ 155
],
"__typename": [
1
@@ -3631,10 +3677,10 @@ export default {
},
"AuthTokenPair": {
"accessOrWorkspaceAgnosticToken": [
- 197
+ 199
],
"refreshToken": [
- 197
+ 199
],
"__typename": [
1
@@ -3642,10 +3688,10 @@ export default {
},
"AvailableWorkspacesAndAccessTokens": {
"tokens": [
- 198
+ 200
],
"availableWorkspaces": [
- 155
+ 157
],
"__typename": [
1
@@ -3683,7 +3729,7 @@ export default {
},
"WorkspaceUrlsAndId": {
"workspaceUrls": [
- 150
+ 152
],
"id": [
3
@@ -3694,10 +3740,10 @@ export default {
},
"SignUp": {
"loginToken": [
- 197
+ 199
],
"workspace": [
- 203
+ 205
],
"__typename": [
1
@@ -3705,7 +3751,7 @@ export default {
},
"TransientToken": {
"transientToken": [
- 197
+ 199
],
"__typename": [
1
@@ -3727,10 +3773,10 @@ export default {
},
"VerifyEmailAndGetLoginToken": {
"loginToken": [
- 197
+ 199
],
"workspaceUrls": [
- 150
+ 152
],
"__typename": [
1
@@ -3746,7 +3792,7 @@ export default {
},
"AuthTokens": {
"tokens": [
- 198
+ 200
],
"__typename": [
1
@@ -3754,7 +3800,7 @@ export default {
},
"LoginToken": {
"loginToken": [
- 197
+ 199
],
"__typename": [
1
@@ -3840,7 +3886,7 @@ export default {
4
],
"targetRecordIdentifier": [
- 213
+ 215
],
"__typename": [
1
@@ -3857,7 +3903,7 @@ export default {
11
],
"status": [
- 216
+ 218
],
"error": [
15
@@ -4018,10 +4064,10 @@ export default {
},
"ApplicationTokenPair": {
"applicationAccessToken": [
- 197
+ 199
],
"applicationRefreshToken": [
- 197
+ 199
],
"__typename": [
1
@@ -4065,7 +4111,7 @@ export default {
6
],
"applicationTokenPair": [
- 221
+ 223
],
"__typename": [
1
@@ -4082,10 +4128,10 @@ export default {
3
],
"frontComponent": [
- 222
+ 224
],
"engineComponentKey": [
- 224
+ 226
],
"label": [
1
@@ -4103,7 +4149,7 @@ export default {
6
],
"availabilityType": [
- 225
+ 227
],
"conditionalAvailabilityExpression": [
1
@@ -4178,7 +4224,7 @@ export default {
1
],
"parts": [
- 219
+ 221
],
"createdAt": [
4
@@ -4203,7 +4249,7 @@ export default {
},
"AISystemPromptPreview": {
"sections": [
- 228
+ 230
],
"estimatedTokenCount": [
21
@@ -4214,7 +4260,7 @@ export default {
},
"AgentChatThreadEdge": {
"node": [
- 226
+ 228
],
"cursor": [
40
@@ -4225,10 +4271,10 @@ export default {
},
"AgentChatThreadConnection": {
"pageInfo": [
- 168
+ 170
],
"edges": [
- 230
+ 232
],
"__typename": [
1
@@ -4265,10 +4311,10 @@ export default {
3
],
"evaluations": [
- 232
+ 234
],
"messages": [
- 227
+ 229
],
"createdAt": [
4
@@ -4339,10 +4385,10 @@ export default {
1
],
"modelFamily": [
- 238
+ 240
],
"inferenceProvider": [
- 239
+ 241
],
"inputCostPerMillionTokensInCredits": [
11
@@ -4351,7 +4397,7 @@ export default {
11
],
"nativeCapabilities": [
- 236
+ 238
],
"deprecated": [
6
@@ -4373,10 +4419,10 @@ export default {
1
],
"modelFamily": [
- 238
+ 240
],
"inferenceProvider": [
- 239
+ 241
],
"isAvailable": [
6
@@ -4399,7 +4445,7 @@ export default {
6
],
"models": [
- 240
+ 242
],
"__typename": [
1
@@ -4413,7 +4459,7 @@ export default {
1
],
"trialPeriods": [
- 235
+ 237
],
"__typename": [
1
@@ -4421,7 +4467,7 @@ export default {
},
"Support": {
"supportDriver": [
- 244
+ 246
],
"supportFrontChatId": [
1
@@ -4447,7 +4493,7 @@ export default {
},
"Captcha": {
"provider": [
- 247
+ 249
],
"siteKey": [
1
@@ -4481,10 +4527,10 @@ export default {
},
"PublicFeatureFlag": {
"key": [
- 162
+ 164
],
"metadata": [
- 249
+ 251
],
"__typename": [
1
@@ -4495,13 +4541,13 @@ export default {
1
],
"authProviders": [
- 164
+ 166
],
"billing": [
- 242
+ 244
],
"aiModels": [
- 237
+ 239
],
"signInPrefilled": [
6
@@ -4522,28 +4568,28 @@ export default {
6
],
"support": [
- 243
+ 245
],
"isAttachmentPreviewEnabled": [
6
],
"sentry": [
- 245
+ 247
],
"captcha": [
- 246
+ 248
],
"chromeExtensionId": [
1
],
"api": [
- 248
+ 250
],
"canManageFeatureFlags": [
6
],
"publicFeatureFlags": [
- 250
+ 252
],
"isMicrosoftMessagingEnabled": [
6
@@ -4593,13 +4639,13 @@ export default {
6
],
"source": [
- 253
+ 255
],
"isEnvOnly": [
6
],
"type": [
- 254
+ 256
],
"options": [
15
@@ -4612,10 +4658,10 @@ export default {
"ConfigVariableType": {},
"ConfigVariablesGroupData": {
"variables": [
- 252
+ 254
],
"name": [
- 256
+ 258
],
"description": [
1
@@ -4630,7 +4676,7 @@ export default {
"ConfigVariablesGroup": {},
"ConfigVariables": {
"groups": [
- 255
+ 257
],
"__typename": [
1
@@ -4655,7 +4701,7 @@ export default {
21
],
"results": [
- 258
+ 260
],
"__typename": [
1
@@ -4672,7 +4718,7 @@ export default {
15
],
"state": [
- 261
+ 263
],
"timestamp": [
11
@@ -4722,7 +4768,7 @@ export default {
},
"QueueJobsResponse": {
"jobs": [
- 260
+ 262
],
"count": [
11
@@ -4734,7 +4780,7 @@ export default {
6
],
"retentionConfig": [
- 262
+ 264
],
"__typename": [
1
@@ -4745,7 +4791,7 @@ export default {
21
],
"results": [
- 258
+ 260
],
"__typename": [
1
@@ -4753,13 +4799,13 @@ export default {
},
"SystemHealthService": {
"id": [
- 266
+ 268
],
"label": [
1
],
"status": [
- 267
+ 269
],
"__typename": [
1
@@ -4769,7 +4815,7 @@ export default {
"AdminPanelHealthServiceStatus": {},
"SystemHealth": {
"services": [
- 265
+ 267
],
"__typename": [
1
@@ -4809,13 +4855,13 @@ export default {
11
],
"workspaceUrls": [
- 150
+ 152
],
"users": [
- 269
+ 271
],
"featureFlags": [
- 161
+ 163
],
"__typename": [
1
@@ -4823,10 +4869,10 @@ export default {
},
"UserLookup": {
"user": [
- 269
+ 271
],
"workspaces": [
- 270
+ 272
],
"__typename": [
1
@@ -4851,7 +4897,7 @@ export default {
1
],
"status": [
- 267
+ 269
],
"__typename": [
1
@@ -4859,7 +4905,7 @@ export default {
},
"AdminPanelHealthServiceData": {
"id": [
- 266
+ 268
],
"label": [
1
@@ -4868,7 +4914,7 @@ export default {
1
],
"status": [
- 267
+ 269
],
"errorMessage": [
1
@@ -4877,7 +4923,7 @@ export default {
1
],
"queues": [
- 273
+ 275
],
"__typename": [
1
@@ -4899,7 +4945,7 @@ export default {
1
],
"data": [
- 275
+ 277
],
"__typename": [
1
@@ -4942,13 +4988,13 @@ export default {
11
],
"timeRange": [
- 279
+ 281
],
"details": [
- 277
+ 279
],
"data": [
- 276
+ 278
],
"__typename": [
1
@@ -4957,10 +5003,10 @@ export default {
"QueueMetricsTimeRange": {},
"Impersonate": {
"loginToken": [
- 197
+ 199
],
"workspace": [
- 203
+ 205
],
"__typename": [
1
@@ -5054,7 +5100,7 @@ export default {
1
],
"fields": [
- 284
+ 286
],
"__typename": [
1
@@ -5151,10 +5197,10 @@ export default {
6
],
"objectPermissions": [
- 288
+ 290
],
"fieldPermissions": [
- 289
+ 291
],
"permissionFlags": [
1
@@ -5204,19 +5250,19 @@ export default {
1
],
"objects": [
- 285
+ 287
],
"fields": [
- 284
+ 286
],
"logicFunctions": [
- 286
+ 288
],
"frontComponents": [
- 287
+ 289
],
"defaultRole": [
- 290
+ 292
],
"sourcePackage": [
1
@@ -5276,13 +5322,13 @@ export default {
1
],
"driver": [
- 295
+ 297
],
"status": [
- 296
+ 298
],
"verificationRecords": [
- 293
+ 295
],
"verifiedAt": [
4
@@ -5329,7 +5375,7 @@ export default {
1
],
"location": [
- 298
+ 300
],
"__typename": [
1
@@ -5357,13 +5403,13 @@ export default {
},
"ImapSmtpCaldavConnectionParameters": {
"IMAP": [
- 300
+ 302
],
"SMTP": [
- 300
+ 302
],
"CALDAV": [
- 300
+ 302
],
"__typename": [
1
@@ -5383,7 +5429,7 @@ export default {
3
],
"connectionParameters": [
- 301
+ 303
],
"__typename": [
1
@@ -5447,7 +5493,7 @@ export default {
1
],
"series": [
- 306
+ 308
],
"xAxisLabel": [
1
@@ -5496,7 +5542,7 @@ export default {
1
],
"data": [
- 308
+ 310
],
"__typename": [
1
@@ -5504,7 +5550,7 @@ export default {
},
"LineChartData": {
"series": [
- 309
+ 311
],
"xAxisLabel": [
1
@@ -5541,7 +5587,7 @@ export default {
},
"PieChartData": {
"data": [
- 311
+ 313
],
"showLegend": [
6
@@ -5624,13 +5670,13 @@ export default {
},
"EventLogQueryResult": {
"records": [
- 314
+ 316
],
"totalCount": [
21
],
"pageInfo": [
- 315
+ 317
],
"__typename": [
1
@@ -5697,7 +5743,7 @@ export default {
32,
{
"input": [
- 318,
+ 320,
"LogicFunctionIdInput!"
]
}
@@ -5709,7 +5755,7 @@ export default {
15,
{
"input": [
- 318,
+ 320,
"LogicFunctionIdInput!"
]
}
@@ -5718,13 +5764,13 @@ export default {
1,
{
"input": [
- 318,
+ 320,
"LogicFunctionIdInput!"
]
}
],
"objectRecordCounts": [
- 174
+ 176
],
"object": [
46,
@@ -5736,7 +5782,7 @@ export default {
}
],
"objects": [
- 175,
+ 177,
{
"paging": [
39,
@@ -5883,7 +5929,7 @@ export default {
}
],
"indexMetadatas": [
- 169,
+ 171,
{
"paging": [
39,
@@ -5896,10 +5942,10 @@ export default {
}
],
"commandMenuItems": [
- 223
+ 225
],
"commandMenuItem": [
- 223,
+ 225,
{
"id": [
3,
@@ -5908,10 +5954,10 @@ export default {
}
],
"frontComponents": [
- 222
+ 224
],
"frontComponent": [
- 222,
+ 224,
{
"id": [
3,
@@ -5926,7 +5972,7 @@ export default {
25,
{
"input": [
- 320,
+ 322,
"AgentIdInput!"
]
}
@@ -5945,11 +5991,30 @@ export default {
"getMeteredProductsUsage": [
140
],
- "navigationMenuItems": [
- 214
- ],
- "navigationMenuItem": [
- 214,
+ "enterprisePortalSession": [
+ 1,
+ {
+ "returnUrlPath": [
+ 1
+ ]
+ }
+ ],
+ "enterpriseCheckoutSession": [
+ 1,
+ {
+ "billingInterval": [
+ 1
+ ]
+ }
+ ],
+ "enterpriseSubscriptionStatus": [
+ 145
+ ],
+ "navigationMenuItems": [
+ 216
+ ],
+ "navigationMenuItem": [
+ 216,
{
"id": [
3,
@@ -5964,7 +6029,7 @@ export default {
2,
{
"input": [
- 321,
+ 323,
"GetApiKeyInput!"
]
}
@@ -5973,13 +6038,13 @@ export default {
29
],
"findWorkspaceInvitations": [
- 147
+ 149
],
"getApprovedAccessDomains": [
- 145
+ 147
],
"getToolIndex": [
- 218
+ 220
],
"getToolInputSchema": [
15,
@@ -6000,7 +6065,7 @@ export default {
}
],
"fields": [
- 182,
+ 184,
{
"paging": [
39,
@@ -6019,7 +6084,7 @@ export default {
66
],
"getPublicWorkspaceDataByDomain": [
- 166,
+ 168,
{
"origin": [
1
@@ -6027,7 +6092,7 @@ export default {
}
],
"checkUserExists": [
- 211,
+ 213,
{
"email": [
1,
@@ -6039,7 +6104,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 212,
+ 214,
{
"inviteHash": [
1,
@@ -6057,7 +6122,7 @@ export default {
}
],
"validatePasswordResetToken": [
- 206,
+ 208,
{
"passwordResetToken": [
1,
@@ -6066,7 +6131,7 @@ export default {
}
],
"findApplicationRegistrationByClientId": [
- 186,
+ 188,
{
"clientId": [
1,
@@ -6096,7 +6161,7 @@ export default {
}
],
"findApplicationRegistrationStats": [
- 184,
+ 186,
{
"id": [
1,
@@ -6123,13 +6188,13 @@ export default {
}
],
"getSSOIdentityProviders": [
- 191
+ 193
],
"webhooks": [
- 234
+ 236
],
"webhook": [
- 234,
+ 236,
{
"id": [
3,
@@ -6138,7 +6203,7 @@ export default {
}
],
"chatThread": [
- 226,
+ 228,
{
"id": [
3,
@@ -6147,7 +6212,7 @@ export default {
}
],
"chatMessages": [
- 227,
+ 229,
{
"threadId": [
3,
@@ -6156,13 +6221,13 @@ export default {
}
],
"getAISystemPromptPreview": [
- 229
+ 231
],
"skills": [
- 220
+ 222
],
"skill": [
- 220,
+ 222,
{
"id": [
3,
@@ -6171,24 +6236,24 @@ export default {
}
],
"chatThreads": [
- 231,
+ 233,
{
"paging": [
39,
"CursorPaging!"
],
"filter": [
- 322,
+ 324,
"AgentChatThreadFilter!"
],
"sorting": [
- 325,
+ 327,
"[AgentChatThreadSort!]!"
]
}
],
"agentTurns": [
- 233,
+ 235,
{
"agentId": [
3,
@@ -6197,43 +6262,43 @@ export default {
}
],
"eventLogs": [
- 316,
+ 318,
{
"input": [
- 329,
+ 331,
"EventLogQueryInput!"
]
}
],
"pieChartData": [
- 312,
+ 314,
{
"input": [
- 333,
+ 335,
"PieChartDataInput!"
]
}
],
"lineChartData": [
- 310,
+ 312,
{
"input": [
- 334,
+ 336,
"LineChartDataInput!"
]
}
],
"barChartData": [
- 307,
+ 309,
{
"input": [
- 335,
+ 337,
"BarChartDataInput!"
]
}
],
"getConnectedImapSmtpCaldavAccount": [
- 302,
+ 304,
{
"id": [
3,
@@ -6242,7 +6307,7 @@ export default {
}
],
"getAutoCompleteAddress": [
- 297,
+ 299,
{
"address": [
1,
@@ -6261,7 +6326,7 @@ export default {
}
],
"getAddressDetails": [
- 299,
+ 301,
{
"placeId": [
1,
@@ -6274,40 +6339,40 @@ export default {
}
],
"getConfigVariablesGrouped": [
- 257
+ 259
],
"getSystemHealthStatus": [
- 268
+ 270
],
"getIndicatorHealthStatus": [
- 274,
+ 276,
{
"indicatorId": [
- 266,
+ 268,
"HealthIndicatorId!"
]
}
],
"getQueueMetrics": [
- 278,
+ 280,
{
"queueName": [
1,
"String!"
],
"timeRange": [
- 279
+ 281
]
}
],
"versionInfo": [
- 272
+ 274
],
"getAdminAiModels": [
- 241
+ 243
],
"getDatabaseConfigVariable": [
- 252,
+ 254,
{
"key": [
1,
@@ -6316,14 +6381,14 @@ export default {
}
],
"getQueueJobs": [
- 263,
+ 265,
{
"queueName": [
1,
"String!"
],
"state": [
- 261,
+ 263,
"JobState!"
],
"limit": [
@@ -6338,19 +6403,19 @@ export default {
7
],
"getPostgresCredentials": [
- 304
+ 306
],
"findManyPublicDomains": [
- 292
+ 294
],
"getEmailingDomains": [
- 294
+ 296
],
"findManyMarketplaceApps": [
- 291
+ 293
],
"findOneMarketplaceApp": [
- 291,
+ 293,
{
"universalIdentifier": [
1,
@@ -6378,7 +6443,7 @@ export default {
},
"LogicFunctionIdInput": {
"id": [
- 319
+ 321
],
"__typename": [
1
@@ -6403,16 +6468,16 @@ export default {
},
"AgentChatThreadFilter": {
"and": [
- 322
+ 324
],
"or": [
- 322
+ 324
],
"id": [
42
],
"updatedAt": [
- 323
+ 325
],
"__typename": [
1
@@ -6450,10 +6515,10 @@ export default {
4
],
"between": [
- 324
+ 326
],
"notBetween": [
- 324
+ 326
],
"__typename": [
1
@@ -6472,13 +6537,13 @@ export default {
},
"AgentChatThreadSort": {
"field": [
- 326
+ 328
],
"direction": [
- 327
+ 329
],
"nulls": [
- 328
+ 330
],
"__typename": [
1
@@ -6489,10 +6554,10 @@ export default {
"SortNulls": {},
"EventLogQueryInput": {
"table": [
- 330
+ 332
],
"filters": [
- 331
+ 333
],
"first": [
21
@@ -6513,7 +6578,7 @@ export default {
1
],
"dateRange": [
- 332
+ 334
],
"recordId": [
1
@@ -6574,7 +6639,7 @@ export default {
6,
{
"input": [
- 337,
+ 339,
"AddQuerySubscriptionInput!"
]
}
@@ -6583,7 +6648,7 @@ export default {
6,
{
"input": [
- 338,
+ 340,
"RemoveQueryFromEventStreamInput!"
]
}
@@ -6612,7 +6677,7 @@ export default {
122,
{
"type": [
- 339,
+ 341,
"AnalyticsType!"
],
"name": [
@@ -6630,7 +6695,7 @@ export default {
75,
{
"input": [
- 340,
+ 342,
"CreatePageLayoutWidgetInput!"
]
}
@@ -6643,7 +6708,7 @@ export default {
"String!"
],
"input": [
- 342,
+ 344,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -6661,7 +6726,7 @@ export default {
110,
{
"input": [
- 343,
+ 345,
"CreatePageLayoutTabInput!"
]
}
@@ -6674,7 +6739,7 @@ export default {
"String!"
],
"input": [
- 344,
+ 346,
"UpdatePageLayoutTabInput!"
]
}
@@ -6692,7 +6757,7 @@ export default {
111,
{
"input": [
- 345,
+ 347,
"CreatePageLayoutInput!"
]
}
@@ -6705,7 +6770,7 @@ export default {
"String!"
],
"input": [
- 346,
+ 348,
"UpdatePageLayoutInput!"
]
}
@@ -6727,7 +6792,7 @@ export default {
"String!"
],
"input": [
- 347,
+ 349,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -6736,7 +6801,7 @@ export default {
32,
{
"input": [
- 318,
+ 320,
"LogicFunctionIdInput!"
]
}
@@ -6745,16 +6810,16 @@ export default {
32,
{
"input": [
- 350,
+ 352,
"CreateLogicFunctionFromSourceInput!"
]
}
],
"executeOneLogicFunction": [
- 215,
+ 217,
{
"input": [
- 351,
+ 353,
"ExecuteOneLogicFunctionInput!"
]
}
@@ -6763,7 +6828,7 @@ export default {
6,
{
"input": [
- 352,
+ 354,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -6772,7 +6837,7 @@ export default {
46,
{
"input": [
- 354,
+ 356,
"CreateOneObjectInput!"
]
}
@@ -6781,7 +6846,7 @@ export default {
46,
{
"input": [
- 356,
+ 358,
"DeleteOneObjectInput!"
]
}
@@ -6790,7 +6855,7 @@ export default {
46,
{
"input": [
- 357,
+ 359,
"UpdateOneObjectInput!"
]
}
@@ -6799,7 +6864,7 @@ export default {
50,
{
"input": [
- 359,
+ 361,
"UpdateViewFieldInput!"
]
}
@@ -6808,7 +6873,7 @@ export default {
50,
{
"input": [
- 361,
+ 363,
"CreateViewFieldInput!"
]
}
@@ -6817,7 +6882,7 @@ export default {
50,
{
"inputs": [
- 361,
+ 363,
"[CreateViewFieldInput!]!"
]
}
@@ -6826,7 +6891,7 @@ export default {
50,
{
"input": [
- 362,
+ 364,
"DeleteViewFieldInput!"
]
}
@@ -6835,7 +6900,7 @@ export default {
50,
{
"input": [
- 363,
+ 365,
"DestroyViewFieldInput!"
]
}
@@ -6844,7 +6909,7 @@ export default {
60,
{
"input": [
- 364,
+ 366,
"CreateViewInput!"
]
}
@@ -6857,7 +6922,7 @@ export default {
"String!"
],
"input": [
- 365,
+ 367,
"UpdateViewInput!"
]
}
@@ -6884,7 +6949,7 @@ export default {
57,
{
"input": [
- 366,
+ 368,
"CreateViewSortInput!"
]
}
@@ -6893,7 +6958,7 @@ export default {
57,
{
"input": [
- 367,
+ 369,
"UpdateViewSortInput!"
]
}
@@ -6902,7 +6967,7 @@ export default {
6,
{
"input": [
- 369,
+ 371,
"DeleteViewSortInput!"
]
}
@@ -6911,7 +6976,7 @@ export default {
6,
{
"input": [
- 370,
+ 372,
"DestroyViewSortInput!"
]
}
@@ -6920,7 +6985,7 @@ export default {
56,
{
"input": [
- 371,
+ 373,
"CreateViewGroupInput!"
]
}
@@ -6929,7 +6994,7 @@ export default {
56,
{
"inputs": [
- 371,
+ 373,
"[CreateViewGroupInput!]!"
]
}
@@ -6938,7 +7003,7 @@ export default {
56,
{
"input": [
- 372,
+ 374,
"UpdateViewGroupInput!"
]
}
@@ -6947,7 +7012,7 @@ export default {
56,
{
"input": [
- 374,
+ 376,
"DeleteViewGroupInput!"
]
}
@@ -6956,7 +7021,7 @@ export default {
56,
{
"input": [
- 375,
+ 377,
"DestroyViewGroupInput!"
]
}
@@ -6965,7 +7030,7 @@ export default {
52,
{
"input": [
- 376,
+ 378,
"CreateViewFilterGroupInput!"
]
}
@@ -6978,7 +7043,7 @@ export default {
"String!"
],
"input": [
- 377,
+ 379,
"UpdateViewFilterGroupInput!"
]
}
@@ -7005,7 +7070,7 @@ export default {
54,
{
"input": [
- 378,
+ 380,
"CreateViewFilterInput!"
]
}
@@ -7014,7 +7079,7 @@ export default {
54,
{
"input": [
- 379,
+ 381,
"UpdateViewFilterInput!"
]
}
@@ -7023,7 +7088,7 @@ export default {
54,
{
"input": [
- 381,
+ 383,
"DeleteViewFilterInput!"
]
}
@@ -7032,7 +7097,7 @@ export default {
54,
{
"input": [
- 382,
+ 384,
"DestroyViewFilterInput!"
]
}
@@ -7041,7 +7106,7 @@ export default {
59,
{
"input": [
- 383,
+ 385,
"UpdateViewFieldGroupInput!"
]
}
@@ -7050,7 +7115,7 @@ export default {
59,
{
"input": [
- 385,
+ 387,
"CreateViewFieldGroupInput!"
]
}
@@ -7059,7 +7124,7 @@ export default {
59,
{
"inputs": [
- 385,
+ 387,
"[CreateViewFieldGroupInput!]!"
]
}
@@ -7068,7 +7133,7 @@ export default {
59,
{
"input": [
- 386,
+ 388,
"DeleteViewFieldGroupInput!"
]
}
@@ -7077,7 +7142,7 @@ export default {
59,
{
"input": [
- 387,
+ 389,
"DestroyViewFieldGroupInput!"
]
}
@@ -7086,31 +7151,31 @@ export default {
60,
{
"input": [
- 388,
+ 390,
"UpsertFieldsWidgetInput!"
]
}
],
"createCommandMenuItem": [
- 223,
+ 225,
{
"input": [
- 391,
+ 393,
"CreateCommandMenuItemInput!"
]
}
],
"updateCommandMenuItem": [
- 223,
+ 225,
{
"input": [
- 392,
+ 394,
"UpdateCommandMenuItemInput!"
]
}
],
"deleteCommandMenuItem": [
- 223,
+ 225,
{
"id": [
3,
@@ -7119,25 +7184,25 @@ export default {
}
],
"createFrontComponent": [
- 222,
+ 224,
{
"input": [
- 393,
+ 395,
"CreateFrontComponentInput!"
]
}
],
"updateFrontComponent": [
- 222,
+ 224,
{
"input": [
- 394,
+ 396,
"UpdateFrontComponentInput!"
]
}
],
"deleteFrontComponent": [
- 222,
+ 224,
{
"id": [
3,
@@ -7149,7 +7214,7 @@ export default {
25,
{
"input": [
- 396,
+ 398,
"CreateAgentInput!"
]
}
@@ -7158,7 +7223,7 @@ export default {
25,
{
"input": [
- 397,
+ 399,
"UpdateAgentInput!"
]
}
@@ -7167,52 +7232,52 @@ export default {
25,
{
"input": [
- 320,
+ 322,
"AgentIdInput!"
]
}
],
"uploadAIChatFile": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
]
}
],
"uploadWorkflowFile": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
]
}
],
"uploadWorkspaceLogo": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
]
}
],
"uploadWorkspaceMemberProfilePicture": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
]
}
],
"uploadFilesFieldFile": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
],
"fieldMetadataId": [
@@ -7222,10 +7287,10 @@ export default {
}
],
"uploadFilesFieldFileByUniversalIdentifier": [
- 146,
+ 148,
{
"file": [
- 398,
+ 400,
"Upload!"
],
"fieldMetadataUniversalIdentifier": [
@@ -7281,26 +7346,38 @@ export default {
"cancelSwitchMeteredPrice": [
143
],
+ "refreshEnterpriseValidityToken": [
+ 6
+ ],
+ "setEnterpriseKey": [
+ 144,
+ {
+ "enterpriseKey": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
"createNavigationMenuItem": [
- 214,
+ 216,
{
"input": [
- 399,
+ 401,
"CreateNavigationMenuItemInput!"
]
}
],
"updateNavigationMenuItem": [
- 214,
+ 216,
{
"input": [
- 400,
+ 402,
"UpdateOneNavigationMenuItemInput!"
]
}
],
"deleteNavigationMenuItem": [
- 214,
+ 216,
{
"id": [
3,
@@ -7312,7 +7389,7 @@ export default {
2,
{
"input": [
- 402,
+ 404,
"CreateApiKeyInput!"
]
}
@@ -7321,7 +7398,7 @@ export default {
2,
{
"input": [
- 403,
+ 405,
"UpdateApiKeyInput!"
]
}
@@ -7330,7 +7407,7 @@ export default {
2,
{
"input": [
- 404,
+ 406,
"RevokeApiKeyInput!"
]
}
@@ -7365,7 +7442,7 @@ export default {
29,
{
"createRoleInput": [
- 405,
+ 407,
"CreateRoleInput!"
]
}
@@ -7374,7 +7451,7 @@ export default {
29,
{
"updateRoleInput": [
- 406,
+ 408,
"UpdateRoleInput!"
]
}
@@ -7392,7 +7469,7 @@ export default {
16,
{
"upsertObjectPermissionsInput": [
- 408,
+ 410,
"UpsertObjectPermissionsInput!"
]
}
@@ -7401,7 +7478,7 @@ export default {
27,
{
"upsertPermissionFlagsInput": [
- 410,
+ 412,
"UpsertPermissionFlagsInput!"
]
}
@@ -7410,16 +7487,16 @@ export default {
26,
{
"upsertFieldPermissionsInput": [
- 411,
+ 413,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 179,
+ 181,
{
"input": [
- 413,
+ 415,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
@@ -7447,10 +7524,10 @@ export default {
}
],
"skipSyncEmailOnboardingStep": [
- 144
+ 146
],
"skipBookOnboardingStep": [
- 144
+ 146
],
"deleteWorkspaceInvitation": [
1,
@@ -7462,7 +7539,7 @@ export default {
}
],
"resendWorkspaceInvitation": [
- 148,
+ 150,
{
"appTokenId": [
1,
@@ -7471,7 +7548,7 @@ export default {
}
],
"sendInvitations": [
- 148,
+ 150,
{
"emails": [
1,
@@ -7483,10 +7560,10 @@ export default {
}
],
"createApprovedAccessDomain": [
- 145,
+ 147,
{
"input": [
- 416,
+ 418,
"CreateApprovedAccessDomainInput!"
]
}
@@ -7495,16 +7572,16 @@ export default {
6,
{
"input": [
- 417,
+ 419,
"DeleteApprovedAccessDomainInput!"
]
}
],
"validateApprovedAccessDomain": [
- 145,
+ 147,
{
"input": [
- 418,
+ 420,
"ValidateApprovedAccessDomainInput!"
]
}
@@ -7513,7 +7590,7 @@ export default {
34,
{
"input": [
- 419,
+ 421,
"CreateOneFieldMetadataInput!"
]
}
@@ -7522,7 +7599,7 @@ export default {
34,
{
"input": [
- 421,
+ 423,
"UpdateOneFieldMetadataInput!"
]
}
@@ -7531,7 +7608,7 @@ export default {
34,
{
"input": [
- 423,
+ 425,
"DeleteOneFieldInput!"
]
}
@@ -7561,7 +7638,7 @@ export default {
}
],
"resendEmailVerificationToken": [
- 149,
+ 151,
{
"email": [
1,
@@ -7577,7 +7654,7 @@ export default {
66,
{
"data": [
- 424,
+ 426,
"ActivateWorkspaceInput!"
]
}
@@ -7586,7 +7663,7 @@ export default {
66,
{
"data": [
- 425,
+ 427,
"UpdateWorkspaceInput!"
]
}
@@ -7595,19 +7672,19 @@ export default {
66
],
"checkCustomDomainValidRecords": [
- 160
+ 162
],
"getAuthorizationUrlForSSO": [
- 201,
+ 203,
{
"input": [
- 426,
+ 428,
"GetAuthorizationUrlForSSOInput!"
]
}
],
"getLoginTokenFromCredentials": [
- 210,
+ 212,
{
"email": [
1,
@@ -7633,7 +7710,7 @@ export default {
}
],
"signIn": [
- 199,
+ 201,
{
"email": [
1,
@@ -7655,7 +7732,7 @@ export default {
}
],
"verifyEmailAndGetLoginToken": [
- 207,
+ 209,
{
"emailVerificationToken": [
1,
@@ -7675,7 +7752,7 @@ export default {
}
],
"verifyEmailAndGetWorkspaceAgnosticToken": [
- 199,
+ 201,
{
"emailVerificationToken": [
1,
@@ -7691,7 +7768,7 @@ export default {
}
],
"getAuthTokensFromOTP": [
- 209,
+ 211,
{
"otp": [
1,
@@ -7711,7 +7788,7 @@ export default {
}
],
"signUp": [
- 199,
+ 201,
{
"email": [
1,
@@ -7733,7 +7810,7 @@ export default {
}
],
"signUpInWorkspace": [
- 204,
+ 206,
{
"email": [
1,
@@ -7764,13 +7841,13 @@ export default {
}
],
"signUpInNewWorkspace": [
- 204
+ 206
],
"generateTransientToken": [
- 205
+ 207
],
"getAuthTokensFromLoginToken": [
- 209,
+ 211,
{
"loginToken": [
1,
@@ -7783,7 +7860,7 @@ export default {
}
],
"authorizeApp": [
- 196,
+ 198,
{
"clientId": [
1,
@@ -7805,7 +7882,7 @@ export default {
}
],
"renewToken": [
- 209,
+ 211,
{
"appToken": [
1,
@@ -7814,7 +7891,7 @@ export default {
}
],
"generateApiKeyToken": [
- 208,
+ 210,
{
"apiKeyId": [
3,
@@ -7827,7 +7904,7 @@ export default {
}
],
"emailPasswordResetLink": [
- 200,
+ 202,
{
"email": [
1,
@@ -7839,7 +7916,7 @@ export default {
}
],
"updatePasswordViaResetToken": [
- 202,
+ 204,
{
"passwordResetToken": [
1,
@@ -7852,10 +7929,10 @@ export default {
}
],
"createApplicationRegistration": [
- 185,
+ 187,
{
"input": [
- 427,
+ 429,
"CreateApplicationRegistrationInput!"
]
}
@@ -7864,7 +7941,7 @@ export default {
7,
{
"input": [
- 428,
+ 430,
"UpdateApplicationRegistrationInput!"
]
}
@@ -7879,7 +7956,7 @@ export default {
}
],
"rotateApplicationRegistrationClientSecret": [
- 187,
+ 189,
{
"id": [
1,
@@ -7891,7 +7968,7 @@ export default {
5,
{
"input": [
- 430,
+ 432,
"CreateApplicationRegistrationVariableInput!"
]
}
@@ -7900,7 +7977,7 @@ export default {
5,
{
"input": [
- 431,
+ 433,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -7918,7 +7995,7 @@ export default {
7,
{
"file": [
- 398,
+ 400,
"Upload!"
],
"universalIdentifier": [
@@ -7940,7 +8017,7 @@ export default {
}
],
"initiateOTPProvisioning": [
- 194,
+ 196,
{
"loginToken": [
1,
@@ -7953,10 +8030,10 @@ export default {
}
],
"initiateOTPProvisioningForAuthenticatedUser": [
- 194
+ 196
],
"deleteTwoFactorAuthenticationMethod": [
- 193,
+ 195,
{
"twoFactorAuthenticationMethodId": [
3,
@@ -7965,7 +8042,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 195,
+ 197,
{
"otp": [
1,
@@ -7974,61 +8051,61 @@ export default {
}
],
"createOIDCIdentityProvider": [
- 192,
+ 194,
{
"input": [
- 433,
+ 435,
"SetupOIDCSsoInput!"
]
}
],
"createSAMLIdentityProvider": [
- 192,
+ 194,
{
"input": [
- 434,
+ 436,
"SetupSAMLSsoInput!"
]
}
],
"deleteSSOIdentityProvider": [
- 188,
+ 190,
{
"input": [
- 435,
+ 437,
"DeleteSsoInput!"
]
}
],
"editSSOIdentityProvider": [
- 189,
+ 191,
{
"input": [
- 436,
+ 438,
"EditSsoInput!"
]
}
],
"createWebhook": [
- 234,
+ 236,
{
"input": [
- 437,
+ 439,
"CreateWebhookInput!"
]
}
],
"updateWebhook": [
- 234,
+ 236,
{
"input": [
- 438,
+ 440,
"UpdateWebhookInput!"
]
}
],
"deleteWebhook": [
- 234,
+ 236,
{
"id": [
3,
@@ -8037,28 +8114,28 @@ export default {
}
],
"createChatThread": [
- 226
+ 228
],
"createSkill": [
- 220,
+ 222,
{
"input": [
- 440,
+ 442,
"CreateSkillInput!"
]
}
],
"updateSkill": [
- 220,
+ 222,
{
"input": [
- 441,
+ 443,
"UpdateSkillInput!"
]
}
],
"deleteSkill": [
- 220,
+ 222,
{
"id": [
3,
@@ -8067,7 +8144,7 @@ export default {
}
],
"activateSkill": [
- 220,
+ 222,
{
"id": [
3,
@@ -8076,7 +8153,7 @@ export default {
}
],
"deactivateSkill": [
- 220,
+ 222,
{
"id": [
3,
@@ -8085,7 +8162,7 @@ export default {
}
],
"evaluateAgentTurn": [
- 232,
+ 234,
{
"turnId": [
3,
@@ -8094,7 +8171,7 @@ export default {
}
],
"runEvaluationInput": [
- 233,
+ 235,
{
"agentId": [
3,
@@ -8107,7 +8184,7 @@ export default {
}
],
"duplicateDashboard": [
- 313,
+ 315,
{
"id": [
3,
@@ -8116,7 +8193,7 @@ export default {
}
],
"impersonate": [
- 280,
+ 282,
{
"userId": [
3,
@@ -8129,7 +8206,7 @@ export default {
}
],
"startChannelSync": [
- 305,
+ 307,
{
"connectedAccountId": [
3,
@@ -8138,7 +8215,7 @@ export default {
}
],
"saveImapSmtpCaldavAccount": [
- 303,
+ 305,
{
"accountOwnerId": [
3,
@@ -8149,7 +8226,7 @@ export default {
"String!"
],
"connectionParameters": [
- 442,
+ 444,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -8158,16 +8235,16 @@ export default {
}
],
"updateLabPublicFeatureFlag": [
- 161,
+ 163,
{
"input": [
- 444,
+ 446,
"UpdateLabPublicFeatureFlagInput!"
]
}
],
"userLookupAdminPanel": [
- 271,
+ 273,
{
"userIdentifier": [
1,
@@ -8241,7 +8318,7 @@ export default {
}
],
"retryJobs": [
- 264,
+ 266,
{
"queueName": [
1,
@@ -8254,7 +8331,7 @@ export default {
}
],
"deleteJobs": [
- 259,
+ 261,
{
"queueName": [
1,
@@ -8267,13 +8344,13 @@ export default {
}
],
"enablePostgresProxy": [
- 304
+ 306
],
"disablePostgresProxy": [
- 304
+ 306
],
"createPublicDomain": [
- 292,
+ 294,
{
"domain": [
1,
@@ -8291,7 +8368,7 @@ export default {
}
],
"checkPublicDomainValidRecords": [
- 160,
+ 162,
{
"domain": [
1,
@@ -8300,14 +8377,14 @@ export default {
}
],
"createEmailingDomain": [
- 294,
+ 296,
{
"domain": [
1,
"String!"
],
"driver": [
- 295,
+ 297,
"EmailingDomainDriver!"
]
}
@@ -8322,7 +8399,7 @@ export default {
}
],
"verifyEmailingDomain": [
- 294,
+ 296,
{
"id": [
1,
@@ -8334,7 +8411,7 @@ export default {
68,
{
"input": [
- 445,
+ 447,
"CreateOneAppTokenInput!"
]
}
@@ -8367,7 +8444,7 @@ export default {
6,
{
"workspaceMigration": [
- 447,
+ 449,
"WorkspaceMigrationInput!"
]
}
@@ -8399,7 +8476,7 @@ export default {
}
],
"createDevelopmentApplication": [
- 281,
+ 283,
{
"universalIdentifier": [
1,
@@ -8412,7 +8489,7 @@ export default {
}
],
"generateApplicationToken": [
- 221,
+ 223,
{
"applicationId": [
3,
@@ -8421,7 +8498,7 @@ export default {
}
],
"syncApplication": [
- 282,
+ 284,
{
"manifest": [
15,
@@ -8430,10 +8507,10 @@ export default {
}
],
"uploadApplicationFile": [
- 283,
+ 285,
{
"file": [
- 398,
+ 400,
"Upload!"
],
"applicationUniversalIdentifier": [
@@ -8441,7 +8518,7 @@ export default {
"String!"
],
"fileFolder": [
- 451,
+ 453,
"FileFolder!"
],
"filePath": [
@@ -8464,7 +8541,7 @@ export default {
}
],
"renewApplicationToken": [
- 221,
+ 223,
{
"applicationRefreshToken": [
1,
@@ -8516,7 +8593,7 @@ export default {
3
],
"gridPosition": [
- 341
+ 343
],
"position": [
15
@@ -8556,7 +8633,7 @@ export default {
3
],
"gridPosition": [
- 341
+ 343
],
"position": [
15
@@ -8638,7 +8715,7 @@ export default {
3
],
"tabs": [
- 348
+ 350
],
"__typename": [
1
@@ -8658,7 +8735,7 @@ export default {
1
],
"widgets": [
- 349
+ 351
],
"__typename": [
1
@@ -8681,7 +8758,7 @@ export default {
3
],
"gridPosition": [
- 341
+ 343
],
"position": [
15
@@ -8750,7 +8827,7 @@ export default {
3
],
"update": [
- 353
+ 355
],
"__typename": [
1
@@ -8796,7 +8873,7 @@ export default {
},
"CreateOneObjectInput": {
"object": [
- 355
+ 357
],
"__typename": [
1
@@ -8853,7 +8930,7 @@ export default {
},
"UpdateOneObjectInput": {
"update": [
- 358
+ 360
],
"id": [
3
@@ -8905,7 +8982,7 @@ export default {
3
],
"update": [
- 360
+ 362
],
"__typename": [
1
@@ -9104,7 +9181,7 @@ export default {
3
],
"update": [
- 368
+ 370
],
"__typename": [
1
@@ -9159,7 +9236,7 @@ export default {
3
],
"update": [
- 373
+ 375
],
"__typename": [
1
@@ -9272,7 +9349,7 @@ export default {
3
],
"update": [
- 380
+ 382
],
"__typename": [
1
@@ -9322,7 +9399,7 @@ export default {
3
],
"update": [
- 384
+ 386
],
"__typename": [
1
@@ -9386,10 +9463,10 @@ export default {
3
],
"groups": [
- 389
+ 391
],
"fields": [
- 390
+ 392
],
"__typename": [
1
@@ -9409,7 +9486,7 @@ export default {
6
],
"fields": [
- 390
+ 392
],
"__typename": [
1
@@ -9437,7 +9514,7 @@ export default {
3
],
"engineComponentKey": [
- 224
+ 226
],
"label": [
1
@@ -9455,7 +9532,7 @@ export default {
6
],
"availabilityType": [
- 225
+ 227
],
"conditionalAvailabilityExpression": [
1
@@ -9487,13 +9564,13 @@ export default {
6
],
"availabilityType": [
- 225
+ 227
],
"availabilityObjectMetadataId": [
3
],
"engineComponentKey": [
- 224
+ 226
],
"__typename": [
1
@@ -9530,7 +9607,7 @@ export default {
3
],
"update": [
- 395
+ 397
],
"__typename": [
1
@@ -9661,7 +9738,7 @@ export default {
3
],
"update": [
- 401
+ 403
],
"__typename": [
1
@@ -9778,7 +9855,7 @@ export default {
},
"UpdateRoleInput": {
"update": [
- 407
+ 409
],
"id": [
3
@@ -9833,7 +9910,7 @@ export default {
3
],
"objectPermissions": [
- 409
+ 411
],
"__typename": [
1
@@ -9875,7 +9952,7 @@ export default {
3
],
"fieldPermissions": [
- 412
+ 414
],
"__typename": [
1
@@ -9906,10 +9983,10 @@ export default {
3
],
"predicates": [
- 414
+ 416
],
"predicateGroups": [
- 415
+ 417
],
"__typename": [
1
@@ -9999,7 +10076,7 @@ export default {
},
"CreateOneFieldMetadataInput": {
"field": [
- 420
+ 422
],
"__typename": [
1
@@ -10072,7 +10149,7 @@ export default {
3
],
"update": [
- 422
+ 424
],
"__typename": [
1
@@ -10272,7 +10349,7 @@ export default {
1
],
"update": [
- 429
+ 431
],
"__typename": [
1
@@ -10335,7 +10412,7 @@ export default {
1
],
"update": [
- 432
+ 434
],
"__typename": [
1
@@ -10405,7 +10482,7 @@ export default {
3
],
"status": [
- 153
+ 155
],
"__typename": [
1
@@ -10436,7 +10513,7 @@ export default {
3
],
"update": [
- 439
+ 441
],
"__typename": [
1
@@ -10510,13 +10587,13 @@ export default {
},
"EmailAccountConnectionParameters": {
"IMAP": [
- 443
+ 445
],
"SMTP": [
- 443
+ 445
],
"CALDAV": [
- 443
+ 445
],
"__typename": [
1
@@ -10555,7 +10632,7 @@ export default {
},
"CreateOneAppTokenInput": {
"appToken": [
- 446
+ 448
],
"__typename": [
1
@@ -10571,7 +10648,7 @@ export default {
},
"WorkspaceMigrationInput": {
"actions": [
- 448
+ 450
],
"__typename": [
1
@@ -10579,10 +10656,10 @@ export default {
},
"WorkspaceMigrationDeleteActionInput": {
"type": [
- 449
+ 451
],
"metadataName": [
- 450
+ 452
],
"universalIdentifier": [
1
@@ -10599,7 +10676,7 @@ export default {
121,
{
"input": [
- 453,
+ 455,
"OnDbEventInput!"
]
}
@@ -10614,10 +10691,10 @@ export default {
}
],
"logicFunctionLogs": [
- 217,
+ 219,
{
"input": [
- 454,
+ 456,
"LogicFunctionLogsInput!"
]
}
diff --git a/packages/twenty-server/src/database/commands/cron-register-all.command.ts b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
index 6c2b5492a78..7a6352c688e 100644
--- a/packages/twenty-server/src/database/commands/cron-register-all.command.ts
+++ b/packages/twenty-server/src/database/commands/cron-register-all.command.ts
@@ -2,12 +2,14 @@ import { Logger } from '@nestjs/common';
import { Command, CommandRunner } from 'nest-commander';
-import { ApplicationVersionCheckCronCommand } from 'src/engine/core-modules/application/application-upgrade/crons/commands/application-version-check.cron.command';
import { MarketplaceCatalogSyncCronCommand } from 'src/engine/core-modules/application/application-marketplace/crons/commands/marketplace-catalog-sync.cron.command';
+import { ApplicationVersionCheckCronCommand } from 'src/engine/core-modules/application/application-upgrade/crons/commands/application-version-check.cron.command';
+import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
import { EventLogCleanupCronCommand } from 'src/engine/core-modules/event-logs/cleanup/commands/event-log-cleanup.cron.command';
+import { CronTriggerCronCommand } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/cron/cron-trigger.cron.command';
import { CheckPublicDomainsValidRecordsCronCommand } from 'src/engine/core-modules/public-domain/crons/commands/check-public-domains-valid-records.cron.command';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { CheckCustomDomainValidRecordsCronCommand } from 'src/engine/core-modules/workspace/crons/commands/check-custom-domain-valid-records.cron.command';
-import { CronTriggerCronCommand } from 'src/engine/core-modules/logic-function/logic-function-trigger/triggers/cron/cron-trigger.cron.command';
import { TrashCleanupCronCommand } from 'src/engine/trash-cleanup/commands/trash-cleanup.cron.command';
import { CleanOnboardingWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-onboarding-workspaces.cron.command';
import { CleanSuspendedWorkspacesCronCommand } from 'src/engine/workspace-manager/workspace-cleaner/commands/clean-suspended-workspaces.cron.command';
@@ -54,6 +56,8 @@ export class CronRegisterAllCommand extends CommandRunner {
private readonly cleanOnboardingWorkspacesCronCommand: CleanOnboardingWorkspacesCronCommand,
private readonly trashCleanupCronCommand: TrashCleanupCronCommand,
private readonly eventLogCleanupCronCommand: EventLogCleanupCronCommand,
+ private readonly enterpriseKeyValidationCronCommand: EnterpriseKeyValidationCronCommand,
+ private readonly twentyConfigService: TwentyConfigService,
private readonly marketplaceCatalogSyncCronCommand: MarketplaceCatalogSyncCronCommand,
private readonly applicationVersionCheckCronCommand: ApplicationVersionCheckCronCommand,
) {
@@ -148,6 +152,10 @@ export class CronRegisterAllCommand extends CommandRunner {
name: 'ApplicationVersionCheck',
command: this.applicationVersionCheckCronCommand,
},
+ {
+ name: 'EnterpriseKeyValidation',
+ command: this.enterpriseKeyValidationCronCommand,
+ },
];
let successCount = 0;
diff --git a/packages/twenty-server/src/database/commands/database-command.module.ts b/packages/twenty-server/src/database/commands/database-command.module.ts
index 42e1a61d616..7cad024640d 100644
--- a/packages/twenty-server/src/database/commands/database-command.module.ts
+++ b/packages/twenty-server/src/database/commands/database-command.module.ts
@@ -9,12 +9,15 @@ import { UpgradeVersionCommandModule } from 'src/database/commands/upgrade-versi
import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { ApiKeyModule } from 'src/engine/core-modules/api-key/api-key.module';
import { GenerateApiKeyCommand } from 'src/engine/core-modules/api-key/commands/generate-api-key.command';
-import { ApplicationUpgradeModule } from 'src/engine/core-modules/application/application-upgrade/application-upgrade.module';
import { MarketplaceModule } from 'src/engine/core-modules/application/application-marketplace/marketplace.module';
+import { ApplicationUpgradeModule } from 'src/engine/core-modules/application/application-upgrade/application-upgrade.module';
+import { EnterpriseKeyValidationCronCommand } from 'src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { EventLogCleanupModule } from 'src/engine/core-modules/event-logs/cleanup/event-log-cleanup.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { FileModule } from 'src/engine/core-modules/file/file.module';
import { PublicDomainModule } from 'src/engine/core-modules/public-domain/public-domain.module';
+import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
@@ -57,6 +60,8 @@ import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/au
TrashCleanupModule,
PublicDomainModule,
EventLogCleanupModule,
+ EnterpriseModule,
+ TwentyConfigModule,
MarketplaceModule,
ApplicationUpgradeModule,
],
@@ -65,6 +70,7 @@ import { AutomatedTriggerModule } from 'src/modules/workflow/workflow-trigger/au
ConfirmationQuestion,
CronRegisterAllCommand,
ListOrphanedWorkspaceEntitiesCommand,
+ EnterpriseKeyValidationCronCommand,
GenerateApiKeyCommand,
],
})
diff --git a/packages/twenty-server/src/engine/core-modules/app-token/app-token.entity.ts b/packages/twenty-server/src/engine/core-modules/app-token/app-token.entity.ts
index 984ca4679c3..43f698c1c7e 100644
--- a/packages/twenty-server/src/engine/core-modules/app-token/app-token.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/app-token/app-token.entity.ts
@@ -27,6 +27,7 @@ export enum AppTokenType {
PasswordResetToken = 'PASSWORD_RESET_TOKEN',
InvitationToken = 'INVITATION_TOKEN',
EmailVerificationToken = 'EMAIL_VERIFICATION_TOKEN',
+ EnterpriseValidityToken = 'ENTERPRISE_VALIDITY_TOKEN',
}
@Entity({ name: 'appToken', schema: 'core' })
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts
index ef406b5f49b..24c2b7abef0 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.exception.ts
@@ -29,6 +29,7 @@ export const AuthExceptionCode = appendCommonExceptionCode({
GOOGLE_API_AUTH_DISABLED: 'GOOGLE_API_AUTH_DISABLED',
MICROSOFT_API_AUTH_DISABLED: 'MICROSOFT_API_AUTH_DISABLED',
MISSING_ENVIRONMENT_VARIABLE: 'MISSING_ENVIRONMENT_VARIABLE',
+ ENTERPRISE_VALIDITY_TOKEN_NOT_VALID: 'ENTERPRISE_VALIDITY_TOKEN_NOT_VALID',
INVALID_JWT_TOKEN_TYPE: 'INVALID_JWT_TOKEN_TYPE',
TWO_FACTOR_AUTHENTICATION_PROVISION_REQUIRED:
'TWO_FACTOR_AUTHENTICATION_PROVISION_REQUIRED',
@@ -80,6 +81,8 @@ const getAuthExceptionUserFriendlyMessage = (
return msg`Two-factor authentication verification is required.`;
case AuthExceptionCode.USER_ALREADY_EXISTS:
return msg`A user with this email already exists.`;
+ case AuthExceptionCode.ENTERPRISE_VALIDITY_TOKEN_NOT_VALID:
+ return msg`Enterprise validity token is not valid.`;
case AuthExceptionCode.INTERNAL_SERVER_ERROR:
case AuthExceptionCode.INVALID_DATA:
case AuthExceptionCode.CLIENT_NOT_FOUND:
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
index e2652149eab..793221ac8ad 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.module.ts
@@ -37,6 +37,7 @@ import { DomainServerConfigModule } from 'src/engine/core-modules/domain/domain-
import { SubdomainManagerModule } from 'src/engine/core-modules/domain/subdomain-manager/subdomain-manager.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
import { EmailVerificationModule } from 'src/engine/core-modules/email-verification/email-verification.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { FileModule } from 'src/engine/core-modules/file/file.module';
@@ -120,6 +121,7 @@ import { JwtAuthStrategy } from './strategies/jwt.auth.strategy';
ApplicationModule,
WorkspaceCacheModule,
SecureHttpClientModule,
+ EnterpriseModule,
FileModule,
],
controllers: [
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 7c48fb102a1..30a38a09c8f 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
@@ -10,22 +10,22 @@ import {
AuthException,
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { GuardRedirectService } from 'src/engine/core-modules/guard-redirect/services/guard-redirect.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
@Injectable()
export class EnterpriseFeaturesEnabledGuard implements CanActivate {
constructor(
private readonly guardRedirectService: GuardRedirectService,
- private readonly twentyConfigService: TwentyConfigService,
+ private readonly enterprisePlanService: EnterprisePlanService,
) {}
canActivate(context: ExecutionContext): boolean {
try {
- if (!this.twentyConfigService.get('ENTERPRISE_KEY')) {
+ if (!this.enterprisePlanService.isValid()) {
throw new AuthException(
- 'Enterprise key missing',
- AuthExceptionCode.MISSING_ENVIRONMENT_VARIABLE,
+ 'Enterprise features are not enabled',
+ AuthExceptionCode.ENTERPRISE_VALIDITY_TOKEN_NOT_VALID,
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts
index 1f8b1099e94..8a0b0cdf53f 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/auth-graphql-api-exception-handler.util.ts
@@ -27,6 +27,7 @@ export const authGraphqlApiExceptionHandler = (exception: AuthException) => {
case AuthExceptionCode.MISSING_ENVIRONMENT_VARIABLE:
case AuthExceptionCode.INVALID_JWT_TOKEN_TYPE:
case AuthExceptionCode.USER_ALREADY_EXISTS:
+ case AuthExceptionCode.ENTERPRISE_VALIDITY_TOKEN_NOT_VALID:
throw new ForbiddenError(exception);
case AuthExceptionCode.GOOGLE_API_AUTH_DISABLED:
case AuthExceptionCode.MICROSOFT_API_AUTH_DISABLED:
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-exception-rest-status.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-exception-rest-status.util.ts
index 1eea3216d1f..1d50c55631b 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-exception-rest-status.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/get-auth-exception-rest-status.util.ts
@@ -23,6 +23,7 @@ export const getAuthExceptionRestStatus = (exception: AuthException) => {
case AuthExceptionCode.EMAIL_NOT_VERIFIED:
case AuthExceptionCode.INVALID_JWT_TOKEN_TYPE:
case AuthExceptionCode.USER_ALREADY_EXISTS:
+ case AuthExceptionCode.ENTERPRISE_VALIDITY_TOKEN_NOT_VALID:
return 403;
case AuthExceptionCode.TWO_FACTOR_AUTHENTICATION_PROVISION_REQUIRED:
case AuthExceptionCode.TWO_FACTOR_AUTHENTICATION_VERIFICATION_REQUIRED:
diff --git a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
index 4454d215e85..756f4079b54 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/billing.module.ts
@@ -32,6 +32,7 @@ import { BillingService } from 'src/engine/core-modules/billing/services/billing
import { MeteredCreditService } from 'src/engine/core-modules/billing/services/metered-credit.service';
import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { MessageQueueModule } from 'src/engine/core-modules/message-queue/message-queue.module';
@@ -66,6 +67,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
]),
DataSourceModule,
MetricsModule,
+ EnterpriseModule,
],
providers: [
BillingSubscriptionService,
diff --git a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
index 93e16d4cc29..33dcacf2a72 100644
--- a/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/billing/services/billing-subscription.service.ts
@@ -38,6 +38,7 @@ import { StripeCustomerService } from 'src/engine/core-modules/billing/stripe/se
import { StripeSubscriptionScheduleService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription-schedule.service';
import { StripeSubscriptionService } from 'src/engine/core-modules/billing/stripe/services/stripe-subscription.service';
import { getPlanKeyFromSubscription } from 'src/engine/core-modules/billing/utils/get-plan-key-from-subscription.util';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -61,6 +62,7 @@ export class BillingSubscriptionService {
@InjectRepository(BillingCustomerEntity)
private readonly billingCustomerRepository: Repository<BillingSubscriptionEntity>,
private readonly meteredCreditService: MeteredCreditService,
+ private readonly enterprisePlanService: EnterprisePlanService,
) {}
async getBillingSubscriptions(workspaceId: string) {
@@ -180,9 +182,7 @@ export class BillingSubscriptionService {
workspaceId: string,
): Promise<BillingEntitlementDTO[]> {
const isBillingEnabled = this.twentyConfigService.get('IS_BILLING_ENABLED');
- const hasValidEnterpriseKey = isDefined(
- this.twentyConfigService.get('ENTERPRISE_KEY'),
- );
+ const hasValidEnterprisePlan = this.enterprisePlanService.isValid();
const entitlements = isBillingEnabled
? await this.billingEntitlementRepository.find({
@@ -202,7 +202,7 @@ export class BillingSubscriptionService {
return Object.values(BillingEntitlementKey).map((key) => ({
key,
value:
- hasValidEnterpriseKey &&
+ hasValidEnterprisePlan &&
(!isBillingEnabled || (entitlementsByKey[key]?.value ?? false)),
}));
}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-key-validation-cron-pattern.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-key-validation-cron-pattern.constant.ts
new file mode 100644
index 00000000000..aac677ba02b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-key-validation-cron-pattern.constant.ts
@@ -0,0 +1,2 @@
+// Run daily at 4 AM UTC
+export const ENTERPRISE_KEY_VALIDATION_CRON_PATTERN = '0 4 * * *';
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-public-key.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-public-key.constant.ts
new file mode 100644
index 00000000000..a07662740a0
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-public-key.constant.ts
@@ -0,0 +1,26 @@
+// RS256 public key for verifying enterprise license JWTs signed by twenty.com
+// The corresponding private key is held exclusively by twenty.com
+export const ENTERPRISE_JWT_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAl12Me8NXrQhsgBTr8slx
+2lTZNJCLwWCIs3zRWZzuHelUgNj2wFEM7R7wx0v/OxQHoXzXqAbgEu67HHNXTAnA
+gcYGzjSqa6o8NZHqUrzjOgvP0Ck8EQYxNYrxHAiDUChMHsFNYvcx/savm6Pn1sTL
+gcYnGuuuAYdsV0L78N5WsdbSfyAPyPv5ULYMSci7OLGUBlIa55da9Qwmie1HC+J4
+MtSSnw9o9OzR1ekw9JxQdho+Rj1mQ9BuvBplGNLabolFZweYdYEyqXReRbqMmNz/
+EuZs6PhKiH6l3sXY6kocC0ZV25rFhHgOChVA91BE8a+Wj0MtGGI/UL/b21G3zsr7
+6wIDAQAB
+-----END PUBLIC KEY-----`;
+
+// Dev-only
+export const ENTERPRISE_JWT_DEV_PUBLIC_KEY = `-----BEGIN PUBLIC KEY-----
+MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAsHEWc84t399KlYyhRkBO
+QCXE8/HE/TKvMk35ccoUeZXnBNhuGpWcHuM6+6ekHiToT239hkBy+Bk/Ybd6wVrs
+Vn0Vc0KarRsmeOrJu+sVREL5AUWt0gitpBoNeBzdfgW8dzdyVKDSCUNvXzEOQKkT
++tmDYhvSs8VSmzer2juSaj4xQ35X/sM+Ea3IHFx8mf9d6fMAJ5u8AE0fAFD9XUbe
+Dmj1SnUz4yy11EeY48+wTguk9WBFjOsA/1Dnc6jL/MN8zH77xRlIs/iPjBriPhCN
+njn0rDVHHdat+3NqKlSbFcQPVzYicxDRXaakJ2IEJhxpEoOFWHJ9bNQKudRqfaoF
+BQIDAQAB
+-----END PUBLIC KEY-----`;
+
+// signed with ENTERPRISE_JWT_DEV_PRIVATE_KEY (expires 2125)
+export const ENTERPRISE_DEV_VALIDITY_TOKEN =
+ 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJkZXYtc3Vic2NyaXB0aW9uLWlkIiwic3RhdHVzIjoidmFsaWQiLCJpYXQiOjE3NzMzMDg4MzMsImV4cCI6NDg5NzUxMTIzM30.qhfrW_SV2Y86fWtWXsALlAVhxmMxylUUIefN0fki10Q2NTGGqFVXZrNn2WacJY37yq3m5y4WgwZw34ua6E0ff_YUXsrlY5OHJWHT9DMqKCRn-JujHJnnYp3VHLncy5CvxH5r9mfPFp-5AWe1pYeR1T63sTiejH3sfDrNE357SB7KVti8LCcnsJxEtXB2tRnvyvdun7A-GKoKYEIam-16ZRKKFs6GaWo8ObHdfm8yBt6uK4DZSGPWb644QyWh9FtDxbzJ0ti54DuHSlErLgIp1NNEsMA0MK7zFY7StRaOdt72rxE1ZHwN7e6HhweTU4ORVUPfYkjDFLB2fF7Pa7Kvdg';
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-default-expiration-days.constant.ts b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-default-expiration-days.constant.ts
new file mode 100644
index 00000000000..0f155e8e5ff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/constants/enterprise-validity-token-default-expiration-days.constant.ts
@@ -0,0 +1,5 @@
+/* @license Enterprise */
+
+const DAYS_TO_MS = (days: number) => days * 24 * 60 * 60 * 1000;
+
+export const ENTERPRISE_VALIDITY_TOKEN_DEFAULT_EXPIRATION_MS = DAYS_TO_MS(30);
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command.ts b/packages/twenty-server/src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command.ts
new file mode 100644
index 00000000000..181f0858af9
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/cron/command/enterprise-key-validation.cron.command.ts
@@ -0,0 +1,35 @@
+/* @license Enterprise */
+
+import { Command, CommandRunner } from 'nest-commander';
+
+import { ENTERPRISE_KEY_VALIDATION_CRON_PATTERN } from 'src/engine/core-modules/enterprise/constants/enterprise-key-validation-cron-pattern.constant';
+import { EnterpriseKeyValidationCronJob } from 'src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job';
+import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decorators/message-queue.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
+
+@Command({
+ name: 'cron:enterprise-key-validation',
+ description:
+ 'Starts a daily cron job to refresh the enterprise validity token',
+})
+export class EnterpriseKeyValidationCronCommand extends CommandRunner {
+ constructor(
+ @InjectMessageQueue(MessageQueue.cronQueue)
+ private readonly messageQueueService: MessageQueueService,
+ ) {
+ super();
+ }
+
+ async run(): Promise<void> {
+ await this.messageQueueService.addCron<undefined>({
+ jobName: EnterpriseKeyValidationCronJob.name,
+ data: undefined,
+ options: {
+ repeat: {
+ pattern: ENTERPRISE_KEY_VALIDATION_CRON_PATTERN,
+ },
+ },
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job.ts b/packages/twenty-server/src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job.ts
new file mode 100644
index 00000000000..42735c810ff
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job.ts
@@ -0,0 +1,74 @@
+/* @license Enterprise */
+
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { IsNull, Repository } from 'typeorm';
+
+import { SentryCronMonitor } from 'src/engine/core-modules/cron/sentry-cron-monitor.decorator';
+import { ENTERPRISE_KEY_VALIDATION_CRON_PATTERN } from 'src/engine/core-modules/enterprise/constants/enterprise-key-validation-cron-pattern.constant';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
+import { Process } from 'src/engine/core-modules/message-queue/decorators/process.decorator';
+import { Processor } from 'src/engine/core-modules/message-queue/decorators/processor.decorator';
+import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+
+@Injectable()
+@Processor(MessageQueue.cronQueue)
+export class EnterpriseKeyValidationCronJob {
+ private readonly logger = new Logger(EnterpriseKeyValidationCronJob.name);
+
+ constructor(
+ private readonly enterprisePlanService: EnterprisePlanService,
+ @InjectRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ ) {}
+
+ @Process(EnterpriseKeyValidationCronJob.name)
+ @SentryCronMonitor(
+ EnterpriseKeyValidationCronJob.name,
+ ENTERPRISE_KEY_VALIDATION_CRON_PATTERN,
+ )
+ async handle(): Promise<void> {
+ this.logger.log(
+ 'Starting enterprise validity token refresh and seat report...',
+ );
+
+ const refreshSuccess =
+ await this.enterprisePlanService.refreshValidityToken();
+
+ if (refreshSuccess) {
+ this.logger.log('Enterprise validity token refreshed successfully');
+ } else {
+ this.logger.warn(
+ 'Enterprise validity token refresh did not succeed. ' +
+ 'Existing validity token will continue to work until expiration.',
+ );
+ }
+
+ try {
+ const seatCount = await this.getActiveUserWorkspaceCount();
+
+ const reportSuccess =
+ await this.enterprisePlanService.reportSeats(seatCount);
+
+ if (reportSuccess) {
+ this.logger.log(`Reported ${seatCount} seats to enterprise API`);
+ } else {
+ this.logger.warn('Seat report did not succeed');
+ }
+ } catch (error) {
+ this.logger.warn(
+ `Failed to get seat count or report: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ );
+ }
+ }
+
+ private async getActiveUserWorkspaceCount(): Promise<number> {
+ const count = await this.userWorkspaceRepository.count({
+ where: { deletedAt: IsNull() },
+ });
+
+ return Math.max(1, count);
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-license-info.dto.ts b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-license-info.dto.ts
new file mode 100644
index 00000000000..0ff8ba149c7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-license-info.dto.ts
@@ -0,0 +1,18 @@
+/* @license Enterprise */
+
+import { Field, ObjectType } from '@nestjs/graphql';
+
+@ObjectType()
+export class EnterpriseLicenseInfoDTO {
+ @Field(() => Boolean)
+ isValid: boolean;
+
+ @Field(() => String, { nullable: true })
+ licensee: string | null;
+
+ @Field(() => Date, { nullable: true })
+ expiresAt: Date | null;
+
+ @Field(() => String, { nullable: true })
+ subscriptionId: string | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-subscription-status.dto.ts b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-subscription-status.dto.ts
new file mode 100644
index 00000000000..ccb28c04e61
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/enterprise-subscription-status.dto.ts
@@ -0,0 +1,24 @@
+/* @license Enterprise */
+
+import { Field, ObjectType } from '@nestjs/graphql';
+
+@ObjectType()
+export class EnterpriseSubscriptionStatusDTO {
+ @Field(() => String)
+ status: string;
+
+ @Field(() => String, { nullable: true })
+ licensee: string | null;
+
+ @Field(() => Date, { nullable: true })
+ expiresAt: Date | null;
+
+ @Field(() => Date, { nullable: true })
+ cancelAt: Date | null;
+
+ @Field(() => Date, { nullable: true })
+ currentPeriodEnd: Date | null;
+
+ @Field(() => Boolean)
+ isCancellationScheduled: boolean;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/dtos/set-enterprise-key.input.ts b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/set-enterprise-key.input.ts
new file mode 100644
index 00000000000..71690f2ebdf
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/dtos/set-enterprise-key.input.ts
@@ -0,0 +1,13 @@
+/* @license Enterprise */
+
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsString } from 'class-validator';
+
+@ArgsType()
+export class SetEnterpriseKeyInput {
+ @Field(() => String)
+ @IsString()
+ @IsNotEmpty()
+ enterpriseKey: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts
new file mode 100644
index 00000000000..f8524aa6c1e
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise-exception.filter.ts
@@ -0,0 +1,25 @@
+/* @license Enterprise */
+
+import { Catch, type ExceptionFilter } from '@nestjs/common';
+
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ EnterpriseException,
+ EnterpriseExceptionCode,
+} from 'src/engine/core-modules/enterprise/enterprise.exception';
+import { UserInputError } from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+
+@Catch(EnterpriseException)
+export class EnterpriseExceptionFilter implements ExceptionFilter {
+ catch(exception: EnterpriseException) {
+ switch (exception.code) {
+ case EnterpriseExceptionCode.INVALID_ENTERPRISE_KEY:
+ case EnterpriseExceptionCode.CONFIG_VARIABLES_IN_DB_DISABLED:
+ throw new UserInputError(exception);
+ default: {
+ assertUnreachable(exception.code);
+ }
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts
new file mode 100644
index 00000000000..332e52446a8
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.exception.ts
@@ -0,0 +1,38 @@
+/* @license Enterprise */
+
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { CustomException } from 'src/utils/custom-exception';
+
+export enum EnterpriseExceptionCode {
+ INVALID_ENTERPRISE_KEY = 'INVALID_ENTERPRISE_KEY',
+ CONFIG_VARIABLES_IN_DB_DISABLED = 'CONFIG_VARIABLES_IN_DB_DISABLED',
+}
+
+const getEnterpriseExceptionUserFriendlyMessage = (
+ code: EnterpriseExceptionCode,
+) => {
+ switch (code) {
+ case EnterpriseExceptionCode.INVALID_ENTERPRISE_KEY:
+ return msg`Invalid enterprise key.`;
+ case EnterpriseExceptionCode.CONFIG_VARIABLES_IN_DB_DISABLED:
+ return msg`IS_CONFIG_VARIABLES_IN_DB_ENABLED is false on your server. Please add ENTERPRISE_KEY to your .env file manually.`;
+ default:
+ assertUnreachable(code);
+ }
+};
+
+export class EnterpriseException extends CustomException<EnterpriseExceptionCode> {
+ constructor(
+ message: string,
+ code: EnterpriseExceptionCode,
+ { userFriendlyMessage }: { userFriendlyMessage?: MessageDescriptor } = {},
+ ) {
+ super(message, code, {
+ userFriendlyMessage:
+ userFriendlyMessage ?? getEnterpriseExceptionUserFriendlyMessage(code),
+ });
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts
new file mode 100644
index 00000000000..c08620f49b6
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.module.ts
@@ -0,0 +1,25 @@
+/* @license Enterprise */
+
+import { Module } from '@nestjs/common';
+import { TypeOrmModule } from '@nestjs/typeorm';
+
+import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
+import { EnterpriseKeyValidationCronJob } from 'src/engine/core-modules/enterprise/cron/jobs/enterprise-key-validation.cron.job';
+import { EnterpriseResolver } from 'src/engine/core-modules/enterprise/enterprise.resolver';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
+import { TwentyConfigModule } from 'src/engine/core-modules/twenty-config/twenty-config.module';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+
+@Module({
+ imports: [
+ TwentyConfigModule,
+ TypeOrmModule.forFeature([UserWorkspaceEntity, AppTokenEntity]),
+ ],
+ providers: [
+ EnterprisePlanService,
+ EnterpriseKeyValidationCronJob,
+ EnterpriseResolver,
+ ],
+ exports: [EnterprisePlanService, EnterpriseKeyValidationCronJob],
+})
+export class EnterpriseModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts
new file mode 100644
index 00000000000..8d26b8929c3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/enterprise.resolver.ts
@@ -0,0 +1,150 @@
+/* @license Enterprise */
+
+import { UseFilters, UseGuards, UsePipes } from '@nestjs/common';
+import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { IsNull, Repository } from 'typeorm';
+
+import { EnterpriseExceptionFilter } from 'src/engine/core-modules/enterprise/enterprise-exception.filter';
+import { EnterpriseLicenseInfoDTO } from 'src/engine/core-modules/enterprise/dtos/enterprise-license-info.dto';
+import { EnterpriseSubscriptionStatusDTO } from 'src/engine/core-modules/enterprise/dtos/enterprise-subscription-status.dto';
+import {
+ EnterpriseException,
+ EnterpriseExceptionCode,
+} from 'src/engine/core-modules/enterprise/enterprise.exception';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
+import { PreventNestToAutoLogGraphqlErrorsFilter } from 'src/engine/core-modules/graphql/filters/prevent-nest-to-auto-log-graphql-errors.filter';
+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
+import { ConfigVariableExceptionCode } from 'src/engine/core-modules/twenty-config/twenty-config.exception';
+import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { AdminPanelGuard } from 'src/engine/guards/admin-panel-guard';
+import { BillingDisabledGuard } from 'src/engine/guards/billing-disabled.guard';
+import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
+import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
+
+@Resolver()
+@UsePipes(ResolverValidationPipe)
+@UseFilters(EnterpriseExceptionFilter, PreventNestToAutoLogGraphqlErrorsFilter)
+export class EnterpriseResolver {
+ constructor(
+ private readonly enterprisePlanService: EnterprisePlanService,
+ @InjectRepository(UserWorkspaceEntity)
+ private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
+ ) {}
+
+ private async getActiveUserWorkspaceCount(): Promise<number> {
+ const count = await this.userWorkspaceRepository.count({
+ where: { deletedAt: IsNull() },
+ });
+
+ return Math.max(1, count);
+ }
+
+ @Query(() => String, { nullable: true })
+ @UseGuards(
+ WorkspaceAuthGuard,
+ BillingDisabledGuard,
+ AdminPanelGuard,
+ NoPermissionGuard,
+ )
+ async enterprisePortalSession(
+ // for existing subscriptions
+ @Args('returnUrlPath', { nullable: true }) returnUrlPath?: string,
+ ): Promise<string | null> {
+ return this.enterprisePlanService.getPortalUrl(returnUrlPath ?? undefined);
+ }
+
+ @Query(() => String, { nullable: true })
+ @UseGuards(
+ WorkspaceAuthGuard,
+ BillingDisabledGuard,
+ AdminPanelGuard,
+ NoPermissionGuard,
+ )
+ async enterpriseCheckoutSession(
+ // for new subscriptions
+ @Args('billingInterval', { nullable: true }) billingInterval?: string,
+ ): Promise<string | null> {
+ const interval = billingInterval === 'yearly' ? 'yearly' : 'monthly';
+ const seatCount = await this.getActiveUserWorkspaceCount();
+
+ return this.enterprisePlanService.getCheckoutUrl(interval, seatCount);
+ }
+
+ @Query(() => EnterpriseSubscriptionStatusDTO, { nullable: true })
+ @UseGuards(
+ WorkspaceAuthGuard,
+ BillingDisabledGuard,
+ AdminPanelGuard,
+ NoPermissionGuard,
+ )
+ async enterpriseSubscriptionStatus(): Promise<EnterpriseSubscriptionStatusDTO | null> {
+ return this.enterprisePlanService.getSubscriptionStatus();
+ }
+
+ @Mutation(() => Boolean)
+ @UseGuards(
+ WorkspaceAuthGuard,
+ BillingDisabledGuard,
+ AdminPanelGuard,
+ NoPermissionGuard,
+ )
+ async refreshEnterpriseValidityToken(): Promise<boolean> {
+ return this.enterprisePlanService.refreshValidityToken();
+ }
+
+ @Mutation(() => EnterpriseLicenseInfoDTO)
+ @UseGuards(
+ WorkspaceAuthGuard,
+ BillingDisabledGuard,
+ AdminPanelGuard,
+ NoPermissionGuard,
+ )
+ async setEnterpriseKey(
+ @Args('enterpriseKey') enterpriseKey: string,
+ ): Promise<EnterpriseLicenseInfoDTO> {
+ try {
+ if (
+ !this.enterprisePlanService.isValidEnterpriseKeyFormat(enterpriseKey)
+ ) {
+ throw new EnterpriseException(
+ 'Invalid enterprise key',
+ EnterpriseExceptionCode.INVALID_ENTERPRISE_KEY,
+ );
+ }
+
+ await this.enterprisePlanService.setEnterpriseKey(enterpriseKey);
+
+ await this.enterprisePlanService.refreshValidityToken();
+
+ const seatCount = await this.getActiveUserWorkspaceCount();
+
+ await this.enterprisePlanService.reportSeats(seatCount);
+
+ return await this.enterprisePlanService.getLicenseInfo();
+ } catch (error) {
+ if (error instanceof EnterpriseException) {
+ throw error;
+ }
+
+ if (
+ error instanceof Error &&
+ 'code' in error &&
+ error.code === ConfigVariableExceptionCode.DATABASE_CONFIG_DISABLED
+ ) {
+ throw new EnterpriseException(
+ 'IS_CONFIG_VARIABLES_IN_DB_ENABLED is false on the server. Please add ENTERPRISE_KEY to your .env file manually.',
+ EnterpriseExceptionCode.CONFIG_VARIABLES_IN_DB_DISABLED,
+ );
+ }
+
+ return {
+ isValid: false,
+ licensee: null,
+ expiresAt: null,
+ subscriptionId: null,
+ };
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/enterprise-plan.service.spec.ts b/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/enterprise-plan.service.spec.ts
new file mode 100644
index 00000000000..558cdedde31
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/__tests__/enterprise-plan.service.spec.ts
@@ -0,0 +1,806 @@
+/* @license Enterprise */
+
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
+import {
+ ConfigVariableException,
+ ConfigVariableExceptionCode,
+} from 'src/engine/core-modules/twenty-config/twenty-config.exception';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+const mockCryptoVerify = jest.fn();
+
+jest.mock('crypto', () => ({
+ ...jest.requireActual('crypto'),
+ verify: (...args: unknown[]) => mockCryptoVerify(...args),
+}));
+
+const createFakeJwt = (payload: Record<string, unknown>): string => {
+ const header = Buffer.from(
+ JSON.stringify({ alg: 'RS256', typ: 'JWT' }),
+ ).toString('base64url');
+ const body = Buffer.from(JSON.stringify(payload)).toString('base64url');
+ const signature = Buffer.from('fake-signature').toString('base64url');
+
+ return `${header}.${body}.${signature}`;
+};
+
+const MOCK_API_URL = 'https://enterprise.example.com';
+const FUTURE_TIMESTAMP = Math.floor(Date.now() / 1000) + 3600;
+const PAST_TIMESTAMP = Math.floor(Date.now() / 1000) - 3600;
+
+const MOCK_KEY_PAYLOAD = {
+ sub: 'sub-123',
+ licensee: 'ACME Corp',
+ iat: 1000,
+};
+
+const MOCK_VALIDITY_PAYLOAD = {
+ sub: 'sub-123',
+ status: 'valid',
+ iat: 1000,
+ exp: FUTURE_TIMESTAMP,
+};
+
+const MOCK_EXPIRED_VALIDITY_PAYLOAD = {
+ sub: 'sub-123',
+ status: 'valid',
+ iat: 1000,
+ exp: PAST_TIMESTAMP,
+};
+
+describe('EnterprisePlanService', () => {
+ let service: EnterprisePlanService;
+
+ const configGetMock = jest.fn();
+ const configSetMock = jest.fn();
+ const appTokenFindOneMock = jest.fn();
+ const transactionMock = jest.fn();
+ const fetchMock = jest.fn();
+
+ let originalFetch: typeof global.fetch;
+
+ const setupEnterpriseKey = (key?: string) => {
+ configGetMock.mockImplementation((configKey: string) => {
+ if (configKey === 'ENTERPRISE_KEY') return key;
+ if (configKey === 'ENTERPRISE_API_URL') return MOCK_API_URL;
+
+ return undefined;
+ });
+ };
+
+ const setupValidState = async (
+ overrides: {
+ keyPayload?: Record<string, unknown>;
+ validityPayload?: Record<string, unknown>;
+ cryptoVerifyResult?: boolean;
+ } = {},
+ ) => {
+ const {
+ keyPayload = MOCK_KEY_PAYLOAD,
+ validityPayload = MOCK_VALIDITY_PAYLOAD,
+ cryptoVerifyResult = true,
+ } = overrides;
+
+ const fakeKey = createFakeJwt(keyPayload);
+ const fakeValidityToken = createFakeJwt(validityPayload);
+
+ setupEnterpriseKey(fakeKey);
+ mockCryptoVerify.mockReturnValue(cryptoVerifyResult);
+ appTokenFindOneMock.mockResolvedValue({ value: fakeValidityToken });
+
+ await service.onModuleInit();
+ };
+
+ beforeEach(async () => {
+ jest.clearAllMocks();
+
+ originalFetch = global.fetch;
+ global.fetch = fetchMock as unknown as typeof fetch;
+
+ configGetMock.mockImplementation((key: string) => {
+ if (key === 'ENTERPRISE_API_URL') return MOCK_API_URL;
+
+ return undefined;
+ });
+
+ appTokenFindOneMock.mockResolvedValue(null);
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ EnterprisePlanService,
+ {
+ provide: TwentyConfigService,
+ useValue: {
+ get: configGetMock,
+ set: configSetMock,
+ },
+ },
+ {
+ provide: getRepositoryToken(AppTokenEntity),
+ useValue: {
+ findOne: appTokenFindOneMock,
+ target: AppTokenEntity,
+ manager: {
+ transaction: transactionMock,
+ },
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get<EnterprisePlanService>(EnterprisePlanService);
+ });
+
+ afterEach(() => {
+ global.fetch = originalFetch;
+ });
+
+ it('should be defined', () => {
+ expect(service).toBeDefined();
+ });
+
+ describe('onModuleInit', () => {
+ it('should populate caches when enterprise key and validity token exist', async () => {
+ await setupValidState();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(true);
+ expect(service.hasValidEnterpriseValidityToken()).toBe(true);
+ });
+
+ it('should handle missing enterprise key', async () => {
+ setupEnterpriseKey(undefined);
+ appTokenFindOneMock.mockResolvedValue(null);
+
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(false);
+ expect(service.hasValidEnterpriseValidityToken()).toBe(false);
+ });
+
+ it('should handle DB error when loading validity token', async () => {
+ setupEnterpriseKey(createFakeJwt(MOCK_KEY_PAYLOAD));
+ mockCryptoVerify.mockReturnValue(true);
+ appTokenFindOneMock.mockRejectedValue(new Error('DB connection failed'));
+
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(true);
+ expect(service.hasValidEnterpriseValidityToken()).toBe(false);
+ });
+
+ it('should fall back to ENTERPRISE_VALIDITY_TOKEN config when DB has no token', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+ const fakeValidityToken = createFakeJwt(MOCK_VALIDITY_PAYLOAD);
+
+ configGetMock.mockImplementation((key: string) => {
+ if (key === 'ENTERPRISE_KEY') return fakeKey;
+ if (key === 'ENTERPRISE_API_URL') return MOCK_API_URL;
+ if (key === 'ENTERPRISE_VALIDITY_TOKEN') return fakeValidityToken;
+
+ return undefined;
+ });
+ mockCryptoVerify.mockReturnValue(true);
+ appTokenFindOneMock.mockResolvedValue(null);
+
+ await service.onModuleInit();
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(true);
+ });
+
+ it('should prefer DB token over ENTERPRISE_VALIDITY_TOKEN config', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+ const dbToken = createFakeJwt(MOCK_VALIDITY_PAYLOAD);
+ const envToken = createFakeJwt(MOCK_EXPIRED_VALIDITY_PAYLOAD);
+
+ configGetMock.mockImplementation((key: string) => {
+ if (key === 'ENTERPRISE_KEY') return fakeKey;
+ if (key === 'ENTERPRISE_API_URL') return MOCK_API_URL;
+ if (key === 'ENTERPRISE_VALIDITY_TOKEN') return envToken;
+
+ return undefined;
+ });
+ mockCryptoVerify.mockReturnValue(true);
+ appTokenFindOneMock.mockResolvedValue({ value: dbToken });
+
+ await service.onModuleInit();
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(true);
+ });
+
+ it('should reject validity token with non-valid status', async () => {
+ const invalidStatusPayload = {
+ ...MOCK_VALIDITY_PAYLOAD,
+ status: 'revoked',
+ };
+
+ setupEnterpriseKey(createFakeJwt(MOCK_KEY_PAYLOAD));
+ mockCryptoVerify.mockReturnValue(true);
+ appTokenFindOneMock.mockResolvedValue({
+ value: createFakeJwt(invalidStatusPayload),
+ });
+
+ await service.onModuleInit();
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(false);
+ });
+ });
+
+ describe('hasValidSignedEnterpriseKey', () => {
+ it('should return false when no enterprise key is configured', async () => {
+ setupEnterpriseKey(undefined);
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(false);
+ });
+
+ it('should return true when key has valid signature', async () => {
+ setupEnterpriseKey(createFakeJwt(MOCK_KEY_PAYLOAD));
+ mockCryptoVerify.mockReturnValue(true);
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(true);
+ });
+
+ it('should return false when key has invalid signature', async () => {
+ setupEnterpriseKey(createFakeJwt(MOCK_KEY_PAYLOAD));
+ mockCryptoVerify.mockReturnValue(false);
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(false);
+ });
+
+ it('should return false when key is not a valid JWT format', async () => {
+ setupEnterpriseKey('not-a-jwt');
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(false);
+ });
+ });
+
+ describe('hasValidEnterpriseValidityToken', () => {
+ it('should return false when no validity token exists', async () => {
+ setupEnterpriseKey(undefined);
+ appTokenFindOneMock.mockResolvedValue(null);
+ await service.onModuleInit();
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(false);
+ });
+
+ it('should return true when validity token is valid and not expired', async () => {
+ await setupValidState();
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(true);
+ });
+
+ it('should return false when validity token is expired', async () => {
+ await setupValidState({
+ validityPayload: MOCK_EXPIRED_VALIDITY_PAYLOAD,
+ });
+
+ expect(service.hasValidEnterpriseValidityToken()).toBe(false);
+ });
+ });
+
+ describe('hasValidEnterpriseKey', () => {
+ it('should return true when signed enterprise key is valid', async () => {
+ await setupValidState();
+
+ expect(service.hasValidEnterpriseKey()).toBe(true);
+ });
+
+ it('should return true with legacy unsigned key as fallback', async () => {
+ setupEnterpriseKey('some-legacy-key');
+ mockCryptoVerify.mockReturnValue(false);
+ appTokenFindOneMock.mockResolvedValue(null);
+ await service.onModuleInit();
+
+ expect(service.hasValidSignedEnterpriseKey()).toBe(false);
+ expect(service.hasValidEnterpriseKey()).toBe(true);
+ });
+
+ it('should return false when no key is configured', async () => {
+ setupEnterpriseKey(undefined);
+ await service.onModuleInit();
+
+ expect(service.hasValidEnterpriseKey()).toBe(false);
+ });
+ });
+
+ describe('isValid', () => {
+ it('should return true when validity token is valid', async () => {
+ await setupValidState();
+
+ expect(service.isValid()).toBe(true);
+ });
+
+ it('should return true with legacy key as fallback', async () => {
+ setupEnterpriseKey('some-legacy-key');
+ mockCryptoVerify.mockReturnValue(false);
+ appTokenFindOneMock.mockResolvedValue(null);
+ await service.onModuleInit();
+
+ expect(service.isValid()).toBe(true);
+ });
+
+ it('should return false when no key or token exists', async () => {
+ setupEnterpriseKey(undefined);
+ appTokenFindOneMock.mockResolvedValue(null);
+ await service.onModuleInit();
+
+ expect(service.isValid()).toBe(false);
+ });
+ });
+
+ describe('isValidEnterpriseKeyFormat', () => {
+ it('should return true for valid JWT format', () => {
+ mockCryptoVerify.mockReturnValue(true);
+ const validKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+
+ expect(service.isValidEnterpriseKeyFormat(validKey)).toBe(true);
+ });
+
+ it('should return false for invalid JWT format', () => {
+ expect(service.isValidEnterpriseKeyFormat('not-a-jwt')).toBe(false);
+ });
+
+ it('should return false when signature verification fails', () => {
+ mockCryptoVerify.mockReturnValue(false);
+ const invalidKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+
+ expect(service.isValidEnterpriseKeyFormat(invalidKey)).toBe(false);
+ });
+ });
+
+ describe('getLicenseInfo', () => {
+ it('should return valid license info when validity token exists', async () => {
+ await setupValidState();
+
+ const licenseInfo = await service.getLicenseInfo();
+
+ expect(licenseInfo).toEqual({
+ isValid: true,
+ licensee: 'ACME Corp',
+ expiresAt: new Date(FUTURE_TIMESTAMP * 1000),
+ subscriptionId: 'sub-123',
+ });
+ });
+
+ it('should return expired license info when validity token is expired', async () => {
+ await setupValidState({
+ validityPayload: MOCK_EXPIRED_VALIDITY_PAYLOAD,
+ });
+
+ const licenseInfo = await service.getLicenseInfo();
+
+ expect(licenseInfo).toEqual({
+ isValid: false,
+ licensee: 'ACME Corp',
+ expiresAt: new Date(PAST_TIMESTAMP * 1000),
+ subscriptionId: 'sub-123',
+ });
+ });
+
+ it('should return legacy license info when only legacy key exists', async () => {
+ setupEnterpriseKey('some-legacy-key');
+ mockCryptoVerify.mockReturnValue(false);
+ appTokenFindOneMock.mockResolvedValue(null);
+
+ const licenseInfo = await service.getLicenseInfo();
+
+ expect(licenseInfo).toEqual({
+ isValid: true,
+ licensee: null,
+ expiresAt: null,
+ subscriptionId: null,
+ });
+ });
+
+ it('should return invalid license info when no key exists', async () => {
+ setupEnterpriseKey(undefined);
+ appTokenFindOneMock.mockResolvedValue(null);
+
+ const licenseInfo = await service.getLicenseInfo();
+
+ expect(licenseInfo).toEqual({
+ isValid: false,
+ licensee: null,
+ expiresAt: null,
+ subscriptionId: null,
+ });
+ });
+ });
+
+ describe('setEnterpriseKey', () => {
+ it('should set the enterprise key via config service', async () => {
+ configSetMock.mockResolvedValue(undefined);
+
+ await service.setEnterpriseKey('new-enterprise-key');
+
+ expect(configSetMock).toHaveBeenCalledWith(
+ 'ENTERPRISE_KEY',
+ 'new-enterprise-key',
+ );
+ });
+
+ it('should throw specific error when DB config is disabled', async () => {
+ configSetMock.mockRejectedValue(
+ new ConfigVariableException(
+ 'Database config disabled',
+ ConfigVariableExceptionCode.DATABASE_CONFIG_DISABLED,
+ ),
+ );
+
+ await expect(service.setEnterpriseKey('key')).rejects.toThrow(
+ 'IS_CONFIG_VARIABLES_IN_DB_ENABLED is false on your server',
+ );
+ });
+
+ it('should re-throw other errors', async () => {
+ configSetMock.mockRejectedValue(new Error('Unexpected error'));
+
+ await expect(service.setEnterpriseKey('key')).rejects.toThrow(
+ 'Unexpected error',
+ );
+ });
+ });
+
+ describe('refreshValidityToken', () => {
+ it('should return false when no enterprise key is configured', async () => {
+ setupEnterpriseKey(undefined);
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('should return false when key is not a valid signed JWT', async () => {
+ setupEnterpriseKey('not-a-valid-jwt');
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('should refresh and return true when API call succeeds', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+ const fakeValidityToken = createFakeJwt(MOCK_VALIDITY_PAYLOAD);
+
+ setupEnterpriseKey(fakeKey);
+ mockCryptoVerify.mockReturnValue(true);
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ validityToken: fakeValidityToken }),
+ });
+
+ transactionMock.mockImplementation(
+ async (callback: (manager: Record<string, jest.Mock>) => void) => {
+ await callback({
+ update: jest.fn(),
+ save: jest.fn(),
+ });
+ },
+ );
+
+ appTokenFindOneMock.mockResolvedValue({ value: fakeValidityToken });
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledWith(`${MOCK_API_URL}/validate`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enterpriseKey: fakeKey }),
+ });
+ });
+
+ it('should return false when API returns non-OK response', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+
+ setupEnterpriseKey(fakeKey);
+ mockCryptoVerify.mockReturnValue(true);
+
+ fetchMock.mockResolvedValue({
+ ok: false,
+ status: 401,
+ json: () => Promise.resolve({ error: 'Unauthorized' }),
+ });
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(false);
+ });
+
+ it('should return false when API response is missing validityToken', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+
+ setupEnterpriseKey(fakeKey);
+ mockCryptoVerify.mockReturnValue(true);
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({}),
+ });
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(false);
+ });
+
+ it('should return false on network error', async () => {
+ const fakeKey = createFakeJwt(MOCK_KEY_PAYLOAD);
+
+ setupEnterpriseKey(fakeKey);
+ mockCryptoVerify.mockReturnValue(true);
+
+ fetchMock.mockRejectedValue(new Error('Network error'));
+
+ const result = await service.refreshValidityToken();
+
+ expect(result).toBe(false);
+ });
+ });
+
+ describe('reportSeats', () => {
+ it('should return false when no enterprise key is configured', async () => {
+ setupEnterpriseKey(undefined);
+
+ const result = await service.reportSeats(10);
+
+ expect(result).toBe(false);
+ expect(fetchMock).not.toHaveBeenCalled();
+ });
+
+ it('should return false when key is not a valid signed JWT', async () => {
+ setupEnterpriseKey('not-a-valid-jwt');
+ appTokenFindOneMock.mockResolvedValue(null);
+ await service.onModuleInit();
+
+ const result = await service.reportSeats(10);
+
+ expect(result).toBe(false);
+ });
+
+ it('should report seats and return true on success', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ success: true }),
+ });
+
+ const result = await service.reportSeats(25);
+
+ expect(result).toBe(true);
+ expect(fetchMock).toHaveBeenCalledWith(
+ `${MOCK_API_URL}/seats`,
+ expect.objectContaining({
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+
+ const callBody = JSON.parse(
+ (fetchMock.mock.calls[0] as [string, { body: string }])[1].body,
+ );
+
+ expect(callBody.seatCount).toBe(25);
+ });
+
+ it('should return false when API returns non-OK response', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({ ok: false, status: 500 });
+
+ const result = await service.reportSeats(10);
+
+ expect(result).toBe(false);
+ });
+
+ it('should return false on network error', async () => {
+ await setupValidState();
+
+ fetchMock.mockRejectedValue(new Error('Connection refused'));
+
+ const result = await service.reportSeats(10);
+
+ expect(result).toBe(false);
+ });
+ });
+
+ describe('getSubscriptionStatus', () => {
+ it('should return null when no enterprise key is configured', async () => {
+ setupEnterpriseKey(undefined);
+
+ const result = await service.getSubscriptionStatus();
+
+ expect(result).toBeNull();
+ });
+
+ it('should return subscription status on success', async () => {
+ await setupValidState();
+
+ const cancelAtTimestamp = Math.floor(Date.now() / 1000) + 86400;
+ const periodEndTimestamp = Math.floor(Date.now() / 1000) + 2592000;
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ status: 'active',
+ cancelAt: cancelAtTimestamp,
+ currentPeriodEnd: periodEndTimestamp,
+ isCancellationScheduled: false,
+ }),
+ });
+
+ const result = await service.getSubscriptionStatus();
+
+ expect(result).toEqual({
+ status: 'active',
+ licensee: 'ACME Corp',
+ expiresAt: new Date(FUTURE_TIMESTAMP * 1000),
+ cancelAt: new Date(cancelAtTimestamp * 1000),
+ currentPeriodEnd: new Date(periodEndTimestamp * 1000),
+ isCancellationScheduled: false,
+ });
+ });
+
+ it('should return null when API returns non-OK response', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({ ok: false, status: 500 });
+
+ const result = await service.getSubscriptionStatus();
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null on network error', async () => {
+ await setupValidState();
+
+ fetchMock.mockRejectedValue(new Error('Network error'));
+
+ const result = await service.getSubscriptionStatus();
+
+ expect(result).toBeNull();
+ });
+
+ it('should handle null cancelAt and currentPeriodEnd', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () =>
+ Promise.resolve({
+ status: 'active',
+ cancelAt: null,
+ currentPeriodEnd: null,
+ }),
+ });
+
+ const result = await service.getSubscriptionStatus();
+
+ expect(result?.cancelAt).toBeNull();
+ expect(result?.currentPeriodEnd).toBeNull();
+ expect(result?.isCancellationScheduled).toBe(false);
+ });
+ });
+
+ describe('getPortalUrl', () => {
+ it('should return null when no API URL is configured', async () => {
+ configGetMock.mockReturnValue(undefined);
+
+ const result = await service.getPortalUrl();
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null when no valid enterprise key exists', async () => {
+ setupEnterpriseKey(undefined);
+
+ const result = await service.getPortalUrl();
+
+ expect(result).toBeNull();
+ });
+
+ it('should return portal URL on success', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ url: 'https://portal.example.com' }),
+ });
+
+ const result = await service.getPortalUrl('https://return.example.com');
+
+ expect(result).toBe('https://portal.example.com');
+ expect(fetchMock).toHaveBeenCalledWith(
+ `${MOCK_API_URL}/portal`,
+ expect.objectContaining({
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ }),
+ );
+ });
+
+ it('should return null when API fails', async () => {
+ await setupValidState();
+
+ fetchMock.mockResolvedValue({ ok: false, status: 500 });
+
+ const result = await service.getPortalUrl();
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null on network error', async () => {
+ await setupValidState();
+
+ fetchMock.mockRejectedValue(new Error('Network error'));
+
+ const result = await service.getPortalUrl();
+
+ expect(result).toBeNull();
+ });
+ });
+
+ describe('getCheckoutUrl', () => {
+ it('should return null when no API URL is configured', async () => {
+ configGetMock.mockReturnValue(undefined);
+
+ const result = await service.getCheckoutUrl('monthly', 5);
+
+ expect(result).toBeNull();
+ });
+
+ it('should return checkout URL on success', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({ url: 'https://checkout.example.com' }),
+ });
+
+ const result = await service.getCheckoutUrl('yearly', 10);
+
+ expect(result).toBe('https://checkout.example.com');
+ expect(fetchMock).toHaveBeenCalledWith(`${MOCK_API_URL}/checkout`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ billingInterval: 'yearly', seatCount: 10 }),
+ });
+ });
+
+ it('should return null when API fails', async () => {
+ fetchMock.mockResolvedValue({ ok: false, status: 500 });
+
+ const result = await service.getCheckoutUrl('monthly', 5);
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null on network error', async () => {
+ fetchMock.mockRejectedValue(new Error('Network error'));
+
+ const result = await service.getCheckoutUrl('monthly', 5);
+
+ expect(result).toBeNull();
+ });
+
+ it('should return null when API response has no url', async () => {
+ fetchMock.mockResolvedValue({
+ ok: true,
+ json: () => Promise.resolve({}),
+ });
+
+ const result = await service.getCheckoutUrl('monthly', 5);
+
+ expect(result).toBeNull();
+ });
+ });
+});
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
new file mode 100644
index 00000000000..535e59602be
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/services/enterprise-plan.service.ts
@@ -0,0 +1,532 @@
+/* @license Enterprise */
+
+import { Injectable, Logger, type OnModuleInit } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import * as crypto from 'crypto';
+
+import { isDefined } from 'twenty-shared/utils';
+import { IsNull, Repository } from 'typeorm';
+
+import {
+ AppTokenEntity,
+ AppTokenType,
+} from 'src/engine/core-modules/app-token/app-token.entity';
+import {
+ ENTERPRISE_JWT_DEV_PUBLIC_KEY,
+ ENTERPRISE_JWT_PUBLIC_KEY,
+} from 'src/engine/core-modules/enterprise/constants/enterprise-public-key.constant';
+import {
+ type EnterpriseKeyPayload,
+ type EnterpriseLicenseInfo,
+ type EnterpriseValidityPayload,
+} from 'src/engine/core-modules/enterprise/types/enterprise-key-payload.type';
+import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
+import {
+ ConfigVariableException,
+ ConfigVariableExceptionCode,
+} from 'src/engine/core-modules/twenty-config/twenty-config.exception';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+@Injectable()
+export class EnterprisePlanService implements OnModuleInit {
+ private readonly logger = new Logger(EnterprisePlanService.name);
+ private cachedValidityPayload: EnterpriseValidityPayload | null = null;
+ private cachedKeyPayload: EnterpriseKeyPayload | null = null;
+
+ constructor(
+ private readonly twentyConfigService: TwentyConfigService,
+ @InjectRepository(AppTokenEntity)
+ private readonly appTokenRepository: Repository<AppTokenEntity>,
+ ) {}
+
+ async onModuleInit() {
+ this.refreshKeyPayload();
+ await this.loadValidityToken();
+ }
+
+ private refreshKeyPayload(): void {
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (!enterpriseKey) {
+ this.cachedKeyPayload = null;
+
+ return;
+ }
+
+ const payload = this.verifyJwt<EnterpriseKeyPayload>(enterpriseKey);
+
+ this.cachedKeyPayload = payload;
+ }
+
+ private async loadValidityToken(): Promise<void> {
+ try {
+ const dbToken = await this.appTokenRepository.findOne({
+ where: {
+ type: AppTokenType.EnterpriseValidityToken,
+ userId: IsNull(),
+ workspaceId: IsNull(),
+ revokedAt: IsNull(),
+ },
+ order: { createdAt: 'DESC' },
+ });
+
+ const tokenValue =
+ dbToken?.value ??
+ this.twentyConfigService.get('ENTERPRISE_VALIDITY_TOKEN');
+
+ if (!tokenValue) {
+ this.cachedValidityPayload = null;
+
+ return;
+ }
+
+ const payload = this.verifyJwt<EnterpriseValidityPayload>(tokenValue);
+
+ if (payload && payload.status === 'valid') {
+ this.cachedValidityPayload = payload;
+ } else {
+ this.cachedValidityPayload = null;
+ }
+ } catch (error) {
+ this.logger.warn(
+ `Failed to load validity token: ${error instanceof Error ? error.message : 'Unknown error'}`,
+ );
+ this.cachedValidityPayload = null;
+ }
+ }
+
+ private async saveNewValidityTokenToDb(token: string): Promise<void> {
+ const payload = this.verifyJwt<EnterpriseValidityPayload>(token);
+
+ if (!isDefined(payload)) {
+ return;
+ }
+
+ await this.appTokenRepository.manager.transaction(
+ async (transactionalEntityManager) => {
+ await transactionalEntityManager.update(
+ this.appTokenRepository.target,
+ {
+ type: AppTokenType.EnterpriseValidityToken,
+ userId: IsNull(),
+ workspaceId: IsNull(),
+ revokedAt: IsNull(),
+ },
+ { revokedAt: new Date() },
+ );
+
+ await transactionalEntityManager.save(this.appTokenRepository.target, {
+ type: AppTokenType.EnterpriseValidityToken,
+ value: token,
+ userId: null,
+ workspaceId: null,
+ expiresAt: new Date(payload.exp * 1000),
+ });
+ },
+ );
+ }
+
+ hasValidSignedEnterpriseKey(): boolean {
+ this.refreshKeyPayload();
+ return isDefined(this.cachedKeyPayload);
+ }
+
+ hasValidEnterpriseValidityToken(): boolean {
+ if (isDefined(this.cachedValidityPayload)) {
+ const now = Math.floor(Date.now() / 1000);
+
+ return this.cachedValidityPayload.exp > now;
+ }
+
+ return false;
+ }
+
+ hasValidEnterpriseKey(): boolean {
+ if (this.hasValidSignedEnterpriseKey()) {
+ return true;
+ }
+
+ return this.checkLegacyKey();
+ }
+
+ isValid(): boolean {
+ if (this.hasValidEnterpriseValidityToken()) {
+ return true;
+ }
+
+ return this.checkLegacyKey(); // temporary
+ }
+
+ isValidEnterpriseKeyFormat(key: string): boolean {
+ return this.verifyJwt<EnterpriseKeyPayload>(key) !== null;
+ }
+
+ private checkLegacyKey(): boolean {
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (!isDefined(enterpriseKey)) {
+ return false;
+ }
+
+ this.logger.warn(
+ 'Unsigned enterprise keys are deprecated and will stop working ' +
+ 'in a future version. Please obtain a signed key from twenty.com.',
+ );
+
+ return true;
+ }
+
+ async getLicenseInfo(): Promise<EnterpriseLicenseInfo> {
+ this.refreshKeyPayload();
+ await this.loadValidityToken();
+
+ if (isDefined(this.cachedValidityPayload)) {
+ const now = Math.floor(Date.now() / 1000);
+
+ return {
+ isValid: this.cachedValidityPayload.exp > now,
+ licensee: this.cachedKeyPayload?.licensee ?? null,
+ expiresAt: new Date(this.cachedValidityPayload.exp * 1000),
+ subscriptionId: this.cachedValidityPayload.sub,
+ };
+ }
+
+ if (this.checkLegacyKey()) {
+ return {
+ isValid: true,
+ licensee: null,
+ expiresAt: null,
+ subscriptionId: null,
+ };
+ }
+
+ return {
+ isValid: false,
+ licensee: null,
+ expiresAt: null,
+ subscriptionId: null,
+ };
+ }
+
+ async setEnterpriseKey(enterpriseKey: string): Promise<void> {
+ try {
+ await this.twentyConfigService.set('ENTERPRISE_KEY', enterpriseKey);
+ } catch (error) {
+ if (
+ error instanceof ConfigVariableException &&
+ error.code === ConfigVariableExceptionCode.DATABASE_CONFIG_DISABLED
+ ) {
+ throw new ConfigVariableException(
+ 'IS_CONFIG_VARIABLES_IN_DB_ENABLED is false on your server. ' +
+ 'Please add ENTERPRISE_KEY to your .env file manually.',
+ ConfigVariableExceptionCode.DATABASE_CONFIG_DISABLED,
+ );
+ }
+
+ throw error;
+ }
+ }
+
+ async refreshValidityToken(): Promise<boolean> {
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (!enterpriseKey) {
+ this.logger.warn('No ENTERPRISE_KEY configured, skipping refresh');
+
+ return false;
+ }
+
+ this.refreshKeyPayload();
+
+ if (!isDefined(this.cachedKeyPayload)) {
+ this.logger.warn(
+ 'ENTERPRISE_KEY is not a valid signed JWT, skipping refresh',
+ );
+
+ return false;
+ }
+
+ const apiUrl = this.twentyConfigService.get('ENTERPRISE_API_URL');
+ const validateUrl = `${apiUrl}/validate`;
+
+ try {
+ const response = await fetch(validateUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enterpriseKey }),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+
+ this.logger.warn(
+ `Enterprise refresh failed with status ${response.status}: ${errorData.error ?? 'Unknown error'}`,
+ );
+
+ return false;
+ }
+
+ const data = await response.json();
+
+ if (!data.validityToken) {
+ this.logger.warn('Enterprise refresh response missing validityToken');
+
+ return false;
+ }
+
+ await this.saveNewValidityTokenToDb(data.validityToken);
+ await this.loadValidityToken();
+
+ this.logger.log('Enterprise validity token refreshed successfully');
+
+ return true;
+ } catch (error) {
+ this.logger.warn(
+ `Enterprise refresh failed: ${error instanceof Error ? error.message : 'Network error'}. Current validity token will continue to work until expiration.`,
+ );
+
+ return false;
+ }
+ }
+
+ async reportSeats(seatCount: number): Promise<boolean> {
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (!enterpriseKey) {
+ return false;
+ }
+
+ if (!isDefined(this.cachedKeyPayload)) {
+ return false;
+ }
+
+ const apiUrl = this.twentyConfigService.get('ENTERPRISE_API_URL');
+ const seatsUrl = `${apiUrl}/seats`;
+
+ try {
+ const response = await fetch(seatsUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enterpriseKey, seatCount }),
+ });
+
+ if (!response.ok) {
+ this.logger.warn(
+ `Seat reporting failed with status ${response.status}`,
+ );
+
+ return false;
+ }
+
+ this.logger.log(`Reported ${seatCount} seats to enterprise API`);
+
+ return true;
+ } catch (error) {
+ this.logger.warn(
+ `Seat reporting failed: ${error instanceof Error ? error.message : 'Network error'}`,
+ );
+
+ return false;
+ }
+ }
+
+ async getSubscriptionStatus(): Promise<{
+ status: string;
+ licensee: string | null;
+ expiresAt: Date | null;
+ cancelAt: Date | null;
+ currentPeriodEnd: Date | null;
+ isCancellationScheduled: boolean;
+ } | null> {
+ this.refreshKeyPayload();
+
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (!enterpriseKey || !isDefined(this.cachedKeyPayload)) {
+ return null;
+ }
+
+ const licenseInfo = await this.getLicenseInfo();
+ const apiUrl = this.twentyConfigService.get('ENTERPRISE_API_URL');
+ const statusUrl = `${apiUrl}/status`;
+
+ try {
+ const response = await fetch(statusUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enterpriseKey }),
+ });
+
+ if (!response.ok) {
+ this.logger.warn(
+ `Enterprise status request failed with status ${response.status}`,
+ );
+
+ return null;
+ }
+
+ const data = await response.json();
+
+ return {
+ status: data.status,
+ licensee: licenseInfo.licensee,
+ expiresAt: licenseInfo.expiresAt,
+ cancelAt: data.cancelAt ? new Date(data.cancelAt * 1000) : null,
+ currentPeriodEnd: data.currentPeriodEnd
+ ? new Date(data.currentPeriodEnd * 1000)
+ : null,
+ isCancellationScheduled: data.isCancellationScheduled ?? false,
+ };
+ } catch (error) {
+ this.logger.warn(
+ `Enterprise status request failed: ${error instanceof Error ? error.message : 'Network error'}`,
+ );
+
+ return null;
+ }
+ }
+
+ async getPortalUrl(returnUrl?: string): Promise<string | null> {
+ const apiUrl = this.twentyConfigService.get('ENTERPRISE_API_URL');
+
+ if (!apiUrl) {
+ return null;
+ }
+
+ this.refreshKeyPayload();
+ const enterpriseKey = this.twentyConfigService.get('ENTERPRISE_KEY');
+
+ if (enterpriseKey && isDefined(this.cachedKeyPayload)) {
+ return this.requestPortalUrlWithKey(apiUrl, enterpriseKey, returnUrl);
+ }
+
+ return null;
+ }
+
+ private async requestPortalUrlWithKey(
+ apiUrl: string,
+ enterpriseKey: string,
+ returnUrl?: string,
+ ): Promise<string | null> {
+ const portalUrl = `${apiUrl}/portal`;
+
+ try {
+ const response = await fetch(portalUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ enterpriseKey, returnUrl }),
+ });
+
+ if (!response.ok) {
+ this.logger.warn(
+ `Enterprise portal request failed with status ${response.status}`,
+ );
+
+ return null;
+ }
+
+ const data = await response.json();
+
+ return data.url ?? null;
+ } catch (error) {
+ this.logger.warn(
+ `Enterprise portal request failed: ${error instanceof Error ? error.message : 'Network error'}`,
+ );
+
+ return null;
+ }
+ }
+
+ async getCheckoutUrl(
+ billingInterval: 'monthly' | 'yearly' = 'monthly',
+ seatCount: number,
+ ): Promise<string | null> {
+ const apiUrl = this.twentyConfigService.get('ENTERPRISE_API_URL');
+
+ if (!apiUrl) {
+ return null;
+ }
+
+ const checkoutUrl = `${apiUrl}/checkout`;
+
+ try {
+ const response = await fetch(checkoutUrl, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ billingInterval, seatCount }),
+ });
+
+ if (!response.ok) {
+ this.logger.warn(
+ `Enterprise checkout request failed with status ${response.status}`,
+ );
+
+ return null;
+ }
+
+ const data = await response.json();
+
+ return data.url ?? null;
+ } catch (error) {
+ this.logger.warn(
+ `Enterprise checkout request failed: ${error instanceof Error ? error.message : 'Network error'}`,
+ );
+
+ return null;
+ }
+ }
+
+ private getPublicKey(): string {
+ const nodeEnv = this.twentyConfigService.get('NODE_ENV');
+
+ return nodeEnv === NodeEnvironment.DEVELOPMENT
+ ? ENTERPRISE_JWT_DEV_PUBLIC_KEY
+ : ENTERPRISE_JWT_PUBLIC_KEY;
+ }
+
+ private verifyJwt<T extends Record<string, unknown>>(
+ token: string,
+ ): T | null {
+ try {
+ const parts = token.split('.');
+
+ if (parts.length !== 3) {
+ return null;
+ }
+
+ const [encodedHeader, encodedPayload, signature] = parts;
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
+
+ const signatureBuffer = Buffer.from(
+ signature.replace(/-/g, '+').replace(/_/g, '/') +
+ '='.repeat((4 - (signature.length % 4)) % 4),
+ 'base64',
+ );
+
+ const isValid = crypto.verify(
+ 'sha256',
+ Buffer.from(signingInput),
+ {
+ key: this.getPublicKey(),
+ padding: crypto.constants.RSA_PKCS1_PADDING,
+ },
+ signatureBuffer,
+ );
+
+ if (!isValid) {
+ return null;
+ }
+
+ const payloadStr = Buffer.from(
+ encodedPayload.replace(/-/g, '+').replace(/_/g, '/') +
+ '='.repeat((4 - (encodedPayload.length % 4)) % 4),
+ 'base64',
+ ).toString('utf-8');
+
+ return JSON.parse(payloadStr) as T;
+ } catch {
+ return null;
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/enterprise/types/enterprise-key-payload.type.ts b/packages/twenty-server/src/engine/core-modules/enterprise/types/enterprise-key-payload.type.ts
new file mode 100644
index 00000000000..64a30d523fc
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/enterprise/types/enterprise-key-payload.type.ts
@@ -0,0 +1,19 @@
+export type EnterpriseKeyPayload = {
+ sub: string;
+ licensee: string;
+ iat: number;
+};
+
+export type EnterpriseValidityPayload = {
+ sub: string;
+ status: 'valid';
+ iat: number;
+ exp: number;
+};
+
+export type EnterpriseLicenseInfo = {
+ isValid: boolean;
+ licensee: string | null;
+ expiresAt: Date | null;
+ subscriptionId: string | null;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.module.ts b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.module.ts
index 2cf8d992904..2bd534b85db 100644
--- a/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/event-logs/event-logs.module.ts
@@ -5,6 +5,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ClickHouseModule } from 'src/database/clickHouse/clickHouse.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { GuardRedirectModule } from 'src/engine/core-modules/guard-redirect/guard-redirect.module';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
@@ -17,6 +18,7 @@ import { EventLogsService } from './event-logs.service';
ClickHouseModule,
PermissionsModule,
BillingModule,
+ EnterpriseModule,
GuardRedirectModule,
TypeOrmModule.forFeature([UserWorkspaceEntity]),
],
diff --git a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
index 952197b064b..648e31e7373 100644
--- a/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/message-queue/jobs.module.ts
@@ -11,18 +11,20 @@ import { UpdateSubscriptionQuantityJob } from 'src/engine/core-modules/billing/j
import { StripeModule } from 'src/engine/core-modules/billing/stripe/stripe.module';
import { EmailSenderJob } from 'src/engine/core-modules/email/email-sender.job';
import { EmailModule } from 'src/engine/core-modules/email/email.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { UpdateWorkspaceMemberEmailJob } from 'src/engine/core-modules/user/jobs/update-workspace-member-email.job';
import { UserVarsModule } from 'src/engine/core-modules/user/user-vars/user-vars.module';
import { UserModule } from 'src/engine/core-modules/user/user.module';
-import { WebhookJobModule } from 'src/engine/metadata-modules/webhook/jobs/webhook-job.module';
import { HandleWorkspaceMemberDeletedJob } from 'src/engine/core-modules/workspace/handle-workspace-member-deleted.job';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceModule } from 'src/engine/core-modules/workspace/workspace.module';
import { AiAgentMonitorModule } from 'src/engine/metadata-modules/ai/ai-agent-monitor/ai-agent-monitor.module';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
-import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
import { LogicFunctionModule } from 'src/engine/metadata-modules/logic-function/logic-function.module';
+import { NavigationMenuItemModule } from 'src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.module';
+import { ObjectMetadataModule } from 'src/engine/metadata-modules/object-metadata/object-metadata.module';
+import { WebhookJobModule } from 'src/engine/metadata-modules/webhook/jobs/webhook-job.module';
import { SubscriptionsModule } from 'src/engine/subscriptions/subscriptions.module';
import { CleanOnboardingWorkspacesJob } from 'src/engine/workspace-manager/workspace-cleaner/crons/clean-onboarding-workspaces.job';
import { CleanSuspendedWorkspacesJob } from 'src/engine/workspace-manager/workspace-cleaner/crons/clean-suspended-workspaces.job';
@@ -32,7 +34,6 @@ import { CalendarEventParticipantManagerModule } from 'src/modules/calendar/cale
import { CalendarModule } from 'src/modules/calendar/calendar.module';
import { AutoCompaniesAndContactsCreationJobModule } from 'src/modules/contact-creation-manager/jobs/auto-companies-and-contacts-creation-job.module';
import { FavoriteModule } from 'src/modules/favorite/favorite.module';
-import { NavigationMenuItemModule } from 'src/engine/metadata-modules/navigation-menu-item/navigation-menu-item.module';
import { MessagingModule } from 'src/modules/messaging/messaging.module';
import { TimelineJobModule } from 'src/modules/timeline/jobs/timeline-job.module';
import { TimelineActivityModule } from 'src/modules/timeline/timeline-activity.module';
@@ -67,6 +68,7 @@ import { WorkflowModule } from 'src/modules/workflow/workflow.module';
AuditJobModule,
AiAgentMonitorModule,
LogicFunctionModule,
+ EnterpriseModule,
],
providers: [
CleanSuspendedWorkspacesJob,
diff --git a/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts b/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts
index fda73a25497..888517e5b09 100644
--- a/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/sso/sso.module.ts
@@ -6,6 +6,7 @@ import { NestjsQueryTypeOrmModule } from '@ptc-org/nestjs-query-typeorm';
import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagEntity } from 'src/engine/core-modules/feature-flag/feature-flag.entity';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { GuardRedirectModule } from 'src/engine/core-modules/guard-redirect/guard-redirect.module';
@@ -23,6 +24,7 @@ import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permi
FeatureFlagEntity,
]),
BillingModule,
+ EnterpriseModule,
GuardRedirectModule,
PermissionsModule,
FeatureFlagModule,
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
index 24508d07987..e7ce5afd024 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/config-variables.ts
@@ -1536,6 +1536,24 @@ export class ConfigVariables {
@IsOptional()
ENTERPRISE_KEY: string;
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.SERVER_CONFIG,
+ isSensitive: true,
+ description:
+ 'Signed enterprise validity token (JWT). Used as fallback when no token is stored in the database.',
+ type: ConfigVariableType.STRING,
+ })
+ @IsOptional()
+ ENTERPRISE_VALIDITY_TOKEN: string;
+
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.SERVER_CONFIG,
+ description: 'Base URL for the Enterprise API on twenty.com',
+ type: ConfigVariableType.STRING,
+ })
+ @IsOptional()
+ ENTERPRISE_API_URL: string = 'https://twenty.com/api/enterprise';
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.OTHER,
description: 'Health monitoring time window in minutes',
diff --git a/packages/twenty-server/src/engine/core-modules/twenty-config/twenty-config.service.ts b/packages/twenty-server/src/engine/core-modules/twenty-config/twenty-config.service.ts
index 90eae6471fb..f5d46223fa6 100644
--- a/packages/twenty-server/src/engine/core-modules/twenty-config/twenty-config.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/twenty-config/twenty-config.service.ts
@@ -201,6 +201,10 @@ export class TwentyConfigService {
return this.get('TYPEORM_LOGGING');
}
+ isBillingEnabled(): boolean {
+ return this.get('IS_BILLING_ENABLED') === true;
+ }
+
private validateNotEnvOnly<T extends keyof ConfigVariables>(
key: T,
operation: string,
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
index 380f6323d8b..9fc98f4d14c 100644
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.module.ts
@@ -7,6 +7,7 @@ import { TypeORMModule } from 'src/database/typeorm/typeorm.module';
import { ApprovedAccessDomainModule } from 'src/engine/core-modules/approved-access-domain/approved-access-domain.module';
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { FileModule } from 'src/engine/core-modules/file/file.module';
import { OnboardingModule } from 'src/engine/core-modules/onboarding/onboarding.module';
@@ -49,6 +50,7 @@ import { WorkspaceDataSourceModule } from 'src/engine/workspace-datasource/works
TokenModule,
PermissionsModule,
OnboardingModule,
+ EnterpriseModule,
FeatureFlagModule,
],
services: [UserWorkspaceService],
diff --git a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
index 1bf41174e4b..ec625e4725b 100644
--- a/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-workspace/user-workspace.service.ts
@@ -572,4 +572,12 @@ export class UserWorkspaceService extends TypeOrmQueryService<UserWorkspaceEntit
),
};
}
+
+ public async getActiveUserWorkspaceCountTotal(): Promise<number> {
+ const count = await this.userWorkspaceRepository.count({
+ where: { deletedAt: IsNull() },
+ });
+
+ return Math.max(1, count);
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.module.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.module.ts
index 65a36e68752..39a67d3a25d 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.module.ts
@@ -14,6 +14,7 @@ import { DnsManagerModule } from 'src/engine/core-modules/dns-manager/dns-manage
import { CustomDomainManagerModule } from 'src/engine/core-modules/domain/custom-domain-manager/custom-domain-manager.module';
import { SubdomainManagerModule } from 'src/engine/core-modules/domain/subdomain-manager/subdomain-manager.module';
import { WorkspaceDomainsModule } from 'src/engine/core-modules/domain/workspace-domains/workspace-domains.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { FeatureFlagModule } from 'src/engine/core-modules/feature-flag/feature-flag.module';
import { FileModule } from 'src/engine/core-modules/file/file.module';
import { MetricsModule } from 'src/engine/core-modules/metrics/metrics.module';
@@ -29,6 +30,7 @@ import { WorkspaceGaugeService } from 'src/engine/core-modules/workspace/workspa
import { workspaceAutoResolverOpts } from 'src/engine/core-modules/workspace/workspace.auto-resolver-opts';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
import { WorkspaceResolver } from 'src/engine/core-modules/workspace/workspace.resolver';
+import { BillingDisabledGuard } from 'src/engine/guards/billing-disabled.guard';
import { AiAgentModule } from 'src/engine/metadata-modules/ai/ai-agent/ai-agent.module';
import { DataSourceModule } from 'src/engine/metadata-modules/data-source/data-source.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
@@ -76,6 +78,7 @@ import { WorkspaceManagerModule } from 'src/engine/workspace-manager/workspace-m
ViewModule,
WorkspaceManyOrAllFlatEntityMapsCacheModule,
ApplicationModule,
+ EnterpriseModule,
],
services: [WorkspaceService],
resolvers: workspaceAutoResolverOpts,
@@ -86,6 +89,7 @@ import { WorkspaceManagerModule } from 'src/engine/workspace-manager/workspace-m
WorkspaceResolver,
WorkspaceService,
WorkspaceGaugeService,
+ BillingDisabledGuard,
CheckCustomDomainValidRecordsCronCommand,
CheckCustomDomainValidRecordsCronJob,
],
diff --git a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
index 1ae160163d9..a4fde479ac8 100644
--- a/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/workspace/workspace.resolver.ts
@@ -25,6 +25,7 @@ import { DomainValidRecords } from 'src/engine/core-modules/dns-manager/dtos/dom
import { DnsManagerService } from 'src/engine/core-modules/dns-manager/services/dns-manager.service';
import { CustomDomainManagerService } from 'src/engine/core-modules/domain/custom-domain-manager/services/custom-domain-manager.service';
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { FeatureFlagDTO } from 'src/engine/core-modules/feature-flag/dtos/feature-flag.dto';
import { FeatureFlagService } from 'src/engine/core-modules/feature-flag/services/feature-flag.service';
import { FileUrlService } from 'src/engine/core-modules/file/file-url/file-url.service';
@@ -97,6 +98,7 @@ export class WorkspaceResolver {
private readonly dnsManagerService: DnsManagerService,
private readonly customDomainManagerService: CustomDomainManagerService,
private readonly applicationService: ApplicationService,
+ private readonly enterprisePlanService: EnterprisePlanService,
) {}
@Query(() => WorkspaceEntity)
@@ -174,7 +176,7 @@ export class WorkspaceResolver {
async billingSubscriptions(
@Parent() workspace: WorkspaceEntity,
): Promise<BillingSubscriptionEntity[] | undefined> {
- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
+ if (!this.twentyConfigService.isBillingEnabled()) {
return [];
}
@@ -272,7 +274,7 @@ export class WorkspaceResolver {
async currentBillingSubscription(
@Parent() workspace: WorkspaceEntity,
): Promise<BillingSubscriptionEntity | undefined> {
- if (!this.twentyConfigService.get('IS_BILLING_ENABLED')) {
+ if (!this.twentyConfigService.isBillingEnabled()) {
return;
}
@@ -310,7 +312,17 @@ export class WorkspaceResolver {
@ResolveField(() => Boolean)
hasValidEnterpriseKey(): boolean {
- return isDefined(this.twentyConfigService.get('ENTERPRISE_KEY'));
+ return this.enterprisePlanService.hasValidEnterpriseKey();
+ }
+
+ @ResolveField(() => Boolean)
+ hasValidSignedEnterpriseKey(): boolean {
+ return this.enterprisePlanService.hasValidSignedEnterpriseKey();
+ }
+
+ @ResolveField(() => Boolean)
+ hasValidEnterpriseValidityToken(): boolean {
+ return this.enterprisePlanService.hasValidEnterpriseValidityToken();
}
@ResolveField(() => WorkspaceUrlsDTO)
diff --git a/packages/twenty-server/src/engine/guards/billing-disabled.guard.ts b/packages/twenty-server/src/engine/guards/billing-disabled.guard.ts
new file mode 100644
index 00000000000..e83d8422c8a
--- /dev/null
+++ b/packages/twenty-server/src/engine/guards/billing-disabled.guard.ts
@@ -0,0 +1,16 @@
+import {
+ type CanActivate,
+ type ExecutionContext,
+ Injectable,
+} from '@nestjs/common';
+
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+
+@Injectable()
+export class BillingDisabledGuard implements CanActivate {
+ constructor(private readonly twentyConfigService: TwentyConfigService) {}
+
+ canActivate(_context: ExecutionContext): boolean {
+ return !this.twentyConfigService.isBillingEnabled();
+ }
+}
diff --git a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/row-level-permission.module.ts b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/row-level-permission.module.ts
index aa576004bb5..828cb74999b 100644
--- a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/row-level-permission.module.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/row-level-permission.module.ts
@@ -5,6 +5,7 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ApplicationModule } from 'src/engine/core-modules/application/application.module';
import { BillingModule } from 'src/engine/core-modules/billing/billing.module';
+import { EnterpriseModule } from 'src/engine/core-modules/enterprise/enterprise.module';
import { WorkspaceManyOrAllFlatEntityMapsCacheModule } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.module';
import { RowLevelPermissionPredicateGroupEntity } from 'src/engine/metadata-modules/row-level-permission-predicate/entities/row-level-permission-predicate-group.entity';
import { RowLevelPermissionPredicateEntity } from 'src/engine/metadata-modules/row-level-permission-predicate/entities/row-level-permission-predicate.entity';
@@ -24,6 +25,7 @@ import { WorkspaceMigrationModule } from 'src/engine/workspace-manager/workspace
WorkspaceMigrationModule,
BillingModule,
ApplicationModule,
+ EnterpriseModule,
],
providers: [
RowLevelPermissionPredicateService,
diff --git a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
index 9a291f26ac2..96293405344 100644
--- a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate-group.service.ts
@@ -8,7 +8,7 @@ import { Repository } from 'typeorm';
import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { findFlatEntityByIdInFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-id-in-flat-entity-maps.util';
import { fromFlatRowLevelPermissionPredicateGroupToDto } from 'src/engine/metadata-modules/flat-row-level-permission-predicate/utils/from-flat-row-level-permission-predicate-group-to-dto.util';
@@ -24,7 +24,7 @@ export class RowLevelPermissionPredicateGroupService {
private readonly billingService: BillingService,
@InjectRepository(RowLevelPermissionPredicateGroupEntity)
private readonly rowLevelPermissionPredicateGroupRepository: Repository<RowLevelPermissionPredicateGroupEntity>,
- private readonly twentyConfigService: TwentyConfigService,
+ private readonly enterprisePlanService: EnterprisePlanService,
) {}
async findByWorkspaceId(
@@ -136,9 +136,7 @@ export class RowLevelPermissionPredicateGroupService {
private async hasRowLevelPermissionFeature(
workspaceId: string,
): Promise<boolean> {
- const hasValidEnterpriseKey = isDefined(
- this.twentyConfigService.get('ENTERPRISE_KEY'),
- );
+ const hasValidEnterprisePlan = this.enterprisePlanService.isValid();
const isRowLevelPermissionEnabled =
await this.billingService.hasEntitlement(
@@ -146,6 +144,6 @@ export class RowLevelPermissionPredicateGroupService {
BillingEntitlementKey.RLS,
);
- return hasValidEnterpriseKey && isRowLevelPermissionEnabled;
+ return hasValidEnterprisePlan && isRowLevelPermissionEnabled;
}
}
diff --git a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate.service.ts b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate.service.ts
index 654fdb1237a..c907fc869ca 100644
--- a/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate.service.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/row-level-permission-predicate/services/row-level-permission-predicate.service.ts
@@ -9,7 +9,7 @@ import { ApplicationService } from 'src/engine/core-modules/application/applicat
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { BillingEntitlementKey } from 'src/engine/core-modules/billing/enums/billing-entitlement-key.enum';
import { BillingService } from 'src/engine/core-modules/billing/services/billing.service';
-import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { EnterprisePlanService } from 'src/engine/core-modules/enterprise/services/enterprise-plan.service';
import { WorkspaceManyOrAllFlatEntityMapsCacheService } from 'src/engine/metadata-modules/flat-entity/services/workspace-many-or-all-flat-entity-maps-cache.service';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { type FlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-maps.type';
@@ -46,8 +46,8 @@ export class RowLevelPermissionPredicateService {
private readonly flatEntityMapsCacheService: WorkspaceManyOrAllFlatEntityMapsCacheService,
private readonly workspaceCacheService: WorkspaceCacheService,
private readonly billingService: BillingService,
- private readonly twentyConfigService: TwentyConfigService,
private readonly applicationService: ApplicationService,
+ private readonly enterprisePlanService: EnterprisePlanService,
) {}
async findByWorkspaceId(
@@ -555,9 +555,7 @@ export class RowLevelPermissionPredicateService {
private async hasRowLevelPermissionFeature(
workspaceId: string,
): Promise<boolean> {
- const hasValidEnterpriseKey = isDefined(
- this.twentyConfigService.get('ENTERPRISE_KEY'),
- );
+ const hasValidEnterprisePlan = this.enterprisePlanService.isValid();
const isRowLevelPermissionEnabled =
await this.billingService.hasEntitlement(
@@ -565,7 +563,7 @@ export class RowLevelPermissionPredicateService {
BillingEntitlementKey.RLS,
);
- return hasValidEnterpriseKey && isRowLevelPermissionEnabled;
+ return hasValidEnterprisePlan && isRowLevelPermissionEnabled;
}
private async hasRowLevelPermissionFeatureOrThrow(workspaceId: string) {
diff --git a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-core-schema.util.ts b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-core-schema.util.ts
index 5d4ecc6d1ce..eb473e1ffa1 100644
--- a/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-core-schema.util.ts
+++ b/packages/twenty-server/src/engine/workspace-manager/dev-seeder/core/utils/seed-core-schema.util.ts
@@ -10,6 +10,7 @@ import {
} from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
import { seedAgents } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-agents.util';
import { seedApiKeys } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-api-keys.util';
+
import { seedFeatureFlags } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-feature-flags.util';
import { seedServerId } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-server-id.util';
import { seedUserWorkspaces } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
diff --git a/packages/twenty-shared/src/types/SettingsPath.ts b/packages/twenty-shared/src/types/SettingsPath.ts
index abd2902f680..f988d56b09b 100644
--- a/packages/twenty-shared/src/types/SettingsPath.ts
+++ b/packages/twenty-shared/src/types/SettingsPath.ts
@@ -10,6 +10,7 @@ export enum SettingsPath {
NewImapSmtpCaldavConnection = 'accounts/new-imap-smtp-caldav-connection',
EditImapSmtpCaldavConnection = 'accounts/edit-imap-smtp-caldav-connection/:connectedAccountId',
Billing = 'billing',
+ Enterprise = 'enterprise',
Objects = 'objects',
ObjectOverview = 'objects/overview',
ObjectDetail = 'objects/:objectNamePlural',
@@ -55,6 +56,7 @@ export enum SettingsPath {
EventLogs = 'security/event-logs',
AdminPanel = 'admin-panel',
+ AdminPanelEnterprise = 'admin-panel#enterprise',
AdminPanelHealthStatus = 'admin-panel#health-status',
AdminPanelIndicatorHealthStatus = 'admin-panel/health-status/:indicatorId',
AdminPanelQueueDetail = 'admin-panel/health-status/queue/:queueName',
diff --git a/packages/twenty-website/package.json b/packages/twenty-website/package.json
index 1432c62c823..5d0fcdb6792 100644
--- a/packages/twenty-website/package.json
+++ b/packages/twenty-website/package.json
@@ -27,6 +27,7 @@
"next-runtime-env": "^3.3.0",
"postgres": "^3.4.3",
"react-tooltip": "^5.13.1",
+ "stripe": "^20.3.1",
"twenty-ui": "workspace:*"
},
"devDependencies": {
diff --git a/packages/twenty-website/src/app/(public)/enterprise/activate/page.tsx b/packages/twenty-website/src/app/(public)/enterprise/activate/page.tsx
new file mode 100644
index 00000000000..554dcf50891
--- /dev/null
+++ b/packages/twenty-website/src/app/(public)/enterprise/activate/page.tsx
@@ -0,0 +1,172 @@
+'use client';
+
+import { useSearchParams } from 'next/navigation';
+import { useEffect, useState } from 'react';
+
+import { ContentContainer } from '@/app/_components/ui/layout/ContentContainer';
+
+type ActivationResult = {
+ enterpriseKey: string;
+ licensee: string;
+ subscriptionId: string;
+};
+
+export default function EnterpriseActivatePage() {
+ const searchParams = useSearchParams();
+ const sessionId = searchParams.get('session_id');
+ const [result, setResult] = useState<ActivationResult | null>(null);
+ const [error, setError] = useState<string | null>(null);
+ const [loading, setLoading] = useState(true);
+ const [copied, setCopied] = useState(false);
+
+ useEffect(() => {
+ if (!sessionId) {
+ setError('No session ID provided. Please complete the checkout first.');
+ setLoading(false);
+
+ return;
+ }
+
+ const activate = async () => {
+ try {
+ const response = await fetch(
+ `/api/enterprise/activate?session_id=${sessionId}`,
+ );
+ const data = await response.json();
+
+ if (!response.ok) {
+ setError(data.error || 'Activation failed');
+
+ return;
+ }
+
+ setResult(data);
+ } catch {
+ setError('Failed to activate enterprise key. Please try again.');
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ activate();
+ }, [sessionId]);
+
+ const handleCopy = async () => {
+ if (!result) return;
+
+ await navigator.clipboard.writeText(result.enterpriseKey);
+ setCopied(true);
+ setTimeout(() => setCopied(false), 2000);
+ };
+
+ return (
+ <ContentContainer>
+ <div style={{ minHeight: '60vh', marginTop: '50px', maxWidth: '700px' }}>
+ <h1 style={{ fontSize: '2rem', marginBottom: '1rem' }}>
+ Enterprise Activation
+ </h1>
+
+ {loading && <p>Activating your enterprise license...</p>}
+
+ {error && (
+ <div
+ style={{
+ padding: '1rem',
+ background: '#fef2f2',
+ border: '1px solid #fecaca',
+ borderRadius: '8px',
+ color: '#dc2626',
+ }}
+ >
+ {error}
+ </div>
+ )}
+
+ {result && (
+ <div>
+ <p style={{ marginBottom: '1rem', color: '#16a34a' }}>
+ Your enterprise license has been activated successfully.
+ </p>
+
+ <div style={{ marginBottom: '1.5rem' }}>
+ <strong>Licensee:</strong> {result.licensee}
+ </div>
+
+ <div style={{ marginBottom: '0.5rem' }}>
+ <strong>Your Enterprise Key:</strong>
+ </div>
+ <p
+ style={{
+ fontSize: '0.875rem',
+ color: '#6b7280',
+ marginBottom: '0.5rem',
+ }}
+ >
+ Copy this key and paste it into your Twenty self-hosted instance
+ settings.
+ </p>
+
+ <div
+ style={{
+ position: 'relative',
+ background: '#f3f4f6',
+ border: '1px solid #d1d5db',
+ borderRadius: '8px',
+ padding: '1rem',
+ fontFamily: 'monospace',
+ fontSize: '0.75rem',
+ wordBreak: 'break-all',
+ lineHeight: '1.5',
+ }}
+ >
+ {result.enterpriseKey}
+ <button
+ onClick={handleCopy}
+ style={{
+ position: 'absolute',
+ top: '0.5rem',
+ right: '0.5rem',
+ padding: '0.375rem 0.75rem',
+ background: copied ? '#16a34a' : '#111827',
+ color: 'white',
+ border: 'none',
+ borderRadius: '4px',
+ cursor: 'pointer',
+ fontSize: '0.75rem',
+ }}
+ >
+ {copied ? 'Copied!' : 'Copy'}
+ </button>
+ </div>
+
+ <div
+ style={{
+ marginTop: '2rem',
+ padding: '1rem',
+ background: '#eff6ff',
+ border: '1px solid #bfdbfe',
+ borderRadius: '8px',
+ }}
+ >
+ <strong>Next steps:</strong>
+ <ol
+ style={{
+ marginTop: '0.5rem',
+ paddingLeft: '1.25rem',
+ lineHeight: '1.75',
+ }}
+ >
+ <li>Copy the enterprise key above</li>
+ <li>
+ Open your Twenty self-hosted instance Settings &rarr;
+ Enterprise
+ </li>
+ <li>Paste the key and click Activate</li>
+ </ol>
+ </div>
+ </div>
+ )}
+ </div>
+ </ContentContainer>
+ );
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/activate/route.ts b/packages/twenty-website/src/app/api/enterprise/activate/route.ts
new file mode 100644
index 00000000000..eb629cb6ca9
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/activate/route.ts
@@ -0,0 +1,62 @@
+import { signEnterpriseKey } from '@/shared/enterprise/enterprise-jwt';
+import { getStripeClient } from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function GET(request: Request) {
+ try {
+ const url = new URL(request.url);
+ const sessionId = url.searchParams.get('session_id');
+
+ if (!sessionId) {
+ return new Response(
+ JSON.stringify({ error: 'Missing session_id parameter' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const stripe = getStripeClient();
+
+ const session = await stripe.checkout.sessions.retrieve(sessionId, {
+ expand: ['subscription', 'customer'],
+ });
+
+ if (session.payment_status !== 'paid') {
+ return new Response(
+ JSON.stringify({ error: 'Payment not completed' }),
+ { status: 402, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const subscription = session.subscription;
+
+ if (!subscription || typeof subscription === 'string') {
+ return new Response(
+ JSON.stringify({ error: 'Subscription not found' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const customer = session.customer;
+ const licensee =
+ customer && typeof customer !== 'string' && !customer.deleted
+ ? (customer.name ?? customer.email ?? 'Unknown')
+ : 'Unknown';
+
+ const enterpriseKey = signEnterpriseKey(subscription.id, licensee);
+
+ return Response.json({
+ enterpriseKey,
+ licensee,
+ subscriptionId: subscription.id,
+ });
+ } catch (error: unknown) {
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Activation error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/checkout/route.ts b/packages/twenty-website/src/app/api/enterprise/checkout/route.ts
new file mode 100644
index 00000000000..302a95f39fd
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/checkout/route.ts
@@ -0,0 +1,47 @@
+import {
+ getEnterprisePriceId,
+ getStripeClient,
+} from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ try {
+ const stripe = getStripeClient();
+ const body = await request.json();
+ const billingInterval = body.billingInterval === 'yearly' ? 'yearly' : 'monthly';
+ const priceId = getEnterprisePriceId(billingInterval);
+ const successUrl =
+ body.successUrl ??
+ `${process.env.NEXT_PUBLIC_WEBSITE_URL}/enterprise/activate?session_id={CHECKOUT_SESSION_ID}`;
+
+
+ const session = await stripe.checkout.sessions.create({
+ mode: 'subscription',
+ line_items: [
+ {
+ price: priceId,
+ quantity: body.seatCount ?? 1,
+ },
+ ],
+ success_url: successUrl,
+ subscription_data: {
+ trial_period_days: 30,
+ metadata: {
+ source: 'enterprise-self-hosted',
+ },
+ },
+ });
+
+ return Response.json({ url: session.url });
+ } catch (error: unknown) {
+ console.error(error);
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Checkout error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/portal/route.ts b/packages/twenty-website/src/app/api/enterprise/portal/route.ts
new file mode 100644
index 00000000000..f9e4ac3a1aa
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/portal/route.ts
@@ -0,0 +1,57 @@
+import { verifyEnterpriseKey } from '@/shared/enterprise/enterprise-jwt';
+import {
+ getStripeClient
+} from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { enterpriseKey, returnUrl } = body;
+
+ if (!enterpriseKey || typeof enterpriseKey !== 'string') {
+ return new Response(
+ JSON.stringify({ error: 'Missing enterpriseKey' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const payload = verifyEnterpriseKey(enterpriseKey);
+
+ if (!payload) {
+ return new Response(
+ JSON.stringify({ error: 'Invalid enterprise key' }),
+ { status: 403, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const stripe = getStripeClient();
+ const subscription = await stripe.subscriptions.retrieve(payload.sub);
+
+ const customerId =
+ typeof subscription.customer === 'string'
+ ? subscription.customer
+ : subscription.customer.id;
+
+ const frontendUrl = process.env.NEXT_PUBLIC_WEBSITE_URL;
+ const fullReturnUrl = returnUrl
+ ? `${frontendUrl}${returnUrl}`
+ : frontendUrl;
+
+ const session = await stripe.billingPortal.sessions.create({
+ customer: customerId,
+ return_url: fullReturnUrl,
+ });
+
+ return Response.json({ url: session.url });
+ } catch (error: unknown) {
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Portal error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/seats/route.ts b/packages/twenty-website/src/app/api/enterprise/seats/route.ts
new file mode 100644
index 00000000000..367bcd114d7
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/seats/route.ts
@@ -0,0 +1,89 @@
+import { verifyEnterpriseKey } from '@/shared/enterprise/enterprise-jwt';
+import { getStripeClient } from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { enterpriseKey, seatCount } = body;
+
+ if (!enterpriseKey || typeof enterpriseKey !== 'string') {
+ return new Response(
+ JSON.stringify({ error: 'Missing enterpriseKey' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ if (typeof seatCount !== 'number' || seatCount < 1) {
+ return new Response(
+ JSON.stringify({ error: 'Invalid seatCount' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const payload = verifyEnterpriseKey(enterpriseKey);
+
+ if (!payload) {
+ return new Response(
+ JSON.stringify({ error: 'Invalid enterprise key' }),
+ { status: 403, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const stripe = getStripeClient();
+
+ const subscription = await stripe.subscriptions.retrieve(payload.sub);
+
+ const NON_UPDATABLE_STATUSES = [
+ 'canceled',
+ 'incomplete_expired',
+ ];
+
+ if (
+ NON_UPDATABLE_STATUSES.includes(subscription.status) ||
+ subscription.cancel_at_period_end
+ ) {
+ return Response.json({
+ success: false,
+ reason: 'Subscription is canceled or scheduled for cancellation',
+ seatCount: subscription.items.data[0]?.quantity ?? 0,
+ subscriptionId: payload.sub,
+ });
+ }
+
+ if (!subscription.items.data[0]) {
+ return new Response(
+ JSON.stringify({ error: 'No subscription item found' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const subscriptionItemId = subscription.items.data[0].id;
+
+ await stripe.subscriptions.update(payload.sub, {
+ items: [
+ {
+ id: subscriptionItemId,
+ quantity: seatCount,
+ },
+ ],
+ proration_behavior: 'create_prorations',
+ });
+
+ return Response.json({
+ success: true,
+ seatCount,
+ subscriptionId: payload.sub,
+ });
+ } catch (error: unknown) {
+ console.error(error);
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Seat update error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/status/route.ts b/packages/twenty-website/src/app/api/enterprise/status/route.ts
new file mode 100644
index 00000000000..fb4006df598
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/status/route.ts
@@ -0,0 +1,58 @@
+import { verifyEnterpriseKey } from '@/shared/enterprise/enterprise-jwt';
+import { getStripeClient } from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { enterpriseKey } = body;
+
+ if (!enterpriseKey || typeof enterpriseKey !== 'string') {
+ return new Response(
+ JSON.stringify({ error: 'Missing enterpriseKey' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const payload = verifyEnterpriseKey(enterpriseKey);
+
+ if (!payload) {
+ return new Response(
+ JSON.stringify({ error: 'Invalid enterprise key' }),
+ { status: 403, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const stripe = getStripeClient();
+ const subscription = await stripe.subscriptions.retrieve(payload.sub);
+
+ const rawCancelAt = subscription.cancel_at;
+ const rawCancelAtPeriodEnd = subscription.cancel_at_period_end;
+ const rawCurrentPeriodEnd = (subscription as any).current_period_end as
+ | number
+ | null;
+
+ const effectiveCancelAt =
+ rawCancelAt ?? (rawCancelAtPeriodEnd ? rawCurrentPeriodEnd : null);
+
+ const isCancellationScheduled =
+ subscription.status !== 'canceled' && effectiveCancelAt !== null;
+
+ return Response.json({
+ subscriptionId: subscription.id,
+ status: subscription.status,
+ cancelAt: effectiveCancelAt,
+ currentPeriodEnd: rawCurrentPeriodEnd,
+ isCancellationScheduled,
+ });
+ } catch (error: unknown) {
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Status error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/app/api/enterprise/validate/route.ts b/packages/twenty-website/src/app/api/enterprise/validate/route.ts
new file mode 100644
index 00000000000..c020e9ed3fa
--- /dev/null
+++ b/packages/twenty-website/src/app/api/enterprise/validate/route.ts
@@ -0,0 +1,73 @@
+import {
+ signValidityToken,
+ verifyEnterpriseKey,
+} from '@/shared/enterprise/enterprise-jwt';
+import { getStripeClient } from '@/shared/enterprise/stripe-client';
+
+export const dynamic = 'force-dynamic';
+
+export async function POST(request: Request) {
+ try {
+ const body = await request.json();
+ const { enterpriseKey } = body;
+
+ if (!enterpriseKey || typeof enterpriseKey !== 'string') {
+ return new Response(
+ JSON.stringify({ error: 'Missing enterpriseKey' }),
+ { status: 400, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const payload = verifyEnterpriseKey(enterpriseKey);
+
+ if (!payload) {
+ return new Response(
+ JSON.stringify({ error: 'Invalid enterprise key' }),
+ { status: 403, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const stripe = getStripeClient();
+
+ const subscription = await stripe.subscriptions.retrieve(payload.sub);
+
+ const activeStatuses = ['active', 'trialing'];
+
+ if (!activeStatuses.includes(subscription.status)) {
+ return new Response(
+ JSON.stringify({
+ error: 'Subscription is not active',
+ status: subscription.status,
+ }),
+ { status: 403, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+
+ const rawCancelAt = subscription.cancel_at;
+ const rawCancelAtPeriodEnd = subscription.cancel_at_period_end;
+ const rawCurrentPeriodEnd = (subscription as { current_period_end?: number })
+ .current_period_end;
+ const effectiveCancelAt =
+ rawCancelAt ??
+ (rawCancelAtPeriodEnd && rawCurrentPeriodEnd ? rawCurrentPeriodEnd : null);
+
+ const validityToken = signValidityToken(payload.sub, {
+ subscriptionCancelAt: effectiveCancelAt,
+ });
+
+ return Response.json({
+ validityToken,
+ licensee: payload.licensee,
+ subscriptionId: payload.sub,
+ subscriptionStatus: subscription.status,
+ });
+ } catch (error: unknown) {
+ const message =
+ error instanceof Error ? error.message : 'Unknown error';
+
+ return new Response(
+ JSON.stringify({ error: `Validation error: ${message}` }),
+ { status: 500, headers: { 'Content-Type': 'application/json' } },
+ );
+ }
+}
diff --git a/packages/twenty-website/src/shared/enterprise/enterprise-jwt.ts b/packages/twenty-website/src/shared/enterprise/enterprise-jwt.ts
new file mode 100644
index 00000000000..168ebf4fd25
--- /dev/null
+++ b/packages/twenty-website/src/shared/enterprise/enterprise-jwt.ts
@@ -0,0 +1,188 @@
+import * as crypto from 'crypto';
+
+export type EnterpriseKeyPayload = {
+ sub: string;
+ licensee: string;
+ iat: number;
+};
+
+export type EnterpriseValidityPayload = {
+ sub: string;
+ status: 'valid';
+ iat: number;
+ exp: number;
+};
+
+const ALGORITHM = 'RS256';
+const DEFAULT_VALIDITY_TOKEN_DURATION_DAYS= 30;
+
+const getValidityTokenDurationDays = (): number => {
+ const value = process.env.ENTERPRISE_VALIDITY_TOKEN_DURATION_DAYS;
+
+ if (value === undefined || value === '') {
+ return DEFAULT_VALIDITY_TOKEN_DURATION_DAYS;
+ }
+
+ const parsed = parseInt(value, 10);
+
+ if (Number.isNaN(parsed) || parsed < 1) {
+ return DEFAULT_VALIDITY_TOKEN_DURATION_DAYS;
+ }
+
+ return parsed;
+};
+
+export type SignValidityTokenOptions = {
+ subscriptionCancelAt: number | null;
+};
+
+const computeValidityExp = (
+ nowSeconds: number,
+ durationDays: number,
+ subscriptionCancelAt: number | null,
+): number => {
+ const defaultExp = nowSeconds + durationDays * 24 * 60 * 60;
+
+ if (subscriptionCancelAt === null || subscriptionCancelAt <= 0) {
+ return defaultExp;
+ }
+
+ return Math.min(defaultExp, subscriptionCancelAt);
+};
+
+const getPrivateKey = (): string => {
+ const key = process.env.ENTERPRISE_JWT_PRIVATE_KEY;
+
+ if (!key) {
+ throw new Error('ENTERPRISE_JWT_PRIVATE_KEY is not configured');
+ }
+
+ return key.replace(/\\n/g, '\n');
+};
+
+const base64UrlEncode = (data: string): string => {
+ return Buffer.from(data)
+ .toString('base64')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '');
+};
+
+const base64UrlDecode = (data: string): string => {
+ const padded = data + '='.repeat((4 - (data.length % 4)) % 4);
+ const base64 = padded.replace(/-/g, '+').replace(/_/g, '/');
+
+ return Buffer.from(base64, 'base64').toString('utf-8');
+};
+
+const signJwt = (
+ payload: Record<string, unknown>,
+ privateKey: string,
+): string => {
+ const header = { alg: ALGORITHM, typ: 'JWT' };
+ const encodedHeader = base64UrlEncode(JSON.stringify(header));
+ const encodedPayload = base64UrlEncode(JSON.stringify(payload));
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
+
+ const signature = crypto
+ .sign('sha256', Buffer.from(signingInput), {
+ key: privateKey,
+ padding: crypto.constants.RSA_PKCS1_PADDING,
+ })
+ .toString('base64')
+ .replace(/\+/g, '-')
+ .replace(/\//g, '_')
+ .replace(/=+$/, '');
+
+ return `${signingInput}.${signature}`;
+};
+
+export const verifyJwt = <T extends Record<string, unknown>>(
+ token: string,
+ publicKey: string,
+): T | null => {
+ try {
+ const parts = token.split('.');
+
+ if (parts.length !== 3) {
+ return null;
+ }
+
+ const [encodedHeader, encodedPayload, signature] = parts;
+ const signingInput = `${encodedHeader}.${encodedPayload}`;
+
+ const signatureBuffer = Buffer.from(
+ signature.replace(/-/g, '+').replace(/_/g, '/') +
+ '='.repeat((4 - (signature.length % 4)) % 4),
+ 'base64',
+ );
+
+ const isValid = crypto.verify(
+ 'sha256',
+ Buffer.from(signingInput),
+ {
+ key: publicKey,
+ padding: crypto.constants.RSA_PKCS1_PADDING,
+ },
+ signatureBuffer,
+ );
+
+ if (!isValid) {
+ return null;
+ }
+
+ return JSON.parse(base64UrlDecode(encodedPayload)) as T;
+ } catch {
+ return null;
+ }
+};
+
+export const signEnterpriseKey = (
+ subscriptionId: string,
+ licensee: string,
+): string => {
+ const payload: EnterpriseKeyPayload = {
+ sub: subscriptionId,
+ licensee,
+ iat: Math.floor(Date.now() / 1000),
+ };
+
+ return signJwt(payload, getPrivateKey());
+};
+
+export const signValidityToken = (
+ subscriptionId: string,
+ options?: SignValidityTokenOptions,
+): string => {
+ const now = Math.floor(Date.now() / 1000);
+ const durationDays = getValidityTokenDurationDays();
+ const subscriptionCancelAt = options?.subscriptionCancelAt ?? null;
+ const exp = computeValidityExp(now, durationDays, subscriptionCancelAt);
+
+ const payload: EnterpriseValidityPayload = {
+ sub: subscriptionId,
+ status: 'valid',
+ iat: now,
+ exp,
+ };
+
+ return signJwt(payload, getPrivateKey());
+};
+
+export const verifyEnterpriseKey = (
+ token: string,
+): EnterpriseKeyPayload | null => {
+ const publicKey = getPublicKey();
+
+ return verifyJwt<EnterpriseKeyPayload>(token, publicKey);
+};
+
+const getPublicKey = (): string => {
+ const key = process.env.ENTERPRISE_JWT_PUBLIC_KEY;
+
+ if (!key) {
+ throw new Error('ENTERPRISE_JWT_PUBLIC_KEY is not configured');
+ }
+
+ return key.replace(/\\n/g, '\n');
+};
diff --git a/packages/twenty-website/src/shared/enterprise/stripe-client.ts b/packages/twenty-website/src/shared/enterprise/stripe-client.ts
new file mode 100644
index 00000000000..133801c30e1
--- /dev/null
+++ b/packages/twenty-website/src/shared/enterprise/stripe-client.ts
@@ -0,0 +1,34 @@
+import Stripe from 'stripe';
+
+let stripeInstance: Stripe | null = null;
+
+export const getStripeClient = (): Stripe => {
+ if (!stripeInstance) {
+ const secretKey = process.env.STRIPE_SECRET_KEY;
+
+ if (!secretKey) {
+ throw new Error('STRIPE_SECRET_KEY is not configured');
+ }
+
+ stripeInstance = new Stripe(secretKey, {});
+ }
+
+ return stripeInstance;
+};
+
+export const getEnterprisePriceId = (
+ billingInterval: 'monthly' | 'yearly' = 'monthly',
+): string => {
+ const envKey =
+ billingInterval === 'yearly'
+ ? 'STRIPE_ENTERPRISE_YEARLY_PRICE_ID'
+ : 'STRIPE_ENTERPRISE_MONTHLY_PRICE_ID';
+
+ const priceId = process.env[envKey];
+
+ if (!priceId) {
+ throw new Error(`${envKey} is not configured`);
+ }
+
+ return priceId;
+};