Skip to content

The open alternative to Salesforce, designed for AI.

feat: admin-issued two-factor authentication recovery codes (#26933)

Abdul Rahman75e42f173aca
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 269623b6fd6..142906531bf 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -3061,9 +3061,11 @@ type Mutation {
generateFrontComponentApplicationTokenPair(applicationId: UUID!): ApplicationTokenPair!
generatePlaygroundToken: AuthToken!
generateTransientToken: TransientToken!
+ generateTwoFactorAuthenticationRecoveryCode(otp: String, userId: UUID!): TwoFactorAuthenticationRecoveryCode!
getAuthTokensFromLoginToken(loginToken: String!, origin: String!): AuthTokens!
getAuthTokensFromOTP(captchaToken: String, loginToken: String!, origin: String!, otp: String!): AuthTokens!
getAuthTokensFromSSOExchangeToken(ssoExchangeToken: String!): AuthTokens!
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode(captchaToken: String, loginToken: String!, origin: String!, recoveryCode: String!): TwoFactorAuthenticationRecoveryCodeRedemption!
getAuthorizationUrlForSSO(input: GetAuthorizationUrlForSSOInput!): GetAuthorizationUrlForSSO!
getLoginTokenFromCredentials(captchaToken: String, email: String!, locale: String, origin: String!, password: String!, verifyEmailRedirectPath: String): LoginToken!
goBackToPreviousOnboardingStep: OnboardingStepNavigation!
@@ -3096,6 +3098,7 @@ type Mutation {
revokeAllOtherUserSessions: Int!
revokeApiKey(input: RevokeApiKeyInput!): ApiKey
revokeApplicationAuthorization(applicationAuthorizationId: UUID!): Boolean!
+ revokeTwoFactorAuthenticationRecoveryCode(userId: UUID!): Boolean!
revokeUserSession(userSessionId: UUID!): Boolean!
rotateApplicationRegistrationClientSecret(id: String!): RotateClientSecret!
runAgent(input: RunAgentInput!): RunAgentResult!
@@ -3849,6 +3852,7 @@ type Query {
skill(id: UUID!): Skill
skills: [Skill!]!
timelineActivityTypes: [TimelineActivityType!]!
+ twoFactorAuthenticationRecoveryStatus(userId: UUID!): TwoFactorAuthenticationRecoveryStatus!
unsubscribeTopics: [UnsubscribeTopic!]!
usageLimits: [UsageLimit!]!
usageQuotaDefinitions: UsageQuotaDefinitions!
@@ -4466,6 +4470,22 @@ type TwoFactorAuthenticationMethodSummary {
twoFactorAuthenticationMethodId: UUID!
}
+type TwoFactorAuthenticationRecoveryCode {
+ expiresAt: DateTime!
+ recoveryCode: String!
+}
+
+type TwoFactorAuthenticationRecoveryCodeRedemption {
+ provisioningUri: String
+ tokens: AuthTokenPair
+}
+
+type TwoFactorAuthenticationRecoveryStatus {
+ hasVerifiedTwoFactorAuthenticationMethod: Boolean!
+ isAwaitingRecoveryEnrollment: Boolean!
+ pendingRecoveryCodeExpiresAt: DateTime
+}
+
"""A UUID scalar type"""
scalar UUID
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index cb2d5809901..2c262d57d7f 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -2113,9 +2113,11 @@ export interface Mutation {
generateFrontComponentApplicationTokenPair: ApplicationTokenPair
generatePlaygroundToken: AuthToken
generateTransientToken: TransientToken
+ generateTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCode
getAuthTokensFromLoginToken: AuthTokens
getAuthTokensFromOTP: AuthTokens
getAuthTokensFromSSOExchangeToken: AuthTokens
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCodeRedemption
getAuthorizationUrlForSSO: GetAuthorizationUrlForSSO
getLoginTokenFromCredentials: LoginToken
goBackToPreviousOnboardingStep: OnboardingStepNavigation
@@ -2149,6 +2151,7 @@ export interface Mutation {
revokeAllOtherUserSessions: Scalars['Int']
revokeApiKey?: ApiKey
revokeApplicationAuthorization: Scalars['Boolean']
+ revokeTwoFactorAuthenticationRecoveryCode: Scalars['Boolean']
revokeUserSession: Scalars['Boolean']
rotateApplicationRegistrationClientSecret: RotateClientSecret
runAgent: RunAgentResult
@@ -2806,6 +2809,7 @@ export interface Query {
skill?: Skill
skills: Skill[]
timelineActivityTypes: TimelineActivityType[]
+ twoFactorAuthenticationRecoveryStatus: TwoFactorAuthenticationRecoveryStatus
unsubscribeTopics: UnsubscribeTopic[]
usageLimits: UsageLimit[]
usageQuotaDefinitions: UsageQuotaDefinitions
@@ -3262,6 +3266,25 @@ export interface TwoFactorAuthenticationMethodSummary {
__typename: 'TwoFactorAuthenticationMethodSummary'
}
+export interface TwoFactorAuthenticationRecoveryCode {
+ expiresAt: Scalars['DateTime']
+ recoveryCode: Scalars['String']
+ __typename: 'TwoFactorAuthenticationRecoveryCode'
+}
+
+export interface TwoFactorAuthenticationRecoveryCodeRedemption {
+ provisioningUri?: Scalars['String']
+ tokens?: AuthTokenPair
+ __typename: 'TwoFactorAuthenticationRecoveryCodeRedemption'
+}
+
+export interface TwoFactorAuthenticationRecoveryStatus {
+ hasVerifiedTwoFactorAuthenticationMethod: Scalars['Boolean']
+ isAwaitingRecoveryEnrollment: Scalars['Boolean']
+ pendingRecoveryCodeExpiresAt?: Scalars['DateTime']
+ __typename: 'TwoFactorAuthenticationRecoveryStatus'
+}
+
export type UnsubscribeHostnameStatus = 'ACTIVE' | 'FAILED' | 'PENDING'
export interface UnsubscribeTopic {
@@ -6247,9 +6270,11 @@ export interface MutationGenqlSelection{
generateFrontComponentApplicationTokenPair?: (ApplicationTokenPairGenqlSelection & { __args: {applicationId: Scalars['UUID']} })
generatePlaygroundToken?: AuthTokenGenqlSelection
generateTransientToken?: TransientTokenGenqlSelection
+ generateTwoFactorAuthenticationRecoveryCode?: (TwoFactorAuthenticationRecoveryCodeGenqlSelection & { __args: {otp?: (Scalars['String'] | null), userId: Scalars['UUID']} })
getAuthTokensFromLoginToken?: (AuthTokensGenqlSelection & { __args: {loginToken: Scalars['String'], origin: Scalars['String']} })
getAuthTokensFromOTP?: (AuthTokensGenqlSelection & { __args: {captchaToken?: (Scalars['String'] | null), loginToken: Scalars['String'], origin: Scalars['String'], otp: Scalars['String']} })
getAuthTokensFromSSOExchangeToken?: (AuthTokensGenqlSelection & { __args: {ssoExchangeToken: Scalars['String']} })
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode?: (TwoFactorAuthenticationRecoveryCodeRedemptionGenqlSelection & { __args: {captchaToken?: (Scalars['String'] | null), loginToken: Scalars['String'], origin: Scalars['String'], recoveryCode: Scalars['String']} })
getAuthorizationUrlForSSO?: (GetAuthorizationUrlForSSOGenqlSelection & { __args: {input: GetAuthorizationUrlForSSOInput} })
getLoginTokenFromCredentials?: (LoginTokenGenqlSelection & { __args: {captchaToken?: (Scalars['String'] | null), email: Scalars['String'], locale?: (Scalars['String'] | null), origin: Scalars['String'], password: Scalars['String'], verifyEmailRedirectPath?: (Scalars['String'] | null)} })
goBackToPreviousOnboardingStep?: OnboardingStepNavigationGenqlSelection
@@ -6283,6 +6308,7 @@ export interface MutationGenqlSelection{
revokeAllOtherUserSessions?: boolean | number
revokeApiKey?: (ApiKeyGenqlSelection & { __args: {input: RevokeApiKeyInput} })
revokeApplicationAuthorization?: { __args: {applicationAuthorizationId: Scalars['UUID']} }
+ revokeTwoFactorAuthenticationRecoveryCode?: { __args: {userId: Scalars['UUID']} }
revokeUserSession?: { __args: {userSessionId: Scalars['UUID']} }
rotateApplicationRegistrationClientSecret?: (RotateClientSecretGenqlSelection & { __args: {id: Scalars['String']} })
runAgent?: (RunAgentResultGenqlSelection & { __args: {input: RunAgentInput} })
@@ -6987,6 +7013,7 @@ export interface QueryGenqlSelection{
skill?: (SkillGenqlSelection & { __args: {id: Scalars['UUID']} })
skills?: SkillGenqlSelection
timelineActivityTypes?: TimelineActivityTypeGenqlSelection
+ twoFactorAuthenticationRecoveryStatus?: (TwoFactorAuthenticationRecoveryStatusGenqlSelection & { __args: {userId: Scalars['UUID']} })
unsubscribeTopics?: UnsubscribeTopicGenqlSelection
usageLimits?: UsageLimitGenqlSelection
usageQuotaDefinitions?: UsageQuotaDefinitionsGenqlSelection
@@ -7507,6 +7534,28 @@ export interface TwoFactorAuthenticationMethodSummaryGenqlSelection{
__scalar?: boolean | number
}
+export interface TwoFactorAuthenticationRecoveryCodeGenqlSelection{
+ expiresAt?: boolean | number
+ recoveryCode?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface TwoFactorAuthenticationRecoveryCodeRedemptionGenqlSelection{
+ provisioningUri?: boolean | number
+ tokens?: AuthTokenPairGenqlSelection
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
+export interface TwoFactorAuthenticationRecoveryStatusGenqlSelection{
+ hasVerifiedTwoFactorAuthenticationMethod?: boolean | number
+ isAwaitingRecoveryEnrollment?: boolean | number
+ pendingRecoveryCodeExpiresAt?: boolean | number
+ __typename?: boolean | number
+ __scalar?: boolean | number
+}
+
export interface UUIDFilterComparison {eq?: (Scalars['UUID'] | null),gt?: (Scalars['UUID'] | null),gte?: (Scalars['UUID'] | null),iLike?: (Scalars['UUID'] | null),in?: (Scalars['UUID'][] | null),is?: (Scalars['Boolean'] | null),isNot?: (Scalars['Boolean'] | null),like?: (Scalars['UUID'] | null),lt?: (Scalars['UUID'] | null),lte?: (Scalars['UUID'] | null),neq?: (Scalars['UUID'] | null),notILike?: (Scalars['UUID'] | null),notIn?: (Scalars['UUID'][] | null),notLike?: (Scalars['UUID'] | null)}
export interface UnsubscribeTopicGenqlSelection{
@@ -10546,6 +10595,30 @@ export interface WorkspaceUrlsAndIdGenqlSelection{
+ const TwoFactorAuthenticationRecoveryCode_possibleTypes: string[] = ['TwoFactorAuthenticationRecoveryCode']
+ export const isTwoFactorAuthenticationRecoveryCode = (obj?: { __typename?: any } | null): obj is TwoFactorAuthenticationRecoveryCode => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isTwoFactorAuthenticationRecoveryCode"')
+ return TwoFactorAuthenticationRecoveryCode_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const TwoFactorAuthenticationRecoveryCodeRedemption_possibleTypes: string[] = ['TwoFactorAuthenticationRecoveryCodeRedemption']
+ export const isTwoFactorAuthenticationRecoveryCodeRedemption = (obj?: { __typename?: any } | null): obj is TwoFactorAuthenticationRecoveryCodeRedemption => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isTwoFactorAuthenticationRecoveryCodeRedemption"')
+ return TwoFactorAuthenticationRecoveryCodeRedemption_possibleTypes.includes(obj.__typename)
+ }
+
+
+
+ const TwoFactorAuthenticationRecoveryStatus_possibleTypes: string[] = ['TwoFactorAuthenticationRecoveryStatus']
+ export const isTwoFactorAuthenticationRecoveryStatus = (obj?: { __typename?: any } | null): obj is TwoFactorAuthenticationRecoveryStatus => {
+ if (!obj?.__typename) throw new Error('__typename is missing in "isTwoFactorAuthenticationRecoveryStatus"')
+ return TwoFactorAuthenticationRecoveryStatus_possibleTypes.includes(obj.__typename)
+ }
+
+
+
const UnsubscribeTopic_possibleTypes: string[] = ['UnsubscribeTopic']
export const isUnsubscribeTopic = (obj?: { __typename?: any } | null): obj is UnsubscribeTopic => {
if (!obj?.__typename) throw new Error('__typename is missing in "isUnsubscribeTopic"')
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index de37e4b014c..a6b2ce08889 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -90,31 +90,31 @@ export default {
461,
462,
464,
- 477,
- 479,
- 481,
- 541,
- 561,
- 568,
- 570,
- 584,
- 590,
- 591,
+ 480,
+ 482,
+ 484,
+ 544,
+ 564,
+ 571,
+ 573,
+ 587,
593,
594,
596,
597,
- 598,
+ 599,
+ 600,
601,
- 602,
- 607,
- 609,
+ 604,
+ 605,
+ 610,
612,
- 617,
- 618,
- 619,
+ 615,
+ 620,
+ 621,
622,
- 623
+ 625,
+ 626
],
"types": {
"ActivateWorkspaceInput": {
@@ -142,7 +142,7 @@ export default {
},
"Agent": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -154,7 +154,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isCustom": [
4
@@ -181,7 +181,7 @@ export default {
285
],
"roleId": [
- 477
+ 480
],
"triggers": [
285
@@ -254,7 +254,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"isSubscribed": [
4
@@ -269,7 +269,7 @@ export default {
184
],
"threadId": [
- 477
+ 480
],
"updatedAt": [
184
@@ -280,7 +280,7 @@ export default {
},
"AgentIdInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -288,13 +288,13 @@ export default {
},
"AgentMessage": {
"agentId": [
- 477
+ 480
],
"createdAt": [
184
],
"id": [
- 477
+ 480
],
"parts": [
13
@@ -306,16 +306,16 @@ export default {
1
],
"senderUserWorkspaceId": [
- 477
+ 480
],
"status": [
1
],
"threadId": [
- 477
+ 480
],
"turnId": [
- 477
+ 480
],
"__typename": [
1
@@ -332,7 +332,7 @@ export default {
1
],
"fileId": [
- 477
+ 480
],
"fileMediaType": [
1
@@ -341,10 +341,10 @@ export default {
1
],
"id": [
- 477
+ 480
],
"messageId": [
- 477
+ 480
],
"orderIndex": [
7
@@ -424,7 +424,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"input": [
1
@@ -448,7 +448,7 @@ export default {
15
],
"threadId": [
- 477
+ 480
],
"threadTitle": [
1
@@ -463,13 +463,13 @@ export default {
"AgentTurnStatus": {},
"AggregateChartConfiguration": {
"aggregateFieldMetadataId": [
- 477
+ 480
],
"aggregateOperation": [
17
],
"configurationType": [
- 601
+ 604
],
"description": [
1
@@ -575,7 +575,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -598,7 +598,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -702,13 +702,13 @@ export default {
1
],
"personId": [
- 477
+ 480
],
"role": [
322
],
"workspaceMemberId": [
- 477
+ 480
],
"__typename": [
1
@@ -722,7 +722,7 @@ export default {
55
],
"applicationRegistrationId": [
- 477
+ 480
],
"applicationVariables": [
58
@@ -752,16 +752,16 @@ export default {
259
],
"healthCheckLogicFunctionId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"logicFunctions": [
297
],
"logoFileId": [
- 477
+ 480
],
"logoUrl": [
1
@@ -776,10 +776,10 @@ export default {
1
],
"packageJsonFileId": [
- 477
+ 480
],
"settingsCustomTabFrontComponentId": [
- 477
+ 480
],
"settingsMenuItems": [
448
@@ -794,7 +794,7 @@ export default {
1
],
"yarnLockFileId": [
- 477
+ 480
],
"__typename": [
1
@@ -802,7 +802,7 @@ export default {
},
"ApplicationAuthorization": {
"applicationId": [
- 477
+ 480
],
"applicationName": [
1
@@ -814,7 +814,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"lastAuthorizedAt": [
184
@@ -826,7 +826,7 @@ export default {
1
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -837,7 +837,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -845,7 +845,7 @@ export default {
},
"ApplicationConnectedAccountDTO": {
"applicationId": [
- 477
+ 480
],
"archivedAt": [
184
@@ -860,7 +860,7 @@ export default {
389
],
"connectionProviderId": [
- 477
+ 480
],
"createdAt": [
184
@@ -872,7 +872,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isOwnedByCurrentUser": [
4
@@ -896,7 +896,7 @@ export default {
184
],
"userWorkspaceId": [
- 477
+ 480
],
"visibility": [
1
@@ -913,7 +913,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"logoUrl": [
1
@@ -1007,7 +1007,7 @@ export default {
},
"ApplicationFileCompletionError": {
"fileId": [
- 477
+ 480
],
"message": [
1
@@ -1055,7 +1055,7 @@ export default {
252
],
"fileId": [
- 477
+ 480
],
"filePath": [
1
@@ -1104,7 +1104,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isConfigured": [
4
@@ -1137,7 +1137,7 @@ export default {
1
],
"ownerWorkspaceId": [
- 477
+ 480
],
"sourcePackage": [
1
@@ -1167,7 +1167,7 @@ export default {
7
],
"versionDistribution": [
- 582
+ 585
],
"__typename": [
1
@@ -1175,7 +1175,7 @@ export default {
},
"ApplicationRegistrationSummary": {
"id": [
- 477
+ 480
],
"latestAvailableVersion": [
1
@@ -1198,7 +1198,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isDeprecated": [
4
@@ -1247,7 +1247,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isDeprecated": [
4
@@ -1289,7 +1289,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isValidated": [
4
@@ -1386,7 +1386,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"inviteHash": [
1
@@ -1404,7 +1404,7 @@ export default {
430
],
"workspaceUrls": [
- 624
+ 627
],
"__typename": [
1
@@ -1435,7 +1435,7 @@ export default {
"AxisNameDisplay": {},
"BarChartConfiguration": {
"aggregateFieldMetadataId": [
- 477
+ 480
],
"aggregateOperation": [
17
@@ -1447,7 +1447,7 @@ export default {
1
],
"configurationType": [
- 601
+ 604
],
"description": [
1
@@ -1483,7 +1483,7 @@ export default {
358
],
"primaryAxisGroupByFieldMetadataId": [
- 477
+ 480
],
"primaryAxisGroupBySubFieldName": [
1
@@ -1504,7 +1504,7 @@ export default {
358
],
"secondaryAxisGroupByFieldMetadataId": [
- 477
+ 480
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -1571,7 +1571,7 @@ export default {
285
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -1613,7 +1613,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -1880,7 +1880,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"interval": [
461
@@ -1909,7 +1909,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"quantity": [
9
@@ -1985,7 +1985,7 @@ export default {
},
"CalendarChannel": {
"connectedAccountId": [
- 477
+ 480
],
"contactAutoCreationPolicy": [
107
@@ -1997,7 +1997,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isContactAutoCreationEnabled": [
4
@@ -2036,7 +2036,7 @@ export default {
"CalendarChannelVisibility": {},
"CalendarConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -2044,7 +2044,7 @@ export default {
},
"CallRecordingSummaryConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -2052,7 +2052,7 @@ export default {
},
"CallRecordingTranscriptConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -2129,7 +2129,7 @@ export default {
"ChartNumberFormat": {},
"ChatConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -2162,7 +2162,7 @@ export default {
},
"ChatThreadsConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -2474,10 +2474,10 @@ export default {
},
"CommandMenuItem": {
"applicationId": [
- 477
+ 480
],
"availabilityObjectMetadataId": [
- 477
+ 480
],
"availabilityType": [
134
@@ -2489,7 +2489,7 @@ export default {
1
],
"coreWorkflowVersionId": [
- 477
+ 480
],
"createdAt": [
184
@@ -2501,7 +2501,7 @@ export default {
259
],
"frontComponentId": [
- 477
+ 480
],
"hotKeys": [
1
@@ -2510,7 +2510,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -2522,10 +2522,10 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 477
+ 480
],
"pageLayoutId": [
- 477
+ 480
],
"payload": [
135
@@ -2537,13 +2537,13 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
],
"workflowVersionId": [
- 477
+ 480
],
"__typename": [
1
@@ -2574,7 +2574,7 @@ export default {
},
"ConnectedAccountPublicDTO": {
"applicationId": [
- 477
+ 480
],
"archivedAt": [
184
@@ -2589,7 +2589,7 @@ export default {
389
],
"connectionProviderId": [
- 477
+ 480
],
"createdAt": [
184
@@ -2601,7 +2601,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"lastCredentialsRefreshedAt": [
184
@@ -2622,7 +2622,7 @@ export default {
184
],
"userWorkspaceId": [
- 477
+ 480
],
"visibility": [
1
@@ -2639,13 +2639,13 @@ export default {
1
],
"id": [
- 477
+ 480
],
"provider": [
1
],
"userWorkspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -2698,7 +2698,7 @@ export default {
285
],
"roleId": [
- 477
+ 480
],
"triggers": [
285
@@ -2718,7 +2718,7 @@ export default {
1
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -2726,7 +2726,7 @@ export default {
},
"CreateAppMessageChannelInput": {
"connectedAccountId": [
- 477
+ 480
],
"displayName": [
1
@@ -2851,7 +2851,7 @@ export default {
},
"CreateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 477
+ 480
],
"availabilityType": [
134
@@ -2863,13 +2863,13 @@ export default {
1
],
"coreWorkflowVersionId": [
- 477
+ 480
],
"engineComponentKey": [
218
],
"frontComponentId": [
- 477
+ 480
],
"hotKeys": [
1
@@ -2884,10 +2884,10 @@ export default {
1
],
"navigationTargetObjectMetadataId": [
- 477
+ 480
],
"pageLayoutId": [
- 477
+ 480
],
"payload": [
285
@@ -2899,7 +2899,7 @@ export default {
1
],
"workflowVersionId": [
- 477
+ 480
],
"__typename": [
1
@@ -2985,7 +2985,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"options": [
285
@@ -3017,7 +3017,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -3031,7 +3031,7 @@ export default {
},
"CreateIndexFieldInput": {
"fieldMetadataId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -3048,7 +3048,7 @@ export default {
278
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -3068,7 +3068,7 @@ export default {
285
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -3086,7 +3086,7 @@ export default {
285
],
"universalIdentifier": [
- 477
+ 480
],
"workflowActionTriggerSettings": [
285
@@ -3100,7 +3100,7 @@ export default {
1
],
"unsubscribeTopicId": [
- 477
+ 480
],
"__typename": [
1
@@ -3111,13 +3111,13 @@ export default {
1
],
"folderId": [
- 477
+ 480
],
"icon": [
1
],
"id": [
- 477
+ 480
],
"link": [
1
@@ -3126,25 +3126,25 @@ export default {
1
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
],
"targetObjectMetadataId": [
- 477
+ 480
],
"targetRecordId": [
- 477
+ 480
],
"type": [
342
],
"userWorkspaceId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3223,7 +3223,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"type": [
368
@@ -3237,7 +3237,7 @@ export default {
367
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
@@ -3254,10 +3254,10 @@ export default {
285
],
"objectMetadataId": [
- 477
+ 480
],
"pageLayoutTabId": [
- 477
+ 480
],
"position": [
285
@@ -3266,7 +3266,7 @@ export default {
1
],
"type": [
- 602
+ 605
],
"__typename": [
1
@@ -3274,13 +3274,13 @@ export default {
},
"CreateRecordExportInput": {
"fieldMetadataIds": [
- 477
+ 480
],
"filter": [
285
],
"objectMetadataId": [
- 477
+ 480
],
"orderBy": [
285
@@ -3344,7 +3344,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"label": [
1
@@ -3364,7 +3364,7 @@ export default {
1
],
"visibility": [
- 481
+ 484
],
"__typename": [
1
@@ -3381,7 +3381,7 @@ export default {
78
],
"operationType": [
- 561
+ 564
],
"periodCount": [
7
@@ -3390,7 +3390,7 @@ export default {
1
],
"resourceType": [
- 568
+ 571
],
"spenderId": [
1
@@ -3399,7 +3399,7 @@ export default {
1
],
"unit": [
- 570
+ 573
],
"__typename": [
1
@@ -3410,7 +3410,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 477
+ 480
],
"expression": [
1
@@ -3428,7 +3428,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -3436,7 +3436,7 @@ export default {
},
"CreateViewFieldGroupInput": {
"id": [
- 477
+ 480
],
"isVisible": [
4
@@ -3448,7 +3448,7 @@ export default {
9
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3459,10 +3459,10 @@ export default {
17
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"isVisible": [
4
@@ -3474,10 +3474,10 @@ export default {
9
],
"viewFieldGroupId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3485,19 +3485,19 @@ export default {
},
"CreateViewFilterGroupInput": {
"id": [
- 477
+ 480
],
"logicalOperator": [
- 590
+ 593
],
"parentViewFilterGroupId": [
- 477
+ 480
],
"positionInViewFilterGroup": [
9
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3505,19 +3505,19 @@ export default {
},
"CreateViewFilterInput": {
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"operand": [
- 591
+ 594
],
"positionInViewFilterGroup": [
9
],
"relationTargetFieldMetadataId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -3526,10 +3526,10 @@ export default {
285
],
"viewFilterGroupId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3540,7 +3540,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isVisible": [
4
@@ -3549,7 +3549,7 @@ export default {
9
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3560,13 +3560,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 477
+ 480
],
"calendarFieldMetadataId": [
- 477
+ 480
],
"calendarLayout": [
- 584
+ 587
],
"groupLoadLimit": [
7
@@ -3575,7 +3575,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isCompact": [
4
@@ -3584,25 +3584,25 @@ export default {
17
],
"kanbanAggregateOperationFieldMetadataId": [
- 477
+ 480
],
"kanbanColumnWidth": [
7
],
"key": [
- 593
+ 596
],
"mainGroupByFieldMetadataId": [
- 477
+ 480
],
"name": [
1
],
"objectMetadataId": [
- 477
+ 480
],
"openRecordIn": [
- 594
+ 597
],
"position": [
9
@@ -3611,10 +3611,10 @@ export default {
4
],
"type": [
- 597
+ 600
],
"visibility": [
- 598
+ 601
],
"__typename": [
1
@@ -3622,19 +3622,19 @@ export default {
},
"CreateViewSortInput": {
"direction": [
- 596
+ 599
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"subFieldName": [
1
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -3645,7 +3645,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"operations": [
1
@@ -3681,7 +3681,7 @@ export default {
"DateTime": {},
"DeleteApprovedAccessDomainInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3689,7 +3689,7 @@ export default {
},
"DeleteOneFieldInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3697,7 +3697,7 @@ export default {
},
"DeleteOneIndexInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3705,7 +3705,7 @@ export default {
},
"DeleteOneObjectInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3713,7 +3713,7 @@ export default {
},
"DeleteSso": {
"identityProviderId": [
- 477
+ 480
],
"__typename": [
1
@@ -3721,7 +3721,7 @@ export default {
},
"DeleteSsoInput": {
"identityProviderId": [
- 477
+ 480
],
"__typename": [
1
@@ -3737,7 +3737,7 @@ export default {
},
"DeleteViewFieldGroupInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3745,7 +3745,7 @@ export default {
},
"DeleteViewFieldInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3753,7 +3753,7 @@ export default {
},
"DeleteViewFilterInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3761,7 +3761,7 @@ export default {
},
"DeleteViewGroupInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3769,7 +3769,7 @@ export default {
},
"DeleteViewSortInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3780,7 +3780,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"name": [
261
@@ -3789,7 +3789,7 @@ export default {
1
],
"userWorkspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -3797,7 +3797,7 @@ export default {
},
"DestroyViewFieldGroupInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3805,7 +3805,7 @@ export default {
},
"DestroyViewFieldInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3813,7 +3813,7 @@ export default {
},
"DestroyViewFilterInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3821,7 +3821,7 @@ export default {
},
"DestroyViewGroupInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3829,7 +3829,7 @@ export default {
},
"DestroyViewSortInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -3871,7 +3871,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isCustomDomainEnabled": [
4
@@ -3888,10 +3888,10 @@ export default {
1
],
"id": [
- 477
+ 480
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
@@ -3914,7 +3914,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"memberCount": [
9
@@ -3934,7 +3934,7 @@ export default {
},
"EditSso": {
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -3954,7 +3954,7 @@ export default {
},
"EditSsoInput": {
"id": [
- 477
+ 480
],
"status": [
432
@@ -3991,7 +3991,7 @@ export default {
},
"EmailThreadConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -4005,7 +4005,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"status": [
215
@@ -4014,13 +4014,13 @@ export default {
216
],
"unsubscribeHostnameStatus": [
- 479
+ 482
],
"updatedAt": [
184
],
"verificationRecords": [
- 579
+ 582
],
"verifiedAt": [
184
@@ -4033,7 +4033,7 @@ export default {
"EmailingDomainTenantStatus": {},
"EmailsConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -4299,7 +4299,7 @@ export default {
},
"ExecuteOneLogicFunctionInput": {
"id": [
- 477
+ 480
],
"payload": [
285
@@ -4322,7 +4322,7 @@ export default {
"FeatureFlagKey": {},
"Field": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -4337,7 +4337,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -4370,7 +4370,7 @@ export default {
1
],
"morphId": [
- 477
+ 480
],
"morphRelations": [
408
@@ -4382,7 +4382,7 @@ export default {
344
],
"objectMetadataId": [
- 477
+ 480
],
"options": [
285
@@ -4411,7 +4411,7 @@ export default {
},
"FieldConfiguration": {
"configurationType": [
- 601
+ 604
],
"fieldDisplayMode": [
242
@@ -4460,7 +4460,7 @@ export default {
244
],
"id": [
- 478
+ 481
],
"isActive": [
105
@@ -4475,7 +4475,7 @@ export default {
105
],
"objectMetadataId": [
- 478
+ 481
],
"or": [
244
@@ -4493,16 +4493,16 @@ export default {
4
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"objectMetadataId": [
- 477
+ 480
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -4516,10 +4516,10 @@ export default {
4
],
"fieldMetadataId": [
- 477
+ 480
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -4527,7 +4527,7 @@ export default {
},
"FieldRichTextConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -4535,7 +4535,7 @@ export default {
},
"FieldsConfiguration": {
"configurationType": [
- 601
+ 604
],
"newFieldDefaultVisibility": [
4
@@ -4555,7 +4555,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"path": [
1
@@ -4572,7 +4572,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -4587,7 +4587,7 @@ export default {
184
],
"fileId": [
- 477
+ 480
],
"uploadUrl": [
1
@@ -4601,7 +4601,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"path": [
1
@@ -4618,7 +4618,7 @@ export default {
},
"FilesConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -4626,7 +4626,7 @@ export default {
},
"FindAvailableSSOIDP": {
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -4641,7 +4641,7 @@ export default {
268
],
"workspace": [
- 621
+ 624
],
"__typename": [
1
@@ -4661,7 +4661,7 @@ export default {
1
],
"unsubscribeTopicId": [
- 477
+ 480
],
"__typename": [
1
@@ -4669,7 +4669,7 @@ export default {
},
"FormFieldConfiguration": {
"configurationType": [
- 601
+ 604
],
"fieldMetadataId": [
1
@@ -4683,7 +4683,7 @@ export default {
1
],
"applicationId": [
- 477
+ 480
],
"applicationName": [
1
@@ -4713,7 +4713,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isHeadless": [
4
@@ -4725,7 +4725,7 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -4739,13 +4739,13 @@ export default {
},
"FrontComponentConfiguration": {
"configurationType": [
- 601
+ 604
],
"frontComponentId": [
- 477
+ 480
],
"headerCommandMenuItemUniversalIdentifiers": [
- 477
+ 480
],
"__typename": [
1
@@ -4764,7 +4764,7 @@ export default {
},
"GetApiKeyInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -4775,7 +4775,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"type": [
1
@@ -4786,7 +4786,7 @@ export default {
},
"GetAuthorizationUrlForSSOInput": {
"identityProviderId": [
- 477
+ 480
],
"workspaceInviteHash": [
1
@@ -4797,7 +4797,7 @@ export default {
},
"GrantApplicationCapabilitiesInput": {
"applicationId": [
- 477
+ 480
],
"capabilities": [
1
@@ -4827,7 +4827,7 @@ export default {
"IdentityProviderType": {},
"IframeConfiguration": {
"configurationType": [
- 601
+ 604
],
"url": [
1
@@ -4886,7 +4886,7 @@ export default {
63
],
"workspace": [
- 625
+ 628
],
"__typename": [
1
@@ -4897,7 +4897,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"indexFieldMetadataList": [
276
@@ -4940,10 +4940,10 @@ export default {
184
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"order": [
9
@@ -4963,7 +4963,7 @@ export default {
277
],
"id": [
- 478
+ 481
],
"isCustom": [
105
@@ -4978,7 +4978,7 @@ export default {
"IndexType": {},
"IngestAppMessagesInput": {
"messageChannelId": [
- 477
+ 480
],
"messages": [
32
@@ -5000,10 +5000,10 @@ export default {
1
],
"messageId": [
- 477
+ 480
],
"messageThreadId": [
- 477
+ 480
],
"__typename": [
1
@@ -5070,7 +5070,7 @@ export default {
},
"LineChartConfiguration": {
"aggregateFieldMetadataId": [
- 477
+ 480
],
"aggregateOperation": [
17
@@ -5082,7 +5082,7 @@ export default {
1
],
"configurationType": [
- 601
+ 604
],
"description": [
1
@@ -5115,7 +5115,7 @@ export default {
358
],
"primaryAxisGroupByFieldMetadataId": [
- 477
+ 480
],
"primaryAxisGroupBySubFieldName": [
1
@@ -5136,7 +5136,7 @@ export default {
358
],
"secondaryAxisGroupByFieldMetadataId": [
- 477
+ 480
],
"secondaryAxisGroupBySubFieldName": [
1
@@ -5188,7 +5188,7 @@ export default {
285
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -5235,7 +5235,7 @@ export default {
},
"ListAppMessageChannelsInput": {
"connectedAccountId": [
- 477
+ 480
],
"__typename": [
1
@@ -5254,7 +5254,7 @@ export default {
},
"LogicFunction": {
"applicationId": [
- 477
+ 480
],
"canRunOnDemand": [
4
@@ -5281,7 +5281,7 @@ export default {
285
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -5299,7 +5299,7 @@ export default {
285
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -5349,7 +5349,7 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"__typename": [
1
@@ -5357,19 +5357,19 @@ export default {
},
"LogicFunctionLogsInput": {
"applicationId": [
- 477
+ 480
],
"applicationUniversalIdentifier": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"name": [
1
],
"universalIdentifier": [
- 477
+ 480
],
"__typename": [
1
@@ -5581,7 +5581,7 @@ export default {
},
"MessageCampaignBodyConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -5589,7 +5589,7 @@ export default {
},
"MessageCampaignDetailsConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -5600,7 +5600,7 @@ export default {
137
],
"connectedAccountId": [
- 477
+ 480
],
"contactAutoCreationPolicy": [
313
@@ -5621,7 +5621,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isContactAutoCreationEnabled": [
4
@@ -5680,7 +5680,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isSentFolder": [
4
@@ -5689,7 +5689,7 @@ export default {
4
],
"messageChannelId": [
- 477
+ 480
],
"name": [
1
@@ -5718,7 +5718,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"reason": [
325
@@ -5727,7 +5727,7 @@ export default {
326
],
"unsubscribeTopicId": [
- 477
+ 480
],
"__typename": [
1
@@ -5779,7 +5779,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"property": [
1
@@ -5788,7 +5788,7 @@ export default {
332
],
"recordId": [
- 477
+ 480
],
"sourceValue": [
1
@@ -5817,13 +5817,13 @@ export default {
"MetadataTranslationProvenance": {},
"MetadataTranslationsInput": {
"fieldMetadataId": [
- 477
+ 480
],
"locale": [
1
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -5852,7 +5852,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -5881,16 +5881,16 @@ export default {
},
"MinimalView": {
"id": [
- 477
+ 480
],
"key": [
- 593
+ 596
],
"objectMetadataId": [
- 477
+ 480
],
"type": [
- 597
+ 600
],
"__typename": [
1
@@ -5902,13 +5902,13 @@ export default {
455,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
],
"activateWorkspace": [
- 606,
+ 609,
{
"data": [
0,
@@ -5917,14 +5917,14 @@ export default {
}
],
"addAgentChatThreadParticipants": [
- 477,
+ 480,
{
"threadId": [
- 477,
+ 480,
"UUID!"
],
"workspaceMemberIds": [
- 477,
+ 480,
"[UUID!]!"
]
}
@@ -5942,7 +5942,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -5951,11 +5951,11 @@ export default {
4,
{
"agentId": [
- 477,
+ 480,
"UUID!"
],
"roleId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -5964,11 +5964,11 @@ export default {
4,
{
"apiKeyId": [
- 477,
+ 480,
"UUID!"
],
"roleId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6061,7 +6061,7 @@ export default {
52,
{
"fileId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6074,7 +6074,7 @@ export default {
"String!"
],
"fileIds": [
- 477,
+ 480,
"[UUID!]!"
]
}
@@ -6278,7 +6278,7 @@ export default {
}
],
"createManyViewFieldGroups": [
- 587,
+ 590,
{
"inputs": [
174,
@@ -6287,7 +6287,7 @@ export default {
}
],
"createManyViewFields": [
- 586,
+ 589,
{
"inputs": [
175,
@@ -6296,7 +6296,7 @@ export default {
}
],
"createManyViewGroups": [
- 592,
+ 595,
{
"inputs": [
178,
@@ -6356,14 +6356,14 @@ export default {
"String!"
],
"objectMetadataId": [
- 477,
+ 480,
"UUID!"
],
"properties": [
285
],
"recordId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6505,7 +6505,7 @@ export default {
}
],
"createUnsubscribeTopic": [
- 480,
+ 483,
{
"input": [
171,
@@ -6514,7 +6514,7 @@ export default {
}
],
"createUsageLimit": [
- 559,
+ 562,
{
"input": [
172,
@@ -6523,7 +6523,7 @@ export default {
}
],
"createValidationRule": [
- 578,
+ 581,
{
"input": [
173,
@@ -6532,7 +6532,7 @@ export default {
}
],
"createView": [
- 583,
+ 586,
{
"input": [
179,
@@ -6541,7 +6541,7 @@ export default {
}
],
"createViewField": [
- 586,
+ 589,
{
"input": [
175,
@@ -6550,7 +6550,7 @@ export default {
}
],
"createViewFieldGroup": [
- 587,
+ 590,
{
"input": [
174,
@@ -6559,7 +6559,7 @@ export default {
}
],
"createViewFilter": [
- 588,
+ 591,
{
"input": [
177,
@@ -6568,7 +6568,7 @@ export default {
}
],
"createViewFilterGroup": [
- 589,
+ 592,
{
"input": [
176,
@@ -6577,7 +6577,7 @@ export default {
}
],
"createViewGroup": [
- 592,
+ 595,
{
"input": [
178,
@@ -6586,7 +6586,7 @@ export default {
}
],
"createViewSort": [
- 595,
+ 598,
{
"input": [
180,
@@ -6595,7 +6595,7 @@ export default {
}
],
"createWebhook": [
- 599,
+ 602,
{
"input": [
181,
@@ -6607,7 +6607,7 @@ export default {
455,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6628,7 +6628,7 @@ export default {
312,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6655,7 +6655,7 @@ export default {
133,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6664,19 +6664,19 @@ export default {
137,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
],
"deleteCurrentWorkspace": [
- 606
+ 609
],
"deleteEmailGroupChannel": [
312,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6694,7 +6694,7 @@ export default {
259,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6703,7 +6703,7 @@ export default {
341,
{
"ids": [
- 477,
+ 480,
"[UUID!]!"
]
}
@@ -6712,7 +6712,7 @@ export default {
4,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6721,7 +6721,7 @@ export default {
341,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6775,7 +6775,7 @@ export default {
1,
{
"roleId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6793,7 +6793,7 @@ export default {
4,
{
"messageId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6811,7 +6811,7 @@ export default {
455,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6820,7 +6820,7 @@ export default {
191,
{
"twoFactorAuthenticationMethodId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6838,16 +6838,16 @@ export default {
4,
{
"usageLimitId": [
- 477,
+ 480,
"UUID!"
]
}
],
"deleteUser": [
- 572
+ 575
],
"deleteUserFromWorkspace": [
- 575,
+ 578,
{
"workspaceMemberIdToDelete": [
1,
@@ -6856,10 +6856,10 @@ export default {
}
],
"deleteValidationRule": [
- 578,
+ 581,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6874,7 +6874,7 @@ export default {
}
],
"deleteViewField": [
- 586,
+ 589,
{
"input": [
193,
@@ -6883,7 +6883,7 @@ export default {
}
],
"deleteViewFieldGroup": [
- 587,
+ 590,
{
"input": [
192,
@@ -6892,7 +6892,7 @@ export default {
}
],
"deleteViewFilter": [
- 588,
+ 591,
{
"input": [
194,
@@ -6910,7 +6910,7 @@ export default {
}
],
"deleteViewGroup": [
- 592,
+ 595,
{
"input": [
195,
@@ -6928,10 +6928,10 @@ export default {
}
],
"deleteWebhook": [
- 599,
+ 602,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -6982,7 +6982,7 @@ export default {
}
],
"destroyViewField": [
- 586,
+ 589,
{
"input": [
199,
@@ -6991,7 +6991,7 @@ export default {
}
],
"destroyViewFieldGroup": [
- 587,
+ 590,
{
"input": [
198,
@@ -7000,7 +7000,7 @@ export default {
}
],
"destroyViewFilter": [
- 588,
+ 591,
{
"input": [
200,
@@ -7018,7 +7018,7 @@ export default {
}
],
"destroyViewGroup": [
- 592,
+ 595,
{
"input": [
201,
@@ -7039,7 +7039,7 @@ export default {
137,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7048,7 +7048,7 @@ export default {
206,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7057,7 +7057,7 @@ export default {
207,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7082,7 +7082,7 @@ export default {
"String!"
],
"workspaceId": [
- 477
+ 480
]
}
],
@@ -7108,7 +7108,7 @@ export default {
}
],
"enrichWorkspaceCompany": [
- 610
+ 613
],
"executeOneLogicFunction": [
299,
@@ -7123,7 +7123,7 @@ export default {
28,
{
"apiKeyId": [
- 477,
+ 480,
"UUID!"
],
"expiresAt": [
@@ -7136,7 +7136,7 @@ export default {
57,
{
"applicationId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7147,6 +7147,18 @@ export default {
"generateTransientToken": [
471
],
+ "generateTwoFactorAuthenticationRecoveryCode": [
+ 477,
+ {
+ "otp": [
+ 1
+ ],
+ "userId": [
+ 480,
+ "UUID!"
+ ]
+ }
+ ],
"getAuthTokensFromLoginToken": [
65,
{
@@ -7189,6 +7201,26 @@ export default {
]
}
],
+ "getAuthTokensFromTwoFactorAuthenticationRecoveryCode": [
+ 478,
+ {
+ "captchaToken": [
+ 1
+ ],
+ "loginToken": [
+ 1,
+ "String!"
+ ],
+ "origin": [
+ 1,
+ "String!"
+ ],
+ "recoveryCode": [
+ 1,
+ "String!"
+ ]
+ }
+ ],
"getAuthorizationUrlForSSO": [
263,
{
@@ -7240,11 +7272,11 @@ export default {
273,
{
"userId": [
- 477,
+ 480,
"UUID!"
],
"workspaceId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7302,7 +7334,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7311,7 +7343,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7320,7 +7352,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7357,7 +7389,7 @@ export default {
4,
{
"agentId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7415,7 +7447,7 @@ export default {
133,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7451,7 +7483,7 @@ export default {
466,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7463,7 +7495,7 @@ export default {
1
],
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7484,7 +7516,16 @@ export default {
4,
{
"applicationAuthorizationId": [
- 477,
+ 480,
+ "UUID!"
+ ]
+ }
+ ],
+ "revokeTwoFactorAuthenticationRecoveryCode": [
+ 4,
+ {
+ "userId": [
+ 480,
"UUID!"
]
}
@@ -7493,7 +7534,7 @@ export default {
4,
{
"userSessionId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7520,7 +7561,7 @@ export default {
50,
{
"applicationId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7537,7 +7578,7 @@ export default {
"String!"
],
"id": [
- 477
+ 480
]
}
],
@@ -7552,11 +7593,11 @@ export default {
"[FileAttachmentInput!]"
],
"mentionedWorkspaceMemberIds": [
- 477,
+ 480,
"[UUID!]"
],
"messageId": [
- 477,
+ 480,
"UUID!"
],
"modelId": [
@@ -7567,7 +7608,7 @@ export default {
"String!"
],
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7598,7 +7639,7 @@ export default {
"[String!]!"
],
"roleId": [
- 477
+ 480
]
}
],
@@ -7758,7 +7799,7 @@ export default {
1
],
"workspaceId": [
- 477
+ 480
],
"workspaceInviteHash": [
1
@@ -7785,7 +7826,7 @@ export default {
"DateTime!"
],
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7794,7 +7835,7 @@ export default {
119,
{
"connectedAccountId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7814,7 +7855,7 @@ export default {
4,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7826,7 +7867,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7838,7 +7879,7 @@ export default {
103
],
"syncApplication": [
- 620,
+ 623,
{
"dryRun": [
4
@@ -7917,7 +7958,7 @@ export default {
10,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -7926,7 +7967,7 @@ export default {
26,
{
"input": [
- 483,
+ 486,
"UpdateApiKeyInput!"
]
}
@@ -7935,7 +7976,7 @@ export default {
312,
{
"input": [
- 484,
+ 487,
"UpdateAppMessageChannelInput!"
]
}
@@ -7944,11 +7985,11 @@ export default {
34,
{
"id": [
- 477,
+ 480,
"UUID!"
],
"input": [
- 485,
+ 488,
"UpdateApplicationInput!"
]
}
@@ -7957,7 +7998,7 @@ export default {
52,
{
"input": [
- 486,
+ 489,
"UpdateApplicationRegistrationInput!"
]
}
@@ -7966,7 +8007,7 @@ export default {
56,
{
"input": [
- 488,
+ 491,
"UpdateApplicationRegistrationVariableInput!"
]
}
@@ -7975,7 +8016,7 @@ export default {
106,
{
"input": [
- 490,
+ 493,
"UpdateCalendarChannelInput!"
]
}
@@ -7984,7 +8025,7 @@ export default {
133,
{
"input": [
- 492,
+ 495,
"UpdateCommandMenuItemInput!"
]
}
@@ -7993,7 +8034,7 @@ export default {
312,
{
"input": [
- 493,
+ 496,
"UpdateEmailGroupChannelInput!"
]
}
@@ -8002,7 +8043,7 @@ export default {
259,
{
"input": [
- 495,
+ 498,
"UpdateFrontComponentInput!"
]
}
@@ -8011,7 +8052,7 @@ export default {
237,
{
"input": [
- 497,
+ 500,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -8020,7 +8061,7 @@ export default {
341,
{
"inputs": [
- 508,
+ 511,
"[UpdateOneNavigationMenuItemInput!]!"
]
}
@@ -8029,16 +8070,16 @@ export default {
344,
{
"inputs": [
- 509,
+ 512,
"[UpdateOneObjectInput!]!"
]
}
],
"updateManyViewGroups": [
- 592,
+ 595,
{
"inputs": [
- 531,
+ 534,
"[UpdateViewGroupInput!]!"
]
}
@@ -8047,7 +8088,7 @@ export default {
312,
{
"input": [
- 500,
+ 503,
"UpdateMessageChannelInput!"
]
}
@@ -8056,7 +8097,7 @@ export default {
319,
{
"input": [
- 502,
+ 505,
"UpdateMessageFolderInput!"
]
}
@@ -8065,7 +8106,7 @@ export default {
319,
{
"input": [
- 504,
+ 507,
"UpdateMessageFoldersInput!"
]
}
@@ -8091,7 +8132,7 @@ export default {
341,
{
"input": [
- 508,
+ 511,
"UpdateOneNavigationMenuItemInput!"
]
}
@@ -8100,7 +8141,7 @@ export default {
3,
{
"input": [
- 482,
+ 485,
"UpdateAgentInput!"
]
}
@@ -8109,7 +8150,7 @@ export default {
4,
{
"applicationId": [
- 477
+ 480
],
"key": [
1,
@@ -8125,7 +8166,7 @@ export default {
239,
{
"input": [
- 507,
+ 510,
"UpdateOneFieldMetadataInput!"
]
}
@@ -8134,7 +8175,7 @@ export default {
4,
{
"input": [
- 498,
+ 501,
"UpdateLogicFunctionFromSourceInput!"
]
}
@@ -8143,7 +8184,7 @@ export default {
344,
{
"input": [
- 509,
+ 512,
"UpdateOneObjectInput!"
]
}
@@ -8152,7 +8193,7 @@ export default {
415,
{
"updateRoleInput": [
- 516,
+ 519,
"UpdateRoleInput!"
]
}
@@ -8165,7 +8206,7 @@ export default {
"String!"
],
"input": [
- 510,
+ 513,
"UpdatePageLayoutInput!"
]
}
@@ -8178,7 +8219,7 @@ export default {
"String!"
],
"input": [
- 511,
+ 514,
"UpdatePageLayoutTabInput!"
]
}
@@ -8191,7 +8232,7 @@ export default {
"String!"
],
"input": [
- 513,
+ 516,
"UpdatePageLayoutWidgetInput!"
]
}
@@ -8204,7 +8245,7 @@ export default {
"String!"
],
"input": [
- 515,
+ 518,
"UpdatePageLayoutWithTabsInput!"
]
}
@@ -8226,7 +8267,7 @@ export default {
455,
{
"input": [
- 518,
+ 521,
"UpdateSkillInput!"
]
}
@@ -8235,25 +8276,25 @@ export default {
466,
{
"input": [
- 519,
+ 522,
"UpdateTimelineActivityTypeInput!"
]
}
],
"updateUnsubscribeTopic": [
- 480,
+ 483,
{
"input": [
- 520,
+ 523,
"UpdateUnsubscribeTopicInput!"
]
}
],
"updateUsageLimit": [
- 559,
+ 562,
{
"input": [
- 521,
+ 524,
"UpdateUsageLimitInput!"
]
}
@@ -8271,121 +8312,121 @@ export default {
}
],
"updateValidationRule": [
- 578,
+ 581,
{
"input": [
- 522,
+ 525,
"UpdateValidationRuleInput!"
]
}
],
"updateView": [
- 583,
+ 586,
{
"id": [
1,
"String!"
],
"input": [
- 533,
+ 536,
"UpdateViewInput!"
]
}
],
"updateViewField": [
- 586,
+ 589,
{
"input": [
- 526,
+ 529,
"UpdateViewFieldInput!"
]
}
],
"updateViewFieldGroup": [
- 587,
+ 590,
{
"input": [
- 524,
+ 527,
"UpdateViewFieldGroupInput!"
]
}
],
"updateViewFilter": [
- 588,
+ 591,
{
"input": [
- 529,
+ 532,
"UpdateViewFilterInput!"
]
}
],
"updateViewFilterGroup": [
- 589,
+ 592,
{
"id": [
1,
"String!"
],
"input": [
- 528,
+ 531,
"UpdateViewFilterGroupInput!"
]
}
],
"updateViewGroup": [
- 592,
+ 595,
{
"input": [
- 531,
+ 534,
"UpdateViewGroupInput!"
]
}
],
"updateViewSort": [
- 595,
+ 598,
{
"input": [
- 534,
+ 537,
"UpdateViewSortInput!"
]
}
],
"updateWebhook": [
- 599,
+ 602,
{
"input": [
- 536,
+ 539,
"UpdateWebhookInput!"
]
}
],
"updateWorkspace": [
- 606,
+ 609,
{
"data": [
- 539,
+ 542,
"UpdateWorkspaceInput!"
]
}
],
"updateWorkspaceAllowedIframeOrigins": [
- 606,
+ 609,
{
"data": [
- 538,
+ 541,
"UpdateWorkspaceAllowedIframeOriginsInput!"
]
}
],
"updateWorkspaceMemberRole": [
- 615,
+ 618,
{
"roleId": [
- 477,
+ 480,
"UUID!"
],
"workspaceMemberId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -8394,7 +8435,7 @@ export default {
4,
{
"input": [
- 540,
+ 543,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -8416,7 +8457,7 @@ export default {
52,
{
"file": [
- 541,
+ 544,
"Upload!"
],
"universalIdentifier": [
@@ -8432,7 +8473,7 @@ export default {
"String!"
],
"file": [
- 541,
+ 544,
"Upload!"
],
"fileFolder": [
@@ -8453,7 +8494,7 @@ export default {
"String!"
],
"file": [
- 541,
+ 544,
"Upload!"
]
}
@@ -8462,7 +8503,7 @@ export default {
254,
{
"file": [
- 541,
+ 544,
"Upload!"
],
"workspaceId": [
@@ -8475,7 +8516,7 @@ export default {
254,
{
"file": [
- 541,
+ 544,
"Upload!"
]
}
@@ -8484,7 +8525,7 @@ export default {
254,
{
"file": [
- 541,
+ 544,
"Upload!"
]
}
@@ -8493,16 +8534,16 @@ export default {
246,
{
"upsertFieldPermissionsInput": [
- 542,
+ 545,
"UpsertFieldPermissionsInput!"
]
}
],
"upsertFieldsWidget": [
- 583,
+ 586,
{
"input": [
- 545,
+ 548,
"UpsertFieldsWidgetInput!"
]
}
@@ -8511,7 +8552,7 @@ export default {
352,
{
"upsertObjectPermissionsInput": [
- 546,
+ 549,
"UpsertObjectPermissionsInput!"
]
}
@@ -8520,25 +8561,25 @@ export default {
416,
{
"upsertPermissionFlagsInput": [
- 547,
+ 550,
"UpsertPermissionFlagsInput!"
]
}
],
"upsertRowLevelPermissionPredicates": [
- 549,
+ 552,
{
"input": [
- 548,
+ 551,
"UpsertRowLevelPermissionPredicatesInput!"
]
}
],
"upsertViewWidget": [
- 583,
+ 586,
{
"input": [
- 550,
+ 553,
"UpsertViewWidgetInput!"
]
}
@@ -8547,13 +8588,13 @@ export default {
60,
{
"input": [
- 576,
+ 579,
"ValidateApprovedAccessDomainInput!"
]
}
],
"verifyEmailAndGetLoginToken": [
- 580,
+ 583,
{
"captchaToken": [
1
@@ -8598,7 +8639,7 @@ export default {
}
],
"verifyTwoFactorAuthenticationMethodForAuthenticatedUser": [
- 581,
+ 584,
{
"otp": [
1,
@@ -8623,7 +8664,7 @@ export default {
},
"NavigationMenuItem": {
"applicationId": [
- 477
+ 480
],
"color": [
1
@@ -8632,13 +8673,13 @@ export default {
184
],
"folderId": [
- 477
+ 480
],
"icon": [
1
],
"id": [
- 477
+ 480
],
"link": [
1
@@ -8647,16 +8688,16 @@ export default {
1
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
],
"targetObjectMetadataId": [
- 477
+ 480
],
"targetRecordId": [
- 477
+ 480
],
"targetRecordIdentifier": [
395
@@ -8668,10 +8709,10 @@ export default {
184
],
"userWorkspaceId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -8680,7 +8721,7 @@ export default {
"NavigationMenuItemType": {},
"NotesConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -8688,7 +8729,7 @@ export default {
},
"Object": {
"applicationId": [
- 477
+ 480
],
"color": [
1
@@ -8722,10 +8763,10 @@ export default {
1
],
"id": [
- 477
+ 480
],
"imageIdentifierFieldMetadataId": [
- 477
+ 480
],
"indexMetadataList": [
274
@@ -8768,7 +8809,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 477
+ 480
],
"labelPlural": [
1
@@ -8789,7 +8830,7 @@ export default {
329
],
"readabilityParentFieldUniversalIdentifiers": [
- 477
+ 480
],
"searchFieldMetadataList": [
434
@@ -8851,7 +8892,7 @@ export default {
348
],
"id": [
- 478
+ 481
],
"isActive": [
105
@@ -8878,7 +8919,7 @@ export default {
348
],
"universalIdentifier": [
- 478
+ 481
],
"__typename": [
1
@@ -8897,7 +8938,7 @@ export default {
},
"ObjectMetadataCommandMenuItemPayload": {
"objectMetadataItemId": [
- 477
+ 480
],
"__typename": [
1
@@ -8918,7 +8959,7 @@ export default {
4
],
"objectMetadataId": [
- 477
+ 480
],
"restrictedFields": [
285
@@ -8947,7 +8988,7 @@ export default {
4
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -9057,19 +9098,19 @@ export default {
},
"PageLayout": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
],
"defaultTabToFocusOnMobileAndSidePanelId": [
- 477
+ 480
],
"deletedAt": [
184
],
"id": [
- 477
+ 480
],
"isFirstTabPinned": [
4
@@ -9081,7 +9122,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"tabs": [
366
@@ -9090,7 +9131,7 @@ export default {
368
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -9101,7 +9142,7 @@ export default {
},
"PageLayoutTab": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -9113,7 +9154,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -9128,7 +9169,7 @@ export default {
367
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
@@ -9137,7 +9178,7 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -9153,7 +9194,7 @@ export default {
"PageLayoutType": {},
"PageLayoutWidget": {
"applicationId": [
- 477
+ 480
],
"conditionalAvailabilityExpression": [
1
@@ -9162,7 +9203,7 @@ export default {
285
],
"configuration": [
- 600
+ 603
],
"createdAt": [
184
@@ -9174,7 +9215,7 @@ export default {
267
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -9186,10 +9227,10 @@ export default {
4
],
"objectMetadataId": [
- 477
+ 480
],
"pageLayoutTabId": [
- 477
+ 480
],
"position": [
372
@@ -9198,10 +9239,10 @@ export default {
1
],
"type": [
- 602
+ 605
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -9277,7 +9318,7 @@ export default {
},
"PermissionFlag": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -9289,7 +9330,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"key": [
1
@@ -9301,7 +9342,7 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -9313,7 +9354,7 @@ export default {
"PermissionFlagType": {},
"PieChartConfiguration": {
"aggregateFieldMetadataId": [
- 477
+ 480
],
"aggregateOperation": [
17
@@ -9322,7 +9363,7 @@ export default {
1
],
"configurationType": [
- 601
+ 604
],
"dateGranularity": [
358
@@ -9343,7 +9384,7 @@ export default {
7
],
"groupByFieldMetadataId": [
- 477
+ 480
],
"groupBySubFieldName": [
1
@@ -9401,7 +9442,7 @@ export default {
285
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -9454,7 +9495,7 @@ export default {
},
"PublicApplicationRegistration": {
"id": [
- 477
+ 480
],
"logoUrl": [
1
@@ -9491,7 +9532,7 @@ export default {
},
"PublicDomain": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -9500,7 +9541,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isValidated": [
4
@@ -9562,13 +9603,13 @@ export default {
1
],
"id": [
- 477
+ 480
],
"logo": [
1
],
"workspaceUrls": [
- 624
+ 627
],
"__typename": [
1
@@ -9579,7 +9620,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"logo": [
1
@@ -9593,7 +9634,7 @@ export default {
14,
{
"agentId": [
- 477,
+ 480,
"UUID!"
],
"limit": [
@@ -9658,7 +9699,7 @@ export default {
37,
{
"applicationId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9667,7 +9708,7 @@ export default {
38,
{
"applicationId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9694,7 +9735,7 @@ export default {
433,
{
"applicationId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9720,10 +9761,10 @@ export default {
}
],
"callRecordingIdForCalendarEvent": [
- 477,
+ 480,
{
"calendarEventId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9732,7 +9773,7 @@ export default {
12,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9741,7 +9782,7 @@ export default {
122,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9750,7 +9791,7 @@ export default {
6,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9768,7 +9809,7 @@ export default {
}
],
"checkWorkspaceInviteHashIsValid": [
- 614,
+ 617,
{
"inviteHash": [
1,
@@ -9789,7 +9830,7 @@ export default {
133,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9798,16 +9839,16 @@ export default {
133
],
"currentUser": [
- 572
+ 575
],
"currentUserApplicationAuthorizations": [
35
],
"currentUserSessions": [
- 574
+ 577
],
"currentWorkspace": [
- 606
+ 609
],
"enterpriseCheckoutSession": [
1,
@@ -9841,7 +9882,7 @@ export default {
40,
{
"universalIdentifier": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9850,7 +9891,7 @@ export default {
239,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -9970,10 +10011,10 @@ export default {
34,
{
"id": [
- 477
+ 480
],
"universalIdentifier": [
- 477
+ 480
]
}
],
@@ -10005,10 +10046,10 @@ export default {
}
],
"findWorkspaceAiStats": [
- 608
+ 611
],
"findWorkspaceFromInviteHash": [
- 606,
+ 609,
{
"inviteHash": [
1,
@@ -10017,13 +10058,13 @@ export default {
}
],
"findWorkspaceInvitations": [
- 613
+ 616
],
"frontComponent": [
259,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10085,7 +10126,7 @@ export default {
138,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10185,7 +10226,7 @@ export default {
391,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10197,7 +10238,7 @@ export default {
415,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10221,15 +10262,15 @@ export default {
}
],
"getUsageAnalytics": [
- 556,
+ 559,
{
"input": [
- 557
+ 560
]
}
],
"getView": [
- 583,
+ 586,
{
"id": [
1,
@@ -10238,7 +10279,7 @@ export default {
}
],
"getViewField": [
- 586,
+ 589,
{
"id": [
1,
@@ -10247,7 +10288,7 @@ export default {
}
],
"getViewFieldGroup": [
- 587,
+ 590,
{
"id": [
1,
@@ -10256,7 +10297,7 @@ export default {
}
],
"getViewFieldGroups": [
- 587,
+ 590,
{
"viewId": [
1,
@@ -10265,7 +10306,7 @@ export default {
}
],
"getViewFields": [
- 586,
+ 589,
{
"viewId": [
1,
@@ -10274,7 +10315,7 @@ export default {
}
],
"getViewFilter": [
- 588,
+ 591,
{
"id": [
1,
@@ -10283,7 +10324,7 @@ export default {
}
],
"getViewFilterGroup": [
- 589,
+ 592,
{
"id": [
1,
@@ -10292,7 +10333,7 @@ export default {
}
],
"getViewFilterGroups": [
- 589,
+ 592,
{
"viewId": [
1
@@ -10300,7 +10341,7 @@ export default {
}
],
"getViewFilters": [
- 588,
+ 591,
{
"viewId": [
1
@@ -10308,7 +10349,7 @@ export default {
}
],
"getViewGroup": [
- 592,
+ 595,
{
"id": [
1,
@@ -10317,7 +10358,7 @@ export default {
}
],
"getViewGroups": [
- 592,
+ 595,
{
"viewId": [
1
@@ -10325,7 +10366,7 @@ export default {
}
],
"getViewSort": [
- 595,
+ 598,
{
"id": [
1,
@@ -10334,7 +10375,7 @@ export default {
}
],
"getViewSorts": [
- 595,
+ 598,
{
"viewId": [
1
@@ -10342,19 +10383,19 @@ export default {
}
],
"getViews": [
- 583,
+ 586,
{
"objectMetadataId": [
1
],
"viewTypes": [
- 597,
+ 600,
"[ViewType!]"
]
}
],
"getWorkspaceCreationDefaults": [
- 611
+ 614
],
"githubClaimAuthorizationUrl": [
1,
@@ -10408,10 +10449,10 @@ export default {
335
],
"mostlyEmptyFieldMetadataIds": [
- 477,
+ 480,
{
"objectMetadataId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10420,7 +10461,7 @@ export default {
106,
{
"connectedAccountId": [
- 477
+ 480
]
}
],
@@ -10431,7 +10472,7 @@ export default {
312,
{
"connectedAccountId": [
- 477
+ 480
]
}
],
@@ -10439,18 +10480,18 @@ export default {
319,
{
"messageChannelId": [
- 477
+ 480
]
}
],
"myUserApplicationVariables": [
- 616
+ 619
],
"navigationMenuItem": [
341,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10462,7 +10503,7 @@ export default {
344,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10541,7 +10582,7 @@ export default {
455,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
@@ -10552,29 +10593,38 @@ export default {
"timelineActivityTypes": [
466
],
+ "twoFactorAuthenticationRecoveryStatus": [
+ 479,
+ {
+ "userId": [
+ 480,
+ "UUID!"
+ ]
+ }
+ ],
"unsubscribeTopics": [
- 480
+ 483
],
"usageLimits": [
- 559
+ 562
],
"usageQuotaDefinitions": [
- 563
+ 566
],
"usageQuotaScopeConsumption": [
- 565,
+ 568,
{
"input": [
- 566,
+ 569,
"UsageQuotaScopeInput!"
]
}
],
"usageQuotasWithConsumption": [
- 567
+ 570
],
"validatePasswordResetToken": [
- 577,
+ 580,
{
"passwordResetToken": [
1,
@@ -10583,25 +10633,25 @@ export default {
}
],
"validationRules": [
- 578,
+ 581,
{
"objectMetadataId": [
- 477,
+ 480,
"UUID!"
]
}
],
"webhook": [
- 599,
+ 602,
{
"id": [
- 477,
+ 480,
"UUID!"
]
}
],
"webhooks": [
- 599
+ 602
],
"__typename": [
1
@@ -10609,7 +10659,7 @@ export default {
},
"RatioAggregateConfig": {
"fieldMetadataId": [
- 477
+ 480
],
"optionValue": [
1
@@ -10629,7 +10679,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"progress": [
7
@@ -10640,7 +10690,7 @@ export default {
},
"RecordIdentifier": {
"id": [
- 477
+ 480
],
"imageIdentifier": [
1
@@ -10671,13 +10721,13 @@ export default {
},
"RecordPermissionsResult": {
"objectMetadataId": [
- 477
+ 480
],
"permissions": [
396
],
"recordId": [
- 477
+ 480
],
"__typename": [
1
@@ -10686,10 +10736,10 @@ export default {
"RecordShareAccessLevel": {},
"RecordSharePrincipalInput": {
"roleId": [
- 477
+ 480
],
"workspaceMemberId": [
- 477
+ 480
],
"__typename": [
1
@@ -10734,10 +10784,10 @@ export default {
8
],
"principalId": [
- 477
+ 480
],
"principalRoleId": [
- 477
+ 480
],
"principalType": [
400
@@ -10758,7 +10808,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"label": [
1
@@ -10769,7 +10819,7 @@ export default {
},
"RecordTableConfiguration": {
"configurationType": [
- 601
+ 604
],
"isUIEditable": [
4
@@ -10786,10 +10836,10 @@ export default {
},
"RecordTargetInput": {
"objectMetadataId": [
- 477
+ 480
],
"recordId": [
- 477
+ 480
],
"__typename": [
1
@@ -10848,7 +10898,7 @@ export default {
},
"RevokeApiKeyInput": {
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -10909,7 +10959,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isEditable": [
4
@@ -10930,10 +10980,10 @@ export default {
418
],
"universalIdentifier": [
- 477
+ 480
],
"workspaceMembers": [
- 615
+ 618
],
"__typename": [
1
@@ -10944,10 +10994,10 @@ export default {
1
],
"id": [
- 477
+ 480
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -11024,16 +11074,16 @@ export default {
},
"RowLevelPermissionPredicateGroupInput": {
"id": [
- 477
+ 480
],
"logicalOperator": [
421
],
"objectMetadataId": [
- 477
+ 480
],
"parentRowLevelPermissionPredicateGroupId": [
- 477
+ 480
],
"positionInRowLevelPermissionPredicateGroup": [
9
@@ -11045,10 +11095,10 @@ export default {
"RowLevelPermissionPredicateGroupLogicalOperator": {},
"RowLevelPermissionPredicateInput": {
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"operand": [
423
@@ -11057,7 +11107,7 @@ export default {
9
],
"rowLevelPermissionPredicateGroupId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -11093,7 +11143,7 @@ export default {
1
],
"runAsWorkspaceMemberId": [
- 477
+ 480
],
"thread": [
429
@@ -11104,7 +11154,7 @@ export default {
},
"RunAgentMessageAttachmentInput": {
"fileId": [
- 477
+ 480
],
"filename": [
1
@@ -11142,7 +11192,7 @@ export default {
4
],
"threadId": [
- 477
+ 480
],
"__typename": [
1
@@ -11161,7 +11211,7 @@ export default {
},
"SSOConnection": {
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -11181,7 +11231,7 @@ export default {
},
"SSOIdentityProvider": {
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -11216,16 +11266,16 @@ export default {
184
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"position": [
9
],
"tsVectorFieldMetadataId": [
- 477
+ 480
],
"updatedAt": [
184
@@ -11236,7 +11286,7 @@ export default {
},
"SendChatMessageResult": {
"mentionedParticipantWorkspaceMemberIds": [
- 477
+ 480
],
"messageId": [
1
@@ -11336,7 +11386,7 @@ export default {
285
],
"workspaceMemberId": [
- 477
+ 480
],
"__typename": [
1
@@ -11344,7 +11394,7 @@ export default {
},
"SendInboxMessageResult": {
"threadId": [
- 477
+ 480
],
"__typename": [
1
@@ -11355,7 +11405,7 @@ export default {
1
],
"result": [
- 613
+ 616
],
"success": [
4
@@ -11442,19 +11492,19 @@ export default {
},
"SettingsMenuItem": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
],
"frontComponentId": [
- 477
+ 480
],
"icon": [
1
],
"id": [
- 477
+ 480
],
"position": [
9
@@ -11466,7 +11516,7 @@ export default {
1
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -11501,7 +11551,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -11518,7 +11568,7 @@ export default {
},
"SetupSso": {
"id": [
- 477
+ 480
],
"issuer": [
1
@@ -11541,7 +11591,7 @@ export default {
63
],
"workspace": [
- 625
+ 628
],
"__typename": [
1
@@ -11560,7 +11610,7 @@ export default {
},
"Skill": {
"applicationId": [
- 477
+ 480
],
"content": [
1
@@ -11575,7 +11625,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -11604,7 +11654,7 @@ export default {
414
],
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -11612,7 +11662,7 @@ export default {
},
"StartWorkspaceSetupChatResult": {
"outcome": [
- 623
+ 626
],
"thread": [
6
@@ -11682,7 +11732,7 @@ export default {
5,
{
"threadId": [
- 477,
+ 480,
"UUID!"
]
}
@@ -11716,7 +11766,7 @@ export default {
"SupportDriver": {},
"TasksConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -11727,7 +11777,7 @@ export default {
1
],
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -11736,13 +11786,13 @@ export default {
467
],
"frontComponentUniversalIdentifier": [
- 477
+ 480
],
"icon": [
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -11754,13 +11804,13 @@ export default {
1
],
"objectUniversalIdentifier": [
- 477
+ 480
],
"replacesTimelineActivityTypeUniversalIdentifier": [
- 477
+ 480
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
@@ -11771,7 +11821,7 @@ export default {
},
"TimelineActivityTypeEmit": {
"objectUniversalIdentifier": [
- 477
+ 480
],
"on": [
1
@@ -11785,13 +11835,13 @@ export default {
},
"TimelineActivityTypeEmitThrough": {
"happensAtFieldUniversalIdentifier": [
- 477
+ 480
],
"relationFieldUniversalIdentifier": [
- 477
+ 480
],
"triggerFieldUniversalIdentifiers": [
- 477
+ 480
],
"__typename": [
1
@@ -11799,7 +11849,7 @@ export default {
},
"TimelineConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -11885,7 +11935,43 @@ export default {
1
],
"twoFactorAuthenticationMethodId": [
- 477
+ 480
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "TwoFactorAuthenticationRecoveryCode": {
+ "expiresAt": [
+ 184
+ ],
+ "recoveryCode": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "TwoFactorAuthenticationRecoveryCodeRedemption": {
+ "provisioningUri": [
+ 1
+ ],
+ "tokens": [
+ 64
+ ],
+ "__typename": [
+ 1
+ ]
+ },
+ "TwoFactorAuthenticationRecoveryStatus": {
+ "hasVerifiedTwoFactorAuthenticationMethod": [
+ 4
+ ],
+ "isAwaitingRecoveryEnrollment": [
+ 4
+ ],
+ "pendingRecoveryCodeExpiresAt": [
+ 184
],
"__typename": [
1
@@ -11894,19 +11980,19 @@ export default {
"UUID": {},
"UUIDFilterComparison": {
"eq": [
- 477
+ 480
],
"gt": [
- 477
+ 480
],
"gte": [
- 477
+ 480
],
"iLike": [
- 477
+ 480
],
"in": [
- 477
+ 480
],
"is": [
4
@@ -11915,25 +12001,25 @@ export default {
4
],
"like": [
- 477
+ 480
],
"lt": [
- 477
+ 480
],
"lte": [
- 477
+ 480
],
"neq": [
- 477
+ 480
],
"notILike": [
- 477
+ 480
],
"notIn": [
- 477
+ 480
],
"notLike": [
- 477
+ 480
],
"__typename": [
1
@@ -11948,7 +12034,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -11957,7 +12043,7 @@ export default {
184
],
"visibility": [
- 481
+ 484
],
"__typename": [
1
@@ -11972,7 +12058,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"label": [
1
@@ -11993,7 +12079,7 @@ export default {
285
],
"roleId": [
- 477
+ 480
],
"triggers": [
285
@@ -12007,7 +12093,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"name": [
1
@@ -12024,7 +12110,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isSyncEnabled": [
4
@@ -12049,7 +12135,7 @@ export default {
1
],
"update": [
- 487
+ 490
],
"__typename": [
1
@@ -12074,7 +12160,7 @@ export default {
1
],
"update": [
- 489
+ 492
],
"__typename": [
1
@@ -12096,10 +12182,10 @@ export default {
},
"UpdateCalendarChannelInput": {
"id": [
- 477
+ 480
],
"update": [
- 491
+ 494
],
"__typename": [
1
@@ -12124,7 +12210,7 @@ export default {
},
"UpdateCommandMenuItemInput": {
"availabilityObjectMetadataId": [
- 477
+ 480
],
"availabilityType": [
134
@@ -12139,7 +12225,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isPinned": [
4
@@ -12148,7 +12234,7 @@ export default {
1
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
@@ -12165,7 +12251,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -12218,7 +12304,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"options": [
285
@@ -12238,10 +12324,10 @@ export default {
},
"UpdateFrontComponentInput": {
"id": [
- 477
+ 480
],
"update": [
- 496
+ 499
],
"__typename": [
1
@@ -12271,10 +12357,10 @@ export default {
},
"UpdateLogicFunctionFromSourceInput": {
"id": [
- 477
+ 480
],
"update": [
- 499
+ 502
],
"__typename": [
1
@@ -12320,10 +12406,10 @@ export default {
},
"UpdateMessageChannelInput": {
"id": [
- 477
+ 480
],
"update": [
- 501
+ 504
],
"__typename": [
1
@@ -12357,10 +12443,10 @@ export default {
},
"UpdateMessageFolderInput": {
"id": [
- 477
+ 480
],
"update": [
- 503
+ 506
],
"__typename": [
1
@@ -12376,10 +12462,10 @@ export default {
},
"UpdateMessageFoldersInput": {
"ids": [
- 477
+ 480
],
"update": [
- 503
+ 506
],
"__typename": [
1
@@ -12390,7 +12476,7 @@ export default {
1
],
"folderId": [
- 477
+ 480
],
"icon": [
1
@@ -12402,7 +12488,7 @@ export default {
1
],
"pageLayoutId": [
- 477
+ 480
],
"position": [
9
@@ -12422,7 +12508,7 @@ export default {
1
],
"imageIdentifierFieldMetadataId": [
- 477
+ 480
],
"isActive": [
4
@@ -12434,7 +12520,7 @@ export default {
4
],
"labelIdentifierFieldMetadataId": [
- 477
+ 480
],
"labelPlural": [
1
@@ -12469,10 +12555,10 @@ export default {
},
"UpdateOneFieldMetadataInput": {
"id": [
- 477
+ 480
],
"update": [
- 494
+ 497
],
"__typename": [
1
@@ -12480,10 +12566,10 @@ export default {
},
"UpdateOneNavigationMenuItemInput": {
"id": [
- 477
+ 480
],
"update": [
- 505
+ 508
],
"__typename": [
1
@@ -12491,10 +12577,10 @@ export default {
},
"UpdateOneObjectInput": {
"id": [
- 477
+ 480
],
"update": [
- 506
+ 509
],
"__typename": [
1
@@ -12505,7 +12591,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"type": [
368
@@ -12536,7 +12622,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"layoutMode": [
367
@@ -12548,7 +12634,7 @@ export default {
1
],
"widgets": [
- 514
+ 517
],
"__typename": [
1
@@ -12568,10 +12654,10 @@ export default {
4
],
"objectMetadataId": [
- 477
+ 480
],
"pageLayoutTabId": [
- 477
+ 480
],
"position": [
285
@@ -12580,7 +12666,7 @@ export default {
1
],
"type": [
- 602
+ 605
],
"__typename": [
1
@@ -12597,13 +12683,13 @@ export default {
285
],
"id": [
- 477
+ 480
],
"objectMetadataId": [
- 477
+ 480
],
"pageLayoutTabId": [
- 477
+ 480
],
"position": [
285
@@ -12612,7 +12698,7 @@ export default {
1
],
"type": [
- 602
+ 605
],
"__typename": [
1
@@ -12626,10 +12712,10 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"tabs": [
- 512
+ 515
],
"type": [
368
@@ -12640,10 +12726,10 @@ export default {
},
"UpdateRoleInput": {
"id": [
- 477
+ 480
],
"update": [
- 517
+ 520
],
"__typename": [
1
@@ -12701,7 +12787,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -12721,7 +12807,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -12747,7 +12833,7 @@ export default {
1
],
"visibility": [
- 481
+ 484
],
"__typename": [
1
@@ -12755,7 +12841,7 @@ export default {
},
"UpdateUsageLimitInput": {
"id": [
- 477
+ 480
],
"payload": [
172
@@ -12766,10 +12852,10 @@ export default {
},
"UpdateValidationRuleInput": {
"id": [
- 477
+ 480
],
"update": [
- 523
+ 526
],
"__typename": [
1
@@ -12780,7 +12866,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 477
+ 480
],
"expression": [
1
@@ -12803,10 +12889,10 @@ export default {
},
"UpdateViewFieldGroupInput": {
"id": [
- 477
+ 480
],
"update": [
- 525
+ 528
],
"__typename": [
1
@@ -12831,10 +12917,10 @@ export default {
},
"UpdateViewFieldInput": {
"id": [
- 477
+ 480
],
"update": [
- 527
+ 530
],
"__typename": [
1
@@ -12854,7 +12940,7 @@ export default {
9
],
"viewFieldGroupId": [
- 477
+ 480
],
"__typename": [
1
@@ -12862,19 +12948,19 @@ export default {
},
"UpdateViewFilterGroupInput": {
"id": [
- 477
+ 480
],
"logicalOperator": [
- 590
+ 593
],
"parentViewFilterGroupId": [
- 477
+ 480
],
"positionInViewFilterGroup": [
9
],
"viewId": [
- 477
+ 480
],
"__typename": [
1
@@ -12882,10 +12968,10 @@ export default {
},
"UpdateViewFilterInput": {
"id": [
- 477
+ 480
],
"update": [
- 530
+ 533
],
"__typename": [
1
@@ -12893,16 +12979,16 @@ export default {
},
"UpdateViewFilterInputUpdates": {
"fieldMetadataId": [
- 477
+ 480
],
"operand": [
- 591
+ 594
],
"positionInViewFilterGroup": [
9
],
"relationTargetFieldMetadataId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -12911,7 +12997,7 @@ export default {
285
],
"viewFilterGroupId": [
- 477
+ 480
],
"__typename": [
1
@@ -12919,10 +13005,10 @@ export default {
},
"UpdateViewGroupInput": {
"id": [
- 477
+ 480
],
"update": [
- 532
+ 535
],
"__typename": [
1
@@ -12930,7 +13016,7 @@ export default {
},
"UpdateViewGroupInputUpdates": {
"fieldMetadataId": [
- 477
+ 480
],
"fieldValue": [
1
@@ -12950,13 +13036,13 @@ export default {
1
],
"calendarEndFieldMetadataId": [
- 477
+ 480
],
"calendarFieldMetadataId": [
- 477
+ 480
],
"calendarLayout": [
- 584
+ 587
],
"groupLoadLimit": [
7
@@ -12965,7 +13051,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isCompact": [
4
@@ -12974,19 +13060,19 @@ export default {
17
],
"kanbanAggregateOperationFieldMetadataId": [
- 477
+ 480
],
"kanbanColumnWidth": [
7
],
"mainGroupByFieldMetadataId": [
- 477
+ 480
],
"name": [
1
],
"openRecordIn": [
- 594
+ 597
],
"position": [
9
@@ -12995,10 +13081,10 @@ export default {
4
],
"type": [
- 597
+ 600
],
"visibility": [
- 598
+ 601
],
"__typename": [
1
@@ -13006,10 +13092,10 @@ export default {
},
"UpdateViewSortInput": {
"id": [
- 477
+ 480
],
"update": [
- 535
+ 538
],
"__typename": [
1
@@ -13017,7 +13103,7 @@ export default {
},
"UpdateViewSortInputUpdates": {
"direction": [
- 596
+ 599
],
"subFieldName": [
1
@@ -13028,10 +13114,10 @@ export default {
},
"UpdateWebhookInput": {
"id": [
- 477
+ 480
],
"update": [
- 537
+ 540
],
"__typename": [
1
@@ -13088,7 +13174,7 @@ export default {
1
],
"defaultRoleId": [
- 477
+ 480
],
"displayName": [
1
@@ -13145,7 +13231,7 @@ export default {
9
],
"workspaceDiscoverability": [
- 612
+ 615
],
"__typename": [
1
@@ -13156,7 +13242,7 @@ export default {
285
],
"workspaceMemberId": [
- 477
+ 480
],
"__typename": [
1
@@ -13168,7 +13254,7 @@ export default {
247
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -13176,7 +13262,7 @@ export default {
},
"UpsertFieldsWidgetFieldInput": {
"fieldMetadataId": [
- 477
+ 480
],
"isVisible": [
4
@@ -13185,7 +13271,7 @@ export default {
9
],
"viewFieldId": [
- 477
+ 480
],
"__typename": [
1
@@ -13193,10 +13279,10 @@ export default {
},
"UpsertFieldsWidgetGroupInput": {
"fields": [
- 543
+ 546
],
"id": [
- 477
+ 480
],
"isVisible": [
4
@@ -13213,13 +13299,13 @@ export default {
},
"UpsertFieldsWidgetInput": {
"fields": [
- 543
+ 546
],
"groups": [
- 544
+ 547
],
"widgetId": [
- 477
+ 480
],
"__typename": [
1
@@ -13230,7 +13316,7 @@ export default {
353
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -13241,7 +13327,7 @@ export default {
1
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -13249,7 +13335,7 @@ export default {
},
"UpsertRowLevelPermissionPredicatesInput": {
"objectMetadataId": [
- 477
+ 480
],
"predicateGroups": [
420
@@ -13258,7 +13344,7 @@ export default {
422
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -13277,22 +13363,22 @@ export default {
},
"UpsertViewWidgetInput": {
"view": [
- 554
+ 557
],
"viewFields": [
- 551
+ 554
],
"viewFilterGroups": [
- 552
+ 555
],
"viewFilters": [
- 553
+ 556
],
"viewSorts": [
- 555
+ 558
],
"widgetId": [
- 477
+ 480
],
"__typename": [
1
@@ -13303,7 +13389,7 @@ export default {
17
],
"fieldMetadataId": [
- 477
+ 480
],
"isVisible": [
4
@@ -13315,7 +13401,7 @@ export default {
9
],
"viewFieldId": [
- 477
+ 480
],
"__typename": [
1
@@ -13323,13 +13409,13 @@ export default {
},
"UpsertViewWidgetViewFilterGroupInput": {
"id": [
- 477
+ 480
],
"logicalOperator": [
- 590
+ 593
],
"parentViewFilterGroupId": [
- 477
+ 480
],
"positionInViewFilterGroup": [
9
@@ -13340,19 +13426,19 @@ export default {
},
"UpsertViewWidgetViewFilterInput": {
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"operand": [
- 591
+ 594
],
"positionInViewFilterGroup": [
9
],
"relationTargetFieldMetadataId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -13361,7 +13447,7 @@ export default {
285
],
"viewFilterGroupId": [
- 477
+ 480
],
"__typename": [
1
@@ -13369,34 +13455,34 @@ export default {
},
"UpsertViewWidgetViewSettingsInput": {
"calendarEndFieldMetadataId": [
- 477
+ 480
],
"calendarFieldMetadataId": [
- 477
+ 480
],
"calendarLayout": [
- 584
+ 587
],
"kanbanAggregateOperation": [
17
],
"kanbanAggregateOperationFieldMetadataId": [
- 477
+ 480
],
"kanbanColumnWidth": [
7
],
"mainGroupByFieldMetadataId": [
- 477
+ 480
],
"openRecordIn": [
- 594
+ 597
],
"shouldHideEmptyGroups": [
4
],
"type": [
- 597
+ 600
],
"__typename": [
1
@@ -13404,13 +13490,13 @@ export default {
},
"UpsertViewWidgetViewSortInput": {
"direction": [
- 596
+ 599
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -13424,22 +13510,22 @@ export default {
184
],
"timeSeries": [
- 569
+ 572
],
"usageByApplication": [
- 558
+ 561
],
"usageByModel": [
- 558
+ 561
],
"usageByOperationType": [
- 558
+ 561
],
"usageByUser": [
- 558
+ 561
],
"userDailyUsage": [
- 571
+ 574
],
"__typename": [
1
@@ -13447,7 +13533,7 @@ export default {
},
"UsageAnalyticsInput": {
"operationTypes": [
- 561
+ 564
],
"periodEnd": [
184
@@ -13484,7 +13570,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"limitKind": [
1
@@ -13493,7 +13579,7 @@ export default {
78
],
"operationType": [
- 561
+ 564
],
"periodCount": [
7
@@ -13502,7 +13588,7 @@ export default {
1
],
"resourceType": [
- 568
+ 571
],
"spenderId": [
1
@@ -13511,7 +13597,7 @@ export default {
1
],
"unit": [
- 570
+ 573
],
"updatedAt": [
184
@@ -13522,10 +13608,10 @@ export default {
},
"UsageLimitOperationDefinition": {
"allowedUnits": [
- 570
+ 573
],
"operationType": [
- 561
+ 564
],
"__typename": [
1
@@ -13534,7 +13620,7 @@ export default {
"UsageOperationType": {},
"UsageQuotaDefinition": {
"allowedOperations": [
- 560
+ 563
],
"allowedSpenderTypes": [
1
@@ -13543,10 +13629,10 @@ export default {
1
],
"operatorOnlyScopes": [
- 564
+ 567
],
"resourceType": [
- 568
+ 571
],
"__typename": [
1
@@ -13554,7 +13640,7 @@ export default {
},
"UsageQuotaDefinitions": {
"definitions": [
- 562
+ 565
],
"hasAllowancePeriod": [
4
@@ -13568,7 +13654,7 @@ export default {
},
"UsageQuotaOperatorOnlyScope": {
"operationType": [
- 561
+ 564
],
"periodUnit": [
1
@@ -13577,7 +13663,7 @@ export default {
1
],
"unit": [
- 570
+ 573
],
"__typename": [
1
@@ -13599,13 +13685,13 @@ export default {
},
"UsageQuotaScopeInput": {
"operationType": [
- 561
+ 564
],
"periodUnit": [
1
],
"resourceType": [
- 568
+ 571
],
"spenderId": [
1
@@ -13614,7 +13700,7 @@ export default {
1
],
"unit": [
- 570
+ 573
],
"__typename": [
1
@@ -13625,7 +13711,7 @@ export default {
78
],
"id": [
- 477
+ 480
],
"isEnforced": [
4
@@ -13634,7 +13720,7 @@ export default {
78
],
"operationType": [
- 561
+ 564
],
"periodEnd": [
184
@@ -13649,7 +13735,7 @@ export default {
78
],
"resourceType": [
- 568
+ 571
],
"spenderId": [
1
@@ -13661,7 +13747,7 @@ export default {
1
],
"unit": [
- 570
+ 573
],
"__typename": [
1
@@ -13682,7 +13768,7 @@ export default {
"UsageUnit": {},
"UsageUserDaily": {
"dailyUsage": [
- 569
+ 572
],
"userWorkspaceId": [
1
@@ -13705,10 +13791,10 @@ export default {
184
],
"currentUserWorkspace": [
- 575
+ 578
],
"currentWorkspace": [
- 606
+ 609
],
"deletedAt": [
184
@@ -13729,7 +13815,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"isEmailVerified": [
4
@@ -13759,16 +13845,16 @@ export default {
286
],
"userWorkspaces": [
- 575
+ 578
],
"workspaceMember": [
- 615
+ 618
],
"workspaceMembers": [
- 615
+ 618
],
"workspaces": [
- 575
+ 578
],
"__typename": [
1
@@ -13817,7 +13903,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"ipAddress": [
1
@@ -13835,7 +13921,7 @@ export default {
1
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -13849,7 +13935,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"isImpersonating": [
4
@@ -13873,10 +13959,10 @@ export default {
184
],
"user": [
- 572
+ 575
],
"userId": [
- 477
+ 480
],
"__typename": [
1
@@ -13884,7 +13970,7 @@ export default {
},
"ValidateApprovedAccessDomainInput": {
"approvedAccessDomainId": [
- 477
+ 480
],
"validationToken": [
1
@@ -13901,7 +13987,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -13912,7 +13998,7 @@ export default {
1
],
"errorFieldMetadataId": [
- 477
+ 480
],
"expression": [
1
@@ -13921,7 +14007,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -13933,7 +14019,7 @@ export default {
1
],
"objectMetadataId": [
- 477
+ 480
],
"__typename": [
1
@@ -13964,7 +14050,7 @@ export default {
63
],
"workspaceUrls": [
- 624
+ 627
],
"__typename": [
1
@@ -13994,22 +14080,22 @@ export default {
1
],
"applicationId": [
- 477
+ 480
],
"calendarEndFieldMetadataId": [
- 477
+ 480
],
"calendarFieldMetadataId": [
- 477
+ 480
],
"calendarLayout": [
- 584
+ 587
],
"createdAt": [
184
],
"createdByUserWorkspaceId": [
- 477
+ 480
],
"deletedAt": [
184
@@ -14021,7 +14107,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -14039,25 +14125,25 @@ export default {
17
],
"kanbanAggregateOperationFieldMetadataId": [
- 477
+ 480
],
"kanbanColumnWidth": [
7
],
"key": [
- 593
+ 596
],
"mainGroupByFieldMetadataId": [
- 477
+ 480
],
"name": [
1
],
"objectMetadataId": [
- 477
+ 480
],
"openRecordIn": [
- 594
+ 597
],
"position": [
9
@@ -14066,37 +14152,37 @@ export default {
4
],
"type": [
- 597
+ 600
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
],
"viewFieldGroups": [
- 587
+ 590
],
"viewFields": [
- 586
+ 589
],
"viewFilterGroups": [
- 589
+ 592
],
"viewFilters": [
- 588
+ 591
],
"viewGroups": [
- 592
+ 595
],
"viewSorts": [
- 595
+ 598
],
"visibility": [
- 598
+ 601
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14105,7 +14191,7 @@ export default {
"ViewCalendarLayout": {},
"ViewConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -14116,7 +14202,7 @@ export default {
17
],
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -14125,10 +14211,10 @@ export default {
184
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -14149,19 +14235,19 @@ export default {
9
],
"universalIdentifier": [
- 477
+ 480
],
"updatedAt": [
184
],
"viewFieldGroupId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14175,7 +14261,7 @@ export default {
184
],
"id": [
- 477
+ 480
],
"isActive": [
4
@@ -14196,13 +14282,13 @@ export default {
184
],
"viewFields": [
- 586
+ 589
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14216,19 +14302,19 @@ export default {
184
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"operand": [
- 591
+ 594
],
"positionInViewFilterGroup": [
9
],
"relationTargetFieldMetadataId": [
- 477
+ 480
],
"subFieldName": [
1
@@ -14240,13 +14326,13 @@ export default {
285
],
"viewFilterGroupId": [
- 477
+ 480
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14260,13 +14346,13 @@ export default {
184
],
"id": [
- 477
+ 480
],
"logicalOperator": [
- 590
+ 593
],
"parentViewFilterGroupId": [
- 477
+ 480
],
"positionInViewFilterGroup": [
9
@@ -14275,10 +14361,10 @@ export default {
184
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14297,7 +14383,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"isVisible": [
4
@@ -14309,10 +14395,10 @@ export default {
184
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14328,13 +14414,13 @@ export default {
184
],
"direction": [
- 596
+ 599
],
"fieldMetadataId": [
- 477
+ 480
],
"id": [
- 477
+ 480
],
"subFieldName": [
1
@@ -14343,10 +14429,10 @@ export default {
184
],
"viewId": [
- 477
+ 480
],
"workspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14357,7 +14443,7 @@ export default {
"ViewVisibility": {},
"Webhook": {
"applicationId": [
- 477
+ 480
],
"createdAt": [
184
@@ -14369,7 +14455,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"operations": [
1
@@ -14464,16 +14550,16 @@ export default {
469
],
"on_ViewConfiguration": [
- 585
+ 588
],
"on_WorkflowConfiguration": [
- 603
+ 606
],
"on_WorkflowRunConfiguration": [
- 604
+ 607
],
"on_WorkflowVersionConfiguration": [
- 605
+ 608
],
"__typename": [
1
@@ -14483,7 +14569,7 @@ export default {
"WidgetType": {},
"WorkflowConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -14491,7 +14577,7 @@ export default {
},
"WorkflowRunConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -14499,7 +14585,7 @@ export default {
},
"WorkflowVersionConfiguration": {
"configurationType": [
- 601
+ 604
],
"__typename": [
1
@@ -14507,7 +14593,7 @@ export default {
},
"Workspace": {
"activationStatus": [
- 607
+ 610
],
"aiAdditionalInstructions": [
1
@@ -14576,7 +14662,7 @@ export default {
4
],
"id": [
- 477
+ 480
],
"installedApplications": [
34
@@ -14627,7 +14713,7 @@ export default {
1
],
"logoFileId": [
- 477
+ 480
],
"metadataVersion": [
9
@@ -14642,22 +14728,22 @@ export default {
184
],
"viewFields": [
- 586
+ 589
],
"viewFilterGroups": [
- 589
+ 592
],
"viewFilters": [
- 588
+ 591
],
"viewGroups": [
- 592
+ 595
],
"viewSorts": [
- 595
+ 598
],
"views": [
- 583
+ 586
],
"workspaceCustomApplication": [
34
@@ -14666,13 +14752,13 @@ export default {
1
],
"workspaceDiscoverability": [
- 612
+ 615
],
"workspaceMembersCount": [
9
],
"workspaceUrls": [
- 624
+ 627
],
"__typename": [
1
@@ -14702,13 +14788,13 @@ export default {
4
],
"outcome": [
- 609
+ 612
],
"personEnrichment": [
285
],
"personOutcome": [
- 622
+ 625
],
"__typename": [
1
@@ -14734,10 +14820,10 @@ export default {
184
],
"id": [
- 477
+ 480
],
"roleId": [
- 477
+ 480
],
"__typename": [
1
@@ -14762,10 +14848,10 @@ export default {
1
],
"dateFormat": [
- 617
+ 620
],
"id": [
- 477
+ 480
],
"locale": [
1
@@ -14774,7 +14860,7 @@ export default {
261
],
"numberFormat": [
- 618
+ 621
],
"openRecordIn": [
363
@@ -14783,7 +14869,7 @@ export default {
415
],
"timeFormat": [
- 619
+ 622
],
"timeZone": [
1
@@ -14795,10 +14881,10 @@ export default {
1
],
"userId": [
- 477
+ 480
],
"userWorkspaceId": [
- 477
+ 480
],
"__typename": [
1
@@ -14806,13 +14892,13 @@ export default {
},
"WorkspaceMemberApplicationVariables": {
"userWorkspaceId": [
- 477
+ 480
],
"variables": [
- 573
+ 576
],
"workspaceMemberId": [
- 477
+ 480
],
"__typename": [
1
@@ -14837,7 +14923,7 @@ export default {
1
],
"id": [
- 477
+ 480
],
"__typename": [
1
@@ -14858,10 +14944,10 @@ export default {
},
"WorkspaceUrlsAndId": {
"id": [
- 477
+ 480
],
"workspaceUrls": [
- 624
+ 627
],
"__typename": [
1
diff --git a/packages/twenty-docs/user-guide/settings/capabilities/member-management.mdx b/packages/twenty-docs/user-guide/settings/capabilities/member-management.mdx
index 08784674673..f8251ce548d 100644
--- a/packages/twenty-docs/user-guide/settings/capabilities/member-management.mdx
+++ b/packages/twenty-docs/user-guide/settings/capabilities/member-management.mdx
@@ -57,6 +57,24 @@ Removed members lose access immediately. Their data (records, notes, tasks) rema
Emails and calendar events of the deleted member are archived and available for other members.
</Note>
+### Reset a Member's Two-Factor Authentication
+If a member lost access to their authenticator app, an admin can give them a one-time recovery code.
+
+You need the **Security** permission and two-factor authentication set up on your own account.
+
+1. Click on the member to open their profile
+2. In the **Two-factor authentication** section, click **Generate recovery code**
+3. Enter the code from your own authenticator app to confirm
+4. Copy the code and share it with the member through a channel you trust
+
+The code works once and expires after 1 hour by default. It is only shown once. Generating a new code replaces the previous one, and you can click **Revoke** to cancel a pending code. The member gets an email when a code is issued.
+
+When the member uses the code, their authenticator for this workspace is removed and they are signed out of their other sessions. If the workspace enforces two-factor authentication, they are asked to set up a new authenticator right away. If they leave before finishing, generate a new code for them: until that setup is done, the member can only set up an authenticator through a recovery code.
+
+<Note>
+You can't generate a recovery code for yourself. Only a server administrator can generate one for another server administrator.
+</Note>
+
## Pending Invitations
Manage invitations that haven't been accepted:
diff --git a/packages/twenty-docs/user-guide/settings/capabilities/profile-settings.mdx b/packages/twenty-docs/user-guide/settings/capabilities/profile-settings.mdx
index 19209d41d3d..13da3a2d6dc 100644
--- a/packages/twenty-docs/user-guide/settings/capabilities/profile-settings.mdx
+++ b/packages/twenty-docs/user-guide/settings/capabilities/profile-settings.mdx
@@ -19,6 +19,14 @@ Enable 2FA to add an extra layer of security to your account:
3. Scan the QR code with your authenticator app
4. Enter the verification code to confirm
+### Lost Your Authenticator
+If you can't access your authenticator app, ask a workspace admin for a recovery code. The code works once and expires after 1 hour by default. Then:
+1. Sign in with your email and password
+2. On the verification screen, click **Lost your authenticator? Use a recovery code**
+3. Enter the recovery code and click **Continue**
+
+Your current authenticator for that workspace is removed and your other sessions are signed out. Set up two-factor authentication again from **Settings → Profile**.
+
### Password Management
- **Change Password**: Update your current password
- **Password Requirements**: Must be at least 8 characters long
diff --git a/packages/twenty-docs/user-guide/settings/how-tos/settings-faq.mdx b/packages/twenty-docs/user-guide/settings/how-tos/settings-faq.mdx
index 0a3f769764c..63eb2ed75c5 100644
--- a/packages/twenty-docs/user-guide/settings/how-tos/settings-faq.mdx
+++ b/packages/twenty-docs/user-guide/settings/how-tos/settings-faq.mdx
@@ -65,6 +65,10 @@ If you want to temporarily disable your workspace (not permanently delete it), g
5. Enter the verification code
</Accordion>
+<Accordion title="I lost my authenticator app. How do I sign in?">
+Ask a workspace admin with the **Security** permission to generate a recovery code from your member page. On the verification screen, click **Lost your authenticator? Use a recovery code** and enter it. The code works once and expires after 1 hour.
+</Accordion>
+
<Accordion title="Can I change my email address?">
To change your email address, please reach out to [[email protected]](mailto:[email protected]).
</Accordion>
diff --git a/packages/twenty-emails/src/emails/two-factor-authentication-recovery-code-issued.email.tsx b/packages/twenty-emails/src/emails/two-factor-authentication-recovery-code-issued.email.tsx
new file mode 100644
index 00000000000..252be20b607
--- /dev/null
+++ b/packages/twenty-emails/src/emails/two-factor-authentication-recovery-code-issued.email.tsx
@@ -0,0 +1,60 @@
+import { Trans } from '@lingui/react';
+import { BaseEmail } from 'src/components/BaseEmail';
+import { MainText } from 'src/components/MainText';
+import { Title } from 'src/components/Title';
+import { createI18nInstance } from 'src/utils/i18n.utils';
+import { type APP_LOCALES } from 'twenty-shared/translations';
+
+type TwoFactorAuthenticationRecoveryCodeIssuedEmailProps = {
+ actorName: string;
+ workspaceDisplayName: string;
+ expiresAt: Date;
+ locale: keyof typeof APP_LOCALES;
+};
+
+export const TwoFactorAuthenticationRecoveryCodeIssuedEmail = ({
+ actorName,
+ workspaceDisplayName,
+ expiresAt,
+ locale,
+}: TwoFactorAuthenticationRecoveryCodeIssuedEmailProps) => {
+ const i18n = createI18nInstance(locale);
+ const formattedExpiresAt = i18n.date(expiresAt, {
+ dateStyle: 'medium',
+ timeStyle: 'long',
+ timeZone: 'UTC',
+ });
+
+ return (
+ <BaseEmail locale={locale}>
+ <Title value={i18n._('Two-factor authentication recovery code issued')} />
+ <MainText>
+ <Trans
+ id="{actorName} generated a recovery code that lets you sign in to {workspaceDisplayName} without your authenticator app."
+ values={{ actorName, workspaceDisplayName }}
+ />
+ <br />
+ <br />
+ <Trans
+ id="The code can be used once and expires on {formattedExpiresAt}. Using it removes your current authenticator for this workspace and signs you out of your other sessions there."
+ values={{ formattedExpiresAt }}
+ />
+ <br />
+ <br />
+ <Trans id="If you did not ask for this, contact your workspace administrator and change your password." />
+ <br />
+ </MainText>
+ <br />
+ <br />
+ </BaseEmail>
+ );
+};
+
+TwoFactorAuthenticationRecoveryCodeIssuedEmail.PreviewProps = {
+ actorName: 'John Doe',
+ workspaceDisplayName: 'Acme',
+ expiresAt: new Date('2026-07-02T10:00:00Z'),
+ locale: 'en',
+} as TwoFactorAuthenticationRecoveryCodeIssuedEmailProps;
+
+export default TwoFactorAuthenticationRecoveryCodeIssuedEmail;
diff --git a/packages/twenty-emails/src/emails/two-factor-authentication-reset.email.tsx b/packages/twenty-emails/src/emails/two-factor-authentication-reset.email.tsx
new file mode 100644
index 00000000000..9f2189f0393
--- /dev/null
+++ b/packages/twenty-emails/src/emails/two-factor-authentication-reset.email.tsx
@@ -0,0 +1,46 @@
+import { Trans } from '@lingui/react';
+import { BaseEmail } from 'src/components/BaseEmail';
+import { MainText } from 'src/components/MainText';
+import { Title } from 'src/components/Title';
+import { createI18nInstance } from 'src/utils/i18n.utils';
+import { type APP_LOCALES } from 'twenty-shared/translations';
+
+type TwoFactorAuthenticationResetEmailProps = {
+ workspaceDisplayName: string;
+ locale: keyof typeof APP_LOCALES;
+};
+
+export const TwoFactorAuthenticationResetEmail = ({
+ workspaceDisplayName,
+ locale,
+}: TwoFactorAuthenticationResetEmailProps) => {
+ const i18n = createI18nInstance(locale);
+
+ return (
+ <BaseEmail locale={locale}>
+ <Title value={i18n._('Two-factor authentication reset')} />
+ <MainText>
+ <Trans
+ id="A recovery code was used to sign in to {workspaceDisplayName}. Your authenticator for this workspace was removed and your other sessions there were signed out."
+ values={{ workspaceDisplayName }}
+ />
+ <br />
+ <br />
+ <Trans id="Set up two-factor authentication again under Settings, Profile." />
+ <br />
+ <br />
+ <Trans id="If this was not you, contact your workspace administrator and change your password." />
+ <br />
+ </MainText>
+ <br />
+ <br />
+ </BaseEmail>
+ );
+};
+
+TwoFactorAuthenticationResetEmail.PreviewProps = {
+ workspaceDisplayName: 'Acme',
+ locale: 'en',
+} as TwoFactorAuthenticationResetEmailProps;
+
+export default TwoFactorAuthenticationResetEmail;
diff --git a/packages/twenty-emails/src/index.ts b/packages/twenty-emails/src/index.ts
index 4796109b6d0..db6ef6aed18 100644
--- a/packages/twenty-emails/src/index.ts
+++ b/packages/twenty-emails/src/index.ts
@@ -13,6 +13,8 @@ export * from './emails/password-update-notify.email';
export * from './emails/send-email-verification-link.email';
export * from './emails/send-invite-link.email';
export * from './emails/server-admin-access-changed.email';
+export * from './emails/two-factor-authentication-recovery-code-issued.email';
+export * from './emails/two-factor-authentication-reset.email';
export * from './emails/validate-approved-access-domain.email';
export * from './emails/warn-suspended-workspace.email';
export * from './utils/email-renderer/email-renderer';
diff --git a/packages/twenty-front/src/generated-admin/graphql.ts b/packages/twenty-front/src/generated-admin/graphql.ts
index 0afc95984b0..423bb8fcb1e 100644
--- a/packages/twenty-front/src/generated-admin/graphql.ts
+++ b/packages/twenty-front/src/generated-admin/graphql.ts
@@ -607,6 +607,7 @@ export type Mutation = {
deleteDatabaseConfigVariable: Scalars['Boolean']['output'];
deleteJobs: DeleteJobsResponse;
deleteWorkspaceUsageLimit: Scalars['Boolean']['output'];
+ generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin: TwoFactorAuthenticationRecoveryCode;
grantWorkspaceCredits: AdminPanelWorkspaceCreditGrant;
refreshUpgradeStatus: InstanceAndAllWorkspacesUpgradeStatus;
removeAiProvider: Scalars['Boolean']['output'];
@@ -669,6 +670,13 @@ export type MutationDeleteWorkspaceUsageLimitArgs = {
};
+export type MutationGenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminArgs = {
+ otp?: InputMaybe<Scalars['String']['input']>;
+ userId: Scalars['UUID']['input'];
+ workspaceId: Scalars['UUID']['input'];
+};
+
+
export type MutationGrantWorkspaceCreditsArgs = {
amount: Scalars['Float']['input'];
clientOperationId: Scalars['UUID']['input'];
@@ -1070,6 +1078,12 @@ export type SystemHealthService = {
status: AdminPanelHealthServiceStatus;
};
+export type TwoFactorAuthenticationRecoveryCode = {
+ __typename?: 'TwoFactorAuthenticationRecoveryCode';
+ expiresAt: Scalars['DateTime']['output'];
+ recoveryCode: Scalars['String']['output'];
+};
+
export type UpdateApplicationRegistrationVariableInput = {
id: Scalars['String']['input'];
update: UpdateApplicationRegistrationVariablePayload;
@@ -1429,6 +1443,15 @@ export type DeleteWorkspaceUsageLimitMutationVariables = Exact<{
export type DeleteWorkspaceUsageLimitMutation = { __typename?: 'Mutation', deleteWorkspaceUsageLimit: boolean };
+export type GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminMutationVariables = Exact<{
+ userId: Scalars['UUID']['input'];
+ workspaceId: Scalars['UUID']['input'];
+ otp?: InputMaybe<Scalars['String']['input']>;
+}>;
+
+
+export type GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminMutation = { __typename?: 'Mutation', generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin: { __typename?: 'TwoFactorAuthenticationRecoveryCode', recoveryCode: string, expiresAt: string } };
+
export type GrantWorkspaceCreditsMutationVariables = Exact<{
workspaceId: Scalars['UUID']['input'];
amount: Scalars['Float']['input'];
@@ -1689,6 +1712,7 @@ export const GetConfigVariablesGroupedDocument = {"kind":"Document","definitions
export const GetDatabaseConfigVariableDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetDatabaseConfigVariable"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"key"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getDatabaseConfigVariable"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"key"},"value":{"kind":"Variable","name":{"kind":"Name","value":"key"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"isSensitive"}},{"kind":"Field","name":{"kind":"Name","value":"isEnvOnly"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"options"}},{"kind":"Field","name":{"kind":"Name","value":"source"}}]}}]}}]} as unknown as DocumentNode<GetDatabaseConfigVariableQuery, GetDatabaseConfigVariableQueryVariables>;
export const CreateWorkspaceUsageLimitDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateWorkspaceUsageLimit"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"payload"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateUsageLimitInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createWorkspaceUsageLimit"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"payload"},"value":{"kind":"Variable","name":{"kind":"Name","value":"payload"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}}]}}]}}]} as unknown as DocumentNode<CreateWorkspaceUsageLimitMutation, CreateWorkspaceUsageLimitMutationVariables>;
export const DeleteWorkspaceUsageLimitDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteWorkspaceUsageLimit"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"usageLimitId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteWorkspaceUsageLimit"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"usageLimitId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"usageLimitId"}}}]}]}}]} as unknown as DocumentNode<DeleteWorkspaceUsageLimitMutation, DeleteWorkspaceUsageLimitMutationVariables>;
+export const GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdmin"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recoveryCode"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]} as unknown as DocumentNode<GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminMutation, GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminMutationVariables>;
export const GrantWorkspaceCreditsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GrantWorkspaceCredits"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"amount"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"Float"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"type"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"BillingCreditGrantType"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"reason"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"expiresInDays"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Int"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"clientOperationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"grantWorkspaceCredits"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"amount"},"value":{"kind":"Variable","name":{"kind":"Name","value":"amount"}}},{"kind":"Argument","name":{"kind":"Name","value":"type"},"value":{"kind":"Variable","name":{"kind":"Name","value":"type"}}},{"kind":"Argument","name":{"kind":"Name","value":"reason"},"value":{"kind":"Variable","name":{"kind":"Name","value":"reason"}}},{"kind":"Argument","name":{"kind":"Name","value":"expiresInDays"},"value":{"kind":"Variable","name":{"kind":"Name","value":"expiresInDays"}}},{"kind":"Argument","name":{"kind":"Name","value":"clientOperationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"clientOperationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"sourceGrantId"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<GrantWorkspaceCreditsMutation, GrantWorkspaceCreditsMutationVariables>;
export const RevokeWorkspaceCreditGrantDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"RevokeWorkspaceCreditGrant"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"creditGrantId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"revokeWorkspaceCreditGrant"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}},{"kind":"Argument","name":{"kind":"Name","value":"creditGrantId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"creditGrantId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"amount"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"effectiveAt"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}},{"kind":"Field","name":{"kind":"Name","value":"revokedAt"}},{"kind":"Field","name":{"kind":"Name","value":"sourceGrantId"}},{"kind":"Field","name":{"kind":"Name","value":"reason"}},{"kind":"Field","name":{"kind":"Name","value":"isActive"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}}]}}]}}]} as unknown as DocumentNode<RevokeWorkspaceCreditGrantMutation, RevokeWorkspaceCreditGrantMutationVariables>;
export const UpdateServerAdminAccessDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateServerAdminAccess"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"canImpersonate"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"Boolean"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateServerAdminAccess"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}},{"kind":"Argument","name":{"kind":"Name","value":"canAccessFullAdminPanel"},"value":{"kind":"Variable","name":{"kind":"Name","value":"canAccessFullAdminPanel"}}},{"kind":"Argument","name":{"kind":"Name","value":"canImpersonate"},"value":{"kind":"Variable","name":{"kind":"Name","value":"canImpersonate"}}},{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"email"}},{"kind":"Field","name":{"kind":"Name","value":"firstName"}},{"kind":"Field","name":{"kind":"Name","value":"lastName"}},{"kind":"Field","name":{"kind":"Name","value":"canAccessFullAdminPanel"}},{"kind":"Field","name":{"kind":"Name","value":"canImpersonate"}}]}}]}}]} as unknown as DocumentNode<UpdateServerAdminAccessMutation, UpdateServerAdminAccessMutationVariables>;
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index fc9933c0f04..a416498be04 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -3222,9 +3222,11 @@ export type Mutation = {
generateFrontComponentApplicationTokenPair: ApplicationTokenPair;
generatePlaygroundToken: AuthToken;
generateTransientToken: TransientToken;
+ generateTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCode;
getAuthTokensFromLoginToken: AuthTokens;
getAuthTokensFromOTP: AuthTokens;
getAuthTokensFromSSOExchangeToken: AuthTokens;
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCodeRedemption;
getAuthorizationUrlForSSO: GetAuthorizationUrlForSso;
getLoginTokenFromCredentials: LoginToken;
goBackToPreviousOnboardingStep: OnboardingStepNavigation;
@@ -3258,6 +3260,7 @@ export type Mutation = {
revokeAllOtherUserSessions: Scalars['Int']['output'];
revokeApiKey?: Maybe<ApiKey>;
revokeApplicationAuthorization: Scalars['Boolean']['output'];
+ revokeTwoFactorAuthenticationRecoveryCode: Scalars['Boolean']['output'];
revokeUserSession: Scalars['Boolean']['output'];
rotateApplicationRegistrationClientSecret: RotateClientSecret;
runAgent: RunAgentResult;
@@ -4009,6 +4012,12 @@ export type MutationGenerateFrontComponentApplicationTokenPairArgs = {
};
+export type MutationGenerateTwoFactorAuthenticationRecoveryCodeArgs = {
+ otp?: InputMaybe<Scalars['String']['input']>;
+ userId: Scalars['UUID']['input'];
+};
+
+
export type MutationGetAuthTokensFromLoginTokenArgs = {
loginToken: Scalars['String']['input'];
origin: Scalars['String']['input'];
@@ -4028,6 +4037,14 @@ export type MutationGetAuthTokensFromSsoExchangeTokenArgs = {
};
+export type MutationGetAuthTokensFromTwoFactorAuthenticationRecoveryCodeArgs = {
+ captchaToken?: InputMaybe<Scalars['String']['input']>;
+ loginToken: Scalars['String']['input'];
+ origin: Scalars['String']['input'];
+ recoveryCode: Scalars['String']['input'];
+};
+
+
export type MutationGetAuthorizationUrlForSsoArgs = {
input: GetAuthorizationUrlForSsoInput;
};
@@ -4175,6 +4192,11 @@ export type MutationRevokeApplicationAuthorizationArgs = {
};
+export type MutationRevokeTwoFactorAuthenticationRecoveryCodeArgs = {
+ userId: Scalars['UUID']['input'];
+};
+
+
export type MutationRevokeUserSessionArgs = {
userSessionId: Scalars['UUID']['input'];
};
@@ -5393,6 +5415,7 @@ export type Query = {
skill?: Maybe<Skill>;
skills: Array<Skill>;
timelineActivityTypes: Array<TimelineActivityType>;
+ twoFactorAuthenticationRecoveryStatus: TwoFactorAuthenticationRecoveryStatus;
unsubscribeTopics: Array<UnsubscribeTopic>;
usageLimits: Array<UsageLimit>;
usageQuotaDefinitions: UsageQuotaDefinitions;
@@ -5879,6 +5902,11 @@ export type QuerySkillArgs = {
};
+export type QueryTwoFactorAuthenticationRecoveryStatusArgs = {
+ userId: Scalars['UUID']['input'];
+};
+
+
export type QueryUsageQuotaScopeConsumptionArgs = {
input: UsageQuotaScopeInput;
};
@@ -6576,6 +6604,25 @@ export type TwoFactorAuthenticationMethodSummary = {
twoFactorAuthenticationMethodId: Scalars['UUID']['output'];
};
+export type TwoFactorAuthenticationRecoveryCode = {
+ __typename?: 'TwoFactorAuthenticationRecoveryCode';
+ expiresAt: Scalars['DateTime']['output'];
+ recoveryCode: Scalars['String']['output'];
+};
+
+export type TwoFactorAuthenticationRecoveryCodeRedemption = {
+ __typename?: 'TwoFactorAuthenticationRecoveryCodeRedemption';
+ provisioningUri?: Maybe<Scalars['String']['output']>;
+ tokens?: Maybe<AuthTokenPair>;
+};
+
+export type TwoFactorAuthenticationRecoveryStatus = {
+ __typename?: 'TwoFactorAuthenticationRecoveryStatus';
+ hasVerifiedTwoFactorAuthenticationMethod: Scalars['Boolean']['output'];
+ isAwaitingRecoveryEnrollment: Scalars['Boolean']['output'];
+ pendingRecoveryCodeExpiresAt?: Maybe<Scalars['DateTime']['output']>;
+};
+
export type UuidFilterComparison = {
eq?: InputMaybe<Scalars['UUID']['input']>;
gt?: InputMaybe<Scalars['UUID']['input']>;
@@ -8464,6 +8511,16 @@ export type GetAuthTokensFromSsoExchangeTokenMutationVariables = Exact<{
export type GetAuthTokensFromSsoExchangeTokenMutation = { __typename?: 'Mutation', getAuthTokensFromSSOExchangeToken: { __typename?: 'AuthTokens', tokens: { __typename?: 'AuthTokenPair', accessOrWorkspaceAgnosticToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, refreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } } };
+export type GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeMutationVariables = Exact<{
+ loginToken: Scalars['String']['input'];
+ recoveryCode: Scalars['String']['input'];
+ captchaToken?: InputMaybe<Scalars['String']['input']>;
+ origin: Scalars['String']['input'];
+}>;
+
+
+export type GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeMutation = { __typename?: 'Mutation', getAuthTokensFromTwoFactorAuthenticationRecoveryCode: { __typename?: 'TwoFactorAuthenticationRecoveryCodeRedemption', provisioningUri?: string | null, tokens?: { __typename?: 'AuthTokenPair', accessOrWorkspaceAgnosticToken: { __typename?: 'AuthToken', token: string, expiresAt: string }, refreshToken: { __typename?: 'AuthToken', token: string, expiresAt: string } } | null } };
+
export type GetAuthorizationUrlForSsoMutationVariables = Exact<{
input: GetAuthorizationUrlForSsoInput;
}>;
@@ -10297,6 +10354,21 @@ export type MetadataTranslationsQueryVariables = Exact<{
export type MetadataTranslationsQuery = { __typename?: 'Query', metadataTranslations: Array<{ __typename?: 'MetadataTranslation', metadataName: string, recordId: string, objectMetadataId?: string | null, property: string, locale: string, sourceValue: string, canonicalValue: string, value: string, provenance: MetadataTranslationProvenance }> };
+export type GenerateTwoFactorAuthenticationRecoveryCodeMutationVariables = Exact<{
+ userId: Scalars['UUID']['input'];
+ otp?: InputMaybe<Scalars['String']['input']>;
+}>;
+
+
+export type GenerateTwoFactorAuthenticationRecoveryCodeMutation = { __typename?: 'Mutation', generateTwoFactorAuthenticationRecoveryCode: { __typename?: 'TwoFactorAuthenticationRecoveryCode', recoveryCode: string, expiresAt: string } };
+
+export type RevokeTwoFactorAuthenticationRecoveryCodeMutationVariables = Exact<{
+ userId: Scalars['UUID']['input'];
+}>;
+
+
+export type RevokeTwoFactorAuthenticationRecoveryCodeMutation = { __typename?: 'Mutation', revokeTwoFactorAuthenticationRecoveryCode: boolean };
+
export type VerifyTwoFactorAuthenticationMethodForAuthenticatedUserMutationVariables = Exact<{
otp: Scalars['String']['input'];
}>;
@@ -10304,6 +10376,13 @@ export type VerifyTwoFactorAuthenticationMethodForAuthenticatedUserMutationVaria
export type VerifyTwoFactorAuthenticationMethodForAuthenticatedUserMutation = { __typename?: 'Mutation', verifyTwoFactorAuthenticationMethodForAuthenticatedUser: { __typename?: 'VerifyTwoFactorAuthenticationMethod', success: boolean } };
+export type TwoFactorAuthenticationRecoveryStatusQueryVariables = Exact<{
+ userId: Scalars['UUID']['input'];
+}>;
+
+
+export type TwoFactorAuthenticationRecoveryStatusQuery = { __typename?: 'Query', twoFactorAuthenticationRecoveryStatus: { __typename?: 'TwoFactorAuthenticationRecoveryStatus', hasVerifiedTwoFactorAuthenticationMethod: boolean, isAwaitingRecoveryEnrollment: boolean, pendingRecoveryCodeExpiresAt?: string | null } };
+
export type CreateUnsubscribeTopicMutationVariables = Exact<{
input: CreateUnsubscribeTopicInput;
}>;
@@ -10804,6 +10883,7 @@ export const GenerateTransientTokenDocument = {"kind":"Document","definitions":[
export const GetAuthTokensFromLoginTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"getAuthTokensFromLoginToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAuthTokensFromLoginToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"loginToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tokens"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenPairFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenPairFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthTokenPair"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessOrWorkspaceAgnosticToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"refreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]} as unknown as DocumentNode<GetAuthTokensFromLoginTokenMutation, GetAuthTokensFromLoginTokenMutationVariables>;
export const GetAuthTokensFromOtpDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"getAuthTokensFromOTP"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAuthTokensFromOTP"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"loginToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tokens"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenPairFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenPairFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthTokenPair"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessOrWorkspaceAgnosticToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"refreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]} as unknown as DocumentNode<GetAuthTokensFromOtpMutation, GetAuthTokensFromOtpMutationVariables>;
export const GetAuthTokensFromSsoExchangeTokenDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"getAuthTokensFromSSOExchangeToken"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"ssoExchangeToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAuthTokensFromSSOExchangeToken"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"ssoExchangeToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"ssoExchangeToken"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tokens"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenPairFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenPairFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthTokenPair"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessOrWorkspaceAgnosticToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"refreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]} as unknown as DocumentNode<GetAuthTokensFromSsoExchangeTokenMutation, GetAuthTokensFromSsoExchangeTokenMutationVariables>;
+export const GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"getAuthTokensFromTwoFactorAuthenticationRecoveryCode"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"recoveryCode"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAuthTokensFromTwoFactorAuthenticationRecoveryCode"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"loginToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"loginToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"recoveryCode"},"value":{"kind":"Variable","name":{"kind":"Name","value":"recoveryCode"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"tokens"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenPairFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"provisioningUri"}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenPairFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthTokenPair"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"accessOrWorkspaceAgnosticToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"refreshToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]} as unknown as DocumentNode<GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeMutation, GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeMutationVariables>;
export const GetAuthorizationUrlForSsoDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GetAuthorizationUrlForSSO"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"GetAuthorizationUrlForSSOInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getAuthorizationUrlForSSO"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"authorizationURL"}}]}}]}}]} as unknown as DocumentNode<GetAuthorizationUrlForSsoMutation, GetAuthorizationUrlForSsoMutationVariables>;
export const GetLoginTokenFromCredentialsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"GetLoginTokenFromCredentials"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"email"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"password"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"origin"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getLoginTokenFromCredentials"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"email"},"value":{"kind":"Variable","name":{"kind":"Name","value":"email"}}},{"kind":"Argument","name":{"kind":"Name","value":"password"},"value":{"kind":"Variable","name":{"kind":"Name","value":"password"}}},{"kind":"Argument","name":{"kind":"Name","value":"captchaToken"},"value":{"kind":"Variable","name":{"kind":"Name","value":"captchaToken"}}},{"kind":"Argument","name":{"kind":"Name","value":"origin"},"value":{"kind":"Variable","name":{"kind":"Name","value":"origin"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"loginToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]} as unknown as DocumentNode<GetLoginTokenFromCredentialsMutation, GetLoginTokenFromCredentialsMutationVariables>;
export const ImpersonateDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"Impersonate"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"impersonate"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}},{"kind":"Argument","name":{"kind":"Name","value":"workspaceId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"workspaceId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspace"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"workspaceUrls"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"WorkspaceUrlsFragment"}}]}},{"kind":"Field","name":{"kind":"Name","value":"id"}}]}},{"kind":"Field","name":{"kind":"Name","value":"loginToken"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"FragmentSpread","name":{"kind":"Name","value":"AuthTokenFragment"}}]}}]}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"WorkspaceUrlsFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"WorkspaceUrls"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"subdomainUrl"}},{"kind":"Field","name":{"kind":"Name","value":"customUrl"}}]}},{"kind":"FragmentDefinition","name":{"kind":"Name","value":"AuthTokenFragment"},"typeCondition":{"kind":"NamedType","name":{"kind":"Name","value":"AuthToken"}},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"token"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]} as unknown as DocumentNode<ImpersonateMutation, ImpersonateMutationVariables>;
@@ -11009,7 +11089,10 @@ export const ValidateApprovedAccessDomainDocument = {"kind":"Document","definiti
export const GetApprovedAccessDomainsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetApprovedAccessDomains"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getApprovedAccessDomains"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"domain"}},{"kind":"Field","name":{"kind":"Name","value":"isValidated"}}]}}]}}]} as unknown as DocumentNode<GetApprovedAccessDomainsQuery, GetApprovedAccessDomainsQueryVariables>;
export const GetSsoIdentityProvidersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetSSOIdentityProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getSSOIdentityProviders"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"issuer"}},{"kind":"Field","name":{"kind":"Name","value":"status"}}]}}]}}]} as unknown as DocumentNode<GetSsoIdentityProvidersQuery, GetSsoIdentityProvidersQueryVariables>;
export const MetadataTranslationsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MetadataTranslations"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"MetadataTranslationsInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"metadataTranslations"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"metadataName"}},{"kind":"Field","name":{"kind":"Name","value":"recordId"}},{"kind":"Field","name":{"kind":"Name","value":"objectMetadataId"}},{"kind":"Field","name":{"kind":"Name","value":"property"}},{"kind":"Field","name":{"kind":"Name","value":"locale"}},{"kind":"Field","name":{"kind":"Name","value":"sourceValue"}},{"kind":"Field","name":{"kind":"Name","value":"canonicalValue"}},{"kind":"Field","name":{"kind":"Name","value":"value"}},{"kind":"Field","name":{"kind":"Name","value":"provenance"}}]}}]}}]} as unknown as DocumentNode<MetadataTranslationsQuery, MetadataTranslationsQueryVariables>;
+export const GenerateTwoFactorAuthenticationRecoveryCodeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"generateTwoFactorAuthenticationRecoveryCode"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}},{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"generateTwoFactorAuthenticationRecoveryCode"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}},{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"recoveryCode"}},{"kind":"Field","name":{"kind":"Name","value":"expiresAt"}}]}}]}}]} as unknown as DocumentNode<GenerateTwoFactorAuthenticationRecoveryCodeMutation, GenerateTwoFactorAuthenticationRecoveryCodeMutationVariables>;
+export const RevokeTwoFactorAuthenticationRecoveryCodeDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"revokeTwoFactorAuthenticationRecoveryCode"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"revokeTwoFactorAuthenticationRecoveryCode"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}}]}]}}]} as unknown as DocumentNode<RevokeTwoFactorAuthenticationRecoveryCodeMutation, RevokeTwoFactorAuthenticationRecoveryCodeMutationVariables>;
export const VerifyTwoFactorAuthenticationMethodForAuthenticatedUserDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"verifyTwoFactorAuthenticationMethodForAuthenticatedUser"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"otp"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"verifyTwoFactorAuthenticationMethodForAuthenticatedUser"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"otp"},"value":{"kind":"Variable","name":{"kind":"Name","value":"otp"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"success"}}]}}]}}]} as unknown as DocumentNode<VerifyTwoFactorAuthenticationMethodForAuthenticatedUserMutation, VerifyTwoFactorAuthenticationMethodForAuthenticatedUserMutationVariables>;
+export const TwoFactorAuthenticationRecoveryStatusDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"twoFactorAuthenticationRecoveryStatus"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"userId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"twoFactorAuthenticationRecoveryStatus"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"userId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"userId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"hasVerifiedTwoFactorAuthenticationMethod"}},{"kind":"Field","name":{"kind":"Name","value":"isAwaitingRecoveryEnrollment"}},{"kind":"Field","name":{"kind":"Name","value":"pendingRecoveryCodeExpiresAt"}}]}}]}}]} as unknown as DocumentNode<TwoFactorAuthenticationRecoveryStatusQuery, TwoFactorAuthenticationRecoveryStatusQueryVariables>;
export const CreateUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"CreateUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"CreateUnsubscribeTopicInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"createUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}}]}}]}}]} as unknown as DocumentNode<CreateUnsubscribeTopicMutation, CreateUnsubscribeTopicMutationVariables>;
export const DeleteUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"DeleteUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"deleteUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}]}]}}]} as unknown as DocumentNode<DeleteUnsubscribeTopicMutation, DeleteUnsubscribeTopicMutationVariables>;
export const UpdateUnsubscribeTopicDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateUnsubscribeTopic"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateUnsubscribeTopicInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateUnsubscribeTopic"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"input"},"value":{"kind":"Variable","name":{"kind":"Name","value":"input"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"description"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}}]}}]}}]} as unknown as DocumentNode<UpdateUnsubscribeTopicMutation, UpdateUnsubscribeTopicMutationVariables>;
diff --git a/packages/twenty-front/src/modules/auth/components/TwoFactorAuthenticationProvisionEffect.tsx b/packages/twenty-front/src/modules/auth/components/TwoFactorAuthenticationProvisionEffect.tsx
index bcd5c64aa6f..9885af035e3 100644
--- a/packages/twenty-front/src/modules/auth/components/TwoFactorAuthenticationProvisionEffect.tsx
+++ b/packages/twenty-front/src/modules/auth/components/TwoFactorAuthenticationProvisionEffect.tsx
@@ -1,5 +1,10 @@
import { loginTokenState } from '@/auth/states/loginTokenState';
import { qrCodeState } from '@/auth/states/qrCode';
+import {
+ SignInUpStep,
+ signInUpStepState,
+} from '@/auth/states/signInUpStepState';
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
import { useOrigin } from '@/domain-manager/hooks/useOrigin';
import { useCurrentUserWorkspaceTwoFactorAuthentication } from '@/settings/two-factor-authentication/hooks/useCurrentUserWorkspaceTwoFactorAuthentication';
import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
@@ -10,6 +15,7 @@ import { AppPath } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
import { useNavigateApp } from '~/hooks/useNavigateApp';
+import { isGraphqlErrorOfType } from '~/utils/is-graphql-error-of-type.util';
export const TwoFactorAuthenticationSetupEffect = () => {
const { initiateCurrentUserWorkspaceOtpProvisioning } =
@@ -21,6 +27,7 @@ export const TwoFactorAuthenticationSetupEffect = () => {
const loginToken = useAtomStateValue(loginTokenState);
const qrCode = useAtomStateValue(qrCodeState);
const setQrCode = useSetAtomState(qrCodeState);
+ const setSignInUpStep = useSetAtomState(signInUpStepState);
const { t } = useLingui();
@@ -54,12 +61,19 @@ export const TwoFactorAuthenticationSetupEffect = () => {
setQrCode(
initiateOTPProvisioningResult.data?.initiateOTPProvisioning.uri,
);
- } catch {
- enqueueToast({
- variant: 'error',
- children: t`Two factor authentication provisioning failed.`,
- dedupeKey: 'two-factor-authentication-provisioning-initiation-failed',
- });
+ } catch (error) {
+ if (isGraphqlErrorOfType(error, 'RECOVERY_ENROLLMENT_RESTRICTED')) {
+ setSignInUpStep(SignInUpStep.TwoFactorAuthenticationRecovery);
+ }
+
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Two factor authentication provisioning failed.`,
+ dedupeKey:
+ 'two-factor-authentication-provisioning-initiation-failed',
+ }),
+ );
}
};
diff --git a/packages/twenty-front/src/modules/auth/components/__tests__/TwoFactorAuthenticationProvisionEffect.test.tsx b/packages/twenty-front/src/modules/auth/components/__tests__/TwoFactorAuthenticationProvisionEffect.test.tsx
new file mode 100644
index 00000000000..23cbc330fd2
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/components/__tests__/TwoFactorAuthenticationProvisionEffect.test.tsx
@@ -0,0 +1,114 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, waitFor } from '@testing-library/react';
+import { Provider as JotaiProvider } from 'jotai';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+
+import { TwoFactorAuthenticationSetupEffect } from '@/auth/components/TwoFactorAuthenticationProvisionEffect';
+import { loginTokenState } from '@/auth/states/loginTokenState';
+import { qrCodeState } from '@/auth/states/qrCode';
+import {
+ SignInUpStep,
+ signInUpStepState,
+} from '@/auth/states/signInUpStepState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+import { dynamicActivate } from '~/utils/i18n/dynamicActivate';
+
+const mockInitiateCurrentUserWorkspaceOtpProvisioning = jest.fn();
+const mockEnqueueToast = jest.fn();
+
+jest.mock(
+ '@/settings/two-factor-authentication/hooks/useCurrentUserWorkspaceTwoFactorAuthentication',
+ () => ({
+ useCurrentUserWorkspaceTwoFactorAuthentication: () => ({
+ initiateCurrentUserWorkspaceOtpProvisioning:
+ mockInitiateCurrentUserWorkspaceOtpProvisioning,
+ }),
+ }),
+);
+
+jest.mock('@/domain-manager/hooks/useOrigin', () => ({
+ useOrigin: () => ({ origin: 'https://apple.twenty.com' }),
+}));
+
+jest.mock('~/hooks/useNavigateApp', () => ({
+ useNavigateApp: () => jest.fn(),
+}));
+
+jest.mock('twenty-ui/components/feedback', () => ({
+ ...jest.requireActual('twenty-ui/components/feedback'),
+ useToast: () => ({ enqueueToast: mockEnqueueToast }),
+}));
+
+dynamicActivate(SOURCE_LOCALE);
+
+const renderEffect = () =>
+ render(
+ <JotaiProvider store={jotaiStore}>
+ <I18nProvider i18n={i18n}>
+ <TwoFactorAuthenticationSetupEffect />
+ </I18nProvider>
+ </JotaiProvider>,
+ );
+
+describe('TwoFactorAuthenticationSetupEffect', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ resetJotaiStore();
+ jotaiStore.set(loginTokenState.atom, 'login-token');
+ jotaiStore.set(
+ signInUpStepState.atom,
+ SignInUpStep.TwoFactorAuthenticationProvision,
+ );
+ });
+
+ it('shows the authenticator returned by the server', async () => {
+ const uri =
+ 'otpauth://totp/Twenty:[email protected]?secret=SECRETKEY&issuer=Twenty';
+
+ mockInitiateCurrentUserWorkspaceOtpProvisioning.mockResolvedValue({
+ data: { initiateOTPProvisioning: { uri } },
+ });
+
+ renderEffect();
+
+ await waitFor(() => expect(jotaiStore.get(qrCodeState.atom)).toBe(uri));
+ });
+
+ it('sends the member to the recovery code step when setup is reserved for a recovery', async () => {
+ mockInitiateCurrentUserWorkspaceOtpProvisioning.mockRejectedValue(
+ new CombinedGraphQLErrors({
+ errors: [
+ {
+ message: 'RECOVERY_ENROLLMENT_RESTRICTED',
+ extensions: {
+ subCode: 'RECOVERY_ENROLLMENT_RESTRICTED',
+ userFriendlyMessage:
+ 'Ask a workspace admin for a new recovery code to finish setting up two-factor authentication.',
+ },
+ },
+ ],
+ }),
+ );
+
+ renderEffect();
+
+ await waitFor(() =>
+ expect(jotaiStore.get(signInUpStepState.atom)).toBe(
+ SignInUpStep.TwoFactorAuthenticationRecovery,
+ ),
+ );
+ expect(mockEnqueueToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: 'error',
+ children:
+ 'Ask a workspace admin for a new recovery code to finish setting up two-factor authentication.',
+ }),
+ );
+ expect(jotaiStore.get(qrCodeState.atom)).toBeNull();
+ });
+});
diff --git a/packages/twenty-front/src/modules/auth/graphql/mutations/getAuthTokensFromTwoFactorAuthenticationRecoveryCode.ts b/packages/twenty-front/src/modules/auth/graphql/mutations/getAuthTokensFromTwoFactorAuthenticationRecoveryCode.ts
new file mode 100644
index 00000000000..04202c4975b
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/graphql/mutations/getAuthTokensFromTwoFactorAuthenticationRecoveryCode.ts
@@ -0,0 +1,22 @@
+import { gql } from '@apollo/client';
+
+export const GET_AUTH_TOKENS_FROM_TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE = gql`
+ mutation getAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ $loginToken: String!
+ $recoveryCode: String!
+ $captchaToken: String
+ $origin: String!
+ ) {
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ loginToken: $loginToken
+ recoveryCode: $recoveryCode
+ captchaToken: $captchaToken
+ origin: $origin
+ ) {
+ tokens {
+ ...AuthTokenPairFragment
+ }
+ provisioningUri
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
index e3d6ee726d8..d460985db4b 100644
--- a/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
+++ b/packages/twenty-front/src/modules/auth/hooks/useAuth.ts
@@ -12,6 +12,7 @@ import {
CheckUserExistsDocument,
GetAuthTokensFromLoginTokenDocument,
GetAuthTokensFromOtpDocument,
+ GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeDocument,
GetLoginTokenFromCredentialsDocument,
GetWorkspaceCreationDefaultsDocument,
SignInDocument,
@@ -104,6 +105,9 @@ export const useAuth = () => {
VerifyEmailAndGetWorkspaceAgnosticTokenDocument,
);
const [getAuthTokensFromOtp] = useMutation(GetAuthTokensFromOtpDocument);
+ const [getAuthTokensFromTwoFactorAuthenticationRecoveryCode] = useMutation(
+ GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeDocument,
+ );
const [signOutMutation] = useMutation(SignOutDocument);
const workspacePublicData = useAtomStateValue(workspacePublicDataState);
@@ -626,6 +630,51 @@ export const useAuth = () => {
[getAuthTokensFromOtp, origin, handleLoadWorkspaceAfterAuthentication],
);
+ const handleGetAuthTokensFromTwoFactorAuthenticationRecoveryCode =
+ useCallback(
+ async (
+ recoveryCode: string,
+ loginToken: string,
+ captchaToken?: string,
+ ) => {
+ const result =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ variables: {
+ captchaToken,
+ origin,
+ recoveryCode,
+ loginToken,
+ },
+ });
+
+ if (isDefined(result.error)) {
+ throw result.error;
+ }
+
+ const redemption =
+ result.data?.getAuthTokensFromTwoFactorAuthenticationRecoveryCode;
+
+ if (!isDefined(redemption)) {
+ throw new Error(
+ 'No getAuthTokensFromTwoFactorAuthenticationRecoveryCode result',
+ );
+ }
+
+ if (isDefined(redemption.provisioningUri)) {
+ return { provisioningUri: redemption.provisioningUri };
+ }
+
+ await handleLoadWorkspaceAfterAuthentication();
+
+ return { provisioningUri: null };
+ },
+ [
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode,
+ origin,
+ handleLoadWorkspaceAfterAuthentication,
+ ],
+ );
+
return {
getLoginTokenFromCredentials: handleGetLoginTokenFromCredentials,
verifyEmailAndGetWorkspaceAgnosticToken:
@@ -642,6 +691,8 @@ export const useAuth = () => {
signInWithGoogle: handleGoogleLogin,
signInWithMicrosoft: handleMicrosoftLogin,
getAuthTokensFromOTP: handleGetAuthTokensFromOTP,
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode:
+ handleGetAuthTokensFromTwoFactorAuthenticationRecoveryCode,
navigateAfterMultiWorkspaceSignInUp,
};
};
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/SignInUpStandardContent.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/SignInUpStandardContent.tsx
index 859d87b5d70..c6590dacac7 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/components/SignInUpStandardContent.tsx
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/SignInUpStandardContent.tsx
@@ -62,6 +62,7 @@ export const SignInUpStandardContent = ({
SignInUpStep.Password,
SignInUpStep.TwoFactorAuthenticationProvision,
SignInUpStep.TwoFactorAuthenticationVerification,
+ SignInUpStep.TwoFactorAuthenticationRecovery,
SignInUpStep.WorkspaceSelection,
SignInUpStep.WorkspaceCreation,
].includes(signInUpStep) && (
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationRecovery.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationRecovery.tsx
new file mode 100644
index 00000000000..832e4cb7262
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationRecovery.tsx
@@ -0,0 +1,141 @@
+import { useAuth } from '@/auth/hooks/useAuth';
+import { StyledTwoFactorInstructions } from '@/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationStyles';
+import { loginTokenState } from '@/auth/states/loginTokenState';
+import { qrCodeState } from '@/auth/states/qrCode';
+import {
+ SignInUpStep,
+ signInUpStepState,
+} from '@/auth/states/signInUpStepState';
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
+import { useReadCaptchaToken } from '@/captcha/hooks/useReadCaptchaToken';
+import { useCaptcha } from '@/client-config/hooks/useCaptcha';
+import { ONBOARDING_CONTENT_BLOCK_WIDTH } from '@/onboarding/constants/OnboardingContentBlockWidth';
+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
+import { useAtomStateValue } from '@/ui/utilities/state/jotai/hooks/useAtomStateValue';
+import { useSetAtomState } from '@/ui/utilities/state/jotai/hooks/useSetAtomState';
+import { styled } from '@linaria/react';
+import { Trans, useLingui } from '@lingui/react/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { type FormEvent, useState } from 'react';
+import { AppPath } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import { MainButton } from 'twenty-ui/components/input';
+import { useToast } from 'twenty-ui/components/feedback';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+import { useNavigateApp } from '~/hooks/useNavigateApp';
+
+const StyledForm = styled.form`
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ max-width: 100%;
+ width: ${ONBOARDING_CONTENT_BLOCK_WIDTH}px;
+`;
+
+const StyledInputContainer = styled.div`
+ margin-bottom: ${themeCssVariables.spacing[4]};
+ width: 100%;
+`;
+
+const StyledActionBackLinkContainer = styled.div`
+ margin: ${themeCssVariables.spacing[3]} 0 0;
+`;
+
+export const SignInUpTwoFactorAuthenticationRecovery = () => {
+ const [recoveryCode, setRecoveryCode] = useState('');
+ const [isLoading, setIsLoading] = useState(false);
+
+ const { getAuthTokensFromTwoFactorAuthenticationRecoveryCode } = useAuth();
+ const { enqueueToast } = useToast();
+ const navigate = useNavigateApp();
+ const { readCaptchaToken } = useReadCaptchaToken();
+ const { isCaptchaReady } = useCaptcha();
+ const loginToken = useAtomStateValue(loginTokenState);
+ const setSignInUpStep = useSetAtomState(signInUpStepState);
+ const setQrCode = useSetAtomState(qrCodeState);
+ const { t } = useLingui();
+
+ const handleSubmit = async (event: FormEvent<HTMLFormElement>) => {
+ event.preventDefault();
+
+ if (!isCaptchaReady) {
+ enqueueToast({
+ variant: 'error',
+ children: t`Captcha (anti-bot check) is still loading, try again`,
+ });
+ return;
+ }
+
+ if (!isNonEmptyString(loginToken)) {
+ return navigate(AppPath.SignInUp);
+ }
+
+ setIsLoading(true);
+
+ try {
+ const { provisioningUri } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ recoveryCode,
+ loginToken,
+ readCaptchaToken(),
+ );
+
+ if (isDefined(provisioningUri)) {
+ setQrCode(provisioningUri);
+ setSignInUpStep(SignInUpStep.TwoFactorAuthenticationProvision);
+ return;
+ }
+
+ enqueueToast({
+ variant: 'info',
+ children: t`Two-factor authentication was reset for this workspace. Set it up again from Settings, Profile.`,
+ });
+ } catch (error) {
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Invalid or expired recovery code.`,
+ }),
+ );
+ } finally {
+ setIsLoading(false);
+ }
+ };
+
+ const handleBack = () => {
+ setSignInUpStep(SignInUpStep.TwoFactorAuthenticationVerification);
+ };
+
+ return (
+ <StyledForm onSubmit={handleSubmit}>
+ <StyledTwoFactorInstructions>
+ <Trans>
+ Enter the recovery code a workspace admin gave you. Your current
+ authenticator for this workspace will be removed.
+ </Trans>
+ </StyledTwoFactorInstructions>
+ <StyledInputContainer>
+ <SettingsTextInput
+ instanceId="sign-in-up-two-factor-authentication-recovery-code"
+ autoComplete="one-time-code"
+ autoFocus
+ value={recoveryCode}
+ placeholder="XXXXX-XXXXX-XXXXX-XXXXX"
+ onChange={setRecoveryCode}
+ fullWidth
+ />
+ </StyledInputContainer>
+ <MainButton
+ type="submit"
+ fullWidth
+ disabled={isLoading || !isNonEmptyString(recoveryCode.trim())}
+ >{t`Continue`}</MainButton>
+ <StyledActionBackLinkContainer>
+ <Button variant="link" onClick={handleBack}>
+ <Trans>Back</Trans>
+ </Button>
+ </StyledActionBackLinkContainer>
+ </StyledForm>
+ );
+};
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
index f86a3e67a62..97b9788c7c2 100644
--- a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification.tsx
@@ -218,6 +218,10 @@ export const SignInUpTOTPVerification = () => {
setSignInUpStep(SignInUpStep.TwoFactorAuthenticationProvision);
};
+ const handleUseRecoveryCode = () => {
+ setSignInUpStep(SignInUpStep.TwoFactorAuthenticationRecovery);
+ };
+
return (
<StyledForm onSubmit={form.handleSubmit(submitOTP)}>
<StyledTwoFactorInstructions>
@@ -269,6 +273,11 @@ export const SignInUpTOTPVerification = () => {
fullWidth
disabled={isLoading}
>{t`Submit`}</MainButton>
+ <StyledActionBackLinkContainer>
+ <Button variant="link" onClick={handleUseRecoveryCode}>
+ <Trans>Lost your authenticator? Use a recovery code</Trans>
+ </Button>
+ </StyledActionBackLinkContainer>
<StyledActionBackLinkContainer>
<Button variant="link" onClick={handleBack}>
<Trans>Back</Trans>
diff --git a/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/__tests__/SignInUpTwoFactorAuthenticationRecovery.test.tsx b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/__tests__/SignInUpTwoFactorAuthenticationRecovery.test.tsx
new file mode 100644
index 00000000000..107c797e933
--- /dev/null
+++ b/packages/twenty-front/src/modules/auth/sign-in-up/components/internal/__tests__/SignInUpTwoFactorAuthenticationRecovery.test.tsx
@@ -0,0 +1,157 @@
+import { CombinedGraphQLErrors } from '@apollo/client/errors';
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { Provider as JotaiProvider } from 'jotai';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+import { ThemeProvider } from 'twenty-ui/theme';
+
+import { SignInUpTwoFactorAuthenticationRecovery } from '@/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationRecovery';
+import { loginTokenState } from '@/auth/states/loginTokenState';
+import { qrCodeState } from '@/auth/states/qrCode';
+import {
+ SignInUpStep,
+ signInUpStepState,
+} from '@/auth/states/signInUpStepState';
+import {
+ jotaiStore,
+ resetJotaiStore,
+} from '@/ui/utilities/state/jotai/jotaiStore';
+import { dynamicActivate } from '~/utils/i18n/dynamicActivate';
+
+const mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode = jest.fn();
+const mockEnqueueToast = jest.fn();
+
+jest.mock('@/auth/hooks/useAuth', () => ({
+ useAuth: () => ({
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode:
+ mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode,
+ }),
+}));
+
+jest.mock('@/captcha/hooks/useReadCaptchaToken', () => ({
+ useReadCaptchaToken: () => ({ readCaptchaToken: () => 'captcha-token' }),
+}));
+
+jest.mock('@/client-config/hooks/useCaptcha', () => ({
+ useCaptcha: () => ({ isCaptchaReady: true }),
+}));
+
+jest.mock('~/hooks/useNavigateApp', () => ({
+ useNavigateApp: () => jest.fn(),
+}));
+
+jest.mock('twenty-ui/components/feedback', () => ({
+ ...jest.requireActual('twenty-ui/components/feedback'),
+ useToast: () => ({ enqueueToast: mockEnqueueToast }),
+}));
+
+dynamicActivate(SOURCE_LOCALE);
+
+const buildGraphqlError = (
+ subCode: string,
+ userFriendlyMessage: string,
+): CombinedGraphQLErrors =>
+ new CombinedGraphQLErrors({
+ errors: [
+ {
+ message: subCode,
+ extensions: { subCode, userFriendlyMessage },
+ },
+ ],
+ });
+
+const renderRecoveryStep = () =>
+ render(
+ <JotaiProvider store={jotaiStore}>
+ <ThemeProvider colorScheme="light">
+ <I18nProvider i18n={i18n}>
+ <SignInUpTwoFactorAuthenticationRecovery />
+ </I18nProvider>
+ </ThemeProvider>
+ </JotaiProvider>,
+ );
+
+const submitRecoveryCode = async (recoveryCode: string) => {
+ const user = userEvent.setup();
+
+ await user.type(
+ screen.getByPlaceholderText('XXXXX-XXXXX-XXXXX-XXXXX'),
+ recoveryCode,
+ );
+ await user.click(screen.getByRole('button', { name: 'Continue' }));
+};
+
+describe('SignInUpTwoFactorAuthenticationRecovery', () => {
+ beforeEach(() => {
+ jest.clearAllMocks();
+ resetJotaiStore();
+ jotaiStore.set(loginTokenState.atom, 'login-token');
+ jotaiStore.set(
+ signInUpStepState.atom,
+ SignInUpStep.TwoFactorAuthenticationRecovery,
+ );
+ });
+
+ it('signs in with the recovery code and reminds the member to set up two-factor authentication again', async () => {
+ mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode.mockResolvedValue({
+ provisioningUri: null,
+ });
+
+ renderRecoveryStep();
+ await submitRecoveryCode('ABCDE-FGHJK-MNPQR-STVWX');
+
+ expect(
+ mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode,
+ ).toHaveBeenCalledWith(
+ 'ABCDE-FGHJK-MNPQR-STVWX',
+ 'login-token',
+ 'captcha-token',
+ );
+ expect(mockEnqueueToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: 'info' }),
+ );
+ });
+
+ it('continues to the setup step with the authenticator issued by the redemption when the workspace enforces two-factor authentication', async () => {
+ const provisioningUri =
+ 'otpauth://totp/Twenty:[email protected]?secret=SECRETKEY&issuer=Twenty';
+
+ mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode.mockResolvedValue({
+ provisioningUri,
+ });
+
+ renderRecoveryStep();
+ await submitRecoveryCode('ABCDE-FGHJK-MNPQR-STVWX');
+
+ expect(jotaiStore.get(signInUpStepState.atom)).toBe(
+ SignInUpStep.TwoFactorAuthenticationProvision,
+ );
+ expect(jotaiStore.get(qrCodeState.atom)).toBe(provisioningUri);
+ expect(jotaiStore.get(loginTokenState.atom)).toBe('login-token');
+ expect(mockEnqueueToast).not.toHaveBeenCalled();
+ });
+
+ it('shows the server message when the code is rejected', async () => {
+ mockGetAuthTokensFromTwoFactorAuthenticationRecoveryCode.mockRejectedValue(
+ buildGraphqlError(
+ 'INVALID_RECOVERY_CODE',
+ 'Invalid or expired recovery code.',
+ ),
+ );
+
+ renderRecoveryStep();
+ await submitRecoveryCode('WRONG-CODE0-00000-00000');
+
+ expect(mockEnqueueToast).toHaveBeenCalledWith(
+ expect.objectContaining({
+ variant: 'error',
+ children: 'Invalid or expired recovery code.',
+ }),
+ );
+ expect(jotaiStore.get(signInUpStepState.atom)).toBe(
+ SignInUpStep.TwoFactorAuthenticationRecovery,
+ );
+ });
+});
diff --git a/packages/twenty-front/src/modules/auth/states/signInUpStepState.ts b/packages/twenty-front/src/modules/auth/states/signInUpStepState.ts
index b1f91b07631..23e434dcba9 100644
--- a/packages/twenty-front/src/modules/auth/states/signInUpStepState.ts
+++ b/packages/twenty-front/src/modules/auth/states/signInUpStepState.ts
@@ -9,6 +9,7 @@ export enum SignInUpStep {
SsoIdentityProviderSelection = 'SSOIdentityProviderSelection',
TwoFactorAuthenticationVerification = 'TwoFactorAuthenticationVerification',
TwoFactorAuthenticationProvision = 'TwoFactorAuthenticationProvision',
+ TwoFactorAuthenticationRecovery = 'TwoFactorAuthenticationRecovery',
}
export const signInUpStepState = createAtomState<SignInUpStep>({
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTwoFactorAuthenticationRecoveryCode.tsx b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTwoFactorAuthenticationRecoveryCode.tsx
new file mode 100644
index 00000000000..340693da40b
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/components/SettingsAdminTwoFactorAuthenticationRecoveryCode.tsx
@@ -0,0 +1,101 @@
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
+import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
+import { TwoFactorAuthenticationRecoveryCodeConfirmationDialog } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeConfirmationDialog';
+import { TwoFactorAuthenticationRecoveryCodeDisplay } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeDisplay';
+import { useGeneratedRecoveryCode } from '@/settings/two-factor-authentication/hooks/useGeneratedRecoveryCode';
+import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
+import { useMutation } from '@apollo/client/react';
+import { styled } from '@linaria/react';
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import { useToast } from 'twenty-ui/components/feedback';
+import { IconKey } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+import { GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminDocument } from '~/generated-admin/graphql';
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[3]};
+ margin-top: ${themeCssVariables.spacing[3]};
+`;
+
+type SettingsAdminTwoFactorAuthenticationRecoveryCodeProps = {
+ userId: string;
+ workspaceId: string;
+ memberName: string;
+};
+
+export const SettingsAdminTwoFactorAuthenticationRecoveryCode = ({
+ userId,
+ workspaceId,
+ memberName,
+}: SettingsAdminTwoFactorAuthenticationRecoveryCodeProps) => {
+ const dialogId = `admin-two-factor-authentication-recovery-code-${userId}-${workspaceId}`;
+ const apolloAdminClient = useApolloAdminClient();
+ const { openDialog } = useDialog();
+ const { enqueueToast } = useToast();
+ const {
+ generatedRecoveryCode,
+ showGeneratedRecoveryCode,
+ clearGeneratedRecoveryCode,
+ } = useGeneratedRecoveryCode();
+
+ const [generateRecoveryCode] = useMutation(
+ GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminDocument,
+ { client: apolloAdminClient },
+ );
+
+ const handleGenerate = async (otp: string) => {
+ try {
+ const result = await generateRecoveryCode({
+ variables: {
+ userId,
+ workspaceId,
+ otp: isNonEmptyString(otp) ? otp : undefined,
+ },
+ });
+
+ const recoveryCode =
+ result.data?.generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin;
+
+ if (isDefined(recoveryCode)) {
+ showGeneratedRecoveryCode(recoveryCode);
+ }
+ } catch (error) {
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Failed to generate a recovery code.`,
+ }),
+ );
+ }
+ };
+
+ return (
+ <StyledContainer>
+ {isDefined(generatedRecoveryCode) && (
+ <TwoFactorAuthenticationRecoveryCodeDisplay
+ recoveryCode={generatedRecoveryCode.recoveryCode}
+ expiresAt={generatedRecoveryCode.expiresAt}
+ memberName={memberName}
+ onExpire={clearGeneratedRecoveryCode}
+ />
+ )}
+ <div>
+ <Button
+ startIcon={<IconKey />}
+ variant="outline"
+ onClick={() => openDialog(dialogId)}
+ >{t`Generate 2FA recovery code`}</Button>
+ </div>
+ <TwoFactorAuthenticationRecoveryCodeConfirmationDialog
+ dialogId={dialogId}
+ memberName={memberName}
+ onConfirm={handleGenerate}
+ />
+ </StyledContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin.ts b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin.ts
new file mode 100644
index 00000000000..c47d05b91eb
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/admin-panel/graphql/mutations/generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin.ts
@@ -0,0 +1,18 @@
+import { gql } from '@apollo/client';
+
+export const GENERATE_TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_AS_SERVER_ADMIN = gql`
+ mutation GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdmin(
+ $userId: UUID!
+ $workspaceId: UUID!
+ $otp: String
+ ) {
+ generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin(
+ userId: $userId
+ workspaceId: $workspaceId
+ otp: $otp
+ ) {
+ recoveryCode
+ expiresAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/members/components/MemberInfosTab.tsx b/packages/twenty-front/src/modules/settings/members/components/MemberInfosTab.tsx
index 6c32e2a5e95..82068f4ad3b 100644
--- a/packages/twenty-front/src/modules/settings/members/components/MemberInfosTab.tsx
+++ b/packages/twenty-front/src/modules/settings/members/components/MemberInfosTab.tsx
@@ -3,9 +3,11 @@ import { useState } from 'react';
import { MemberEmailField } from '@/settings/members/components/MemberEmailField';
import { MemberNameFields } from '@/settings/members/components/MemberNameFields';
+import { MemberTwoFactorAuthenticationRecoverySection } from '@/settings/members/components/MemberTwoFactorAuthenticationRecoverySection';
import { WorkspaceMemberPictureUploader } from '@/settings/workspace-member/components/WorkspaceMemberPictureUploader';
import { type WorkspaceMember } from '@/workspace-member/types/WorkspaceMember';
import { t } from '@lingui/core/macro';
+import { isDefined } from 'twenty-shared/utils';
import { Section } from 'twenty-ui/components/layout';
import { Button } from 'twenty-ui/primitives/input';
import { themeCssVariables } from 'twenty-ui/theme';
@@ -15,6 +17,7 @@ type MemberInfosTabProps = {
onNameChange: (firstName: string, lastName: string) => void;
onImpersonate?: () => void;
onDelete: () => void;
+ twoFactorAuthenticationRecoveryUserId?: string;
};
const StyledNameRow = styled.div`
@@ -33,6 +36,7 @@ export const MemberInfosTab = ({
onNameChange,
onImpersonate,
onDelete,
+ twoFactorAuthenticationRecoveryUserId,
}: MemberInfosTabProps) => {
const [firstName, setFirstName] = useState(member.name.firstName);
const [lastName, setLastName] = useState(member.name.lastName);
@@ -82,6 +86,14 @@ export const MemberInfosTab = ({
<MemberEmailField email={member.userEmail} />
</Section.Root>
+ {isDefined(twoFactorAuthenticationRecoveryUserId) && (
+ <MemberTwoFactorAuthenticationRecoverySection
+ key={twoFactorAuthenticationRecoveryUserId}
+ userId={twoFactorAuthenticationRecoveryUserId}
+ memberName={`${firstName} ${lastName}`.trim()}
+ />
+ )}
+
<Section.Root>
<Section.Header
title={t`Admin`}
diff --git a/packages/twenty-front/src/modules/settings/members/components/MemberTwoFactorAuthenticationRecoverySection.tsx b/packages/twenty-front/src/modules/settings/members/components/MemberTwoFactorAuthenticationRecoverySection.tsx
new file mode 100644
index 00000000000..9be2b2d88da
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/members/components/MemberTwoFactorAuthenticationRecoverySection.tsx
@@ -0,0 +1,171 @@
+import { getTwoFactorAuthenticationErrorToastOptions } from '@/auth/utils/getTwoFactorAuthenticationErrorToastOptions';
+import { TwoFactorAuthenticationRecoveryCodeConfirmationDialog } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeConfirmationDialog';
+import { TwoFactorAuthenticationRecoveryCodeDisplay } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeDisplay';
+import { useGeneratedRecoveryCode } from '@/settings/two-factor-authentication/hooks/useGeneratedRecoveryCode';
+import { useDialog } from '@/ui/layout/dialog/hooks/useDialog';
+import { useMutation, useQuery } from '@apollo/client/react';
+import { styled } from '@linaria/react';
+import { t } from '@lingui/core/macro';
+import { isNonEmptyString } from '@sniptt/guards';
+import { isDefined } from 'twenty-shared/utils';
+import { useToast } from 'twenty-ui/components/feedback';
+import { Section } from 'twenty-ui/components/layout';
+import { Status } from 'twenty-ui/primitives/data-display';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+import {
+ GenerateTwoFactorAuthenticationRecoveryCodeDocument,
+ RevokeTwoFactorAuthenticationRecoveryCodeDocument,
+ TwoFactorAuthenticationRecoveryStatusDocument,
+} from '~/generated-metadata/graphql';
+import { beautifyExactDateTime } from '~/utils/date-utils';
+
+const StyledContent = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[3]};
+`;
+
+const StyledActionRow = styled.div`
+ align-items: center;
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledNotice = styled.div`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.sm};
+`;
+
+type MemberTwoFactorAuthenticationRecoverySectionProps = {
+ userId: string;
+ memberName: string;
+};
+
+export const MemberTwoFactorAuthenticationRecoverySection = ({
+ userId,
+ memberName,
+}: MemberTwoFactorAuthenticationRecoverySectionProps) => {
+ const generateRecoveryCodeDialogId = `member-two-factor-authentication-recovery-code-dialog-${userId}`;
+ const { openDialog } = useDialog();
+ const { enqueueToast } = useToast();
+ const {
+ generatedRecoveryCode,
+ showGeneratedRecoveryCode,
+ clearGeneratedRecoveryCode,
+ } = useGeneratedRecoveryCode();
+
+ const { data, refetch } = useQuery(
+ TwoFactorAuthenticationRecoveryStatusDocument,
+ { variables: { userId }, fetchPolicy: 'network-only' },
+ );
+
+ const [generateRecoveryCode] = useMutation(
+ GenerateTwoFactorAuthenticationRecoveryCodeDocument,
+ );
+ const [revokeRecoveryCode] = useMutation(
+ RevokeTwoFactorAuthenticationRecoveryCodeDocument,
+ );
+
+ const recoveryStatus = data?.twoFactorAuthenticationRecoveryStatus;
+
+ if (!isDefined(recoveryStatus)) {
+ return null;
+ }
+
+ const handleGenerate = async (otp: string) => {
+ try {
+ const result = await generateRecoveryCode({
+ variables: { userId, otp: isNonEmptyString(otp) ? otp : undefined },
+ });
+
+ const recoveryCode =
+ result.data?.generateTwoFactorAuthenticationRecoveryCode;
+
+ if (isDefined(recoveryCode)) {
+ showGeneratedRecoveryCode(recoveryCode);
+ }
+
+ await refetch();
+ } catch (error) {
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Failed to generate a recovery code.`,
+ }),
+ );
+ }
+ };
+
+ const handleRevoke = async () => {
+ try {
+ await revokeRecoveryCode({ variables: { userId } });
+ clearGeneratedRecoveryCode();
+ await refetch();
+ enqueueToast({
+ variant: 'success',
+ children: t`Recovery code revoked.`,
+ });
+ } catch (error) {
+ enqueueToast(
+ getTwoFactorAuthenticationErrorToastOptions({
+ error,
+ fallbackMessage: t`Failed to revoke the recovery code.`,
+ }),
+ );
+ }
+ };
+
+ const pendingRecoveryCodeExpiresAt =
+ recoveryStatus.pendingRecoveryCodeExpiresAt;
+
+ return (
+ <Section.Root>
+ <Section.Header
+ title={t`Two-factor authentication`}
+ description={t`Let this member sign in again if they lost their authenticator app`}
+ />
+ {recoveryStatus.hasVerifiedTwoFactorAuthenticationMethod ||
+ recoveryStatus.isAwaitingRecoveryEnrollment ? (
+ <StyledContent>
+ {isDefined(generatedRecoveryCode) && (
+ <TwoFactorAuthenticationRecoveryCodeDisplay
+ recoveryCode={generatedRecoveryCode.recoveryCode}
+ expiresAt={generatedRecoveryCode.expiresAt}
+ memberName={memberName}
+ onExpire={clearGeneratedRecoveryCode}
+ />
+ )}
+ <StyledActionRow>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => openDialog(generateRecoveryCodeDialogId)}
+ >{t`Generate recovery code`}</Button>
+ {isDefined(pendingRecoveryCodeExpiresAt) && (
+ <>
+ <Status color="orange" weight="medium">
+ {t`Code pending until ${beautifyExactDateTime(pendingRecoveryCodeExpiresAt)}`}
+ </Status>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={handleRevoke}
+ >{t`Revoke`}</Button>
+ </>
+ )}
+ </StyledActionRow>
+ </StyledContent>
+ ) : (
+ <StyledNotice>
+ {t`This member hasn't set up two-factor authentication.`}
+ </StyledNotice>
+ )}
+ <TwoFactorAuthenticationRecoveryCodeConfirmationDialog
+ dialogId={generateRecoveryCodeDialogId}
+ memberName={memberName}
+ onConfirm={handleGenerate}
+ />
+ </Section.Root>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/members/components/__tests__/MemberTwoFactorAuthenticationRecoverySection.test.tsx b/packages/twenty-front/src/modules/settings/members/components/__tests__/MemberTwoFactorAuthenticationRecoverySection.test.tsx
new file mode 100644
index 00000000000..c55da4bf9c2
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/members/components/__tests__/MemberTwoFactorAuthenticationRecoverySection.test.tsx
@@ -0,0 +1,142 @@
+import { type MockedResponse } from '@apollo/client/testing';
+import { MockedProvider } from '@apollo/client/testing/react';
+import { i18n } from '@lingui/core';
+import { I18nProvider } from '@lingui/react';
+import { render, screen, waitFor } from '@testing-library/react';
+import userEvent from '@testing-library/user-event';
+import { createStore, Provider } from 'jotai';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+import { ThemeProvider } from 'twenty-ui/theme';
+
+import { MemberTwoFactorAuthenticationRecoverySection } from '@/settings/members/components/MemberTwoFactorAuthenticationRecoverySection';
+import {
+ RevokeTwoFactorAuthenticationRecoveryCodeDocument,
+ TwoFactorAuthenticationRecoveryStatusDocument,
+} from '~/generated-metadata/graphql';
+import { dynamicActivate } from '~/utils/i18n/dynamicActivate';
+
+const enqueueToast = jest.fn();
+
+jest.mock('twenty-ui/components/feedback', () => ({
+ ...jest.requireActual('twenty-ui/components/feedback'),
+ useToast: () => ({ enqueueToast }),
+}));
+
+dynamicActivate(SOURCE_LOCALE);
+
+const USER_ID = '20202020-3957-4908-9c36-2929a23f8357';
+
+const statusMock = ({
+ hasVerifiedTwoFactorAuthenticationMethod,
+ isAwaitingRecoveryEnrollment = false,
+ pendingRecoveryCodeExpiresAt,
+}: {
+ hasVerifiedTwoFactorAuthenticationMethod: boolean;
+ isAwaitingRecoveryEnrollment?: boolean;
+ pendingRecoveryCodeExpiresAt: string | null;
+}): MockedResponse => ({
+ request: {
+ query: TwoFactorAuthenticationRecoveryStatusDocument,
+ variables: { userId: USER_ID },
+ },
+ result: {
+ data: {
+ twoFactorAuthenticationRecoveryStatus: {
+ __typename: 'TwoFactorAuthenticationRecoveryStatus',
+ hasVerifiedTwoFactorAuthenticationMethod,
+ isAwaitingRecoveryEnrollment,
+ pendingRecoveryCodeExpiresAt,
+ },
+ },
+ },
+});
+
+const renderSection = (mocks: MockedResponse[]) =>
+ render(
+ <Provider store={createStore()}>
+ <MockedProvider mocks={mocks}>
+ <ThemeProvider colorScheme="light">
+ <I18nProvider i18n={i18n}>
+ <MemberTwoFactorAuthenticationRecoverySection
+ userId={USER_ID}
+ memberName="Jony Ive"
+ />
+ </I18nProvider>
+ </ThemeProvider>
+ </MockedProvider>
+ </Provider>,
+ );
+
+beforeEach(() => jest.clearAllMocks());
+
+it('explains that there is nothing to recover when the member has no authenticator', async () => {
+ renderSection([
+ statusMock({
+ hasVerifiedTwoFactorAuthenticationMethod: false,
+ pendingRecoveryCodeExpiresAt: null,
+ }),
+ ]);
+
+ expect(
+ await screen.findByText(
+ "This member hasn't set up two-factor authentication.",
+ ),
+ ).toBeInTheDocument();
+ expect(
+ screen.queryByRole('button', { name: 'Generate recovery code' }),
+ ).not.toBeInTheDocument();
+});
+
+it('lets the admin issue a new code to a member who has not finished setting up the authenticator from a recovery', async () => {
+ renderSection([
+ statusMock({
+ hasVerifiedTwoFactorAuthenticationMethod: false,
+ isAwaitingRecoveryEnrollment: true,
+ pendingRecoveryCodeExpiresAt: null,
+ }),
+ ]);
+
+ expect(
+ await screen.findByRole('button', { name: 'Generate recovery code' }),
+ ).toBeInTheDocument();
+});
+
+it('shows a pending code and revokes it', async () => {
+ const revoke = jest.fn(() => ({
+ data: { revokeTwoFactorAuthenticationRecoveryCode: true },
+ }));
+
+ renderSection([
+ statusMock({
+ hasVerifiedTwoFactorAuthenticationMethod: true,
+ pendingRecoveryCodeExpiresAt: new Date(
+ Date.now() + 60 * 60 * 1000,
+ ).toISOString(),
+ }),
+ {
+ request: {
+ query: RevokeTwoFactorAuthenticationRecoveryCodeDocument,
+ variables: { userId: USER_ID },
+ },
+ result: revoke,
+ },
+ statusMock({
+ hasVerifiedTwoFactorAuthenticationMethod: true,
+ pendingRecoveryCodeExpiresAt: null,
+ }),
+ ]);
+
+ const user = userEvent.setup();
+
+ await user.click(await screen.findByRole('button', { name: 'Revoke' }));
+
+ await waitFor(() =>
+ expect(
+ screen.queryByRole('button', { name: 'Revoke' }),
+ ).not.toBeInTheDocument(),
+ );
+ expect(revoke).toHaveBeenCalledTimes(1);
+ expect(enqueueToast).toHaveBeenCalledWith(
+ expect.objectContaining({ variant: 'success' }),
+ );
+});
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeConfirmationDialog.tsx b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeConfirmationDialog.tsx
new file mode 100644
index 00000000000..d69a749ed6e
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeConfirmationDialog.tsx
@@ -0,0 +1,88 @@
+import { TwoFactorAuthenticationVerificationCodeDash } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationVerificationCodeDash';
+import { TwoFactorAuthenticationVerificationCodeSlot } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationVerificationCodeSlot';
+import { ConfirmationDialog } from '@/ui/layout/dialog/components/ConfirmationDialog';
+import { styled } from '@linaria/react';
+import { t } from '@lingui/core/macro';
+import { OTPInput } from 'input-otp';
+import { useState } from 'react';
+import { themeCssVariables } from 'twenty-ui/theme';
+
+const OTP_LENGTH = 6;
+
+const StyledConfirmationContent = styled.div`
+ align-items: center;
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[4]};
+`;
+
+const StyledOTPContainer = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[1]};
+`;
+
+type TwoFactorAuthenticationRecoveryCodeConfirmationDialogProps = {
+ dialogId: string;
+ memberName: string;
+ onConfirm: (otp: string) => void;
+};
+
+export const TwoFactorAuthenticationRecoveryCodeConfirmationDialog = ({
+ dialogId,
+ memberName,
+ onConfirm,
+}: TwoFactorAuthenticationRecoveryCodeConfirmationDialogProps) => {
+ const [otp, setOtp] = useState('');
+
+ return (
+ <ConfirmationDialog
+ dialogId={dialogId}
+ title={t`Generate a recovery code`}
+ confirmButtonColor="accent"
+ confirmButtonText={t`Generate code`}
+ isConfirmButtonDisabled={otp.length !== OTP_LENGTH}
+ onConfirmClick={() => {
+ onConfirm(otp);
+ setOtp('');
+ }}
+ onClose={() => setOtp('')}
+ subtitle={
+ <StyledConfirmationContent>
+ <div>
+ {t`The code lets ${memberName} sign in to this workspace once without their authenticator app. Using it removes their current authenticator and signs them out of their other sessions here. They will be notified by email.`}
+ </div>
+ <div>{t`Enter your two-factor authentication code to confirm.`}</div>
+ <OTPInput
+ maxLength={OTP_LENGTH}
+ value={otp}
+ onChange={setOtp}
+ autoFocus
+ render={({ slots }) => (
+ <StyledOTPContainer>
+ {slots.slice(0, 3).map((slot, index) => (
+ <TwoFactorAuthenticationVerificationCodeSlot
+ key={index}
+ char={slot.char}
+ placeholderChar={slot.placeholderChar}
+ isActive={slot.isActive}
+ hasFakeCaret={slot.hasFakeCaret}
+ />
+ ))}
+ <TwoFactorAuthenticationVerificationCodeDash />
+ {slots.slice(3).map((slot, index) => (
+ <TwoFactorAuthenticationVerificationCodeSlot
+ key={index + 3}
+ char={slot.char}
+ placeholderChar={slot.placeholderChar}
+ isActive={slot.isActive}
+ hasFakeCaret={slot.hasFakeCaret}
+ />
+ ))}
+ </StyledOTPContainer>
+ )}
+ />
+ </StyledConfirmationContent>
+ }
+ />
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeDisplay.tsx b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeDisplay.tsx
new file mode 100644
index 00000000000..6c5e77f25ea
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeDisplay.tsx
@@ -0,0 +1,75 @@
+import { TwoFactorAuthenticationRecoveryCodeExpiryEffect } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeExpiryEffect';
+import { SettingsTextInput } from '@/ui/input/components/SettingsTextInput';
+import { styled } from '@linaria/react';
+import { useLingui } from '@lingui/react/macro';
+import { IconCopy } from 'twenty-ui/icon';
+import { Button } from 'twenty-ui/primitives/input';
+import { themeCssVariables } from 'twenty-ui/theme';
+import { useCopyToClipboard } from '~/hooks/useCopyToClipboard';
+import { beautifyExactDateTime } from '~/utils/date-utils';
+
+const StyledContainer = styled.div`
+ display: flex;
+ flex-direction: column;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledCodeRow = styled.div`
+ display: flex;
+ gap: ${themeCssVariables.spacing[2]};
+`;
+
+const StyledCodeInputContainer = styled.div`
+ flex: 1;
+`;
+
+const StyledHint = styled.div`
+ color: ${themeCssVariables.font.color.tertiary};
+ font-size: ${themeCssVariables.font.size.sm};
+`;
+
+type TwoFactorAuthenticationRecoveryCodeDisplayProps = {
+ recoveryCode: string;
+ expiresAt: string;
+ memberName: string;
+ onExpire: () => void;
+};
+
+export const TwoFactorAuthenticationRecoveryCodeDisplay = ({
+ recoveryCode,
+ expiresAt,
+ memberName,
+ onExpire,
+}: TwoFactorAuthenticationRecoveryCodeDisplayProps) => {
+ const { t } = useLingui();
+ const { copyToClipboard } = useCopyToClipboard();
+ const formattedExpiresAt = beautifyExactDateTime(expiresAt);
+
+ return (
+ <StyledContainer>
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={expiresAt}
+ onExpire={onExpire}
+ />
+ <StyledCodeRow>
+ <StyledCodeInputContainer>
+ <SettingsTextInput
+ instanceId="two-factor-authentication-recovery-code-display"
+ value={recoveryCode}
+ readOnly
+ fullWidth
+ />
+ </StyledCodeInputContainer>
+ <Button
+ startIcon={<IconCopy />}
+ onClick={() =>
+ copyToClipboard(recoveryCode, t`Recovery code copied to clipboard`)
+ }
+ >{t`Copy`}</Button>
+ </StyledCodeRow>
+ <StyledHint>
+ {t`Share this code with ${memberName} through a channel you trust. It works once and expires at ${formattedExpiresAt}. You won't be able to see it again.`}
+ </StyledHint>
+ </StyledContainer>
+ );
+};
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeExpiryEffect.tsx b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeExpiryEffect.tsx
new file mode 100644
index 00000000000..71817e02f4c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeExpiryEffect.tsx
@@ -0,0 +1,31 @@
+import { useEffect } from 'react';
+
+const MINIMUM_DISPLAY_DURATION_MS = 5 * 60 * 1000;
+const MAXIMUM_TIMEOUT_DELAY_MS = 2_147_483_647;
+
+type TwoFactorAuthenticationRecoveryCodeExpiryEffectProps = {
+ expiresAt: string;
+ onExpire: () => void;
+};
+
+export const TwoFactorAuthenticationRecoveryCodeExpiryEffect = ({
+ expiresAt,
+ onExpire,
+}: TwoFactorAuthenticationRecoveryCodeExpiryEffectProps) => {
+ useEffect(() => {
+ const expiryTimeoutId = setTimeout(
+ onExpire,
+ Math.min(
+ Math.max(
+ new Date(expiresAt).getTime() - Date.now(),
+ MINIMUM_DISPLAY_DURATION_MS,
+ ),
+ MAXIMUM_TIMEOUT_DELAY_MS,
+ ),
+ );
+
+ return () => clearTimeout(expiryTimeoutId);
+ }, [expiresAt, onExpire]);
+
+ return null;
+};
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/components/__tests__/TwoFactorAuthenticationRecoveryCodeExpiryEffect.test.tsx b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/__tests__/TwoFactorAuthenticationRecoveryCodeExpiryEffect.test.tsx
new file mode 100644
index 00000000000..dd103fedf4c
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/components/__tests__/TwoFactorAuthenticationRecoveryCodeExpiryEffect.test.tsx
@@ -0,0 +1,99 @@
+import { render } from '@testing-library/react';
+
+import { TwoFactorAuthenticationRecoveryCodeExpiryEffect } from '@/settings/two-factor-authentication/components/TwoFactorAuthenticationRecoveryCodeExpiryEffect';
+
+const ONE_HOUR_MS = 60 * 60 * 1000;
+const FIVE_MINUTES_MS = 5 * 60 * 1000;
+const FORTY_DAYS_MS = 40 * 24 * ONE_HOUR_MS;
+
+const inOneHour = () => new Date(Date.now() + ONE_HOUR_MS).toISOString();
+
+describe('TwoFactorAuthenticationRecoveryCodeExpiryEffect', () => {
+ beforeEach(() => jest.useFakeTimers());
+ afterEach(() => jest.useRealTimers());
+
+ it('calls onExpire once the code expires', () => {
+ const onExpire = jest.fn();
+
+ render(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={inOneHour()}
+ onExpire={onExpire}
+ />,
+ );
+
+ jest.advanceTimersByTime(ONE_HOUR_MS - 1000);
+ expect(onExpire).not.toHaveBeenCalled();
+
+ jest.advanceTimersByTime(1000);
+ expect(onExpire).toHaveBeenCalledTimes(1);
+ });
+
+ it('waits for the newer expiry when a new code replaces the old one', () => {
+ const onExpire = jest.fn();
+ const { rerender } = render(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={inOneHour()}
+ onExpire={onExpire}
+ />,
+ );
+
+ jest.advanceTimersByTime(ONE_HOUR_MS / 2);
+ rerender(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={inOneHour()}
+ onExpire={onExpire}
+ />,
+ );
+ jest.advanceTimersByTime(ONE_HOUR_MS / 2);
+
+ expect(onExpire).not.toHaveBeenCalled();
+ });
+
+ it('keeps the code visible for a while when the browser clock is ahead of the server', () => {
+ const onExpire = jest.fn();
+
+ render(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={new Date(Date.now() - ONE_HOUR_MS).toISOString()}
+ onExpire={onExpire}
+ />,
+ );
+
+ jest.advanceTimersByTime(FIVE_MINUTES_MS - 1000);
+ expect(onExpire).not.toHaveBeenCalled();
+
+ jest.advanceTimersByTime(1000);
+ expect(onExpire).toHaveBeenCalledTimes(1);
+ });
+
+ it('keeps the code visible when the expiry is beyond the longest timer delay', () => {
+ const onExpire = jest.fn();
+
+ render(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={new Date(Date.now() + FORTY_DAYS_MS).toISOString()}
+ onExpire={onExpire}
+ />,
+ );
+
+ jest.advanceTimersByTime(ONE_HOUR_MS);
+
+ expect(onExpire).not.toHaveBeenCalled();
+ });
+
+ it('does not call onExpire after unmounting', () => {
+ const onExpire = jest.fn();
+ const { unmount } = render(
+ <TwoFactorAuthenticationRecoveryCodeExpiryEffect
+ expiresAt={inOneHour()}
+ onExpire={onExpire}
+ />,
+ );
+
+ unmount();
+ jest.advanceTimersByTime(ONE_HOUR_MS);
+
+ expect(onExpire).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/generateTwoFactorAuthenticationRecoveryCode.ts b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/generateTwoFactorAuthenticationRecoveryCode.ts
new file mode 100644
index 00000000000..d7a930378bf
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/generateTwoFactorAuthenticationRecoveryCode.ts
@@ -0,0 +1,13 @@
+import { gql } from '@apollo/client';
+
+export const GENERATE_TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE = gql`
+ mutation generateTwoFactorAuthenticationRecoveryCode(
+ $userId: UUID!
+ $otp: String
+ ) {
+ generateTwoFactorAuthenticationRecoveryCode(userId: $userId, otp: $otp) {
+ recoveryCode
+ expiresAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/revokeTwoFactorAuthenticationRecoveryCode.ts b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/revokeTwoFactorAuthenticationRecoveryCode.ts
new file mode 100644
index 00000000000..10ea522bf20
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/mutations/revokeTwoFactorAuthenticationRecoveryCode.ts
@@ -0,0 +1,7 @@
+import { gql } from '@apollo/client';
+
+export const REVOKE_TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE = gql`
+ mutation revokeTwoFactorAuthenticationRecoveryCode($userId: UUID!) {
+ revokeTwoFactorAuthenticationRecoveryCode(userId: $userId)
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/queries/twoFactorAuthenticationRecoveryStatus.ts b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/queries/twoFactorAuthenticationRecoveryStatus.ts
new file mode 100644
index 00000000000..e32e60fabd9
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/graphql/queries/twoFactorAuthenticationRecoveryStatus.ts
@@ -0,0 +1,11 @@
+import { gql } from '@apollo/client';
+
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_STATUS = gql`
+ query twoFactorAuthenticationRecoveryStatus($userId: UUID!) {
+ twoFactorAuthenticationRecoveryStatus(userId: $userId) {
+ hasVerifiedTwoFactorAuthenticationMethod
+ isAwaitingRecoveryEnrollment
+ pendingRecoveryCodeExpiresAt
+ }
+ }
+`;
diff --git a/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useGeneratedRecoveryCode.ts b/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useGeneratedRecoveryCode.ts
new file mode 100644
index 00000000000..260960e1801
--- /dev/null
+++ b/packages/twenty-front/src/modules/settings/two-factor-authentication/hooks/useGeneratedRecoveryCode.ts
@@ -0,0 +1,26 @@
+import { useCallback, useState } from 'react';
+
+type GeneratedRecoveryCode = {
+ recoveryCode: string;
+ expiresAt: string;
+};
+
+export const useGeneratedRecoveryCode = () => {
+ const [generatedRecoveryCode, setGeneratedRecoveryCode] =
+ useState<GeneratedRecoveryCode | null>(null);
+
+ const showGeneratedRecoveryCode = (
+ recoveryCodeToShow: GeneratedRecoveryCode,
+ ) => setGeneratedRecoveryCode(recoveryCodeToShow);
+
+ const clearGeneratedRecoveryCode = useCallback(
+ () => setGeneratedRecoveryCode(null),
+ [],
+ );
+
+ return {
+ generatedRecoveryCode,
+ showGeneratedRecoveryCode,
+ clearGeneratedRecoveryCode,
+ };
+};
diff --git a/packages/twenty-front/src/modules/ui/layout/dialog/components/ConfirmationDialog.tsx b/packages/twenty-front/src/modules/ui/layout/dialog/components/ConfirmationDialog.tsx
index 6667b0c57e4..b855de346c9 100644
--- a/packages/twenty-front/src/modules/ui/layout/dialog/components/ConfirmationDialog.tsx
+++ b/packages/twenty-front/src/modules/ui/layout/dialog/components/ConfirmationDialog.tsx
@@ -34,6 +34,7 @@ export const ConfirmationDialog = ({
dialogId,
title,
loading,
+ isConfirmButtonDisabled = false,
subtitle,
onConfirmClick,
onClose,
@@ -51,8 +52,9 @@ export const ConfirmationDialog = ({
useState<string>('');
const isValidValue =
- !isNonEmptyString(confirmationValue) ||
- inputConfirmationValue === confirmationValue;
+ !isConfirmButtonDisabled &&
+ (!isNonEmptyString(confirmationValue) ||
+ inputConfirmationValue === confirmationValue);
const { closeDialog } = useDialog();
diff --git a/packages/twenty-front/src/modules/ui/layout/dialog/types/ConfirmationDialogProps.ts b/packages/twenty-front/src/modules/ui/layout/dialog/types/ConfirmationDialogProps.ts
index af974a4ca37..26380b30efe 100644
--- a/packages/twenty-front/src/modules/ui/layout/dialog/types/ConfirmationDialogProps.ts
+++ b/packages/twenty-front/src/modules/ui/layout/dialog/types/ConfirmationDialogProps.ts
@@ -5,6 +5,7 @@ export type ConfirmationDialogProps = {
dialogId: string;
title: string;
loading?: boolean;
+ isConfirmButtonDisabled?: boolean;
subtitle: ReactNode;
onClose?: () => void;
onConfirmClick: () => void;
diff --git a/packages/twenty-front/src/pages/auth/SignInUp.tsx b/packages/twenty-front/src/pages/auth/SignInUp.tsx
index de9db78ece3..7030ce0b2bc 100644
--- a/packages/twenty-front/src/pages/auth/SignInUp.tsx
+++ b/packages/twenty-front/src/pages/auth/SignInUp.tsx
@@ -30,6 +30,7 @@ import { useMemo } from 'react';
import { SignInUpGlobalScopeFormEffect } from '@/auth/sign-in-up/components/internal/SignInUpGlobalScopeFormEffect';
import { SignInUpSsoExchangeTokenEffect } from '@/auth/sign-in-up/components/internal/SignInUpSsoExchangeTokenEffect';
import { SignInUpTwoFactorAuthenticationProvision } from '@/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationProvision';
+import { SignInUpTwoFactorAuthenticationRecovery } from '@/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationRecovery';
import { SignInUpTOTPVerification } from '@/auth/sign-in-up/components/internal/SignInUpTwoFactorAuthenticationVerification';
import { useWorkspaceFromInviteHash } from '@/auth/sign-in-up/hooks/useWorkspaceFromInviteHash';
import { clientConfigApiStatusState } from '@/client-config/states/clientConfigApiStatusState';
@@ -116,6 +117,10 @@ export const SignInUp = () => {
return t`Verify code from the app`;
}
+ if (signInUpStep === SignInUpStep.TwoFactorAuthenticationRecovery) {
+ return t`Use a recovery code`;
+ }
+
if (isGlobalScope) {
return t`Welcome to Twenty`;
}
@@ -175,6 +180,10 @@ export const SignInUp = () => {
return <SignInUpTOTPVerification />;
}
+ if (signInUpStep === SignInUpStep.TwoFactorAuthenticationRecovery) {
+ return <SignInUpTwoFactorAuthenticationRecovery />;
+ }
+
if (isDefined(workspacePublicData) && isOnAWorkspace) {
return (
<>
diff --git a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminUserDetail.tsx b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminUserDetail.tsx
index 7f5e9306cba..7a98605424c 100644
--- a/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminUserDetail.tsx
+++ b/packages/twenty-front/src/pages/settings/admin-panel/SettingsAdminUserDetail.tsx
@@ -17,6 +17,7 @@ import {
import { currentUserState } from '@/auth/states/currentUserState';
import { useApolloAdminClient } from '@/settings/admin-panel/apollo/hooks/useApolloAdminClient';
import { SettingsAdminServerAdminAccess } from '@/settings/admin-panel/components/SettingsAdminServerAdminAccess';
+import { SettingsAdminTwoFactorAuthenticationRecoveryCode } from '@/settings/admin-panel/components/SettingsAdminTwoFactorAuthenticationRecoveryCode';
import { SettingsAdminWorkspaceContent } from '@/settings/admin-panel/components/SettingsAdminWorkspaceContent';
import { SETTINGS_ADMIN_USER_LOOKUP_WORKSPACE_TABS_ID } from '@/settings/admin-panel/constants/SettingsAdminUserLookupWorkspaceTabsId';
import { useHandleImpersonate } from '@/settings/admin-panel/hooks/useHandleImpersonate';
@@ -164,6 +165,17 @@ export const SettingsAdminUserDetail = () => {
</Button>
</StyledButtonContainer>
)}
+ {currentUser?.canAccessFullAdminPanel &&
+ activeWorkspace &&
+ isDefined(user) &&
+ user.id !== currentUser.id && (
+ <SettingsAdminTwoFactorAuthenticationRecoveryCode
+ key={`${user.id}-${activeWorkspace.id}`}
+ userId={user.id}
+ workspaceId={activeWorkspace.id}
+ memberName={displayName}
+ />
+ )}
</Section.Root>
);
diff --git a/packages/twenty-front/src/pages/settings/members/SettingsWorkspaceMember.tsx b/packages/twenty-front/src/pages/settings/members/SettingsWorkspaceMember.tsx
index 3475b60d2e9..62921a707bb 100644
--- a/packages/twenty-front/src/pages/settings/members/SettingsWorkspaceMember.tsx
+++ b/packages/twenty-front/src/pages/settings/members/SettingsWorkspaceMember.tsx
@@ -57,6 +57,8 @@ export const SettingsWorkspaceMember = () => {
const isImpersonating = useAtomStateValue(isImpersonatingState);
const canImpersonate =
useHasPermissionFlag(PermissionFlagType.IMPERSONATE) && !isImpersonating;
+ const canManageTwoFactorAuthenticationRecovery =
+ useHasPermissionFlag(PermissionFlagType.SECURITY) && !isImpersonating;
const {
roles,
@@ -235,6 +237,14 @@ export const SettingsWorkspaceMember = () => {
}
onNameChange={debouncedUpdateName}
onDelete={() => openDialog(DELETE_MEMBER_MODAL_ID)}
+ twoFactorAuthenticationRecoveryUserId={
+ canManageTwoFactorAuthenticationRecovery &&
+ isDefined(member.userId) &&
+ isDefined(currentUser?.id) &&
+ member.userId !== currentUser.id
+ ? member.userId
+ : undefined
+ }
/>
)}
diff --git a/packages/twenty-server/.env.example b/packages/twenty-server/.env.example
index d312329f74d..4da86e3b150 100644
--- a/packages/twenty-server/.env.example
+++ b/packages/twenty-server/.env.example
@@ -71,6 +71,7 @@ FRONTEND_URL=http://localhost:3001
# EMAIL_SMTP_USER=
# EMAIL_SMTP_PASSWORD=
# PASSWORD_RESET_TOKEN_EXPIRES_IN=5m
+# TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_EXPIRES_IN=1h
# CAPTCHA_DRIVER=
# CAPTCHA_SITE_KEY=
# CAPTCHA_SECRET_KEY=
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791375726691-add-two-factor-authentication-recovery-code-index.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791375726691-add-two-factor-authentication-recovery-code-index.ts
new file mode 100644
index 00000000000..feac478f503
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791375726691-add-two-factor-authentication-recovery-code-index.ts
@@ -0,0 +1,19 @@
+import { QueryRunner } from 'typeorm';
+
+import { RegisteredInstanceCommand } from 'src/engine/core-modules/upgrade/decorators/registered-instance-command.decorator';
+import { FastInstanceCommand } from 'src/engine/core-modules/upgrade/interfaces/fast-instance-command.interface';
+
+@RegisteredInstanceCommand('2.46.0', 1791375726691)
+export class AddTwoFactorAuthenticationRecoveryCodeIndexFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'CREATE UNIQUE INDEX "IDX_APP_TOKEN_RECOVERY_CODE_PENDING_UNIQUE" ON "core"."appToken" ("userId", "workspaceId") WHERE "type" = \'TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE\' AND "deletedAt" IS NULL AND "revokedAt" IS NULL',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'DROP INDEX "core"."IDX_APP_TOKEN_RECOVERY_CODE_PENDING_UNIQUE"',
+ );
+ }
+}
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
index 57205367f07..4de89244b33 100644
--- a/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/instance-commands.constant.ts
@@ -229,6 +229,7 @@ import { AddScopeAndDefaultValueToApplicationVariablesFastInstanceCommand } from
import { CreatePendingWakeUpTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791299810581-create-pending-wake-up-table';
import { CreateAgentRunSuspensionTableFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791301683545-create-agent-run-suspension-table';
import { AddUserApplicationVariableValueFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791328043361-add-user-application-variable-value';
+import { AddTwoFactorAuthenticationRecoveryCodeIndexFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-46/2-46-instance-command-fast-1791375726691-add-two-factor-authentication-recovery-code-index';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -460,4 +461,5 @@ export const INSTANCE_COMMANDS = [
CreatePendingWakeUpTableFastInstanceCommand,
CreateAgentRunSuspensionTableFastInstanceCommand,
AddUserApplicationVariableValueFastInstanceCommand,
+ AddTwoFactorAuthenticationRecoveryCodeIndexFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
index cf5c8bbca3e..8574fa18415 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/admin-panel.resolver.ts
@@ -35,6 +35,7 @@ import { ServerAdminDTO } from 'src/engine/core-modules/admin-panel/dtos/server-
import { SigningKeyDTO } from 'src/engine/core-modules/admin-panel/dtos/signing-key.dto';
import { SigningKeysAdminPanelDTO } from 'src/engine/core-modules/admin-panel/dtos/signing-keys-admin-panel.dto';
import { SystemHealthDTO } from 'src/engine/core-modules/admin-panel/dtos/system-health.dto';
+import { GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminInput } from 'src/engine/core-modules/admin-panel/dtos/generate-two-factor-authentication-recovery-code-as-server-admin.input';
import { UpdateServerAdminAccessInput } from 'src/engine/core-modules/admin-panel/dtos/update-server-admin-access.input';
import { UpdateWorkspaceFeatureFlagInput } from 'src/engine/core-modules/admin-panel/dtos/update-workspace-feature-flag.input';
import { UserLookup } from 'src/engine/core-modules/admin-panel/dtos/user-lookup.dto';
@@ -86,6 +87,8 @@ import { ConfigVariableGraphqlApiExceptionFilter } from 'src/engine/core-modules
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { ThrottlerGraphqlApiExceptionFilter } from 'src/engine/core-modules/throttler/filters/throttler-graphql-api-exception.filter';
import { TwoFactorAuthenticationExceptionFilter } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter';
+import { TwoFactorAuthenticationRecoveryCodeDTO } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code.dto';
+import { TwoFactorAuthenticationRecoveryService } from 'src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service';
import { UsageBreakdownItemDTO } from 'src/engine/core-modules/usage/dtos/usage-breakdown-item.dto';
import { UsageAnalyticsService } from 'src/engine/core-modules/usage/services/usage-analytics.service';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -133,6 +136,7 @@ export class AdminPanelResolver {
constructor(
private readonly adminUserLookupService: AdminPanelUserLookupService,
private readonly adminServerAdminService: AdminPanelServerAdminService,
+ private readonly twoFactorAuthenticationRecoveryService: TwoFactorAuthenticationRecoveryService,
private readonly adminStatisticsService: AdminPanelStatisticsService,
private readonly adminBillingService: AdminPanelBillingService,
private readonly adminChatService: AdminPanelChatService,
@@ -242,6 +246,36 @@ export class AdminPanelResolver {
});
}
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: false,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ AdminPanelGuard,
+ )
+ @Mutation(() => TwoFactorAuthenticationRecoveryCodeDTO)
+ async generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin(
+ @Args()
+ input: GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminInput,
+ @AuthUser() actor: AuthContextUser,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ ): Promise<TwoFactorAuthenticationRecoveryCodeDTO> {
+ return this.twoFactorAuthenticationRecoveryService.generateRecoveryCode({
+ actor,
+ actorWorkspaceId: workspace.id,
+ otp: input.otp,
+ targetUserId: input.userId,
+ targetWorkspaceId: input.workspaceId,
+ });
+ }
+
@UseGuards(AdminPanelGuard)
@Mutation(() => Boolean)
async updateWorkspaceFeatureFlag(
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/generate-two-factor-authentication-recovery-code-as-server-admin.input.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/generate-two-factor-authentication-recovery-code-as-server-admin.input.ts
new file mode 100644
index 00000000000..8e608371af2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/dtos/generate-two-factor-authentication-recovery-code-as-server-admin.input.ts
@@ -0,0 +1,14 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+import { GenerateTwoFactorAuthenticationRecoveryCodeInput } from 'src/engine/core-modules/two-factor-authentication/dto/generate-two-factor-authentication-recovery-code.input';
+
+@ArgsType()
+export class GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdminInput extends GenerateTwoFactorAuthenticationRecoveryCodeInput {
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ workspaceId: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service.ts b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service.ts
index a62039e9755..77ba0d05a6e 100644
--- a/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/admin-panel/services/admin-panel-server-admin.service.ts
@@ -2,7 +2,6 @@ import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { msg } from '@lingui/core/macro';
-import { isNonEmptyString } from '@sniptt/guards';
import { ServerAdminAccessChangedEmail, renderEmail } from 'twenty-emails';
import { SOURCE_LOCALE } from 'twenty-shared/translations';
import { isDefined } from 'twenty-shared/utils';
@@ -19,8 +18,6 @@ import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { NodeEnvironment } from 'src/engine/core-modules/twenty-config/interfaces/node-environment.interface';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { TwoFactorAuthenticationService } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.service';
-import { twoFactorAuthenticationMethodsValidator } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.validation';
-import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
@Injectable()
@@ -30,8 +27,6 @@ export class AdminPanelServerAdminService {
constructor(
@InjectRepository(UserEntity)
private readonly userRepository: Repository<UserEntity>,
- @InjectRepository(UserWorkspaceEntity)
- private readonly userWorkspaceRepository: Repository<UserWorkspaceEntity>,
private readonly coreEntityCacheService: CoreEntityCacheService,
private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService,
private readonly emailService: EmailService,
@@ -76,11 +71,19 @@ export class AdminPanelServerAdminService {
throw new UserInputError('User not found.');
}
- await this.assertFreshStepUpAuthentication({
- actorUserId: actor.id,
- actorWorkspaceId,
- otp,
- });
+ if (
+ this.twentyConfigService.get('NODE_ENV') !== NodeEnvironment.DEVELOPMENT
+ ) {
+ await this.twoFactorAuthenticationService.assertFreshStepUpAuthenticationOrThrow(
+ {
+ userId: actor.id,
+ workspaceId: actorWorkspaceId,
+ otp,
+ otpRequiredMessage: msg`Enter your two-factor authentication code to manage server administrators.`,
+ twoFactorAuthenticationRequiredMessage: msg`Enable two-factor authentication in your current workspace to manage server administrators.`,
+ },
+ );
+ }
const nextCanAccessFullAdminPanel =
canAccessFullAdminPanel ?? targetUser.canAccessFullAdminPanel;
@@ -143,66 +146,6 @@ export class AdminPanelServerAdminService {
return this.toServerAdminDTO(targetUser);
}
- private async assertFreshStepUpAuthentication({
- actorUserId,
- actorWorkspaceId,
- otp,
- }: {
- actorUserId: string;
- actorWorkspaceId: string;
- otp?: string;
- }): Promise<void> {
- const isDevelopment =
- this.twentyConfigService.get('NODE_ENV') === NodeEnvironment.DEVELOPMENT;
-
- if (isDevelopment) {
- return;
- }
-
- if (!isNonEmptyString(otp)) {
- throw new UserInputError(
- 'A two-factor authentication code is required to change server administrator access.',
- {
- userFriendlyMessage: msg`Enter your two-factor authentication code to manage server administrators.`,
- },
- );
- }
-
- // Verify against the actor's current workspace only — checking the same code
- // against every workspace they belong to would allow one OTP guess per
- // workspace, weakening brute-force resistance.
- const actorUserWorkspace = await this.userWorkspaceRepository.findOne({
- where: { userId: actorUserId, workspaceId: actorWorkspaceId },
- relations: ['twoFactorAuthenticationMethods'],
- });
-
- const hasVerifiedTwoFactor =
- isDefined(actorUserWorkspace) &&
- twoFactorAuthenticationMethodsValidator.areDefined(
- actorUserWorkspace.twoFactorAuthenticationMethods,
- ) &&
- twoFactorAuthenticationMethodsValidator.areVerified(
- actorUserWorkspace.twoFactorAuthenticationMethods,
- );
-
- if (!hasVerifiedTwoFactor) {
- throw new UserInputError(
- 'Enable two-factor authentication in your current workspace to manage server administrators.',
- {
- userFriendlyMessage: msg`Enable two-factor authentication in your current workspace to manage server administrators.`,
- },
- );
- }
-
- // A wrong code throws INVALID_OTP, which the resolver's
- // TwoFactorAuthenticationExceptionFilter maps to a user-friendly message.
- await this.twoFactorAuthenticationService.verifyTwoFactorAuthenticationMethodForAuthenticatedUser(
- actorUserId,
- otp,
- actorWorkspaceId,
- );
- }
-
private async notifyAdministrators({
actor,
targetUser,
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 bb162cab669..d2fdda89246 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
@@ -13,6 +13,7 @@ import {
UpdateDateColumn,
} from 'typeorm';
+import { type UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
import { type AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -27,6 +28,7 @@ export enum AppTokenType {
EmailVerificationToken = 'EMAIL_VERIFICATION_TOKEN',
EnterpriseValidityToken = 'ENTERPRISE_VALIDITY_TOKEN',
SsoExchangeToken = 'SSO_EXCHANGE_TOKEN',
+ TwoFactorAuthenticationRecoveryCode = 'TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE',
}
@Entity({ name: 'appToken', schema: 'core' })
@@ -38,6 +40,14 @@ export enum AppTokenType {
unique: true,
where: `"type" = 'SSO_EXCHANGE_TOKEN' AND "deletedAt" IS NULL AND "revokedAt" IS NULL`,
})
+@Index(
+ 'IDX_APP_TOKEN_RECOVERY_CODE_PENDING_UNIQUE',
+ ['userId', 'workspaceId'],
+ {
+ unique: true,
+ where: `"type" = 'TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE' AND "deletedAt" IS NULL AND "revokedAt" IS NULL`,
+ },
+)
export class AppTokenEntity {
@PrimaryGeneratedColumn('uuid')
id: string;
@@ -98,5 +108,7 @@ export class AppTokenEntity {
codeChallenge?: string;
scope?: string;
authProvider?: AuthProviderEnum;
+ revokedReason?: UserSessionRevokedReason;
+ issuedByUserId?: string;
} | null;
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
index 7a612f78cfb..6d08adf1075 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.spec.ts
@@ -31,6 +31,7 @@ import { UserSessionService } from 'src/engine/core-modules/user-session/service
import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { TwoFactorAuthenticationService } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.service';
+import { TwoFactorAuthenticationRecoveryService } from 'src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
import { UserService } from 'src/engine/core-modules/user/services/user.service';
@@ -239,6 +240,10 @@ describe('AuthResolver', () => {
provide: TwoFactorAuthenticationService,
useValue: {},
},
+ {
+ provide: TwoFactorAuthenticationRecoveryService,
+ useValue: {},
+ },
{
provide: TwentyConfigService,
useValue: {},
diff --git a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
index 416fc9f5068..7dec8578bb6 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/auth.resolver.ts
@@ -82,7 +82,10 @@ import { IMPERSONATION_DENIAL_BY_REASON } from 'src/engine/core-modules/imperson
import { IMPERSONATION_DENIAL_LOG_MESSAGE_BY_REASON } from 'src/engine/core-modules/impersonation/constants/impersonation-denial-log-message-by-reason.constant';
import { ImpersonationAuthorizationService } from 'src/engine/core-modules/impersonation/services/impersonation-authorization.service';
import { SsoService } from 'src/engine/core-modules/sso/services/sso.service';
+import { TwoFactorAuthenticationRecoveryCodeRedemptionDTO } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-redemption.dto';
+import { TwoFactorAuthenticationRecoveryCodeVerificationInput } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-verification.input';
import { TwoFactorAuthenticationVerificationInput } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-verification.input';
+import { TwoFactorAuthenticationRecoveryService } from 'src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service';
import { TwoFactorAuthenticationExceptionFilter } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter';
import { TwoFactorAuthenticationService } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.service';
import { UserSessionCookieService } from 'src/engine/core-modules/user-session/services/user-session-cookie.service';
@@ -147,6 +150,7 @@ export class AuthResolver {
@InjectRepository(AppTokenEntity)
private readonly appTokenRepository: Repository<AppTokenEntity>,
private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService,
+ private readonly twoFactorAuthenticationRecoveryService: TwoFactorAuthenticationRecoveryService,
private authService: AuthService,
private renewTokenService: RenewTokenService,
private userService: UserService,
@@ -454,6 +458,56 @@ export class AuthResolver {
return authTokens;
}
+ @Mutation(() => TwoFactorAuthenticationRecoveryCodeRedemptionDTO)
+ @UseGuards(CaptchaGuard, PublicEndpointGuard, NoPermissionGuard)
+ @AllowSuspendedWorkspace()
+ async getAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ @Args()
+ recoveryCodeVerificationInput: TwoFactorAuthenticationRecoveryCodeVerificationInput,
+ @Args('origin') origin: string,
+ @Context() context: { req: Request },
+ ): Promise<TwoFactorAuthenticationRecoveryCodeRedemptionDTO> {
+ const loginTokenPayload = await this.loginTokenService.verifyLoginToken(
+ recoveryCodeVerificationInput.loginToken,
+ );
+
+ assertLoginTokenIsNotForImpersonation(loginTokenPayload);
+
+ const { sub: email, authProvider, workspaceId } = loginTokenPayload;
+
+ const workspace = await this.validateWorkspaceAccess(origin, workspaceId);
+
+ const user = await this.userService.findUserByEmailOrThrow(email);
+
+ const { provisioningUri } =
+ await this.twoFactorAuthenticationRecoveryService.redeemRecoveryCode({
+ userId: user.id,
+ userEmail: email,
+ workspace,
+ recoveryCode: recoveryCodeVerificationInput.recoveryCode,
+ });
+
+ if (isDefined(provisioningUri)) {
+ return { tokens: null, provisioningUri };
+ }
+
+ await this.loginTokenService.consumeLoginTokenOrThrow(loginTokenPayload);
+
+ const authTokens = await this.authService.verify(
+ email,
+ workspace.id,
+ authProvider,
+ );
+
+ await this.userSessionService.issueSessionForTokenPair({
+ tokenPair: authTokens.tokens,
+ request: context.req,
+ origin: 'sign_in',
+ });
+
+ return { tokens: authTokens.tokens, provisioningUri: null };
+ }
+
@Mutation(() => AvailableWorkspacesAndAccessTokensDTO)
@UseGuards(CaptchaGuard, PublicEndpointGuard, NoPermissionGuard)
@AllowSuspendedWorkspace()
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/refresh-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/refresh-token.service.ts
index c9a341dfb91..be912ffa5b0 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/refresh-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/refresh-token.service.ts
@@ -3,7 +3,7 @@ import { InjectRepository } from '@nestjs/typeorm';
import { addMilliseconds } from 'date-fns';
import ms from 'ms';
-import { Repository } from 'typeorm';
+import { type EntityManager, Repository } from 'typeorm';
import {
AppTokenEntity,
@@ -16,6 +16,7 @@ import {
import { type AuthToken } from 'src/engine/core-modules/auth/dto/auth-token.dto';
import { type RefreshTokenJwtPayload } from 'src/engine/core-modules/auth/types/refresh-token-jwt-payload.type';
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { isRevokedRefreshTokenStillRenewable } from 'src/engine/core-modules/auth/utils/is-revoked-refresh-token-still-renewable.util';
import { JwtWrapperService } from 'src/engine/core-modules/jwt/services/jwt-wrapper.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserEntity } from 'src/engine/core-modules/user/user.entity';
@@ -77,10 +78,14 @@ export class RefreshTokenService {
}
if (token.revokedAt) {
- const wasRevokedBeforeGracePeriod =
- token.revokedAt.getTime() <= Date.now() - ms(reuseGracePeriod);
-
- if (wasRevokedBeforeGracePeriod) {
+ const isStillRenewable = isRevokedRefreshTokenStillRenewable({
+ revokedAt: token.revokedAt,
+ revokedReason: token.context?.revokedReason,
+ reuseGracePeriod,
+ now: new Date(),
+ });
+
+ if (!isStillRenewable) {
// Reject the stale token but don't revoke all tokens — the most
// common cause is a lost renewal response, not actual token theft.
throw new AuthException(
@@ -109,6 +114,7 @@ export class RefreshTokenService {
async generateRefreshToken(
payload: Omit<RefreshTokenJwtPayload, 'type' | 'sub' | 'jti'>,
isImpersonationToken: boolean = false,
+ entityManager?: EntityManager,
): Promise<AuthToken> {
const expiresIn = isImpersonationToken
? '1d'
@@ -123,13 +129,16 @@ export class RefreshTokenService {
const expiresAt = addMilliseconds(new Date().getTime(), ms(expiresIn));
- const refreshToken = this.appTokenRepository.create({
+ const appTokenRepository =
+ entityManager?.getRepository(AppTokenEntity) ?? this.appTokenRepository;
+
+ const refreshToken = appTokenRepository.create({
...payload,
expiresAt,
type: AppTokenType.RefreshToken,
});
- await this.appTokenRepository.save(refreshToken);
+ await appTokenRepository.save(refreshToken);
const jwtPayload: RefreshTokenJwtPayload = {
...payload,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/token/services/renew-token.service.ts b/packages/twenty-server/src/engine/core-modules/auth/token/services/renew-token.service.ts
index 4e0143f28bf..cec6a43a431 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/token/services/renew-token.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/token/services/renew-token.service.ts
@@ -14,6 +14,7 @@ import { AccessTokenService } from 'src/engine/core-modules/auth/token/services/
import { RefreshTokenService } from 'src/engine/core-modules/auth/token/services/refresh-token.service';
import { WorkspaceAgnosticTokenService } from 'src/engine/core-modules/auth/token/services/workspace-agnostic-token.service';
import { JwtTokenTypeEnum } from 'src/engine/core-modules/auth/types/jwt-token-type.enum';
+import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util';
import { AuthProviderEnum } from 'src/engine/core-modules/workspace/types/workspace.type';
@Injectable()
@@ -47,26 +48,65 @@ export class RenewTokenService {
impersonatedUserWorkspaceId,
} = await this.refreshTokenService.verifyRefreshToken(token);
- // Revoke old refresh token only if not already revoked.
- // If it was already revoked (concurrent race condition within grace
- // period), we preserve the original revokedAt timestamp so the grace
- // window stays anchored and cannot be extended by repeated reuse.
- await this.appTokenRepository.update(
- {
- id,
- revokedAt: IsNull(),
- },
- {
- revokedAt: new Date(),
- },
- );
-
// Support legacy token when targetedTokenType is undefined.
const targetedTokenType =
targetedTokenTypeFromPayload ?? JwtTokenTypeEnum.ACCESS;
const resolvedAuthProvider = authProvider ?? AuthProviderEnum.Password;
+ const refreshToken = await this.appTokenRepository.manager.transaction(
+ async (entityManager) => {
+ await acquireUserAuthenticationLock({
+ entityManager,
+ userId: user.id,
+ mode: 'shared',
+ });
+
+ const appTokenRepository = entityManager.getRepository(AppTokenEntity);
+
+ // A security revocation committed after the first read must still stop this renewal
+ const lockedToken = await appTokenRepository.findOneBy({ id });
+
+ if (
+ !isDefined(lockedToken) ||
+ isDefined(lockedToken.context?.revokedReason)
+ ) {
+ throw new AuthException(
+ 'This refresh token has been revoked.',
+ AuthExceptionCode.FORBIDDEN_EXCEPTION,
+ );
+ }
+
+ // Revoke old refresh token only if not already revoked.
+ // If it was already revoked (concurrent race condition within grace
+ // period), we preserve the original revokedAt timestamp so the grace
+ // window stays anchored and cannot be extended by repeated reuse.
+ await appTokenRepository.update(
+ {
+ id,
+ revokedAt: IsNull(),
+ },
+ {
+ revokedAt: new Date(),
+ },
+ );
+
+ return await this.refreshTokenService.generateRefreshToken(
+ {
+ userId: user.id,
+ workspaceId,
+ authProvider: resolvedAuthProvider,
+ targetedTokenType,
+ isImpersonating,
+ impersonatorUserWorkspaceId,
+ impersonatedUserWorkspaceId,
+ },
+ false,
+ entityManager,
+ );
+ },
+ );
+
const accessToken =
isDefined(authProvider) &&
targetedTokenType === JwtTokenTypeEnum.WORKSPACE_AGNOSTIC &&
@@ -86,16 +126,6 @@ export class RenewTokenService {
impersonatedUserWorkspaceId,
});
- const refreshToken = await this.refreshTokenService.generateRefreshToken({
- userId: user.id,
- workspaceId,
- authProvider: resolvedAuthProvider,
- targetedTokenType,
- isImpersonating,
- impersonatorUserWorkspaceId,
- impersonatedUserWorkspaceId,
- });
-
return {
accessOrWorkspaceAgnosticToken: accessToken,
refreshToken,
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/is-revoked-refresh-token-still-renewable.util.spec.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/is-revoked-refresh-token-still-renewable.util.spec.ts
new file mode 100644
index 00000000000..ff84f7cc129
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/__tests__/is-revoked-refresh-token-still-renewable.util.spec.ts
@@ -0,0 +1,39 @@
+import { isRevokedRefreshTokenStillRenewable } from 'src/engine/core-modules/auth/utils/is-revoked-refresh-token-still-renewable.util';
+import { UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
+
+describe('isRevokedRefreshTokenStillRenewable', () => {
+ const now = new Date('2026-01-01T12:00:00.000Z');
+
+ it('accepts a token rotated moments ago by a concurrent renewal', () => {
+ expect(
+ isRevokedRefreshTokenStillRenewable({
+ revokedAt: new Date(now.getTime() - 10 * 1000),
+ revokedReason: undefined,
+ reuseGracePeriod: '1m',
+ now,
+ }),
+ ).toBe(true);
+ });
+
+ it('rejects a token revoked before the reuse grace period', () => {
+ expect(
+ isRevokedRefreshTokenStillRenewable({
+ revokedAt: new Date(now.getTime() - 5 * 60 * 1000),
+ revokedReason: undefined,
+ reuseGracePeriod: '1m',
+ now,
+ }),
+ ).toBe(false);
+ });
+
+ it('rejects a token revoked for a security reason even inside the reuse grace period', () => {
+ expect(
+ isRevokedRefreshTokenStillRenewable({
+ revokedAt: new Date(now.getTime() - 10 * 1000),
+ revokedReason: UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ reuseGracePeriod: '1m',
+ now,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util.ts
new file mode 100644
index 00000000000..3cc6d6563af
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util.ts
@@ -0,0 +1,20 @@
+import { type EntityManager } from 'typeorm';
+
+// A two-factor recovery must not interleave with an OTP verification or a refresh token renewal that already read the
+// user's state, so they all take this lock in the transaction that writes their outcome
+export const acquireUserAuthenticationLock = async ({
+ entityManager,
+ userId,
+ mode,
+}: {
+ entityManager: EntityManager;
+ userId: string;
+ mode: 'shared' | 'exclusive';
+}): Promise<void> => {
+ await entityManager.query(
+ mode === 'shared'
+ ? 'SELECT pg_advisory_xact_lock_shared(hashtextextended($1, 0))'
+ : 'SELECT pg_advisory_xact_lock(hashtextextended($1, 0))',
+ [`user-authentication:${userId}`],
+ );
+};
diff --git a/packages/twenty-server/src/engine/core-modules/auth/utils/is-revoked-refresh-token-still-renewable.util.ts b/packages/twenty-server/src/engine/core-modules/auth/utils/is-revoked-refresh-token-still-renewable.util.ts
new file mode 100644
index 00000000000..0a4ecd5b09b
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/auth/utils/is-revoked-refresh-token-still-renewable.util.ts
@@ -0,0 +1,23 @@
+import ms from 'ms';
+import { isDefined } from 'twenty-shared/utils';
+
+import { type UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
+
+export const isRevokedRefreshTokenStillRenewable = ({
+ revokedAt,
+ revokedReason,
+ reuseGracePeriod,
+ now,
+}: {
+ revokedAt: Date;
+ revokedReason: UserSessionRevokedReason | undefined;
+ reuseGracePeriod: string;
+ now: Date;
+}): boolean => {
+ // A revocation with a recorded reason is a security action, not a renewal race between tabs
+ if (isDefined(revokedReason)) {
+ return false;
+ }
+
+ return revokedAt.getTime() > now.getTime() - ms(reuseGracePeriod);
+};
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 67177ddcc30..64fd1ad501e 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
@@ -142,6 +142,16 @@ export class ConfigVariables {
@IsOptional()
PASSWORD_RESET_TOKEN_EXPIRES_IN = '5m';
+ @ConfigVariablesMetadata({
+ group: ConfigVariablesGroup.TOKENS_DURATION,
+ description:
+ 'Duration for which an admin-issued two-factor authentication recovery code is valid',
+ type: ConfigVariableType.STRING,
+ })
+ @IsPositiveDuration()
+ @IsOptional()
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_EXPIRES_IN = '1h';
+
@ConfigVariablesMetadata({
group: ConfigVariablesGroup.GOOGLE_AUTH,
description: 'Enable or disable the Google Calendar integration',
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant.ts
new file mode 100644
index 00000000000..823f291da39
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant.ts
@@ -0,0 +1,12 @@
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET =
+ '0123456789ABCDEFGHJKMNPQRSTVWXYZ';
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_LENGTH = 20;
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_GROUP_SIZE = 5;
+
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX = 5;
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_WINDOW_MS =
+ 15 * 60 * 1000;
+
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_MAX = 10;
+export const TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_WINDOW_MS =
+ 60 * 60 * 1000;
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/generate-two-factor-authentication-recovery-code.input.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/generate-two-factor-authentication-recovery-code.input.ts
new file mode 100644
index 00000000000..8ff8154d421
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/generate-two-factor-authentication-recovery-code.input.ts
@@ -0,0 +1,13 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsOptional, IsString } from 'class-validator';
+
+import { TwoFactorAuthenticationRecoveryTargetInput } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-target.input';
+
+@ArgsType()
+export class GenerateTwoFactorAuthenticationRecoveryCodeInput extends TwoFactorAuthenticationRecoveryTargetInput {
+ @Field(() => String, { nullable: true })
+ @IsOptional()
+ @IsString()
+ otp?: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-redemption.dto.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-redemption.dto.ts
new file mode 100644
index 00000000000..4dc68905126
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-redemption.dto.ts
@@ -0,0 +1,12 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+import { AuthTokenPair } from 'src/engine/core-modules/auth/dto/auth-token-pair.dto';
+
+@ObjectType('TwoFactorAuthenticationRecoveryCodeRedemption')
+export class TwoFactorAuthenticationRecoveryCodeRedemptionDTO {
+ @Field(() => AuthTokenPair, { nullable: true })
+ tokens: AuthTokenPair | null;
+
+ @Field(() => String, { nullable: true })
+ provisioningUri: string | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-verification.input.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-verification.input.ts
new file mode 100644
index 00000000000..be16e1fe018
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-verification.input.ts
@@ -0,0 +1,21 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsOptional, IsString } from 'class-validator';
+
+@ArgsType()
+export class TwoFactorAuthenticationRecoveryCodeVerificationInput {
+ @Field(() => String)
+ @IsString()
+ @IsNotEmpty()
+ recoveryCode: string;
+
+ @Field(() => String)
+ @IsNotEmpty()
+ @IsString()
+ loginToken: string;
+
+ @Field(() => String, { nullable: true })
+ @IsString()
+ @IsOptional()
+ captchaToken?: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code.dto.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code.dto.ts
new file mode 100644
index 00000000000..b4527ad682f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code.dto.ts
@@ -0,0 +1,10 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+@ObjectType('TwoFactorAuthenticationRecoveryCode')
+export class TwoFactorAuthenticationRecoveryCodeDTO {
+ @Field(() => String)
+ recoveryCode: string;
+
+ @Field(() => Date)
+ expiresAt: Date;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-status.dto.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-status.dto.ts
new file mode 100644
index 00000000000..69967f3dfe7
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-status.dto.ts
@@ -0,0 +1,13 @@
+import { Field, ObjectType } from '@nestjs/graphql';
+
+@ObjectType('TwoFactorAuthenticationRecoveryStatus')
+export class TwoFactorAuthenticationRecoveryStatusDTO {
+ @Field(() => Boolean)
+ hasVerifiedTwoFactorAuthenticationMethod: boolean;
+
+ @Field(() => Boolean)
+ isAwaitingRecoveryEnrollment: boolean;
+
+ @Field(() => Date, { nullable: true })
+ pendingRecoveryCodeExpiresAt: Date | null;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-target.input.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-target.input.ts
new file mode 100644
index 00000000000..49176eee87d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-target.input.ts
@@ -0,0 +1,13 @@
+import { ArgsType, Field } from '@nestjs/graphql';
+
+import { IsNotEmpty, IsUUID } from 'class-validator';
+
+import { UUIDScalarType } from 'src/engine/api/graphql/workspace-schema-builder/graphql-types/scalars';
+
+@ArgsType()
+export class TwoFactorAuthenticationRecoveryTargetInput {
+ @Field(() => UUIDScalarType)
+ @IsNotEmpty()
+ @IsUUID()
+ userId: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.spec.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.spec.ts
new file mode 100644
index 00000000000..ae6a992542a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.spec.ts
@@ -0,0 +1,569 @@
+import { Test, type TestingModule } from '@nestjs/testing';
+import { getRepositoryToken } from '@nestjs/typeorm';
+
+import { renderEmail } from 'twenty-emails';
+import { TwoFactorAuthenticationStrategy } from 'twenty-shared/types';
+import {
+ IsNull,
+ MoreThan,
+ MoreThanOrEqual,
+ Not,
+ QueryFailedError,
+} from 'typeorm';
+
+import {
+ AppTokenEntity,
+ AppTokenType,
+} from 'src/engine/core-modules/app-token/app-token.entity';
+import { EmailService } from 'src/engine/core-modules/email/email.service';
+import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import { TwoFactorAuthenticationMethodEntity } from 'src/engine/core-modules/two-factor-authentication/entities/two-factor-authentication-method.entity';
+import { TwoFactorAuthenticationRecoveryService } from 'src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service';
+import { OTPStatus } from 'src/engine/core-modules/two-factor-authentication/strategies/otp/otp.constants';
+import { TwoFactorAuthenticationExceptionCode } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception';
+import { TwoFactorAuthenticationService } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.service';
+import { buildTwoFactorAuthenticationRecoveryCodeRedemptionRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-redemption-rate-limit-key.util';
+import { hashTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util';
+import { UserSessionService } from 'src/engine/core-modules/user-session/services/user-session.service';
+import { UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
+import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
+import { getWorkspaceScopedRepositoryToken } from 'src/engine/twenty-orm/workspace-scoped-repository/get-workspace-scoped-repository-token.util';
+
+jest.mock('twenty-emails', () => ({
+ ...jest.requireActual('twenty-emails'),
+ renderEmail: jest.fn().mockResolvedValue('email'),
+}));
+
+const WORKSPACE_ID = 'workspace-id';
+const TARGET_USER_ID = 'target-user-id';
+const TARGET_USER_WORKSPACE_ID = 'target-user-workspace-id';
+const MEMBERSHIP_CREATED_AT = new Date('2026-01-01T00:00:00.000Z');
+const REPLACEMENT_PROVISIONING_URI =
+ 'otpauth://totp/Twenty%20-%20Apple:[email protected]?secret=REPLACEMENT';
+
+const ACTOR = {
+ id: 'actor-user-id',
+ email: '[email protected]',
+ firstName: 'Jane',
+ lastName: 'Admin',
+ canImpersonate: false,
+ canAccessFullAdminPanel: false,
+};
+
+const buildTargetUserWorkspace = ({
+ canImpersonate = false,
+ canAccessFullAdminPanel = false,
+}: {
+ canImpersonate?: boolean;
+ canAccessFullAdminPanel?: boolean;
+} = {}) => ({
+ id: TARGET_USER_WORKSPACE_ID,
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ locale: 'en',
+ createdAt: MEMBERSHIP_CREATED_AT,
+ user: {
+ id: TARGET_USER_ID,
+ email: '[email protected]',
+ canImpersonate,
+ canAccessFullAdminPanel,
+ },
+ workspace: { id: WORKSPACE_ID, displayName: 'Apple' },
+});
+
+describe('TwoFactorAuthenticationRecoveryService', () => {
+ let service: TwoFactorAuthenticationRecoveryService;
+ let appTokenRepository: {
+ insert: jest.Mock;
+ findOne: jest.Mock;
+ exists: jest.Mock;
+ };
+ let methodRepository: { exists: jest.Mock };
+ let transactionalRepositories: {
+ method: { delete: jest.Mock; insert: jest.Mock };
+ appToken: { update: jest.Mock; createQueryBuilder: jest.Mock };
+ };
+ let refreshTokenRevocationQueryBuilder: {
+ update: jest.Mock;
+ set: jest.Mock;
+ where: jest.Mock;
+ setParameters: jest.Mock;
+ execute: jest.Mock;
+ };
+ let twoFactorAuthenticationService: {
+ assertFreshStepUpAuthenticationOrThrow: jest.Mock;
+ revokeRecoveryCodes: jest.Mock;
+ generatePendingTotpSecret: jest.Mock;
+ };
+ let userWorkspaceService: { getUserWorkspaceForUser: jest.Mock };
+ let userSessionService: { revokeAllSessionsForUser: jest.Mock };
+ let throttlerService: { tokenBucketThrottleOrThrow: jest.Mock };
+ let emailService: { send: jest.Mock };
+
+ beforeEach(async () => {
+ refreshTokenRevocationQueryBuilder = {
+ update: jest.fn(() => refreshTokenRevocationQueryBuilder),
+ set: jest.fn(() => refreshTokenRevocationQueryBuilder),
+ where: jest.fn(() => refreshTokenRevocationQueryBuilder),
+ setParameters: jest.fn(() => refreshTokenRevocationQueryBuilder),
+ execute: jest.fn(),
+ };
+ transactionalRepositories = {
+ method: { delete: jest.fn(), insert: jest.fn() },
+ appToken: {
+ update: jest.fn().mockResolvedValue({ affected: 1 }),
+ createQueryBuilder: jest.fn(() => refreshTokenRevocationQueryBuilder),
+ },
+ };
+
+ const entityManager = {
+ query: jest.fn(),
+ getRepository: (entity: unknown) => {
+ if (entity === TwoFactorAuthenticationMethodEntity) {
+ return transactionalRepositories.method;
+ }
+
+ return transactionalRepositories.appToken;
+ },
+ };
+
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ TwoFactorAuthenticationRecoveryService,
+ {
+ provide: getWorkspaceScopedRepositoryToken(
+ TwoFactorAuthenticationMethodEntity,
+ ),
+ useValue: {
+ exists: jest.fn().mockResolvedValue(true),
+ },
+ },
+ {
+ provide: getRepositoryToken(AppTokenEntity),
+ useValue: {
+ insert: jest.fn(),
+ findOne: jest.fn(),
+ exists: jest.fn().mockResolvedValue(false),
+ manager: {
+ transaction: jest.fn(
+ (callback: (manager: typeof entityManager) => unknown) =>
+ callback(entityManager),
+ ),
+ },
+ },
+ },
+ {
+ provide: TwoFactorAuthenticationService,
+ useValue: {
+ assertFreshStepUpAuthenticationOrThrow: jest.fn(),
+ revokeRecoveryCodes: jest.fn().mockResolvedValue(0),
+ generatePendingTotpSecret: jest.fn().mockReturnValue({
+ uri: REPLACEMENT_PROVISIONING_URI,
+ encryptedSecret: 'encrypted-replacement-secret',
+ status: OTPStatus.PENDING,
+ }),
+ },
+ },
+ {
+ provide: UserWorkspaceService,
+ useValue: {
+ getUserWorkspaceForUser: jest
+ .fn()
+ .mockResolvedValue(buildTargetUserWorkspace()),
+ },
+ },
+ {
+ provide: UserSessionService,
+ useValue: { revokeAllSessionsForUser: jest.fn() },
+ },
+ {
+ provide: ThrottlerService,
+ useValue: { tokenBucketThrottleOrThrow: jest.fn() },
+ },
+ { provide: EmailService, useValue: { send: jest.fn() } },
+ {
+ provide: I18nService,
+ useValue: {
+ getI18nInstance: () => ({
+ _: (message: { message?: string }) => message.message ?? '',
+ }),
+ },
+ },
+ {
+ provide: TwentyConfigService,
+ useValue: {
+ get: (key: string) =>
+ key === 'TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_EXPIRES_IN'
+ ? '1h'
+ },
+ },
+ ],
+ }).compile();
+
+ service = module.get(TwoFactorAuthenticationRecoveryService);
+ appTokenRepository = module.get(getRepositoryToken(AppTokenEntity));
+ methodRepository = module.get(
+ getWorkspaceScopedRepositoryToken(TwoFactorAuthenticationMethodEntity),
+ );
+ twoFactorAuthenticationService = module.get(TwoFactorAuthenticationService);
+ userWorkspaceService = module.get(UserWorkspaceService);
+ userSessionService = module.get(UserSessionService);
+ throttlerService = module.get(ThrottlerService);
+ emailService = module.get(EmailService);
+ });
+
+ afterEach(() => {
+ jest.clearAllMocks();
+ });
+
+ describe('generateRecoveryCode', () => {
+ const generate = () =>
+ service.generateRecoveryCode({
+ actor: ACTOR,
+ actorWorkspaceId: WORKSPACE_ID,
+ otp: '123456',
+ targetUserId: TARGET_USER_ID,
+ targetWorkspaceId: WORKSPACE_ID,
+ });
+
+ it('stores only a hash of the code, replaces pending codes and notifies the member', async () => {
+ const before = Date.now();
+
+ const { recoveryCode, expiresAt } = await generate();
+
+ expect(recoveryCode).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){3}$/);
+ expect(expiresAt.getTime()).toBeGreaterThanOrEqual(
+ before + 60 * 60 * 1000,
+ );
+ expect(
+ twoFactorAuthenticationService.assertFreshStepUpAuthenticationOrThrow,
+ ).toHaveBeenCalledWith(
+ expect.objectContaining({
+ userId: ACTOR.id,
+ workspaceId: WORKSPACE_ID,
+ otp: '123456',
+ }),
+ );
+ expect(
+ twoFactorAuthenticationService.revokeRecoveryCodes,
+ ).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ userId: TARGET_USER_ID,
+ });
+ expect(appTokenRepository.insert).toHaveBeenCalledWith({
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ value: hashTwoFactorAuthenticationRecoveryCode(recoveryCode),
+ expiresAt,
+ context: { issuedByUserId: ACTOR.id },
+ });
+ expect(emailService.send).toHaveBeenCalledWith(
+ expect.objectContaining({ to: '[email protected]' }),
+ );
+ expect(
+ JSON.stringify((renderEmail as jest.Mock).mock.calls[0][0].props),
+ ).not.toContain(recoveryCode);
+ });
+
+ it('names the admin by email in the notification when they have no name', async () => {
+ await service.generateRecoveryCode({
+ actor: { ...ACTOR, firstName: '', lastName: '' },
+ actorWorkspaceId: WORKSPACE_ID,
+ otp: '123456',
+ targetUserId: TARGET_USER_ID,
+ targetWorkspaceId: WORKSPACE_ID,
+ });
+
+ expect(
+ JSON.stringify((renderEmail as jest.Mock).mock.calls[0][0].props),
+ ).toContain('[email protected]');
+ });
+
+ it('refuses a target with server admin privileges the actor lacks', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(
+ buildTargetUserWorkspace({ canAccessFullAdminPanel: true }),
+ );
+
+ await expect(generate()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ });
+ expect(appTokenRepository.insert).not.toHaveBeenCalled();
+ });
+
+ it('lets a server admin generate a code for another server admin', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(
+ buildTargetUserWorkspace({ canImpersonate: true }),
+ );
+
+ await service.generateRecoveryCode({
+ actor: { ...ACTOR, canAccessFullAdminPanel: true },
+ actorWorkspaceId: WORKSPACE_ID,
+ otp: '123456',
+ targetUserId: TARGET_USER_ID,
+ targetWorkspaceId: WORKSPACE_ID,
+ });
+
+ expect(appTokenRepository.insert).toHaveBeenCalled();
+ });
+
+ it('refuses a member with no authenticator to recover', async () => {
+ methodRepository.exists.mockResolvedValue(false);
+
+ await expect(generate()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ });
+ expect(appTokenRepository.insert).not.toHaveBeenCalled();
+ });
+
+ it('issues a new code to a member who has not finished setting up the authenticator from a previous recovery', async () => {
+ methodRepository.exists.mockResolvedValue(false);
+ appTokenRepository.exists.mockResolvedValue(true);
+
+ await generate();
+
+ expect(appTokenRepository.insert).toHaveBeenCalled();
+ });
+
+ it('refuses a user who is not a member of the workspace', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(null);
+
+ await expect(generate()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ });
+ });
+
+ it('reports a conflict when another code was issued for the member at the same time', async () => {
+ appTokenRepository.insert.mockRejectedValue(
+ Object.assign(new QueryFailedError('INSERT', [], new Error()), {
+ code: '23505',
+ }),
+ );
+
+ await expect(generate()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_ISSUANCE_CONFLICT,
+ });
+ expect(emailService.send).not.toHaveBeenCalled();
+ });
+
+ it('keeps the code when the notification email fails', async () => {
+ emailService.send.mockRejectedValue(new Error('SMTP down'));
+
+ await expect(generate()).resolves.toEqual(
+ expect.objectContaining({ recoveryCode: expect.any(String) }),
+ );
+ });
+ });
+
+ describe('redeemRecoveryCode', () => {
+ const redeem = ({
+ isTwoFactorAuthenticationEnforced = false,
+ }: { isTwoFactorAuthenticationEnforced?: boolean } = {}) =>
+ service.redeemRecoveryCode({
+ userId: TARGET_USER_ID,
+ userEmail: '[email protected]',
+ workspace: {
+ id: WORKSPACE_ID,
+ displayName: 'Apple',
+ isTwoFactorAuthenticationEnforced,
+ },
+ recoveryCode: 'abcde-fghjk-mnpqr-stvwx',
+ });
+
+ const redeemableCodeWhere = {
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ value: hashTwoFactorAuthenticationRecoveryCode('ABCDEFGHJKMNPQRSTVWX'),
+ deletedAt: IsNull(),
+ revokedAt: IsNull(),
+ createdAt: MoreThanOrEqual(MEMBERSHIP_CREATED_AT),
+ };
+
+ it('consumes the code, removes the authenticator and revokes refresh tokens together, then signs out the member', async () => {
+ await expect(redeem()).resolves.toEqual({ provisioningUri: null });
+
+ expect(throttlerService.tokenBucketThrottleOrThrow).toHaveBeenCalledWith(
+ buildTwoFactorAuthenticationRecoveryCodeRedemptionRateLimitKey({
+ userWorkspaceId: TARGET_USER_WORKSPACE_ID,
+ }),
+ 1,
+ expect.any(Number),
+ expect.any(Number),
+ );
+ expect(transactionalRepositories.appToken.update).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining(redeemableCodeWhere),
+ { deletedAt: expect.any(Date), revokedAt: expect.any(Date) },
+ );
+ expect(transactionalRepositories.method.delete).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ userWorkspaceId: TARGET_USER_WORKSPACE_ID,
+ });
+ expect(refreshTokenRevocationQueryBuilder.where).toHaveBeenCalledWith({
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ type: AppTokenType.RefreshToken,
+ expiresAt: MoreThan(expect.any(Date)),
+ });
+ expect(refreshTokenRevocationQueryBuilder.set).toHaveBeenCalledWith({
+ revokedAt: expect.any(Function),
+ context: expect.any(Function),
+ });
+ expect(
+ refreshTokenRevocationQueryBuilder.set.mock.calls[0][0].revokedAt(),
+ ).toBe(`COALESCE("revokedAt", now())`);
+ expect(
+ refreshTokenRevocationQueryBuilder.set.mock.calls[0][0].context(),
+ ).toContain(`COALESCE("context", '{}'::jsonb) ||`);
+ expect(
+ refreshTokenRevocationQueryBuilder.setParameters,
+ ).toHaveBeenCalledWith({
+ revokedReason: UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ });
+ expect(refreshTokenRevocationQueryBuilder.execute).toHaveBeenCalled();
+ expect(transactionalRepositories.method.insert).not.toHaveBeenCalled();
+ expect(userSessionService.revokeAllSessionsForUser).toHaveBeenCalledWith({
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ reason: UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ });
+ expect(
+ transactionalRepositories.appToken.update.mock.invocationCallOrder[0],
+ ).toBeLessThan(
+ userSessionService.revokeAllSessionsForUser.mock.invocationCallOrder[0],
+ );
+ expect(emailService.send).toHaveBeenCalledWith(
+ expect.objectContaining({ to: '[email protected]' }),
+ );
+ });
+
+ it('hands the replacement authenticator only to the redeeming request when the workspace enforces two-factor authentication', async () => {
+ await expect(
+ redeem({ isTwoFactorAuthenticationEnforced: true }),
+ ).resolves.toEqual({ provisioningUri: REPLACEMENT_PROVISIONING_URI });
+
+ expect(transactionalRepositories.appToken.update).toHaveBeenNthCalledWith(
+ 1,
+ expect.objectContaining({
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ }),
+ { deletedAt: expect.any(Date) },
+ );
+ expect(transactionalRepositories.method.insert).toHaveBeenCalledWith({
+ workspaceId: WORKSPACE_ID,
+ userWorkspaceId: TARGET_USER_WORKSPACE_ID,
+ secret: 'encrypted-replacement-secret',
+ status: OTPStatus.PENDING,
+ strategy: TwoFactorAuthenticationStrategy.TOTP,
+ });
+ expect(
+ transactionalRepositories.method.delete.mock.invocationCallOrder[0],
+ ).toBeLessThan(
+ transactionalRepositories.method.insert.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('rejects an unknown, expired, used or revoked code without signing anyone out', async () => {
+ transactionalRepositories.appToken.update.mockResolvedValueOnce({
+ affected: 0,
+ });
+
+ await expect(redeem()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.INVALID_RECOVERY_CODE,
+ });
+ expect(
+ userSessionService.revokeAllSessionsForUser,
+ ).not.toHaveBeenCalled();
+ expect(transactionalRepositories.method.delete).not.toHaveBeenCalled();
+ expect(transactionalRepositories.appToken.update).toHaveBeenCalledTimes(
+ 1,
+ );
+ expect(emailService.send).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('assertEnrollmentNotReservedForRecoveryOrThrow', () => {
+ const assertEnrollmentAllowed = () =>
+ service.assertEnrollmentNotReservedForRecoveryOrThrow({
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ });
+
+ it('refuses public enrollment until the authenticator issued by a recovery is verified, however long ago it was redeemed', async () => {
+ methodRepository.exists.mockResolvedValue(false);
+ appTokenRepository.exists.mockResolvedValue(true);
+
+ await expect(assertEnrollmentAllowed()).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ });
+ expect(appTokenRepository.exists).toHaveBeenCalledWith({
+ where: {
+ userId: TARGET_USER_ID,
+ workspaceId: WORKSPACE_ID,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ deletedAt: Not(IsNull()),
+ revokedAt: IsNull(),
+ createdAt: MoreThanOrEqual(MEMBERSHIP_CREATED_AT),
+ },
+ });
+ });
+
+ it('allows enrollment when no redeemed recovery is waiting for its authenticator', async () => {
+ methodRepository.exists.mockResolvedValue(false);
+ appTokenRepository.exists.mockResolvedValue(false);
+
+ await expect(assertEnrollmentAllowed()).resolves.toBeUndefined();
+ });
+
+ it('leaves non-members to the provisioning flow', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(null);
+
+ await expect(assertEnrollmentAllowed()).resolves.toBeUndefined();
+ expect(appTokenRepository.exists).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('revokeRecoveryCode', () => {
+ it('refuses to revoke a server administrator code for an actor without those privileges', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(
+ buildTargetUserWorkspace({ canImpersonate: true }),
+ );
+
+ await expect(
+ service.revokeRecoveryCode({
+ actor: ACTOR,
+ targetUserId: TARGET_USER_ID,
+ targetWorkspaceId: WORKSPACE_ID,
+ }),
+ ).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ });
+ expect(
+ twoFactorAuthenticationService.revokeRecoveryCodes,
+ ).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('getRecoveryStatus', () => {
+ it('hides a server administrator status from an actor without those privileges', async () => {
+ userWorkspaceService.getUserWorkspaceForUser.mockResolvedValue(
+ buildTargetUserWorkspace({ canImpersonate: true }),
+ );
+
+ await expect(
+ service.getRecoveryStatus({
+ actor: ACTOR,
+ targetUserId: TARGET_USER_ID,
+ targetWorkspaceId: WORKSPACE_ID,
+ }),
+ ).rejects.toMatchObject({
+ code: TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ });
+ expect(appTokenRepository.findOne).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.ts
new file mode 100644
index 00000000000..5df93e8412d
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service.ts
@@ -0,0 +1,616 @@
+import { Injectable, Logger } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { type MessageDescriptor } from '@lingui/core';
+import { msg } from '@lingui/core/macro';
+import ms from 'ms';
+import {
+ TwoFactorAuthenticationRecoveryCodeIssuedEmail,
+ TwoFactorAuthenticationResetEmail,
+ renderEmail,
+} from 'twenty-emails';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
+import { TwoFactorAuthenticationStrategy } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+import {
+ IsNull,
+ MoreThan,
+ MoreThanOrEqual,
+ Not,
+ QueryFailedError,
+ Repository,
+} from 'typeorm';
+
+import { POSTGRESQL_ERROR_CODES } from 'src/engine/api/graphql/workspace-query-runner/constants/postgres-error-codes.constants';
+import { type QueryFailedErrorWithCode } from 'src/engine/api/graphql/workspace-query-runner/utils/workspace-query-runner-graphql-api-exception-handler.util';
+import {
+ AppTokenEntity,
+ AppTokenType,
+} from 'src/engine/core-modules/app-token/app-token.entity';
+import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util';
+import { type AuthContextUser } from 'src/engine/core-modules/auth/types/auth-context.type';
+import { EmailService } from 'src/engine/core-modules/email/email.service';
+import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
+import { userHasAdminPrivileges } from 'src/engine/core-modules/impersonation/utils/user-has-admin-privileges.util';
+import { ThrottlerService } from 'src/engine/core-modules/throttler/throttler.service';
+import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
+import {
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_MAX,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_WINDOW_MS,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_WINDOW_MS,
+} from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant';
+import { TwoFactorAuthenticationMethodEntity } from 'src/engine/core-modules/two-factor-authentication/entities/two-factor-authentication-method.entity';
+import { OTPStatus } from 'src/engine/core-modules/two-factor-authentication/strategies/otp/otp.constants';
+import {
+ TwoFactorAuthenticationException,
+ TwoFactorAuthenticationExceptionCode,
+} from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception';
+import { TwoFactorAuthenticationService } from 'src/engine/core-modules/two-factor-authentication/two-factor-authentication.service';
+import { buildTwoFactorAuthenticationRecoveryCodeIssuanceRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-issuance-rate-limit-key.util';
+import { buildTwoFactorAuthenticationRecoveryCodeRedemptionRateLimitKey } from 'src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-redemption-rate-limit-key.util';
+import { generateTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util';
+import { hashTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util';
+import { UserSessionService } from 'src/engine/core-modules/user-session/services/user-session.service';
+import { UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
+import { type UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
+import { UserWorkspaceService } from 'src/engine/core-modules/user-workspace/user-workspace.service';
+import { type UserEntity } from 'src/engine/core-modules/user/user.entity';
+import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
+import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
+import { WorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/workspace-scoped-repository';
+
+type RecoveryCodeActor = Pick<
+ AuthContextUser,
+ | 'id'
+ | 'email'
+ | 'firstName'
+ | 'lastName'
+ | 'canImpersonate'
+ | 'canAccessFullAdminPanel'
+>;
+
+@Injectable()
+// oxlint-disable-next-line twenty/inject-workspace-repository
+export class TwoFactorAuthenticationRecoveryService {
+ private readonly logger = new Logger(
+ TwoFactorAuthenticationRecoveryService.name,
+ );
+
+ constructor(
+ @InjectWorkspaceScopedRepository(TwoFactorAuthenticationMethodEntity)
+ private readonly twoFactorAuthenticationMethodRepository: WorkspaceScopedRepository<TwoFactorAuthenticationMethodEntity>,
+ @InjectRepository(AppTokenEntity)
+ private readonly appTokenRepository: Repository<AppTokenEntity>,
+ private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService,
+ private readonly userWorkspaceService: UserWorkspaceService,
+ private readonly userSessionService: UserSessionService,
+ private readonly throttlerService: ThrottlerService,
+ private readonly emailService: EmailService,
+ private readonly i18nService: I18nService,
+ private readonly twentyConfigService: TwentyConfigService,
+ ) {}
+
+ async generateRecoveryCode({
+ actor,
+ actorWorkspaceId,
+ otp,
+ targetUserId,
+ targetWorkspaceId,
+ }: {
+ actor: RecoveryCodeActor;
+ actorWorkspaceId: WorkspaceEntity['id'];
+ otp?: string;
+ targetUserId: UserEntity['id'];
+ targetWorkspaceId: WorkspaceEntity['id'];
+ }): Promise<{ recoveryCode: string; expiresAt: Date }> {
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ buildTwoFactorAuthenticationRecoveryCodeIssuanceRateLimitKey({
+ actorUserId: actor.id,
+ }),
+ 1,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_MAX,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ISSUANCE_RATE_LIMIT_WINDOW_MS,
+ );
+
+ if (actor.id === targetUserId) {
+ throw new TwoFactorAuthenticationException(
+ 'A recovery code cannot be generated for yourself',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ {
+ userFriendlyMessage: msg`You can't generate a recovery code for yourself. Reset two-factor authentication from your profile instead.`,
+ },
+ );
+ }
+
+ await this.twoFactorAuthenticationService.assertFreshStepUpAuthenticationOrThrow(
+ {
+ userId: actor.id,
+ workspaceId: actorWorkspaceId,
+ otp,
+ otpRequiredMessage: msg`Enter your two-factor authentication code to generate a recovery code.`,
+ twoFactorAuthenticationRequiredMessage: msg`Set up two-factor authentication on your own account before generating a recovery code.`,
+ },
+ );
+
+ const targetUserWorkspace =
+ await this.getManageableTargetUserWorkspaceOrThrow({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ });
+
+ const hasRecoverableTwoFactorAuthentication =
+ (await this.hasVerifiedTwoFactorAuthenticationMethod(
+ targetUserWorkspace,
+ )) || (await this.isAwaitingRecoveryEnrollment(targetUserWorkspace));
+
+ if (!hasRecoverableTwoFactorAuthentication) {
+ throw new TwoFactorAuthenticationException(
+ 'The member has no verified two-factor authentication method',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ {
+ userFriendlyMessage: msg`This member hasn't set up two-factor authentication, so there is nothing to recover.`,
+ },
+ );
+ }
+
+ await this.twoFactorAuthenticationService.revokeRecoveryCodes({
+ workspaceId: targetWorkspaceId,
+ userId: targetUserId,
+ });
+
+ const recoveryCode = generateTwoFactorAuthenticationRecoveryCode();
+ const expiresAt = new Date(
+ Date.now() +
+ ms(
+ this.twentyConfigService.get(
+ 'TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_EXPIRES_IN',
+ ),
+ ),
+ );
+
+ try {
+ await this.appTokenRepository.insert({
+ userId: targetUserId,
+ workspaceId: targetWorkspaceId,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ value: hashTwoFactorAuthenticationRecoveryCode(recoveryCode),
+ expiresAt,
+ context: { issuedByUserId: actor.id },
+ });
+ } catch (error) {
+ if (
+ error instanceof QueryFailedError &&
+ (error as QueryFailedErrorWithCode).code ===
+ POSTGRESQL_ERROR_CODES.UNIQUE_VIOLATION
+ ) {
+ throw new TwoFactorAuthenticationException(
+ 'A recovery code was issued concurrently for this member',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_ISSUANCE_CONFLICT,
+ );
+ }
+
+ throw error;
+ }
+
+ await this.sendRecoveryCodeIssuedEmail({
+ actor,
+ targetUserWorkspace,
+ expiresAt,
+ });
+
+ return { recoveryCode, expiresAt };
+ }
+
+ async revokeRecoveryCode({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ }: {
+ actor: RecoveryCodeActor;
+ targetUserId: UserEntity['id'];
+ targetWorkspaceId: WorkspaceEntity['id'];
+ }): Promise<boolean> {
+ const targetUserWorkspace =
+ await this.getManageableTargetUserWorkspaceOrThrow({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ });
+
+ const revokedCount =
+ await this.twoFactorAuthenticationService.revokeRecoveryCodes({
+ workspaceId: targetWorkspaceId,
+ userId: targetUserWorkspace.userId,
+ });
+
+ return revokedCount > 0;
+ }
+
+ async getRecoveryStatus({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ }: {
+ actor: RecoveryCodeActor;
+ targetUserId: UserEntity['id'];
+ targetWorkspaceId: WorkspaceEntity['id'];
+ }): Promise<{
+ hasVerifiedTwoFactorAuthenticationMethod: boolean;
+ isAwaitingRecoveryEnrollment: boolean;
+ pendingRecoveryCodeExpiresAt: Date | null;
+ }> {
+ const targetUserWorkspace =
+ await this.getManageableTargetUserWorkspaceOrThrow({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ });
+
+ const hasVerifiedTwoFactorAuthenticationMethod =
+ await this.hasVerifiedTwoFactorAuthenticationMethod(targetUserWorkspace);
+
+ const isAwaitingRecoveryEnrollment =
+ !hasVerifiedTwoFactorAuthenticationMethod &&
+ (await this.isAwaitingRecoveryEnrollment(targetUserWorkspace));
+
+ const pendingRecoveryCode = await this.appTokenRepository.findOne({
+ where: {
+ userId: targetUserWorkspace.userId,
+ workspaceId: targetWorkspaceId,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ deletedAt: IsNull(),
+ revokedAt: IsNull(),
+ expiresAt: MoreThan(new Date()),
+ },
+ });
+
+ return {
+ hasVerifiedTwoFactorAuthenticationMethod,
+ isAwaitingRecoveryEnrollment,
+ pendingRecoveryCodeExpiresAt: pendingRecoveryCode?.expiresAt ?? null,
+ };
+ }
+
+ async redeemRecoveryCode({
+ userId,
+ userEmail,
+ workspace,
+ recoveryCode,
+ }: {
+ userId: UserEntity['id'];
+ userEmail: string;
+ workspace: Pick<
+ WorkspaceEntity,
+ 'id' | 'displayName' | 'isTwoFactorAuthenticationEnforced'
+ >;
+ recoveryCode: string;
+ }): Promise<{ provisioningUri: string | null }> {
+ const userWorkspace = await this.getTargetUserWorkspaceOrThrow({
+ targetUserId: userId,
+ targetWorkspaceId: workspace.id,
+ });
+
+ await this.throttlerService.tokenBucketThrottleOrThrow(
+ buildTwoFactorAuthenticationRecoveryCodeRedemptionRateLimitKey({
+ userWorkspaceId: userWorkspace.id,
+ }),
+ 1,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_WINDOW_MS,
+ );
+
+ const redemption = await this.appTokenRepository.manager.transaction(
+ async (entityManager) => {
+ await acquireUserAuthenticationLock({
+ entityManager,
+ userId,
+ mode: 'exclusive',
+ });
+
+ const appTokenRepository = entityManager.getRepository(AppTokenEntity);
+
+ // A redeemed code stays unrevoked only while it reserves enrollment for the authenticator it issued
+ const consumeResult = await appTokenRepository.update(
+ {
+ userId,
+ workspaceId: workspace.id,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ value: hashTwoFactorAuthenticationRecoveryCode(recoveryCode),
+ deletedAt: IsNull(),
+ revokedAt: IsNull(),
+ expiresAt: MoreThan(new Date()),
+ createdAt: MoreThanOrEqual(userWorkspace.createdAt),
+ },
+ workspace.isTwoFactorAuthenticationEnforced
+ ? { deletedAt: new Date() }
+ : { deletedAt: new Date(), revokedAt: new Date() },
+ );
+
+ if ((consumeResult.affected ?? 0) === 0) {
+ return null;
+ }
+
+ const twoFactorAuthenticationMethodRepository =
+ entityManager.getRepository(TwoFactorAuthenticationMethodEntity);
+
+ await twoFactorAuthenticationMethodRepository.delete({
+ workspaceId: workspace.id,
+ userWorkspaceId: userWorkspace.id,
+ });
+
+ await appTokenRepository
+ .createQueryBuilder()
+ .update()
+ // Tokens already rotated are still renewable within the reuse grace period, so they need the reason too
+ .set({
+ revokedAt: () => `COALESCE("revokedAt", now())`,
+ context: () =>
+ `COALESCE("context", '{}'::jsonb) || jsonb_build_object('revokedReason', :revokedReason::text)`,
+ })
+ .where({
+ userId,
+ workspaceId: workspace.id,
+ type: AppTokenType.RefreshToken,
+ expiresAt: MoreThan(new Date()),
+ })
+ .setParameters({
+ revokedReason:
+ UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ })
+ .execute();
+
+ if (!workspace.isTwoFactorAuthenticationEnforced) {
+ return { provisioningUri: null };
+ }
+
+ const { uri, encryptedSecret, status } =
+ this.twoFactorAuthenticationService.generatePendingTotpSecret({
+ userEmail,
+ workspaceId: workspace.id,
+ workspaceDisplayName: workspace.displayName,
+ });
+
+ await twoFactorAuthenticationMethodRepository.insert({
+ workspaceId: workspace.id,
+ userWorkspaceId: userWorkspace.id,
+ secret: encryptedSecret,
+ status,
+ strategy: TwoFactorAuthenticationStrategy.TOTP,
+ });
+
+ return { provisioningUri: uri };
+ },
+ );
+
+ if (!isDefined(redemption)) {
+ throw new TwoFactorAuthenticationException(
+ 'Invalid recovery code',
+ TwoFactorAuthenticationExceptionCode.INVALID_RECOVERY_CODE,
+ );
+ }
+
+ await this.userSessionService.revokeAllSessionsForUser({
+ userId,
+ workspaceId: workspace.id,
+ reason: UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ });
+
+ await this.sendTwoFactorAuthenticationResetEmail({
+ userWorkspace,
+ workspaceDisplayName: workspace.displayName,
+ });
+
+ return redemption;
+ }
+
+ async assertEnrollmentNotReservedForRecoveryOrThrow({
+ userId,
+ workspaceId,
+ }: {
+ userId: UserEntity['id'];
+ workspaceId: WorkspaceEntity['id'];
+ }): Promise<void> {
+ const userWorkspace =
+ await this.userWorkspaceService.getUserWorkspaceForUser({
+ userId,
+ workspaceId,
+ });
+
+ if (
+ !isDefined(userWorkspace) ||
+ (await this.hasVerifiedTwoFactorAuthenticationMethod(userWorkspace))
+ ) {
+ return;
+ }
+
+ if (await this.isAwaitingRecoveryEnrollment(userWorkspace)) {
+ throw new TwoFactorAuthenticationException(
+ 'Enrollment after a recovery must use the authenticator issued with the recovery code',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ );
+ }
+ }
+
+ private isAwaitingRecoveryEnrollment(
+ userWorkspace: Pick<
+ UserWorkspaceEntity,
+ 'userId' | 'workspaceId' | 'createdAt'
+ >,
+ ): Promise<boolean> {
+ return this.appTokenRepository.exists({
+ where: {
+ userId: userWorkspace.userId,
+ workspaceId: userWorkspace.workspaceId,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ deletedAt: Not(IsNull()),
+ revokedAt: IsNull(),
+ createdAt: MoreThanOrEqual(userWorkspace.createdAt),
+ },
+ });
+ }
+
+ private async getTargetUserWorkspaceOrThrow({
+ targetUserId,
+ targetWorkspaceId,
+ }: {
+ targetUserId: UserEntity['id'];
+ targetWorkspaceId: WorkspaceEntity['id'];
+ }): Promise<UserWorkspaceEntity> {
+ const userWorkspace =
+ await this.userWorkspaceService.getUserWorkspaceForUser({
+ userId: targetUserId,
+ workspaceId: targetWorkspaceId,
+ relations: ['user', 'workspace'],
+ });
+
+ if (!isDefined(userWorkspace)) {
+ throw new TwoFactorAuthenticationException(
+ 'The user is not a member of this workspace',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ {
+ userFriendlyMessage: msg`This user is not a member of the workspace.`,
+ },
+ );
+ }
+
+ return userWorkspace;
+ }
+
+ private async getManageableTargetUserWorkspaceOrThrow({
+ actor,
+ targetUserId,
+ targetWorkspaceId,
+ }: {
+ actor: RecoveryCodeActor;
+ targetUserId: UserEntity['id'];
+ targetWorkspaceId: WorkspaceEntity['id'];
+ }): Promise<UserWorkspaceEntity> {
+ const targetUserWorkspace = await this.getTargetUserWorkspaceOrThrow({
+ targetUserId,
+ targetWorkspaceId,
+ });
+
+ this.assertActorCanManageRecoveryCodesForTargetOrThrow({
+ actor,
+ targetUserWorkspace,
+ });
+
+ return targetUserWorkspace;
+ }
+
+ private hasVerifiedTwoFactorAuthenticationMethod(
+ userWorkspace: Pick<UserWorkspaceEntity, 'id' | 'workspaceId'>,
+ ): Promise<boolean> {
+ return this.twoFactorAuthenticationMethodRepository.exists(
+ userWorkspace.workspaceId,
+ {
+ where: {
+ userWorkspaceId: userWorkspace.id,
+ status: OTPStatus.VERIFIED,
+ },
+ },
+ );
+ }
+
+ private assertActorCanManageRecoveryCodesForTargetOrThrow({
+ actor,
+ targetUserWorkspace,
+ }: {
+ actor: RecoveryCodeActor;
+ targetUserWorkspace: UserWorkspaceEntity;
+ }): void {
+ if (
+ userHasAdminPrivileges(targetUserWorkspace.user) &&
+ !userHasAdminPrivileges(actor)
+ ) {
+ throw new TwoFactorAuthenticationException(
+ 'Only a server administrator can manage recovery codes for a server administrator',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ {
+ userFriendlyMessage: msg`Only a server administrator can manage recovery codes for this member.`,
+ },
+ );
+ }
+ }
+
+ private async sendRecoveryCodeIssuedEmail({
+ actor,
+ targetUserWorkspace,
+ expiresAt,
+ }: {
+ actor: RecoveryCodeActor;
+ targetUserWorkspace: UserWorkspaceEntity;
+ expiresAt: Date;
+ }): Promise<void> {
+ const locale = targetUserWorkspace.locale ?? SOURCE_LOCALE;
+
+ await this.sendSecurityEmail({
+ to: targetUserWorkspace.user.email,
+ locale,
+ subject: msg`A two-factor authentication recovery code was generated for you`,
+ buildEmailTemplate: () =>
+ TwoFactorAuthenticationRecoveryCodeIssuedEmail({
+ actorName:
+ `${actor.firstName} ${actor.lastName}`.trim() || actor.email,
+ workspaceDisplayName: targetUserWorkspace.workspace.displayName ?? '',
+ expiresAt,
+ locale,
+ }),
+ });
+ }
+
+ private async sendTwoFactorAuthenticationResetEmail({
+ userWorkspace,
+ workspaceDisplayName,
+ }: {
+ userWorkspace: UserWorkspaceEntity;
+ workspaceDisplayName: WorkspaceEntity['displayName'];
+ }): Promise<void> {
+ const locale = userWorkspace.locale ?? SOURCE_LOCALE;
+
+ await this.sendSecurityEmail({
+ to: userWorkspace.user.email,
+ locale,
+ subject: msg`Your two-factor authentication was reset`,
+ buildEmailTemplate: () =>
+ TwoFactorAuthenticationResetEmail({
+ workspaceDisplayName: workspaceDisplayName ?? '',
+ locale,
+ }),
+ });
+ }
+
+ private async sendSecurityEmail({
+ to,
+ locale,
+ subject,
+ buildEmailTemplate,
+ }: {
+ to: string;
+ locale: UserWorkspaceEntity['locale'];
+ subject: MessageDescriptor;
+ buildEmailTemplate: () => Parameters<typeof renderEmail>[0];
+ }): Promise<void> {
+ try {
+ const emailTemplate = buildEmailTemplate();
+ const html = await renderEmail(emailTemplate, { pretty: true });
+ const text = await renderEmail(emailTemplate, { plainText: true });
+ const i18n = this.i18nService.getI18nInstance(locale);
+
+ await this.emailService.send({
+ from: `${this.twentyConfigService.get('EMAIL_FROM_NAME')} <${this.twentyConfigService.get('EMAIL_FROM_ADDRESS')}>`,
+ to,
+ subject: i18n._(subject),
+ text,
+ html,
+ });
+ } catch (error) {
+ this.logger.error(
+ 'Failed to send a two-factor authentication recovery email',
+ error,
+ );
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.spec.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.spec.ts
index 60d70a2bda0..b452e387264 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.spec.ts
@@ -1,4 +1,5 @@
import {
+ ConflictError,
ForbiddenError,
UserInputError,
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
@@ -105,5 +106,32 @@ describe('TwoFactorAuthenticationExceptionFilter', () => {
expect(error).toBeInstanceOf(ForbiddenError);
}
});
+
+ it.each([
+ [
+ TwoFactorAuthenticationExceptionCode.INVALID_RECOVERY_CODE,
+ UserInputError,
+ ],
+ [
+ TwoFactorAuthenticationExceptionCode.STEP_UP_AUTHENTICATION_REQUIRED,
+ UserInputError,
+ ],
+ [
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED,
+ ForbiddenError,
+ ],
+ [
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ ForbiddenError,
+ ],
+ [
+ TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_ISSUANCE_CONFLICT,
+ ConflictError,
+ ],
+ ])('should map %s to the matching GraphQL error', (code, ExpectedError) => {
+ const exception = new TwoFactorAuthenticationException('Error', code);
+
+ expect(() => filter.catch(exception)).toThrow(ExpectedError);
+ });
});
});
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.ts
index c5b64966159..6bf6319055a 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication-exception.filter.ts
@@ -4,6 +4,7 @@ import { assertUnreachable } from 'twenty-shared/utils';
import { msg } from '@lingui/core/macro';
import {
+ ConflictError,
ForbiddenError,
UserInputError,
} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
@@ -21,6 +22,14 @@ export class TwoFactorAuthenticationExceptionFilter implements ExceptionFilter {
subCode: exception.code,
userFriendlyMessage: msg`Invalid verification code. Please try again.`,
});
+ case TwoFactorAuthenticationExceptionCode.INVALID_RECOVERY_CODE:
+ case TwoFactorAuthenticationExceptionCode.STEP_UP_AUTHENTICATION_REQUIRED:
+ throw new UserInputError(exception);
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED:
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED:
+ throw new ForbiddenError(exception);
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_ISSUANCE_CONFLICT:
+ throw new ConflictError(exception);
case TwoFactorAuthenticationExceptionCode.INVALID_CONFIGURATION:
case TwoFactorAuthenticationExceptionCode.TWO_FACTOR_AUTHENTICATION_METHOD_NOT_FOUND:
case TwoFactorAuthenticationExceptionCode.MALFORMED_DATABASE_OBJECT:
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception.ts
index 06a6d9173d0..d7d43436116 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.exception.ts
@@ -10,6 +10,11 @@ export enum TwoFactorAuthenticationExceptionCode {
INVALID_OTP = 'INVALID_OTP',
TWO_FACTOR_AUTHENTICATION_METHOD_ALREADY_PROVISIONED = 'TWO_FACTOR_AUTHENTICATION_METHOD_ALREADY_PROVISIONED',
MALFORMED_DATABASE_OBJECT = 'MALFORMED_DATABASE_OBJECT',
+ INVALID_RECOVERY_CODE = 'INVALID_RECOVERY_CODE',
+ RECOVERY_CODE_TARGET_NOT_ALLOWED = 'RECOVERY_CODE_TARGET_NOT_ALLOWED',
+ RECOVERY_CODE_ISSUANCE_CONFLICT = 'RECOVERY_CODE_ISSUANCE_CONFLICT',
+ RECOVERY_ENROLLMENT_RESTRICTED = 'RECOVERY_ENROLLMENT_RESTRICTED',
+ STEP_UP_AUTHENTICATION_REQUIRED = 'STEP_UP_AUTHENTICATION_REQUIRED',
}
const getTwoFactorAuthenticationExceptionUserFriendlyMessage = (
@@ -26,6 +31,16 @@ const getTwoFactorAuthenticationExceptionUserFriendlyMessage = (
return msg`Two-factor authentication is already set up.`;
case TwoFactorAuthenticationExceptionCode.MALFORMED_DATABASE_OBJECT:
return msg`An error occurred with two-factor authentication data.`;
+ case TwoFactorAuthenticationExceptionCode.INVALID_RECOVERY_CODE:
+ return msg`Invalid or expired recovery code.`;
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_TARGET_NOT_ALLOWED:
+ return msg`You can't generate a recovery code for this member.`;
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_CODE_ISSUANCE_CONFLICT:
+ return msg`Another recovery code was just generated for this member. Refresh the page to see it.`;
+ case TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED:
+ return msg`Ask a workspace admin for a new recovery code to finish setting up two-factor authentication.`;
+ case TwoFactorAuthenticationExceptionCode.STEP_UP_AUTHENTICATION_REQUIRED:
+ return msg`Enter your two-factor authentication code to continue.`;
default:
assertUnreachable(code);
}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
index 7decc5aedf6..40fb75a0621 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.module.ts
@@ -1,12 +1,16 @@
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
+import { AppTokenEntity } from 'src/engine/core-modules/app-token/app-token.entity';
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 { SecretEncryptionModule } from 'src/engine/core-modules/secret-encryption/secret-encryption.module';
import { ThrottlerModule } from 'src/engine/core-modules/throttler/throttler.module';
+import { TwoFactorAuthenticationRecoveryService } from 'src/engine/core-modules/two-factor-authentication/services/two-factor-authentication-recovery.service';
+import { UserSessionModule } from 'src/engine/core-modules/user-session/user-session.module';
import { UserWorkspaceModule } from 'src/engine/core-modules/user-workspace/user-workspace.module';
import { UserModule } from 'src/engine/core-modules/user/user.module';
+import { PermissionsModule } from 'src/engine/metadata-modules/permissions/permissions.module';
import { provideWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/provide-workspace-scoped-repository';
import { TwoFactorAuthenticationResolver } from './two-factor-authentication.resolver';
import { TwoFactorAuthenticationService } from './two-factor-authentication.service';
@@ -20,14 +24,23 @@ import { TwoFactorAuthenticationMethodEntity } from './entities/two-factor-authe
TokenModule,
SecretEncryptionModule,
ThrottlerModule,
- TypeOrmModule.forFeature([TwoFactorAuthenticationMethodEntity]),
+ UserSessionModule,
+ PermissionsModule,
+ TypeOrmModule.forFeature([
+ TwoFactorAuthenticationMethodEntity,
+ AppTokenEntity,
+ ]),
UserModule,
],
providers: [
TwoFactorAuthenticationService,
+ TwoFactorAuthenticationRecoveryService,
TwoFactorAuthenticationResolver,
provideWorkspaceScopedRepository(TwoFactorAuthenticationMethodEntity),
],
- exports: [TwoFactorAuthenticationService],
+ exports: [
+ TwoFactorAuthenticationService,
+ TwoFactorAuthenticationRecoveryService,
+ ],
})
export class TwoFactorAuthenticationModule {}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.spec.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.spec.ts
index 23e70ad4ce5..c9bb56b00c1 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.spec.ts
@@ -13,6 +13,12 @@ import { type WorkspaceEntity } from 'src/engine/core-modules/workspace/workspac
import { TwoFactorAuthenticationResolver } from './two-factor-authentication.resolver';
import { TwoFactorAuthenticationService } from './two-factor-authentication.service';
+import { TwoFactorAuthenticationRecoveryService } from './services/two-factor-authentication-recovery.service';
+import {
+ TwoFactorAuthenticationException,
+ TwoFactorAuthenticationExceptionCode,
+} from './two-factor-authentication.exception';
+import { PermissionsService } from 'src/engine/metadata-modules/permissions/permissions.service';
import { type DeleteTwoFactorAuthenticationMethodInput } from './dto/delete-two-factor-authentication-method.input';
import { type InitiateTwoFactorAuthenticationProvisioningInput } from './dto/initiate-two-factor-authentication-provisioning.input';
@@ -29,6 +35,10 @@ const createMockTwoFactorAuthenticationService = () => ({
verifyTwoFactorAuthenticationMethodForAuthenticatedUser: jest.fn(),
});
+const createMockTwoFactorAuthenticationRecoveryService = () => ({
+ assertEnrollmentNotReservedForRecoveryOrThrow: jest.fn(),
+});
+
const createMockLoginTokenService = () => ({
verifyLoginToken: jest.fn(),
});
@@ -46,6 +56,9 @@ describe('TwoFactorAuthenticationResolver', () => {
let twoFactorAuthenticationService: ReturnType<
typeof createMockTwoFactorAuthenticationService
>;
+ let twoFactorAuthenticationRecoveryService: ReturnType<
+ typeof createMockTwoFactorAuthenticationRecoveryService
+ >;
let loginTokenService: ReturnType<typeof createMockLoginTokenService>;
let userService: ReturnType<typeof createMockUserService>;
let workspaceDomainsService: ReturnType<
@@ -91,6 +104,14 @@ describe('TwoFactorAuthenticationResolver', () => {
provide: TwoFactorAuthenticationService,
useFactory: createMockTwoFactorAuthenticationService,
},
+ {
+ provide: TwoFactorAuthenticationRecoveryService,
+ useFactory: createMockTwoFactorAuthenticationRecoveryService,
+ },
+ {
+ provide: PermissionsService,
+ useValue: {},
+ },
{
provide: LoginTokenService,
useFactory: createMockLoginTokenService,
@@ -116,6 +137,9 @@ describe('TwoFactorAuthenticationResolver', () => {
TwoFactorAuthenticationResolver,
);
twoFactorAuthenticationService = module.get(TwoFactorAuthenticationService);
+ twoFactorAuthenticationRecoveryService = module.get(
+ TwoFactorAuthenticationRecoveryService,
+ );
loginTokenService = module.get(LoginTokenService);
userService = module.get(UserService);
workspaceDomainsService = module.get(WorkspaceDomainsService);
@@ -179,6 +203,48 @@ describe('TwoFactorAuthenticationResolver', () => {
);
});
+ it('should refuse provisioning while enrollment is reserved for a recovery code redemption', async () => {
+ const restrictedException = new TwoFactorAuthenticationException(
+ 'Enrollment reserved for recovery',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ );
+
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow.mockRejectedValue(
+ restrictedException,
+ );
+
+ await expect(
+ resolver.initiateOTPProvisioning(mockInput, origin),
+ ).rejects.toBe(restrictedException);
+ expect(
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow,
+ ).toHaveBeenCalledWith({
+ userId: mockUser.id,
+ workspaceId: mockWorkspace.id,
+ });
+ expect(
+ twoFactorAuthenticationService.initiateStrategyConfiguration,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('should withhold the URI when a recovery is redeemed while provisioning runs', async () => {
+ const restrictedException = new TwoFactorAuthenticationException(
+ 'Enrollment reserved for recovery',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ );
+
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(restrictedException);
+
+ await expect(
+ resolver.initiateOTPProvisioning(mockInput, origin),
+ ).rejects.toBe(restrictedException);
+ expect(
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow,
+ ).toHaveBeenCalledTimes(2);
+ });
+
it('should throw WORKSPACE_NOT_FOUND when workspace is not found', async () => {
workspaceDomainsService.getWorkspaceByOriginOrDefaultWorkspace.mockResolvedValue(
null,
@@ -252,6 +318,54 @@ describe('TwoFactorAuthenticationResolver', () => {
);
});
+ it('should refuse provisioning while enrollment is reserved for a recovery code redemption', async () => {
+ const restrictedException = new TwoFactorAuthenticationException(
+ 'Enrollment reserved for recovery',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ );
+
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow.mockRejectedValue(
+ restrictedException,
+ );
+
+ await expect(
+ resolver.initiateOTPProvisioningForAuthenticatedUser(
+ mockUser,
+ mockWorkspace,
+ ),
+ ).rejects.toBe(restrictedException);
+ expect(
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow,
+ ).toHaveBeenCalledWith({
+ userId: mockUser.id,
+ workspaceId: mockWorkspace.id,
+ });
+ expect(
+ twoFactorAuthenticationService.initiateStrategyConfiguration,
+ ).not.toHaveBeenCalled();
+ });
+
+ it('should withhold the URI when a recovery is redeemed while provisioning runs', async () => {
+ const restrictedException = new TwoFactorAuthenticationException(
+ 'Enrollment reserved for recovery',
+ TwoFactorAuthenticationExceptionCode.RECOVERY_ENROLLMENT_RESTRICTED,
+ );
+
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow
+ .mockResolvedValueOnce(undefined)
+ .mockRejectedValueOnce(restrictedException);
+
+ await expect(
+ resolver.initiateOTPProvisioningForAuthenticatedUser(
+ mockUser,
+ mockWorkspace,
+ ),
+ ).rejects.toBe(restrictedException);
+ expect(
+ twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow,
+ ).toHaveBeenCalledTimes(2);
+ });
+
it('should throw INTERNAL_SERVER_ERROR when URI is missing', async () => {
twoFactorAuthenticationService.initiateStrategyConfiguration.mockResolvedValue(
undefined,
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
index dc66eca952a..daa866a0a94 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.resolver.ts
@@ -1,6 +1,7 @@
import { UseFilters, UseGuards } from '@nestjs/common';
-import { Args, Mutation } from '@nestjs/graphql';
+import { Args, Mutation, Query } from '@nestjs/graphql';
+import { PermissionFlagType } from 'twenty-shared/constants';
import { assertIsDefinedOrThrow, isDefined } from 'twenty-shared/utils';
import { InjectWorkspaceScopedRepository } from 'src/engine/twenty-orm/workspace-scoped-repository/inject-workspace-scoped-repository.decorator';
@@ -24,11 +25,13 @@ import { AllowSuspendedWorkspace } from 'src/engine/decorators/auth/allow-suspen
import { CustomPermissionGuard } from 'src/engine/guards/custom-permission.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { AuthPrincipalGuard } from 'src/engine/guards/auth-principal.guard';
+import { SettingsPermissionGuard } from 'src/engine/guards/settings-permission.guard';
import { PublicEndpointGuard } from 'src/engine/guards/public-endpoint.guard';
import { PermissionsGraphqlApiExceptionFilter } from 'src/engine/metadata-modules/permissions/utils/permissions-graphql-api-exception.filter';
import { TwoFactorAuthenticationExceptionFilter } from './two-factor-authentication-exception.filter';
import { TwoFactorAuthenticationService } from './two-factor-authentication.service';
+import { TwoFactorAuthenticationRecoveryService } from './services/two-factor-authentication-recovery.service';
import { DeleteTwoFactorAuthenticationMethodInput } from './dto/delete-two-factor-authentication-method.input';
import { DeleteTwoFactorAuthenticationMethodDTO } from './dto/delete-two-factor-authentication-method.dto';
@@ -36,6 +39,10 @@ import { InitiateTwoFactorAuthenticationProvisioningInput } from './dto/initiate
import { InitiateTwoFactorAuthenticationProvisioningDTO } from './dto/initiate-two-factor-authentication-provisioning.dto';
import { VerifyTwoFactorAuthenticationMethodInput } from './dto/verify-two-factor-authentication-method.input';
import { VerifyTwoFactorAuthenticationMethodDTO } from './dto/verify-two-factor-authentication-method.dto';
+import { GenerateTwoFactorAuthenticationRecoveryCodeInput } from './dto/generate-two-factor-authentication-recovery-code.input';
+import { TwoFactorAuthenticationRecoveryCodeDTO } from './dto/two-factor-authentication-recovery-code.dto';
+import { TwoFactorAuthenticationRecoveryStatusDTO } from './dto/two-factor-authentication-recovery-status.dto';
+import { TwoFactorAuthenticationRecoveryTargetInput } from './dto/two-factor-authentication-recovery-target.input';
import { TwoFactorAuthenticationMethodEntity } from './entities/two-factor-authentication-method.entity';
@MetadataResolver()
@@ -48,6 +55,7 @@ import { TwoFactorAuthenticationMethodEntity } from './entities/two-factor-authe
export class TwoFactorAuthenticationResolver {
constructor(
private readonly twoFactorAuthenticationService: TwoFactorAuthenticationService,
+ private readonly twoFactorAuthenticationRecoveryService: TwoFactorAuthenticationRecoveryService,
private readonly loginTokenService: LoginTokenService,
private readonly userService: UserService,
private readonly workspaceDomainsService: WorkspaceDomainsService,
@@ -93,6 +101,10 @@ export class TwoFactorAuthenticationResolver {
const user = await this.userService.findUserByEmailOrThrow(userEmail);
+ await this.twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow(
+ { userId: user.id, workspaceId: workspace.id },
+ );
+
const uri =
await this.twoFactorAuthenticationService.initiateStrategyConfiguration(
user.id,
@@ -108,6 +120,11 @@ export class TwoFactorAuthenticationResolver {
);
}
+ // A recovery redeemed while this request ran may have replaced the method, so the URI could hold its secret
+ await this.twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow(
+ { userId: user.id, workspaceId: workspace.id },
+ );
+
return { uri };
}
@@ -130,6 +147,10 @@ export class TwoFactorAuthenticationResolver {
@AuthUser() user: AuthContextUser,
@AuthWorkspace() workspace: WorkspaceEntity,
): Promise<InitiateTwoFactorAuthenticationProvisioningDTO> {
+ await this.twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow(
+ { userId: user.id, workspaceId: workspace.id },
+ );
+
const uri =
await this.twoFactorAuthenticationService.initiateStrategyConfiguration(
user.id,
@@ -145,6 +166,10 @@ export class TwoFactorAuthenticationResolver {
);
}
+ await this.twoFactorAuthenticationRecoveryService.assertEnrollmentNotReservedForRecoveryOrThrow(
+ { userId: user.id, workspaceId: workspace.id },
+ );
+
return { uri };
}
@@ -225,4 +250,91 @@ export class TwoFactorAuthenticationResolver {
workspace.id,
);
}
+
+ @Query(() => TwoFactorAuthenticationRecoveryStatusDTO)
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: false,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.SECURITY),
+ )
+ async twoFactorAuthenticationRecoveryStatus(
+ @Args() { userId }: TwoFactorAuthenticationRecoveryTargetInput,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthUser() user: AuthContextUser,
+ ): Promise<TwoFactorAuthenticationRecoveryStatusDTO> {
+ return await this.twoFactorAuthenticationRecoveryService.getRecoveryStatus({
+ actor: user,
+ targetUserId: userId,
+ targetWorkspaceId: workspace.id,
+ });
+ }
+
+ @Mutation(() => TwoFactorAuthenticationRecoveryCodeDTO)
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: false,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.SECURITY),
+ )
+ async generateTwoFactorAuthenticationRecoveryCode(
+ @Args() { userId, otp }: GenerateTwoFactorAuthenticationRecoveryCodeInput,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthUser() user: AuthContextUser,
+ ): Promise<TwoFactorAuthenticationRecoveryCodeDTO> {
+ return await this.twoFactorAuthenticationRecoveryService.generateRecoveryCode(
+ {
+ actor: user,
+ actorWorkspaceId: workspace.id,
+ otp,
+ targetUserId: userId,
+ targetWorkspaceId: workspace.id,
+ },
+ );
+ }
+
+ @Mutation(() => Boolean)
+ @UseGuards(
+ AuthPrincipalGuard({
+ userSession: {
+ standard: true,
+ impersonated: false,
+ playground: false,
+ workspaceAgnostic: false,
+ },
+ apiKey: false,
+ oauthClient: false,
+ application: false,
+ }),
+ SettingsPermissionGuard(PermissionFlagType.SECURITY),
+ )
+ async revokeTwoFactorAuthenticationRecoveryCode(
+ @Args() { userId }: TwoFactorAuthenticationRecoveryTargetInput,
+ @AuthWorkspace() workspace: WorkspaceEntity,
+ @AuthUser() user: AuthContextUser,
+ ): Promise<boolean> {
+ return await this.twoFactorAuthenticationRecoveryService.revokeRecoveryCode(
+ {
+ actor: user,
+ targetUserId: userId,
+ targetWorkspaceId: workspace.id,
+ },
+ );
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
index 40e54d82797..e6f4ff965dc 100644
--- a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/two-factor-authentication.service.ts
@@ -1,13 +1,22 @@
import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+import { type MessageDescriptor } from '@lingui/core';
+import { isNonEmptyString } from '@sniptt/guards';
import { authenticator } from 'otplib';
import { TwoFactorAuthenticationStrategy } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { type EntityManager, IsNull, Repository } from 'typeorm';
+import {
+ AppTokenEntity,
+ AppTokenType,
+} from 'src/engine/core-modules/app-token/app-token.entity';
import {
AuthException,
AuthExceptionCode,
} from 'src/engine/core-modules/auth/auth.exception';
+import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util';
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
import { type PlaintextString } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
import { SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
@@ -42,6 +51,8 @@ export class TwoFactorAuthenticationService {
constructor(
@InjectWorkspaceScopedRepository(TwoFactorAuthenticationMethodEntity)
private readonly twoFactorAuthenticationMethodRepository: WorkspaceScopedRepository<TwoFactorAuthenticationMethodEntity>,
+ @InjectRepository(AppTokenEntity)
+ private readonly appTokenRepository: Repository<AppTokenEntity>,
private readonly userWorkspaceService: UserWorkspaceService,
private readonly secretEncryptionService: SecretEncryptionService,
private readonly throttlerService: ThrottlerService,
@@ -128,24 +139,18 @@ export class TwoFactorAuthenticationService {
return reuseUri;
}
- const { uri, context } = new TotpStrategy(
- TOTP_DEFAULT_CONFIGURATION,
- ).initiate(
+ const { uri, encryptedSecret, status } = this.generatePendingTotpSecret({
userEmail,
- `Twenty${workspaceDisplayName ? ` - ${workspaceDisplayName}` : ''}`,
- );
-
- const encryptedSecret = this.secretEncryptionService.encryptVersioned(
- context.secret,
- { workspaceId },
- );
+ workspaceId,
+ workspaceDisplayName,
+ });
await this.twoFactorAuthenticationMethodRepository.upsert(
workspaceId,
{
userWorkspaceId: userWorkspace.id,
secret: encryptedSecret,
- status: context.status,
+ status,
strategy: TwoFactorAuthenticationStrategy.TOTP,
},
['userWorkspaceId', 'strategy'],
@@ -154,6 +159,32 @@ export class TwoFactorAuthenticationService {
return uri;
}
+ generatePendingTotpSecret({
+ userEmail,
+ workspaceId,
+ workspaceDisplayName,
+ }: {
+ userEmail: string;
+ workspaceId: WorkspaceEntity['id'];
+ workspaceDisplayName?: string;
+ }): { uri: string; encryptedSecret: EncryptedString; status: OTPStatus } {
+ const { uri, context } = new TotpStrategy(
+ TOTP_DEFAULT_CONFIGURATION,
+ ).initiate(
+ userEmail,
+ `Twenty${workspaceDisplayName ? ` - ${workspaceDisplayName}` : ''}`,
+ );
+
+ return {
+ uri,
+ encryptedSecret: this.secretEncryptionService.encryptVersioned(
+ context.secret,
+ { workspaceId },
+ ),
+ status: context.status,
+ };
+ }
+
async validateStrategy(
userId: UserEntity['id'],
token: string,
@@ -213,10 +244,107 @@ export class TwoFactorAuthenticationService {
);
}
- await this.twoFactorAuthenticationMethodRepository.update(
+ await this.appTokenRepository.manager.transaction(async (entityManager) => {
+ await acquireUserAuthenticationLock({
+ entityManager,
+ userId,
+ mode: 'exclusive',
+ });
+
+ // A recovery that committed after the read replaced this method, and its enrollment reservation must survive
+ const updateResult = await entityManager
+ .getRepository(TwoFactorAuthenticationMethodEntity)
+ .update(
+ {
+ id: userTwoFactorAuthenticationMethod.id,
+ workspaceId,
+ secret: userTwoFactorAuthenticationMethod.secret,
+ },
+ { status: OTPStatus.VERIFIED },
+ );
+
+ if ((updateResult.affected ?? 0) === 0) {
+ throw new TwoFactorAuthenticationException(
+ 'Two Factor Authentication Method not found.',
+ TwoFactorAuthenticationExceptionCode.INVALID_CONFIGURATION,
+ );
+ }
+
+ await this.revokeRecoveryCodes({
+ workspaceId,
+ userId,
+ includeRedeemed: true,
+ entityManager,
+ });
+ });
+ }
+
+ async revokeRecoveryCodes({
+ workspaceId,
+ userId,
+ includeRedeemed = false,
+ entityManager,
+ }: {
+ workspaceId: WorkspaceEntity['id'];
+ userId: UserEntity['id'];
+ includeRedeemed?: boolean;
+ entityManager?: EntityManager;
+ }): Promise<number> {
+ const appTokenRepository =
+ entityManager?.getRepository(AppTokenEntity) ?? this.appTokenRepository;
+
+ const updateResult = await appTokenRepository.update(
+ {
+ workspaceId,
+ userId,
+ type: AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ revokedAt: IsNull(),
+ ...(includeRedeemed ? {} : { deletedAt: IsNull() }),
+ },
+ { revokedAt: new Date() },
+ );
+
+ return updateResult.affected ?? 0;
+ }
+
+ async assertFreshStepUpAuthenticationOrThrow({
+ userId,
+ workspaceId,
+ otp,
+ otpRequiredMessage,
+ twoFactorAuthenticationRequiredMessage,
+ }: {
+ userId: UserEntity['id'];
+ workspaceId: WorkspaceEntity['id'];
+ otp?: string;
+ otpRequiredMessage: MessageDescriptor;
+ twoFactorAuthenticationRequiredMessage: MessageDescriptor;
+ }): Promise<void> {
+ if (!isNonEmptyString(otp)) {
+ throw new TwoFactorAuthenticationException(
+ 'A two-factor authentication code is required for this action',
+ TwoFactorAuthenticationExceptionCode.STEP_UP_AUTHENTICATION_REQUIRED,
+ { userFriendlyMessage: otpRequiredMessage },
+ );
+ }
+
+ const hasVerifiedTwoFactorAuthenticationMethod =
+ await this.twoFactorAuthenticationMethodRepository.exists(workspaceId, {
+ where: { userWorkspace: { userId }, status: OTPStatus.VERIFIED },
+ });
+
+ if (!hasVerifiedTwoFactorAuthenticationMethod) {
+ throw new TwoFactorAuthenticationException(
+ 'Two-factor authentication must be enabled in the current workspace for this action',
+ TwoFactorAuthenticationExceptionCode.STEP_UP_AUTHENTICATION_REQUIRED,
+ { userFriendlyMessage: twoFactorAuthenticationRequiredMessage },
+ );
+ }
+
+ await this.verifyTwoFactorAuthenticationMethodForAuthenticatedUser(
+ userId,
+ otp,
workspaceId,
- { id: userTwoFactorAuthenticationMethod.id },
- { status: OTPStatus.VERIFIED },
);
}
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-issuance-rate-limit-key.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-issuance-rate-limit-key.util.ts
new file mode 100644
index 00000000000..55cd000e490
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-issuance-rate-limit-key.util.ts
@@ -0,0 +1,5 @@
+export const buildTwoFactorAuthenticationRecoveryCodeIssuanceRateLimitKey = ({
+ actorUserId,
+}: {
+ actorUserId: string;
+}): string => `two-factor-authentication-recovery-code-issuance:${actorUserId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-redemption-rate-limit-key.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-redemption-rate-limit-key.util.ts
new file mode 100644
index 00000000000..ab8421aec93
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/build-two-factor-authentication-recovery-code-redemption-rate-limit-key.util.ts
@@ -0,0 +1,5 @@
+export const buildTwoFactorAuthenticationRecoveryCodeRedemptionRateLimitKey = ({
+ userWorkspaceId,
+}: {
+ userWorkspaceId: string;
+}): string => `two-factor-authentication-recovery-code:${userWorkspaceId}`;
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.spec.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.spec.ts
new file mode 100644
index 00000000000..49941e6f5c2
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.spec.ts
@@ -0,0 +1,16 @@
+import { TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET } from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant';
+import { generateTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util';
+
+describe('generateTwoFactorAuthenticationRecoveryCode', () => {
+ it('returns four dash-separated groups of five symbols from the alphabet', () => {
+ const recoveryCode = generateTwoFactorAuthenticationRecoveryCode();
+
+ expect(recoveryCode).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){3}$/);
+
+ for (const symbol of recoveryCode.replace(/-/g, '')) {
+ expect(TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET).toContain(
+ symbol,
+ );
+ }
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.ts
new file mode 100644
index 00000000000..d610a04588c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/generate-two-factor-authentication-recovery-code.util.ts
@@ -0,0 +1,34 @@
+import { randomBytes } from 'crypto';
+
+import {
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_GROUP_SIZE,
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_LENGTH,
+} from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant';
+
+export const generateTwoFactorAuthenticationRecoveryCode = (): string => {
+ const symbols = Array.from(
+ randomBytes(TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_LENGTH),
+ (byte) =>
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET[
+ byte % TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_ALPHABET.length
+ ],
+ ).join('');
+
+ const groups: string[] = [];
+
+ for (
+ let index = 0;
+ index < symbols.length;
+ index += TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_GROUP_SIZE
+ ) {
+ groups.push(
+ symbols.slice(
+ index,
+ index + TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_GROUP_SIZE,
+ ),
+ );
+ }
+
+ return groups.join('-');
+};
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.spec.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.spec.ts
new file mode 100644
index 00000000000..773abdbe77c
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.spec.ts
@@ -0,0 +1,17 @@
+import { hashTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util';
+
+describe('hashTwoFactorAuthenticationRecoveryCode', () => {
+ it('returns the sha256 hex digest of the normalized code', () => {
+ expect(
+ hashTwoFactorAuthenticationRecoveryCode('ABCDEFGHJKMNPQRSTVWX'),
+ ).toBe('8582f0401bebbf68f0492d9590c5b80f40e8f33a29c45cfd13e185b2eb4c0170');
+ });
+
+ it('ignores case, dashes and spaces', () => {
+ expect(
+ hashTwoFactorAuthenticationRecoveryCode('abcde-fghjk-mnpqr-stvwx'),
+ ).toBe(
+ hashTwoFactorAuthenticationRecoveryCode(' ABCDE FGHJK MNPQR STVWX '),
+ );
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.ts b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.ts
new file mode 100644
index 00000000000..316b4422926
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util.ts
@@ -0,0 +1,8 @@
+import { createHash } from 'crypto';
+
+export const hashTwoFactorAuthenticationRecoveryCode = (
+ recoveryCode: string,
+): string =>
+ createHash('sha256')
+ .update(recoveryCode.toUpperCase().replace(/[^0-9A-Z]/g, ''))
+ .digest('hex');
diff --git a/packages/twenty-server/src/engine/core-modules/user-session/types/user-session-revoked-reason.type.ts b/packages/twenty-server/src/engine/core-modules/user-session/types/user-session-revoked-reason.type.ts
index ec69989dbaf..b0ac54b3548 100644
--- a/packages/twenty-server/src/engine/core-modules/user-session/types/user-session-revoked-reason.type.ts
+++ b/packages/twenty-server/src/engine/core-modules/user-session/types/user-session-revoked-reason.type.ts
@@ -4,4 +4,5 @@ export enum UserSessionRevokedReason {
Superseded = 'SUPERSEDED',
PasswordChanged = 'PASSWORD_CHANGED',
ImpersonationEnded = 'IMPERSONATION_ENDED',
+ TwoFactorAuthenticationReset = 'TWO_FACTOR_AUTHENTICATION_RESET',
}
diff --git a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
index e2581c036bb..52a9bc375c9 100644
--- a/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
+++ b/packages/twenty-server/test/integration/endpoint-permissions/__snapshots__/endpoint-permission-declarations.integration-spec.ts.snap
@@ -22,6 +22,7 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"AdminPanelResolver.findAdminApplicationRegistrationVariables {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"AdminPanelResolver.findAllApplicationRegistrations {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"AdminPanelResolver.findOneAdminApplicationRegistration {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
+ "AdminPanelResolver.generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}},{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
"AdminPanelResolver.getAdminAiModels {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"AdminPanelResolver.getAdminAiUsageByWorkspace {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"AdminPanelResolver.getAdminChatThreadMessages {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
@@ -184,6 +185,7 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"AuthResolver.getAuthTokensFromLoginToken {"applicationTarget":null,"authPrincipalGuards":[]}",
"AuthResolver.getAuthTokensFromOTP {"applicationTarget":null,"authPrincipalGuards":[]}",
"AuthResolver.getAuthTokensFromSSOExchangeToken {"applicationTarget":null,"authPrincipalGuards":[]}",
+ "AuthResolver.getAuthTokensFromTwoFactorAuthenticationRecoveryCode {"applicationTarget":null,"authPrincipalGuards":[]}",
"AuthResolver.getAuthorizationUrlForSSO {"applicationTarget":null,"authPrincipalGuards":[]}",
"AuthResolver.getLoginTokenFromCredentials {"applicationTarget":null,"authPrincipalGuards":[]}",
"AuthResolver.getWorkspaceCreationDefaults {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":{"withUser":true,"withoutUser":false},"oauthClient":{"withUser":true,"withoutUser":false},"userSession":true}]}",
@@ -524,8 +526,11 @@ exports[`endpoint permission declarations should match the AuthPrincipalGuard an
"ToolIndexResolver.getToolIndex {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"ToolIndexResolver.getToolInputSchema {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":true,"application":true,"oauthClient":true,"userSession":{"impersonated":true,"playground":true,"standard":true,"workspaceAgnostic":false}}]}",
"TwoFactorAuthenticationResolver.deleteTwoFactorAuthenticationMethod {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
+ "TwoFactorAuthenticationResolver.generateTwoFactorAuthenticationRecoveryCode {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
"TwoFactorAuthenticationResolver.initiateOTPProvisioning {"applicationTarget":null,"authPrincipalGuards":[]}",
"TwoFactorAuthenticationResolver.initiateOTPProvisioningForAuthenticatedUser {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":true}}]}",
+ "TwoFactorAuthenticationResolver.revokeTwoFactorAuthenticationRecoveryCode {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
+ "TwoFactorAuthenticationResolver.twoFactorAuthenticationRecoveryStatus {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
"TwoFactorAuthenticationResolver.verifyTwoFactorAuthenticationMethodForAuthenticatedUser {"applicationTarget":null,"authPrincipalGuards":[{"apiKey":false,"application":false,"oauthClient":false,"userSession":{"impersonated":false,"playground":false,"standard":true,"workspaceAgnostic":false}}]}",
"UnsubscribeController.handleOneClickUnsubscribe {"applicationTarget":null,"authPrincipalGuards":[]}",
"UnsubscribeController.handlePreferencesPage {"applicationTarget":null,"authPrincipalGuards":[]}",
diff --git a/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts
new file mode 100644
index 00000000000..32c49f8445b
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/suites/auth/two-factor-authentication/two-factor-authentication-recovery-code.integration-spec.ts
@@ -0,0 +1,953 @@
+import gql from 'graphql-tag';
+import IORedis from 'ioredis';
+import { authenticator } from 'otplib';
+import { type QueryRunner } from 'typeorm';
+import { buildAppleWorkspaceOrigin } from 'test/integration/graphql/utils/build-apple-workspace-origin.util';
+import { generateTwoFactorAuthenticationRecoveryCode } from 'test/integration/graphql/utils/generate-two-factor-authentication-recovery-code.util';
+import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';
+import { getAuthTokensFromOtp } from 'test/integration/graphql/utils/get-auth-tokens-from-otp.util';
+import { getAuthTokensFromTwoFactorAuthenticationRecoveryCode } from 'test/integration/graphql/utils/get-auth-tokens-from-two-factor-authentication-recovery-code.util';
+import { getLoginTokenFromCredentialsQueryFactory } from 'test/integration/graphql/utils/get-login-token-from-credentials.query-factory.util';
+import { initiateOtpProvisioning } from 'test/integration/graphql/utils/initiate-otp-provisioning.util';
+import { initiateOtpProvisioningForAuthenticatedUser } from 'test/integration/graphql/utils/initiate-otp-provisioning-for-authenticated-user.util';
+import { renewToken } from 'test/integration/graphql/utils/renew-token.util';
+import { verifyTwoFactorAuthenticationMethod } from 'test/integration/graphql/utils/verify-two-factor-authentication-method.util';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { makeAdminPanelApiRequest } from 'test/integration/twenty-config/utils/make-admin-panel-api-request.util';
+
+import { AppTokenType } from 'src/engine/core-modules/app-token/app-token.entity';
+import { acquireUserAuthenticationLock } from 'src/engine/core-modules/auth/utils/acquire-user-authentication-lock.util';
+import { CacheStorageNamespace } from 'src/engine/core-modules/cache-storage/types/cache-storage-namespace.enum';
+import { TOKEN_BUCKET_THROTTLE_KEY_PREFIX } from 'src/engine/core-modules/throttler/constants/token-bucket-throttle-key-prefix.constant';
+import { TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX } from 'src/engine/core-modules/two-factor-authentication/constants/two-factor-authentication-recovery-code.constant';
+import { hashTwoFactorAuthenticationRecoveryCode } from 'src/engine/core-modules/two-factor-authentication/utils/hash-two-factor-authentication-recovery-code.util';
+import { UserSessionRevokedReason } from 'src/engine/core-modules/user-session/types/user-session-revoked-reason.type';
+import {
+ SEED_APPLE_WORKSPACE_ID,
+ SEED_YCOMBINATOR_WORKSPACE_ID,
+} from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+import { USER_WORKSPACE_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-user-workspaces.util';
+import { USER_DATA_SEED_IDS } from 'src/engine/workspace-manager/dev-seeder/core/utils/seed-users.util';
+
+const TOTP_STEP_DURATION_MS = 30_000;
+const MINIMUM_STEP_REMAINING_MS = 5_000;
+const JONY_EMAIL = '[email protected]';
+const SEEDED_PASSWORD = '[email protected]';
+
+type TwoFactorAuthenticationMethodRow = Record<string, unknown>;
+
+const waitUntilSafelyInsideTotpStep = async (): Promise<void> => {
+ const millisecondsRemainingInStep =
+ TOTP_STEP_DURATION_MS - (Date.now() % TOTP_STEP_DURATION_MS);
+
+ if (millisecondsRemainingInStep < MINIMUM_STEP_REMAINING_MS) {
+ await new Promise((resolve) =>
+ setTimeout(resolve, millisecondsRemainingInStep + 100),
+ );
+ }
+};
+
+const generateOtp = async (secret: string): Promise<string> => {
+ await waitUntilSafelyInsideTotpStep();
+
+ return authenticator.generate(secret);
+};
+
+const clearTwoFactorAuthenticationRateLimits = async (): Promise<void> => {
+ const redis = new IORedis(process.env.REDIS_URL ?? 'redis://localhost:6379');
+
+ try {
+ const keys = await redis.keys(
+ `${CacheStorageNamespace.IntegrationTests}:${CacheStorageNamespace.EngineWorkspace}:${TOKEN_BUCKET_THROTTLE_KEY_PREFIX}:two-factor-authentication-*`,
+ );
+
+ if (keys.length > 0) {
+ await redis.del(...keys);
+ }
+ } finally {
+ redis.disconnect();
+ }
+};
+
+const selectMethodRows = (
+ userWorkspaceId: string,
+): Promise<TwoFactorAuthenticationMethodRow[]> =>
+ global.testDataSource.query(
+ `SELECT * FROM core."twoFactorAuthenticationMethod" WHERE "userWorkspaceId" = $1`,
+ [userWorkspaceId],
+ );
+
+const deleteMethodRows = (userWorkspaceId: string) =>
+ global.testDataSource.query(
+ `DELETE FROM core."twoFactorAuthenticationMethod" WHERE "userWorkspaceId" = $1`,
+ [userWorkspaceId],
+ );
+
+const insertMethodRows = async (
+ rows: TwoFactorAuthenticationMethodRow[],
+): Promise<void> => {
+ for (const row of rows) {
+ await global.testDataSource.query(
+ `INSERT INTO core."twoFactorAuthenticationMethod" ("id", "workspaceId", "userWorkspaceId", "secret", "status", "strategy", "createdAt", "updatedAt", "deletedAt") VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`,
+ [
+ row.id,
+ row.workspaceId,
+ row.userWorkspaceId,
+ row.secret,
+ row.status,
+ row.strategy,
+ row.createdAt,
+ row.updatedAt,
+ row.deletedAt,
+ ],
+ );
+ }
+};
+
+const deleteRecoveryCodes = () =>
+ global.testDataSource.query(
+ `DELETE FROM core."appToken" WHERE "type" = $1 AND "userId" = ANY($2)`,
+ [
+ AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ [
+ USER_DATA_SEED_IDS.JANE,
+ USER_DATA_SEED_IDS.JONY,
+ USER_DATA_SEED_IDS.PHIL,
+ ],
+ ],
+ );
+
+const selectPendingRecoveryCodes = (): Promise<{ id: string }[]> =>
+ global.testDataSource.query(
+ `SELECT "id" FROM core."appToken" WHERE "type" = $1 AND "userId" = $2 AND "workspaceId" = $3 AND "deletedAt" IS NULL AND "revokedAt" IS NULL`,
+ [
+ AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ USER_DATA_SEED_IDS.JONY,
+ SEED_APPLE_WORKSPACE_ID,
+ ],
+ );
+
+const selectOpenRecoveryCodes = (): Promise<{ id: string }[]> =>
+ global.testDataSource.query(
+ `SELECT "id" FROM core."appToken" WHERE "type" = $1 AND "userId" = $2 AND "workspaceId" = $3 AND "revokedAt" IS NULL`,
+ [
+ AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ USER_DATA_SEED_IDS.JONY,
+ SEED_APPLE_WORKSPACE_ID,
+ ],
+ );
+
+const enrollAuthenticator = async (accessToken: string): Promise<string> => {
+ const { data } = await initiateOtpProvisioningForAuthenticatedUser({
+ accessToken,
+ expectToFail: false,
+ });
+
+ const secret =
+ data.initiateOTPProvisioningForAuthenticatedUser.uri.match(
+ /[?&]secret=([^&]+)/,
+ )?.[1];
+
+ if (secret === undefined) {
+ throw new Error('Expected the otpauth URI to contain a secret');
+ }
+
+ await verifyTwoFactorAuthenticationMethod({
+ otp: await generateOtp(secret),
+ accessToken,
+ expectToFail: false,
+ });
+
+ return secret;
+};
+
+const getJonyLoginToken = async (): Promise<string> => {
+ const response = await makeMetadataApiRequest(
+ getLoginTokenFromCredentialsQueryFactory({
+ email: JONY_EMAIL,
+ password: SEEDED_PASSWORD,
+ origin: buildAppleWorkspaceOrigin(),
+ }),
+ null,
+ );
+
+ return response.body.data.getLoginTokenFromCredentials.loginToken.token;
+};
+
+const insertRecoveryCode = async ({
+ recoveryCode,
+ workspaceId,
+ expiresAt,
+ revokedAt = null,
+}: {
+ recoveryCode: string;
+ workspaceId: string;
+ expiresAt: Date;
+ revokedAt?: Date | null;
+}) =>
+ global.testDataSource.query(
+ `INSERT INTO core."appToken" ("userId", "workspaceId", "type", "value", "expiresAt", "revokedAt") VALUES ($1, $2, $3, $4, $5, $6)`,
+ [
+ USER_DATA_SEED_IDS.JONY,
+ workspaceId,
+ AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ hashTwoFactorAuthenticationRecoveryCode(recoveryCode),
+ expiresAt,
+ revokedAt,
+ ],
+ );
+
+const getRecoveryStatus = async (userId: string) => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: gql`
+ query TwoFactorAuthenticationRecoveryStatus($userId: UUID!) {
+ twoFactorAuthenticationRecoveryStatus(userId: $userId) {
+ hasVerifiedTwoFactorAuthenticationMethod
+ isAwaitingRecoveryEnrollment
+ pendingRecoveryCodeExpiresAt
+ }
+ }
+ `,
+ variables: { userId },
+ },
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ return response.body;
+};
+
+const setTwoFactorAuthenticationEnforced = async (
+ isTwoFactorAuthenticationEnforced: boolean,
+) => {
+ const response = await makeMetadataApiRequest(
+ {
+ query: gql`
+ mutation UpdateWorkspace($isTwoFactorAuthenticationEnforced: Boolean) {
+ updateWorkspace(
+ data: {
+ isTwoFactorAuthenticationEnforced: $isTwoFactorAuthenticationEnforced
+ }
+ ) {
+ id
+ }
+ }
+ `,
+ variables: { isTwoFactorAuthenticationEnforced },
+ },
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ expect(response.body.errors).toBeUndefined();
+};
+
+const holdUserAuthenticationLock = async (
+ userId: string,
+): Promise<QueryRunner> => {
+ const queryRunner = global.testDataSource.createQueryRunner();
+
+ await queryRunner.connect();
+ await queryRunner.startTransaction();
+ await acquireUserAuthenticationLock({
+ entityManager: queryRunner.manager,
+ userId,
+ mode: 'exclusive',
+ });
+
+ return queryRunner;
+};
+
+const waitUntilARequestAwaitsTheUserAuthenticationLock =
+ async (): Promise<void> => {
+ for (let attempt = 0; attempt < 100; attempt++) {
+ const waitingLocks = await global.testDataSource.query(
+ `SELECT 1 FROM pg_locks WHERE "locktype" = 'advisory' AND NOT "granted"`,
+ );
+
+ if (waitingLocks.length > 0) {
+ return;
+ }
+
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+
+ throw new Error('No request waited on the user authentication lock');
+ };
+
+const releaseUserAuthenticationLock = async (queryRunner: QueryRunner) => {
+ if (queryRunner.isTransactionActive) {
+ await queryRunner.rollbackTransaction();
+ }
+
+ await queryRunner.release();
+};
+
+describe('Two-factor authentication recovery codes (integration)', () => {
+ let janeOriginalMethodRows: TwoFactorAuthenticationMethodRow[];
+ let janeSecret: string;
+ let jonySecret: string;
+
+ const generateCodeForJony = async () => {
+ const { data, errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp: await generateOtp(janeSecret),
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+
+ return data.generateTwoFactorAuthenticationRecoveryCode;
+ };
+
+ beforeAll(async () => {
+ await clearTwoFactorAuthenticationRateLimits();
+ await deleteRecoveryCodes();
+
+ janeOriginalMethodRows = await selectMethodRows(
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ );
+
+ await deleteMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JANE);
+ await deleteMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JONY);
+
+ janeSecret = await enrollAuthenticator(APPLE_JANE_ADMIN_ACCESS_TOKEN);
+ jonySecret = await enrollAuthenticator(APPLE_JONY_MEMBER_ACCESS_TOKEN);
+ });
+
+ beforeEach(async () => {
+ await clearTwoFactorAuthenticationRateLimits();
+ });
+
+ afterAll(async () => {
+ await deleteRecoveryCodes();
+ await deleteMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JONY);
+ await deleteMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JANE);
+
+ await insertMethodRows(janeOriginalMethodRows);
+
+ await clearTwoFactorAuthenticationRateLimits();
+ });
+
+ describe('issuing a code', () => {
+ it('is refused to a member without the security permission', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JANE,
+ otp: await generateOtp(jonySecret),
+ accessToken: APPLE_PHIL_GUEST_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.code).toBe('FORBIDDEN');
+ });
+
+ it('requires the admin to confirm with their own code', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe(
+ 'STEP_UP_AUTHENTICATION_REQUIRED',
+ );
+ });
+
+ it('refuses an admin who has no authenticator in this workspace', async () => {
+ const janeMethodRows = await selectMethodRows(
+ USER_WORKSPACE_DATA_SEED_IDS.JANE,
+ );
+
+ await deleteMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JANE);
+
+ try {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp: '000000',
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe(
+ 'STEP_UP_AUTHENTICATION_REQUIRED',
+ );
+ expect(await selectPendingRecoveryCodes()).toHaveLength(0);
+ } finally {
+ await insertMethodRows(janeMethodRows);
+ }
+ });
+
+ it('rejects a wrong confirmation code', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp: '000000',
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe('INVALID_OTP');
+ });
+
+ it('refuses to target the admin themselves', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JANE,
+ otp: await generateOtp(janeSecret),
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_CODE_TARGET_NOT_ALLOWED',
+ );
+ });
+
+ it('refuses a member who has no authenticator to recover', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.PHIL,
+ otp: await generateOtp(janeSecret),
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_CODE_TARGET_NOT_ALLOWED',
+ );
+ });
+
+ it('reports the pending code in the member status and can be revoked', async () => {
+ const { expiresAt } = await generateCodeForJony();
+
+ const statusWithCode = await getRecoveryStatus(USER_DATA_SEED_IDS.JONY);
+
+ expect(statusWithCode.errors).toBeUndefined();
+ expect(statusWithCode.data.twoFactorAuthenticationRecoveryStatus).toEqual(
+ {
+ hasVerifiedTwoFactorAuthenticationMethod: true,
+ isAwaitingRecoveryEnrollment: false,
+ pendingRecoveryCodeExpiresAt: expiresAt,
+ },
+ );
+
+ const revokeResponse = await makeMetadataApiRequest(
+ {
+ query: gql`
+ mutation RevokeTwoFactorAuthenticationRecoveryCode($userId: UUID!) {
+ revokeTwoFactorAuthenticationRecoveryCode(userId: $userId)
+ }
+ `,
+ variables: { userId: USER_DATA_SEED_IDS.JONY },
+ },
+ APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ );
+
+ expect(
+ revokeResponse.body.data.revokeTwoFactorAuthenticationRecoveryCode,
+ ).toBe(true);
+
+ const statusAfterRevoke = await getRecoveryStatus(
+ USER_DATA_SEED_IDS.JONY,
+ );
+
+ expect(
+ statusAfterRevoke.data.twoFactorAuthenticationRecoveryStatus
+ .pendingRecoveryCodeExpiresAt,
+ ).toBeNull();
+ });
+
+ it('leaves exactly one usable code when two are issued at the same time', async () => {
+ const otp = await generateOtp(janeSecret);
+
+ const responses = await Promise.all(
+ [0, 1].map(() =>
+ generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp,
+ accessToken: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ }),
+ ),
+ );
+
+ for (const { errors } of responses) {
+ if (errors !== undefined) {
+ expect(errors[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_CODE_ISSUANCE_CONFLICT',
+ );
+ }
+ }
+
+ expect(await selectPendingRecoveryCodes()).toHaveLength(1);
+
+ await deleteRecoveryCodes();
+ });
+ });
+
+ describe('redeeming a code', () => {
+ it('rejects codes that are unknown, expired, revoked or issued in another workspace', async () => {
+ await insertRecoveryCode({
+ recoveryCode: 'EXPIR-EDCOD-E0000-00001',
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ expiresAt: new Date(Date.now() - 60_000),
+ });
+ await insertRecoveryCode({
+ recoveryCode: 'REVOK-EDCOD-E0000-00002',
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ expiresAt: new Date(Date.now() + 60_000),
+ revokedAt: new Date(),
+ });
+ await insertRecoveryCode({
+ recoveryCode: 'OTHER-WORKS-PACE0-00003',
+ workspaceId: SEED_YCOMBINATOR_WORKSPACE_ID,
+ expiresAt: new Date(Date.now() + 60_000),
+ });
+
+ const loginToken = await getJonyLoginToken();
+
+ for (const recoveryCode of [
+ 'UNKNO-WNCOD-E0000-00000',
+ 'EXPIR-EDCOD-E0000-00001',
+ 'REVOK-EDCOD-E0000-00002',
+ 'OTHER-WORKS-PACE0-00003',
+ ]) {
+ const { errors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken,
+ recoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.extensions?.subCode).toBe('INVALID_RECOVERY_CODE');
+ }
+
+ expect(
+ await selectMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JONY),
+ ).toHaveLength(1);
+ });
+
+ it('removes the authenticator, signs out other sessions and works only once', async () => {
+ const otpLoginToken = await getJonyLoginToken();
+
+ const { data: otpData, errors: otpErrors } = await getAuthTokensFromOtp({
+ loginToken: otpLoginToken,
+ otp: await generateOtp(jonySecret),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(otpErrors).toBeUndefined();
+
+ const rotatedRefreshToken =
+ otpData.getAuthTokensFromOTP.tokens.refreshToken.token;
+
+ const rotationResponse = await renewToken(rotatedRefreshToken);
+
+ expect(rotationResponse.body.errors).toBeUndefined();
+
+ const refreshTokenFromBeforeRecovery =
+ rotationResponse.body.data.renewToken.tokens.refreshToken.token;
+
+ const { recoveryCode } = await generateCodeForJony();
+ const loginToken = await getJonyLoginToken();
+
+ const { errors: loginErrors } = await getAuthTokensFromLoginToken({
+ loginToken,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(loginErrors?.[0]?.extensions?.subCode).toBe(
+ 'TWO_FACTOR_AUTHENTICATION_VERIFICATION_REQUIRED',
+ );
+
+ const { data, errors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken,
+ recoveryCode: recoveryCode.toLowerCase(),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+ expect(
+ data.getAuthTokensFromTwoFactorAuthenticationRecoveryCode.tokens
+ ?.accessOrWorkspaceAgnosticToken.token,
+ ).toBeDefined();
+ expect(
+ data.getAuthTokensFromTwoFactorAuthenticationRecoveryCode
+ .provisioningUri,
+ ).toBeNull();
+ expect(await selectMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JONY)).toEqual(
+ [],
+ );
+
+ const { errors: loginTokenReplayErrors } =
+ await getAuthTokensFromLoginToken({
+ loginToken,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(loginTokenReplayErrors?.[0]?.extensions?.code).toBe(
+ 'UNAUTHENTICATED',
+ );
+
+ const revokedSessions = await global.testDataSource.query(
+ `SELECT "revokedReason" FROM core."userSession" WHERE "userId" = $1 AND "workspaceId" = $2 AND "revokedAt" IS NOT NULL AND "revokedReason" = $3`,
+ [
+ USER_DATA_SEED_IDS.JONY,
+ SEED_APPLE_WORKSPACE_ID,
+ UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ ],
+ );
+
+ expect(revokedSessions.length).toBeGreaterThan(0);
+
+ for (const refreshToken of [
+ refreshTokenFromBeforeRecovery,
+ rotatedRefreshToken,
+ ]) {
+ const renewResponse = await renewToken(refreshToken);
+
+ expect(renewResponse.body.data).toBeNull();
+ expect(renewResponse.body.errors?.[0]?.extensions?.code).toBe(
+ 'FORBIDDEN',
+ );
+ }
+
+ const { errors: replayErrors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken: await getJonyLoginToken(),
+ recoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(replayErrors?.[0]?.extensions?.subCode).toBe(
+ 'INVALID_RECOVERY_CODE',
+ );
+
+ const { errors: signInErrors } = await getAuthTokensFromLoginToken({
+ loginToken: await getJonyLoginToken(),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(signInErrors).toBeUndefined();
+
+ jonySecret = await enrollAuthenticator(APPLE_JONY_MEMBER_ACCESS_TOKEN);
+ });
+
+ it('admits exactly one of two simultaneous redemptions and keeps the winner signed in', async () => {
+ const { recoveryCode } = await generateCodeForJony();
+ const loginToken = await getJonyLoginToken();
+ const [{ now: raceStartedAt }] =
+ await global.testDataSource.query('SELECT now()');
+
+ const responses = await Promise.all(
+ [0, 1].map(() =>
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken,
+ recoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ }),
+ ),
+ );
+
+ expect(
+ responses.filter(({ errors }) => errors === undefined),
+ ).toHaveLength(1);
+
+ const activeSessionsFromRace = await global.testDataSource.query(
+ `SELECT "id" FROM core."userSession" WHERE "userId" = $1 AND "workspaceId" = $2 AND "revokedAt" IS NULL AND "createdAt" >= $3`,
+ [USER_DATA_SEED_IDS.JONY, SEED_APPLE_WORKSPACE_ID, raceStartedAt],
+ );
+
+ expect(activeSessionsFromRace).toHaveLength(1);
+
+ jonySecret = await enrollAuthenticator(APPLE_JONY_MEMBER_ACCESS_TOKEN);
+ });
+
+ it('revokes the previous code when a new one is issued, and pending codes after a successful authenticator sign-in', async () => {
+ const { recoveryCode: firstRecoveryCode } = await generateCodeForJony();
+ const { recoveryCode: secondRecoveryCode } = await generateCodeForJony();
+
+ const { errors: firstCodeErrors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken: await getJonyLoginToken(),
+ recoveryCode: firstRecoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(firstCodeErrors?.[0]?.extensions?.subCode).toBe(
+ 'INVALID_RECOVERY_CODE',
+ );
+
+ await getAuthTokensFromOtp({
+ loginToken: await getJonyLoginToken(),
+ otp: await generateOtp(jonySecret),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ const { errors: secondCodeErrors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken: await getJonyLoginToken(),
+ recoveryCode: secondRecoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(secondCodeErrors?.[0]?.extensions?.subCode).toBe(
+ 'INVALID_RECOVERY_CODE',
+ );
+ });
+
+ it('hands the replacement authenticator only to the redeeming request when the workspace enforces two-factor authentication', async () => {
+ const { recoveryCode } = await generateCodeForJony();
+
+ await setTwoFactorAuthenticationEnforced(true);
+
+ try {
+ const { data, errors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken: await getJonyLoginToken(),
+ recoveryCode,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(errors).toBeUndefined();
+
+ const { tokens, provisioningUri } =
+ data.getAuthTokensFromTwoFactorAuthenticationRecoveryCode;
+
+ expect(tokens).toBeNull();
+
+ const replacementSecret =
+ provisioningUri?.match(/[?&]secret=([^&]+)/)?.[1];
+
+ expect(replacementSecret).toBeDefined();
+
+ const methodRows = await selectMethodRows(
+ USER_WORKSPACE_DATA_SEED_IDS.JONY,
+ );
+
+ expect(methodRows).toHaveLength(1);
+ expect(methodRows[0].status).toBe('PENDING');
+
+ const { errors: provisioningErrors } = await initiateOtpProvisioning({
+ loginToken: await getJonyLoginToken(),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ expect(provisioningErrors?.[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_ENROLLMENT_RESTRICTED',
+ );
+
+ const { errors: authenticatedProvisioningErrors } =
+ await initiateOtpProvisioningForAuthenticatedUser({
+ accessToken: APPLE_JONY_MEMBER_ACCESS_TOKEN,
+ expectToFail: true,
+ });
+
+ expect(authenticatedProvisioningErrors?.[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_ENROLLMENT_RESTRICTED',
+ );
+ expect(
+ (await selectMethodRows(USER_WORKSPACE_DATA_SEED_IDS.JONY))[0].secret,
+ ).toBe(methodRows[0].secret);
+
+ const awaitingStatus = await getRecoveryStatus(USER_DATA_SEED_IDS.JONY);
+
+ expect(
+ awaitingStatus.data.twoFactorAuthenticationRecoveryStatus,
+ ).toMatchObject({
+ hasVerifiedTwoFactorAuthenticationMethod: false,
+ isAwaitingRecoveryEnrollment: true,
+ });
+
+ await generateCodeForJony();
+
+ const { errors: otpErrors } = await getAuthTokensFromOtp({
+ loginToken: await getJonyLoginToken(),
+ otp: await generateOtp(replacementSecret as string),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ expect(otpErrors).toBeUndefined();
+ expect(await selectOpenRecoveryCodes()).toEqual([]);
+
+ jonySecret = replacementSecret as string;
+ } finally {
+ await setTwoFactorAuthenticationEnforced(false);
+ }
+ });
+
+ it('keeps the enrollment reservation of a recovery that lands while an OTP sign-in is in flight', async () => {
+ const loginToken = await getJonyLoginToken();
+ const otp = await generateOtp(jonySecret);
+ const lock = await holdUserAuthenticationLock(USER_DATA_SEED_IDS.JONY);
+
+ let otpSignIn: ReturnType<typeof getAuthTokensFromOtp> | undefined;
+
+ try {
+ otpSignIn = getAuthTokensFromOtp({
+ loginToken,
+ otp,
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ await waitUntilARequestAwaitsTheUserAuthenticationLock();
+
+ await lock.query(
+ `DELETE FROM core."twoFactorAuthenticationMethod" WHERE "userWorkspaceId" = $1`,
+ [USER_WORKSPACE_DATA_SEED_IDS.JONY],
+ );
+ await lock.query(
+ `INSERT INTO core."appToken" ("userId", "workspaceId", "type", "value", "expiresAt", "deletedAt") VALUES ($1, $2, $3, $4, now() + interval '1 hour', now())`,
+ [
+ USER_DATA_SEED_IDS.JONY,
+ SEED_APPLE_WORKSPACE_ID,
+ AppTokenType.TwoFactorAuthenticationRecoveryCode,
+ hashTwoFactorAuthenticationRecoveryCode('RESERVED-ENROLLMENT'),
+ ],
+ );
+ await lock.commitTransaction();
+ } finally {
+ await releaseUserAuthenticationLock(lock);
+ }
+
+ const { errors } = await otpSignIn;
+
+ expect(errors?.[0]?.extensions?.subCode).toBe('INVALID_CONFIGURATION');
+ expect(await selectOpenRecoveryCodes()).toHaveLength(1);
+
+ await deleteRecoveryCodes();
+ jonySecret = await enrollAuthenticator(APPLE_JONY_MEMBER_ACCESS_TOKEN);
+ });
+
+ it('refuses a refresh token renewal that was in flight when a recovery revoked the sessions', async () => {
+ const { data } = await getAuthTokensFromOtp({
+ loginToken: await getJonyLoginToken(),
+ otp: await generateOtp(jonySecret),
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: false,
+ });
+
+ const lock = await holdUserAuthenticationLock(USER_DATA_SEED_IDS.JONY);
+
+ let renewal: ReturnType<typeof renewToken> | undefined;
+
+ try {
+ renewal = renewToken(
+ data.getAuthTokensFromOTP.tokens.refreshToken.token,
+ );
+
+ await waitUntilARequestAwaitsTheUserAuthenticationLock();
+
+ await lock.query(
+ `UPDATE core."appToken" SET "revokedAt" = COALESCE("revokedAt", now()), "context" = COALESCE("context", '{}'::jsonb) || jsonb_build_object('revokedReason', $4::text) WHERE "userId" = $1 AND "workspaceId" = $2 AND "type" = $3`,
+ [
+ USER_DATA_SEED_IDS.JONY,
+ SEED_APPLE_WORKSPACE_ID,
+ AppTokenType.RefreshToken,
+ UserSessionRevokedReason.TwoFactorAuthenticationReset,
+ ],
+ );
+ await lock.commitTransaction();
+ } finally {
+ await releaseUserAuthenticationLock(lock);
+ }
+
+ const response = await renewal;
+
+ expect(response.body.data).toBeNull();
+ expect(response.body.errors?.[0]?.extensions?.code).toBe('FORBIDDEN');
+ });
+
+ it('stops accepting guesses once the member bucket is spent', async () => {
+ const loginToken = await getJonyLoginToken();
+ const subCodes: string[] = [];
+
+ for (
+ let attempt = 0;
+ attempt <=
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX;
+ attempt++
+ ) {
+ const { errors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken,
+ recoveryCode: 'WRONG-GUESS-00000-00000',
+ origin: buildAppleWorkspaceOrigin(),
+ expectToFail: true,
+ });
+
+ subCodes.push(errors?.[0]?.extensions?.subCode);
+ }
+
+ expect(subCodes.slice(0, -1)).toEqual(
+ Array(
+ TWO_FACTOR_AUTHENTICATION_RECOVERY_CODE_REDEMPTION_RATE_LIMIT_MAX,
+ ).fill('INVALID_RECOVERY_CODE'),
+ );
+ expect(subCodes[subCodes.length - 1]).toBe('LIMIT_REACHED');
+ });
+ });
+
+ describe('server admin panel', () => {
+ const generateAsServerAdmin = async (workspaceId: string) => {
+ const response = await makeAdminPanelApiRequest({
+ query: gql`
+ mutation GenerateTwoFactorAuthenticationRecoveryCodeAsServerAdmin(
+ $userId: UUID!
+ $workspaceId: UUID!
+ $otp: String
+ ) {
+ generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin(
+ userId: $userId
+ workspaceId: $workspaceId
+ otp: $otp
+ ) {
+ recoveryCode
+ expiresAt
+ }
+ }
+ `,
+ variables: {
+ userId: USER_DATA_SEED_IDS.JONY,
+ workspaceId,
+ otp: await generateOtp(janeSecret),
+ },
+ });
+
+ return response.body;
+ };
+
+ it('issues a code for a member of the given workspace', async () => {
+ const { data, errors } = await generateAsServerAdmin(
+ SEED_APPLE_WORKSPACE_ID,
+ );
+
+ expect(errors).toBeUndefined();
+ expect(
+ data.generateTwoFactorAuthenticationRecoveryCodeAsServerAdmin
+ .recoveryCode,
+ ).toMatch(/^[0-9A-Z]{5}(-[0-9A-Z]{5}){3}$/);
+ });
+
+ it('reaches members of other workspaces but still requires an authenticator to recover', async () => {
+ const { errors } = await generateAsServerAdmin(
+ SEED_YCOMBINATOR_WORKSPACE_ID,
+ );
+
+ expect(errors?.[0]?.extensions?.subCode).toBe(
+ 'RECOVERY_CODE_TARGET_NOT_ALLOWED',
+ );
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts b/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts
index c0ea2073030..2ecc1b6b92e 100644
--- a/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts
+++ b/packages/twenty-server/test/integration/graphql/suites/impersonation/failing-impersonated-two-factor-authentication.integration-spec.ts
@@ -1,7 +1,9 @@
import { deleteTwoFactorAuthenticationMethod } from 'test/integration/graphql/suites/user-session/utils/delete-two-factor-authentication-method.util';
import { generatePlaygroundToken } from 'test/integration/graphql/suites/user-session/utils/generate-playground-token.util';
+import { generateTwoFactorAuthenticationRecoveryCode } from 'test/integration/graphql/utils/generate-two-factor-authentication-recovery-code.util';
import { getAuthTokensFromLoginToken } from 'test/integration/graphql/utils/get-auth-tokens-from-login-token.util';
import { getAuthTokensFromOtp } from 'test/integration/graphql/utils/get-auth-tokens-from-otp.util';
+import { getAuthTokensFromTwoFactorAuthenticationRecoveryCode } from 'test/integration/graphql/utils/get-auth-tokens-from-two-factor-authentication-recovery-code.util';
import { impersonate } from 'test/integration/graphql/utils/impersonate.util';
import { initiateOtpProvisioning } from 'test/integration/graphql/utils/initiate-otp-provisioning.util';
import { initiateOtpProvisioningForAuthenticatedUser } from 'test/integration/graphql/utils/initiate-otp-provisioning-for-authenticated-user.util';
@@ -91,6 +93,29 @@ describe('Impersonation - two-factor authentication mutations denial (integratio
expectImpersonationLoginTokenRejected(errors);
});
+ it('rejects exchanging a recovery code for tokens with an impersonation login token', async () => {
+ const { errors } =
+ await getAuthTokensFromTwoFactorAuthenticationRecoveryCode({
+ loginToken: impersonationLoginToken,
+ origin: impersonationOrigin,
+ recoveryCode: 'ABCDE-FGHJK-MNPQR-STVWX',
+ expectToFail: true,
+ });
+
+ expectImpersonationLoginTokenRejected(errors);
+ });
+
+ it('rejects generating a recovery code while impersonating', async () => {
+ const { errors } = await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp: '123456',
+ accessToken: impersonationAccessToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(errors);
+ });
+
it('rejects initiating OTP provisioning while impersonating', async () => {
const { errors } = await initiateOtpProvisioningForAuthenticatedUser({
accessToken: impersonationAccessToken,
@@ -158,5 +183,15 @@ describe('Impersonation - two-factor authentication mutations denial (integratio
});
expectImpersonationDenied(deletionErrors);
+
+ const { errors: recoveryCodeErrors } =
+ await generateTwoFactorAuthenticationRecoveryCode({
+ userId: USER_DATA_SEED_IDS.JONY,
+ otp: '123456',
+ accessToken: playgroundToken,
+ expectToFail: true,
+ });
+
+ expectImpersonationDenied(recoveryCodeErrors);
});
});
diff --git a/packages/twenty-server/test/integration/graphql/utils/generate-two-factor-authentication-recovery-code.util.ts b/packages/twenty-server/test/integration/graphql/utils/generate-two-factor-authentication-recovery-code.util.ts
new file mode 100644
index 00000000000..4ce4cfbcbd2
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/generate-two-factor-authentication-recovery-code.util.ts
@@ -0,0 +1,56 @@
+import gql from 'graphql-tag';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+import { type TwoFactorAuthenticationRecoveryCodeDTO } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code.dto';
+
+type GenerateTwoFactorAuthenticationRecoveryCodeUtilArgs = {
+ userId: string;
+ otp?: string;
+ accessToken: string;
+ expectToFail?: boolean;
+};
+
+export const generateTwoFactorAuthenticationRecoveryCode = async ({
+ userId,
+ otp,
+ accessToken,
+ expectToFail,
+}: GenerateTwoFactorAuthenticationRecoveryCodeUtilArgs): CommonResponseBody<{
+ generateTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCodeDTO;
+}> => {
+ const mutation = gql`
+ mutation GenerateTwoFactorAuthenticationRecoveryCode(
+ $userId: UUID!
+ $otp: String
+ ) {
+ generateTwoFactorAuthenticationRecoveryCode(userId: $userId, otp: $otp) {
+ recoveryCode
+ expiresAt
+ }
+ }
+ `;
+
+ const response = await makeMetadataApiRequest(
+ { query: mutation, variables: { userId, otp } },
+ accessToken,
+ );
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage: 'Recovery code generation should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'Recovery code generation has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};
diff --git a/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts
index 631fefa8f8f..d059c348c75 100644
--- a/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts
+++ b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-otp.util.ts
@@ -36,6 +36,9 @@ export const getAuthTokensFromOtp = async ({
accessOrWorkspaceAgnosticToken {
token
}
+ refreshToken {
+ token
+ }
}
}
}
diff --git a/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-two-factor-authentication-recovery-code.util.ts b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-two-factor-authentication-recovery-code.util.ts
new file mode 100644
index 00000000000..2b076ec2918
--- /dev/null
+++ b/packages/twenty-server/test/integration/graphql/utils/get-auth-tokens-from-two-factor-authentication-recovery-code.util.ts
@@ -0,0 +1,65 @@
+import gql from 'graphql-tag';
+import { makeMetadataApiRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type CommonResponseBody } from 'test/integration/metadata/types/common-response-body.type';
+import { warnIfErrorButNotExpectedToFail } from 'test/integration/metadata/utils/warn-if-error-but-not-expected-to-fail.util';
+import { warnIfNoErrorButExpectedToFail } from 'test/integration/metadata/utils/warn-if-no-error-but-expected-to-fail.util';
+
+import { type TwoFactorAuthenticationRecoveryCodeRedemptionDTO } from 'src/engine/core-modules/two-factor-authentication/dto/two-factor-authentication-recovery-code-redemption.dto';
+
+type GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeUtilArgs = {
+ loginToken: string;
+ recoveryCode: string;
+ origin: string;
+ expectToFail?: boolean;
+};
+
+export const getAuthTokensFromTwoFactorAuthenticationRecoveryCode = async ({
+ loginToken,
+ recoveryCode,
+ origin,
+ expectToFail,
+}: GetAuthTokensFromTwoFactorAuthenticationRecoveryCodeUtilArgs): CommonResponseBody<{
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode: TwoFactorAuthenticationRecoveryCodeRedemptionDTO;
+}> => {
+ const mutation = gql`
+ mutation GetAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ $loginToken: String!
+ $recoveryCode: String!
+ $origin: String!
+ ) {
+ getAuthTokensFromTwoFactorAuthenticationRecoveryCode(
+ loginToken: $loginToken
+ recoveryCode: $recoveryCode
+ origin: $origin
+ ) {
+ tokens {
+ accessOrWorkspaceAgnosticToken {
+ token
+ }
+ }
+ provisioningUri
+ }
+ }
+ `;
+
+ const response = await makeMetadataApiRequest(
+ { query: mutation, variables: { loginToken, recoveryCode, origin } },
+ null,
+ );
+
+ if (expectToFail === true) {
+ warnIfNoErrorButExpectedToFail({
+ response,
+ errorMessage: 'Recovery code sign-in should have failed but did not',
+ });
+ }
+
+ if (expectToFail === false) {
+ warnIfErrorButNotExpectedToFail({
+ response,
+ errorMessage: 'Recovery code sign-in has failed but should not',
+ });
+ }
+
+ return { data: response.body.data, errors: response.body.errors };
+};