Skip to content

The open alternative to Salesforce, designed for AI.

feat(core): let apps report a connection auth failure with a reason (#25297)

Abdul Rahmanaac65836988a
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 95a36772be9..8af52d6e85c 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -1884,6 +1884,7 @@ type ConnectedAccountPublicDTO {
provider: String!
lastCredentialsRefreshedAt: DateTime
authFailedAt: DateTime
+ authFailedReason: String
archivedAt: DateTime
handleAliases: [String!]
scopes: [String!]
@@ -2170,6 +2171,7 @@ type AppConnection {
accessToken: String!
scopes: [String!]!
authFailedAt: String
+ authFailedReason: String
}
type ResendEmailVerificationToken {
@@ -3938,6 +3940,7 @@ type Mutation {
deleteAppKeyValue(key: String!, scope: AppKeyValueScope = WORKSPACE): Boolean!
enqueueJob(input: EnqueueJobInput!): EnqueueJobResult! @deprecated(reason: "Use enqueueJobs instead.")
enqueueJobs(input: EnqueueJobsInput!): EnqueueJobsResult!
+ reportAppConnectionAuthFailure(input: ReportAppConnectionAuthFailureInput!): Boolean!
createChatThread: AgentChatThread!
sendChatMessage(threadId: UUID!, text: String!, messageId: UUID!, browsingContext: JSON, modelId: String, fileAttachments: [FileAttachmentInput!]): SendChatMessageResult!
retryChatMessage(threadId: UUID!, modelId: String): SendChatMessageResult!
@@ -5156,6 +5159,11 @@ input EnqueueJobItemInput {
jobId: String
}
+input ReportAppConnectionAuthFailureInput {
+ id: ID!
+ reason: String
+}
+
input FileAttachmentInput {
id: UUID!
filename: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index 7ef89540053..4a8d2815abe 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -1512,6 +1512,7 @@ export interface ConnectedAccountPublicDTO {
provider: Scalars['String']
lastCredentialsRefreshedAt?: Scalars['DateTime']
authFailedAt?: Scalars['DateTime']
+ authFailedReason?: Scalars['String']
archivedAt?: Scalars['DateTime']
handleAliases?: Scalars['String'][]
scopes?: Scalars['String'][]
@@ -1791,6 +1792,7 @@ export interface AppConnection {
accessToken: Scalars['String']
scopes: Scalars['String'][]
authFailedAt?: Scalars['String']
+ authFailedReason?: Scalars['String']
__typename: 'AppConnection'
}
@@ -3383,6 +3385,7 @@ export interface Mutation {
/** @deprecated Use enqueueJobs instead. */
enqueueJob: EnqueueJobResult
enqueueJobs: EnqueueJobsResult
+ reportAppConnectionAuthFailure: Scalars['Boolean']
createChatThread: AgentChatThread
sendChatMessage: SendChatMessageResult
retryChatMessage: SendChatMessageResult
@@ -5027,6 +5030,7 @@ export interface ConnectedAccountPublicDTOGenqlSelection{
provider?: boolean | number
lastCredentialsRefreshedAt?: boolean | number
authFailedAt?: boolean | number
+ authFailedReason?: boolean | number
archivedAt?: boolean | number
handleAliases?: boolean | number
scopes?: boolean | number
@@ -5321,6 +5325,7 @@ export interface AppConnectionGenqlSelection{
accessToken?: boolean | number
scopes?: boolean | number
authFailedAt?: boolean | number
+ authFailedReason?: boolean | number
__typename?: boolean | number
__scalar?: boolean | number
}
@@ -7027,6 +7032,7 @@ export interface MutationGenqlSelection{
/** @deprecated Use enqueueJobs instead. */
enqueueJob?: (EnqueueJobResultGenqlSelection & { __args: {input: EnqueueJobInput} })
enqueueJobs?: (EnqueueJobsResultGenqlSelection & { __args: {input: EnqueueJobsInput} })
+ reportAppConnectionAuthFailure?: { __args: {input: ReportAppConnectionAuthFailureInput} }
createChatThread?: AgentChatThreadGenqlSelection
sendChatMessage?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], text: Scalars['String'], messageId: Scalars['UUID'], browsingContext?: (Scalars['JSON'] | null), modelId?: (Scalars['String'] | null), fileAttachments?: (FileAttachmentInput[] | null)} })
retryChatMessage?: (SendChatMessageResultGenqlSelection & { __args: {threadId: Scalars['UUID'], modelId?: (Scalars['String'] | null)} })
@@ -7487,6 +7493,8 @@ export interface EnqueueJobsInput {logicFunctionUniversalIdentifier: Scalars['St
export interface EnqueueJobItemInput {payload?: (Scalars['JSON'] | null),jobId?: (Scalars['String'] | null)}
+export interface ReportAppConnectionAuthFailureInput {id: Scalars['ID'],reason?: (Scalars['String'] | null)}
+
export interface FileAttachmentInput {id: Scalars['UUID'],filename: Scalars['String']}
export interface AgentChatQuestionAnswerInput {questionIndex: Scalars['Int'],selectedOptionIndices: Scalars['Int'][],freeText?: (Scalars['String'] | null)}
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index 9ac1e332cb1..1199083538a 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -100,7 +100,7 @@ export default {
401,
413,
530,
- 555
+ 556
],
"types": {
"BillingProductDTO": {
@@ -3603,6 +3603,9 @@ export default {
"authFailedAt": [
4
],
+ "authFailedReason": [
+ 1
+ ],
"archivedAt": [
4
],
@@ -4221,6 +4224,9 @@ export default {
"authFailedAt": [
1
],
+ "authFailedReason": [
+ 1
+ ],
"__typename": [
1
]
@@ -9606,6 +9612,15 @@ export default {
]
}
],
+ "reportAppConnectionAuthFailure": [
+ 8,
+ {
+ "input": [
+ 543,
+ "ReportAppConnectionAuthFailureInput!"
+ ]
+ }
+ ],
"createChatThread": [
357
],
@@ -9631,7 +9646,7 @@ export default {
1
],
"fileAttachments": [
- 543,
+ 544,
"[FileAttachmentInput!]"
]
}
@@ -9660,14 +9675,14 @@ export default {
"UUID!"
],
"answers": [
- 544,
+ 545,
"[AgentChatQuestionAnswerInput!]!"
],
"modelId": [
1
],
"fileAttachments": [
- 543,
+ 544,
"[FileAttachmentInput!]"
]
}
@@ -9745,7 +9760,7 @@ export default {
355,
{
"input": [
- 545,
+ 546,
"CreateSkillInput!"
]
}
@@ -9754,7 +9769,7 @@ export default {
355,
{
"input": [
- 546,
+ 547,
"UpdateSkillInput!"
]
}
@@ -9812,7 +9827,7 @@ export default {
384,
{
"input": [
- 547,
+ 548,
"UpdateTimelineActivityTypeInput!"
]
}
@@ -9830,7 +9845,7 @@ export default {
272,
{
"input": [
- 548,
+ 549,
"GetAuthorizationUrlForSSOInput!"
]
}
@@ -9996,7 +10011,7 @@ export default {
275,
{
"input": [
- 549
+ 550
]
}
],
@@ -10174,7 +10189,7 @@ export default {
8,
{
"input": [
- 550,
+ 551,
"UpdateWorkspaceMemberSettingsInput!"
]
}
@@ -10208,7 +10223,7 @@ export default {
227,
{
"input": [
- 551,
+ 552,
"SetupOIDCSsoInput!"
]
}
@@ -10217,7 +10232,7 @@ export default {
227,
{
"input": [
- 552,
+ 553,
"SetupSAMLSsoInput!"
]
}
@@ -10226,7 +10241,7 @@ export default {
223,
{
"input": [
- 553,
+ 554,
"DeleteSsoInput!"
]
}
@@ -10235,7 +10250,7 @@ export default {
224,
{
"input": [
- 554,
+ 555,
"EditSsoInput!"
]
}
@@ -10264,7 +10279,7 @@ export default {
351,
{
"type": [
- 555,
+ 556,
"AnalyticsType!"
],
"name": [
@@ -10307,7 +10322,7 @@ export default {
341,
{
"input": [
- 556,
+ 557,
"CreateCalendarEventInput!"
]
}
@@ -10316,7 +10331,7 @@ export default {
350,
{
"input": [
- 557,
+ 558,
"SendEmailInput!"
]
}
@@ -10338,7 +10353,7 @@ export default {
"String!"
],
"connectionParameters": [
- 559,
+ 560,
"EmailAccountConnectionParameters!"
],
"id": [
@@ -10350,7 +10365,7 @@ export default {
188,
{
"input": [
- 561,
+ 562,
"UpdateLabPublicFeatureFlagInput!"
]
}
@@ -10443,7 +10458,7 @@ export default {
"String!"
],
"files": [
- 562,
+ 563,
"[ApplicationFileUploadRequestInput!]!"
]
}
@@ -13055,6 +13070,17 @@ export default {
1
]
},
+ "ReportAppConnectionAuthFailureInput": {
+ "id": [
+ 221
+ ],
+ "reason": [
+ 1
+ ],
+ "__typename": [
+ 1
+ ]
+ },
"FileAttachmentInput": {
"id": [
3
@@ -13309,7 +13335,7 @@ export default {
1
],
"files": [
- 558
+ 559
],
"__typename": [
1
@@ -13331,13 +13357,13 @@ export default {
1
],
"IMAP": [
- 560
+ 561
],
"SMTP": [
- 560
+ 561
],
"CALDAV": [
- 560
+ 561
],
"__typename": [
1
@@ -13402,7 +13428,7 @@ export default {
264,
{
"input": [
- 564,
+ 565,
"LogicFunctionLogsInput!"
]
}
diff --git a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
index dc8badf77d5..dfad0a3aea0 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
@@ -216,17 +216,18 @@ export const createLinearIssueHandler = async (input: {
Each connection has:
-| Field | Description |
-| ----------------- | -------------------------------------------------------------------------------------------------------- |
-| `id` | Unique row id; pass to `getConnection(id)` to refetch a single one |
-| `visibility` | `'user'` (private to one workspace member) or `'workspace'` (shared with all members) |
-| `scopes` | OAuth permissions granted by the upstream provider (distinct from `visibility` — those are unrelated) |
-| `userWorkspaceId` | The owner's userWorkspace id — useful for picking "the request user's connection" in HTTP-route triggers |
-| `workspaceMemberId` | The owner's workspace member id, or `null` if they've since left the workspace |
-| `accessToken` | Fresh OAuth access token (refreshed automatically if expired) |
-| `name` | The connection's display name (auto-derived at OAuth callback, user-renameable) |
-| `handle` | The connected upstream account's email, refreshed on each reconnect; resolved from the OIDC `id_token` returned at token exchange, falling back to the connecting Twenty user's email when the provider doesn't return one |
-| `authFailedAt` | Set when the most recent refresh failed; the user must reconnect |
+| Field | Description |
+| ------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `id` | Unique row id; pass to `getConnection(id)` to refetch a single one |
+| `visibility` | `'user'` (private to one workspace member) or `'workspace'` (shared with all members) |
+| `scopes` | OAuth permissions granted by the upstream provider (distinct from `visibility` — those are unrelated) |
+| `userWorkspaceId` | The owner's userWorkspace id — useful for picking "the request user's connection" in HTTP-route triggers |
+| `workspaceMemberId` | The owner's workspace member id, or `null` if they've since left the workspace |
+| `accessToken` | Fresh OAuth access token (refreshed automatically if expired) |
+| `name` | The connection's display name (auto-derived at OAuth callback, user-renameable) |
+| `handle` | The connected upstream account's email, refreshed on each reconnect; resolved from the OIDC `id_token` returned at token exchange, falling back to the connecting Twenty user's email when the provider doesn't return one |
+| `authFailedAt` | Set when the most recent refresh failed, or when the app reported the credential dead via `reportConnectionAuthFailure`; the user must reconnect |
+| `authFailedReason` | Human-readable explanation for `authFailedAt`, when the reporter gave one; shown on the connection detail page in settings |
Key points:
@@ -236,6 +237,28 @@ Key points:
</Accordion>
+<Accordion title="reportConnectionAuthFailure" description="Tell the platform a credential is dead">
+
+The platform sets `authFailedAt` on its own only when an OAuth refresh fails. Providers whose tokens are never refreshed (a Slack bot token, for example) fail only at call time inside your handlers, so the connection row in settings would keep showing **Connected** while every call dies. When your code hits a definitive auth rejection, report it:
+
+```ts
+import { reportConnectionAuthFailure } from 'twenty-sdk/logic-function';
+
+await reportConnectionAuthFailure({
+ connectionId: connection.id,
+ reason:
+ 'Slack rejected the stored token (invalid_auth). Reconnect to restore the integration.',
+});
+```
+
+This sets `authFailedAt` and the optional reason on the connection. The settings row flips to **Reconnect needed** with a Reconnect button, the connection detail page shows the reason, and `getConnection` starts throwing `AppConnectionAuthFailedError` for that row. The flag and reason clear automatically when the user reconnects. A `reason` longer than 1000 characters is rejected, so truncate provider payloads before passing them.
+
+Only report failures that a reconnect would actually fix (an `invalid_auth`-class rejection from the provider), never transient network errors. An app can only report its own connections, and a request user can only report their own user-visibility credentials.
+
+The mutation behind this helper ships with Twenty 2.40.0, so calling it against an older server fails. If your app uses it, declare the dependency in your `package.json`: `"engines": { "twenty": ">=2.40.0" }`.
+
+</Accordion>
+
<Accordion title="Per-user vs workspace-shared visibility" description="How users choose between private and shared credentials">
When a user clicks "Add connection," they're prompted to pick a visibility:
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index e839bd84353..6012101422e 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -272,6 +272,7 @@ export type AppConnection = {
__typename?: 'AppConnection';
accessToken: Scalars['String']['output'];
authFailedAt?: Maybe<Scalars['String']['output']>;
+ authFailedReason?: Maybe<Scalars['String']['output']>;
handle: Scalars['String']['output'];
id: Scalars['ID']['output'];
name: Scalars['String']['output'];
@@ -1123,6 +1124,7 @@ export type ConnectedAccountPublicDto = {
applicationId?: Maybe<Scalars['UUID']['output']>;
archivedAt?: Maybe<Scalars['DateTime']['output']>;
authFailedAt?: Maybe<Scalars['DateTime']['output']>;
+ authFailedReason?: Maybe<Scalars['String']['output']>;
connectionParameters?: Maybe<PublicImapSmtpCaldavConnectionParameters>;
connectionProviderId?: Maybe<Scalars['UUID']['output']>;
createdAt: Scalars['DateTime']['output'];
@@ -2964,6 +2966,7 @@ export type Mutation = {
renameChatThread: AgentChatThread;
renewApplicationToken: ApplicationTokenPair;
renewToken: AuthTokens;
+ reportAppConnectionAuthFailure: Scalars['Boolean']['output'];
resendEmailVerificationToken: ResendEmailVerificationToken;
resendWorkspaceInvitation: SendInvitations;
resetCommandMenuItem: CommandMenuItem;
@@ -3761,6 +3764,11 @@ export type MutationRenewTokenArgs = {
};
+export type MutationReportAppConnectionAuthFailureArgs = {
+ input: ReportAppConnectionAuthFailureInput;
+};
+
+
export type MutationResendEmailVerificationTokenArgs = {
email: Scalars['String']['input'];
origin: Scalars['String']['input'];
@@ -5453,6 +5461,11 @@ export type RemoveQueryFromEventStreamInput = {
queryId: Scalars['String']['input'];
};
+export type ReportAppConnectionAuthFailureInput = {
+ id: Scalars['ID']['input'];
+ reason?: InputMaybe<Scalars['String']['input']>;
+};
+
export type ResendEmailVerificationToken = {
__typename?: 'ResendEmailVerificationToken';
success: Scalars['Boolean']['output'];
@@ -8739,7 +8752,7 @@ export type MyCalendarChannelsQuery = { __typename?: 'Query', myCalendarChannels
export type MyConnectedAccountsQueryVariables = Exact<{ [key: string]: never; }>;
-export type MyConnectedAccountsQuery = { __typename?: 'Query', myConnectedAccounts: Array<{ __typename?: 'ConnectedAccountPublicDTO', id: string, handle: string, provider: string, authFailedAt?: string | null, archivedAt?: string | null, scopes?: Array<string> | null, handleAliases?: Array<string> | null, lastSignedInAt?: string | null, userWorkspaceId: string, connectionProviderId?: string | null, name?: string | null, visibility: string, lastCredentialsRefreshedAt?: string | null, createdAt: string, updatedAt: string, connectionParameters?: { __typename?: 'PublicImapSmtpCaldavConnectionParameters', IMAP?: { __typename?: 'PublicConnectionParametersOutput', host: string, port: number, connectionSecurity?: EmailConnectionSecurity | null, username?: string | null } | null, SMTP?: { __typename?: 'PublicConnectionParametersOutput', host: string, port: number, connectionSecurity?: EmailConnectionSecurity | null, username?: string | null } | null, CALDAV?: { __typename?: 'PublicConnectionParametersOutput', host: string, username?: string | null } | null } | null }> };
+export type MyConnectedAccountsQuery = { __typename?: 'Query', myConnectedAccounts: Array<{ __typename?: 'ConnectedAccountPublicDTO', id: string, handle: string, provider: string, authFailedAt?: string | null, authFailedReason?: string | null, archivedAt?: string | null, scopes?: Array<string> | null, handleAliases?: Array<string> | null, lastSignedInAt?: string | null, userWorkspaceId: string, connectionProviderId?: string | null, name?: string | null, visibility: string, lastCredentialsRefreshedAt?: string | null, createdAt: string, updatedAt: string, connectionParameters?: { __typename?: 'PublicImapSmtpCaldavConnectionParameters', IMAP?: { __typename?: 'PublicConnectionParametersOutput', host: string, port: number, connectionSecurity?: EmailConnectionSecurity | null, username?: string | null } | null, SMTP?: { __typename?: 'PublicConnectionParametersOutput', host: string, port: number, connectionSecurity?: EmailConnectionSecurity | null, username?: string | null } | null, CALDAV?: { __typename?: 'PublicConnectionParametersOutput', host: string, username?: string | null } | null } | null }> };
export type MyMessageChannelsQueryVariables = Exact<{
connectedAccountId?: InputMaybe<Scalars['UUID']['input']>;
@@ -9944,7 +9957,7 @@ export const UpdateMessageChannelDocument = {"kind":"Document","definitions":[{"
export const UpdateMessageFoldersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"UpdateMessageFolders"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"input"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UpdateMessageFoldersInput"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"updateMessageFolders"},"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":"isSynced"}},{"kind":"Field","name":{"kind":"Name","value":"pendingSyncAction"}}]}}]}}]} as unknown as DocumentNode<UpdateMessageFoldersMutation, UpdateMessageFoldersMutationVariables>;
export const GetConnectedImapSmtpCaldavAccountDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"GetConnectedImapSmtpCaldavAccount"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"id"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"getConnectedImapSmtpCaldavAccount"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"id"},"value":{"kind":"Variable","name":{"kind":"Name","value":"id"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"connectionParameters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"IMAP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"SMTP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"username"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}}]}},{"kind":"Field","name":{"kind":"Name","value":"CALDAV"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}}]}}]}}]} as unknown as DocumentNode<GetConnectedImapSmtpCaldavAccountQuery, GetConnectedImapSmtpCaldavAccountQueryVariables>;
export const MyCalendarChannelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyCalendarChannels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myCalendarChannels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"syncStatus"}},{"kind":"Field","name":{"kind":"Name","value":"syncStage"}},{"kind":"Field","name":{"kind":"Name","value":"syncStageStartedAt"}},{"kind":"Field","name":{"kind":"Name","value":"isContactAutoCreationEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccountId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyCalendarChannelsQuery, MyCalendarChannelsQueryVariables>;
-export const MyConnectedAccountsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"authFailedAt"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"scopes"}},{"kind":"Field","name":{"kind":"Name","value":"handleAliases"}},{"kind":"Field","name":{"kind":"Name","value":"lastSignedInAt"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"connectionProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"lastCredentialsRefreshedAt"}},{"kind":"Field","name":{"kind":"Name","value":"connectionParameters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"IMAP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"SMTP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"CALDAV"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyConnectedAccountsQuery, MyConnectedAccountsQueryVariables>;
+export const MyConnectedAccountsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myConnectedAccounts"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"provider"}},{"kind":"Field","name":{"kind":"Name","value":"authFailedAt"}},{"kind":"Field","name":{"kind":"Name","value":"authFailedReason"}},{"kind":"Field","name":{"kind":"Name","value":"archivedAt"}},{"kind":"Field","name":{"kind":"Name","value":"scopes"}},{"kind":"Field","name":{"kind":"Name","value":"handleAliases"}},{"kind":"Field","name":{"kind":"Name","value":"lastSignedInAt"}},{"kind":"Field","name":{"kind":"Name","value":"userWorkspaceId"}},{"kind":"Field","name":{"kind":"Name","value":"connectionProviderId"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"lastCredentialsRefreshedAt"}},{"kind":"Field","name":{"kind":"Name","value":"connectionParameters"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"IMAP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"SMTP"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"port"}},{"kind":"Field","name":{"kind":"Name","value":"connectionSecurity"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}},{"kind":"Field","name":{"kind":"Name","value":"CALDAV"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"host"}},{"kind":"Field","name":{"kind":"Name","value":"username"}}]}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyConnectedAccountsQuery, MyConnectedAccountsQueryVariables>;
export const MyMessageChannelsDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyMessageChannels"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myMessageChannels"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"connectedAccountId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"connectedAccountId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}},{"kind":"Field","name":{"kind":"Name","value":"displayName"}},{"kind":"Field","name":{"kind":"Name","value":"visibility"}},{"kind":"Field","name":{"kind":"Name","value":"type"}},{"kind":"Field","name":{"kind":"Name","value":"isContactAutoCreationEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"contactAutoCreationPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"messageFolderImportPolicy"}},{"kind":"Field","name":{"kind":"Name","value":"excludeNonProfessionalEmails"}},{"kind":"Field","name":{"kind":"Name","value":"excludeGroupEmails"}},{"kind":"Field","name":{"kind":"Name","value":"isSyncEnabled"}},{"kind":"Field","name":{"kind":"Name","value":"syncStatus"}},{"kind":"Field","name":{"kind":"Name","value":"syncStage"}},{"kind":"Field","name":{"kind":"Name","value":"syncStageStartedAt"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccountId"}},{"kind":"Field","name":{"kind":"Name","value":"connectedAccount"},"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"handle"}}]}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyMessageChannelsQuery, MyMessageChannelsQueryVariables>;
export const MyMessageFoldersDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"query","name":{"kind":"Name","value":"MyMessageFolders"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"messageChannelId"}},"type":{"kind":"NamedType","name":{"kind":"Name","value":"UUID"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"myMessageFolders"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"messageChannelId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"messageChannelId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}},{"kind":"Field","name":{"kind":"Name","value":"isSynced"}},{"kind":"Field","name":{"kind":"Name","value":"isSentFolder"}},{"kind":"Field","name":{"kind":"Name","value":"parentFolderId"}},{"kind":"Field","name":{"kind":"Name","value":"externalId"}},{"kind":"Field","name":{"kind":"Name","value":"pendingSyncAction"}},{"kind":"Field","name":{"kind":"Name","value":"messageChannelId"}},{"kind":"Field","name":{"kind":"Name","value":"createdAt"}},{"kind":"Field","name":{"kind":"Name","value":"updatedAt"}}]}}]}}]} as unknown as DocumentNode<MyMessageFoldersQuery, MyMessageFoldersQueryVariables>;
export const ClaimApplicationRegistrationOwnershipDocument = {"kind":"Document","definitions":[{"kind":"OperationDefinition","operation":"mutation","name":{"kind":"Name","value":"ClaimApplicationRegistrationOwnership"},"variableDefinitions":[{"kind":"VariableDefinition","variable":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}},"type":{"kind":"NonNullType","type":{"kind":"NamedType","name":{"kind":"Name","value":"String"}}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"claimApplicationRegistrationOwnership"},"arguments":[{"kind":"Argument","name":{"kind":"Name","value":"applicationRegistrationId"},"value":{"kind":"Variable","name":{"kind":"Name","value":"applicationRegistrationId"}}}],"selectionSet":{"kind":"SelectionSet","selections":[{"kind":"Field","name":{"kind":"Name","value":"id"}},{"kind":"Field","name":{"kind":"Name","value":"name"}}]}}]}}]} as unknown as DocumentNode<ClaimApplicationRegistrationOwnershipMutation, ClaimApplicationRegistrationOwnershipMutationVariables>;
diff --git a/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyConnectedAccounts.ts b/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyConnectedAccounts.ts
index 4632c5a8898..73b53e51833 100644
--- a/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyConnectedAccounts.ts
+++ b/packages/twenty-front/src/modules/settings/accounts/graphql/queries/getMyConnectedAccounts.ts
@@ -7,6 +7,7 @@ export const GET_MY_CONNECTED_ACCOUNTS = gql`
handle
provider
authFailedAt
+ authFailedReason
archivedAt
scopes
handleAliases
diff --git a/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx b/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx
index 0976921ba41..eacc7a1b19e 100644
--- a/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx
+++ b/packages/twenty-front/src/modules/side-panel/pages/__stories__/SidePanelComposerPages.stories.tsx
@@ -30,6 +30,7 @@ const storyConnectedAccounts = [
handle: '[email protected]',
provider: 'google',
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
scopes: ['https://www.googleapis.com/auth/calendar.events'],
handleAliases: '',
@@ -48,6 +49,7 @@ const storyConnectedAccounts = [
handle: '[email protected]',
provider: 'microsoft',
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
scopes: ['Calendars.ReadWrite'],
handleAliases: '',
diff --git a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx
index 22931ce8e5a..d70c4e5318d 100644
--- a/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx
+++ b/packages/twenty-front/src/modules/workflow/workflow-steps/workflow-actions/components/__stories__/WorkflowEditActionEmailBase.stories.tsx
@@ -23,6 +23,7 @@ const mockedConnectedAccounts = [
handle: '[email protected]',
provider: 'google',
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
scopes: ['email', 'calendar'],
handleAliases: ['[email protected]'],
diff --git a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsCalendars.stories.tsx b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsCalendars.stories.tsx
index 6a850fa0835..f5e56a3c90d 100644
--- a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsCalendars.stories.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsCalendars.stories.tsx
@@ -41,6 +41,7 @@ export const TwoConnectedAccounts: Story = {
handle: '[email protected]',
provider: 'google',
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
scopes: ['calendar'],
handleAliases: '',
diff --git a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
index 39078501f62..90798df2c84 100644
--- a/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
+++ b/packages/twenty-front/src/pages/settings/accounts/__stories__/SettingsAccountsEmails.stories.tsx
@@ -42,6 +42,7 @@ export const TwoConnectedAccounts: Story = {
handle: '[email protected]',
provider: 'google',
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
scopes: ['email'],
handleAliases: '',
diff --git a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
index ee7a32b02c7..c66b6975912 100644
--- a/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
+++ b/packages/twenty-front/src/pages/settings/applications/SettingsApplicationConnectionDetail.tsx
@@ -1,6 +1,7 @@
import { useMutation, useQuery } from '@apollo/client/react';
import { styled } from '@linaria/react';
import { Trans, useLingui } from '@lingui/react/macro';
+import { isNonEmptyString } from '@sniptt/guards';
import { type ReactNode } from 'react';
import { useParams } from 'react-router-dom';
import { SettingsPath } from 'twenty-shared/types';
@@ -258,6 +259,13 @@ export const SettingsApplicationConnectionDetail = () => {
label: t`Auth failed at`,
value: formatDateTime(connection.authFailedAt),
},
+ {
+ key: 'authFailedReason',
+ label: t`Auth failure reason`,
+ value: isNonEmptyString(connection.authFailedReason)
+ ? connection.authFailedReason
+ : '-',
+ },
{
key: 'createdAt',
label: t`Created`,
diff --git a/packages/twenty-sdk/package.json b/packages/twenty-sdk/package.json
index 7fb3167b96e..7e7b7ac9795 100644
--- a/packages/twenty-sdk/package.json
+++ b/packages/twenty-sdk/package.json
@@ -108,7 +108,8 @@
},
"engines": {
"node": "^24.5.0",
- "yarn": "^4.0.2"
+ "yarn": "^4.0.2",
+ "twenty": ">=2.40.0"
},
"typesVersions": {
"*": {
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
index 274f29147cd..80908ae49dd 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/find-connection-for-request.spec.ts
@@ -16,6 +16,7 @@ const buildConnection = (
accessToken: 'token-fresh',
scopes: ['read'],
authFailedAt: null,
+ authFailedReason: null,
...overrides,
});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
index 7d28b7a4bac..39820122f54 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/get-connection.spec.ts
@@ -25,6 +25,7 @@ const buildConnection = (
accessToken: 'fresh',
scopes: ['read'],
authFailedAt: null,
+ authFailedReason: null,
...overrides,
});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/report-connection-auth-failure.spec.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/report-connection-auth-failure.spec.ts
new file mode 100644
index 00000000000..600e8ccf6fa
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/__tests__/report-connection-auth-failure.spec.ts
@@ -0,0 +1,80 @@
+import {
+ afterEach,
+ beforeEach,
+ describe,
+ expect,
+ it,
+ vi,
+ type MockInstance,
+} from 'vitest';
+
+import { reportConnectionAuthFailure } from '@/sdk/logic-function/connections/report-connection-auth-failure';
+
+describe('reportConnectionAuthFailure', () => {
+ let fetchSpy: MockInstance<typeof fetch>;
+
+ beforeEach(() => {
+ process.env.TWENTY_API_URL = 'https://api.test';
+ process.env.TWENTY_APP_ACCESS_TOKEN = 'app-token';
+ fetchSpy = vi.spyOn(globalThis, 'fetch');
+ });
+
+ afterEach(() => {
+ delete process.env.TWENTY_API_URL;
+ delete process.env.TWENTY_APP_ACCESS_TOKEN;
+ fetchSpy.mockRestore();
+ });
+
+ it('sends the mutation with the connection id and reason', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({ data: { reportAppConnectionAuthFailure: true } }),
+ { status: 200 },
+ ),
+ );
+
+ await reportConnectionAuthFailure({
+ connectionId: 'c-1',
+ reason: 'Slack rejected the token',
+ });
+
+ const [url, requestInit] = fetchSpy.mock.calls[0];
+
+ expect(String(url)).toBe('https://api.test/metadata');
+
+ const body = JSON.parse(String(requestInit?.body));
+
+ expect(body.query).toContain('reportAppConnectionAuthFailure');
+ expect(body.variables).toEqual({
+ input: { id: 'c-1', reason: 'Slack rejected the token' },
+ });
+ });
+
+ it('omits the reason when none is given', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({ data: { reportAppConnectionAuthFailure: true } }),
+ { status: 200 },
+ ),
+ );
+
+ await reportConnectionAuthFailure({ connectionId: 'c-2' });
+
+ const body = JSON.parse(String(fetchSpy.mock.calls[0][1]?.body));
+
+ expect(body.variables).toEqual({ input: { id: 'c-2' } });
+ });
+
+ it('propagates a GraphQL error', async () => {
+ fetchSpy.mockResolvedValue(
+ new Response(
+ JSON.stringify({ errors: [{ message: 'Connection c-3 not found' }] }),
+ { status: 200 },
+ ),
+ );
+
+ await expect(
+ reportConnectionAuthFailure({ connectionId: 'c-3' }),
+ ).rejects.toThrow('Connection c-3 not found');
+ });
+});
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
index 4cfb2eb7ecd..3417d7089f3 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/get-connection.ts
@@ -15,6 +15,7 @@ const GET_APP_CONNECTION_QUERY = `
accessToken
scopes
authFailedAt
+ authFailedReason
}
}
`;
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
index cd06a77f732..a71c2e841fa 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/list-connections.ts
@@ -14,6 +14,7 @@ const LIST_APP_CONNECTIONS_QUERY = `
accessToken
scopes
authFailedAt
+ authFailedReason
}
}
`;
diff --git a/packages/twenty-sdk/src/sdk/logic-function/connections/report-connection-auth-failure.ts b/packages/twenty-sdk/src/sdk/logic-function/connections/report-connection-auth-failure.ts
new file mode 100644
index 00000000000..06891f07d40
--- /dev/null
+++ b/packages/twenty-sdk/src/sdk/logic-function/connections/report-connection-auth-failure.ts
@@ -0,0 +1,24 @@
+import { postGraphqlRequest } from '@/sdk/logic-function/utils/post-graphql-request.util';
+
+const REPORT_APP_CONNECTION_AUTH_FAILURE_MUTATION = `
+ mutation ReportAppConnectionAuthFailure($input: ReportAppConnectionAuthFailureInput!) {
+ reportAppConnectionAuthFailure(input: $input)
+ }
+`;
+
+export const reportConnectionAuthFailure = async ({
+ connectionId,
+ reason,
+}: {
+ connectionId: string;
+ reason?: string;
+}): Promise<void> => {
+ await postGraphqlRequest<
+ { input: { id: string; reason?: string } },
+ { reportAppConnectionAuthFailure: boolean }
+ >({
+ query: REPORT_APP_CONNECTION_AUTH_FAILURE_MUTATION,
+ variables: { input: { id: connectionId, reason } },
+ caller: 'reportConnectionAuthFailure',
+ });
+};
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index 6a4e9cef88d..fb28415bc55 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -54,6 +54,7 @@ export { getConnection } from '@/sdk/logic-function/connections/get-connection';
export { listConnections } from '@/sdk/logic-function/connections/list-connections';
export type { ListConnectionsFilter } from '@/sdk/logic-function/connections/list-connections';
export { findConnectionForRequest } from '@/sdk/logic-function/connections/find-connection-for-request';
+export { reportConnectionAuthFailure } from '@/sdk/logic-function/connections/report-connection-auth-failure';
export { AppConnectionAuthFailedError } from '@/sdk/logic-function/connections/errors/app-connection-auth-failed.error';
export type { AppConnection } from '@/sdk/logic-function/connections/types/app-connection.type';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788781233982-add-auth-failed-reason-to-connected-account.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788781233982-add-auth-failed-reason-to-connected-account.ts
new file mode 100644
index 00000000000..b3233e402b3
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788781233982-add-auth-failed-reason-to-connected-account.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.40.0', 1788781233982)
+export class AddAuthFailedReasonToConnectedAccountFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" ADD "authFailedReason" varchar',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" DROP COLUMN "authFailedReason"',
+ );
+ }
+}
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 9284ed6073c..7d747061f88 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
@@ -178,6 +178,7 @@ import { EraseObjectNavigationCommandMenuItemPayloadsSlowInstanceCommand } from
import { ReshapeUsageLimitPeriodFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-38/2-38-instance-command-fast-1788367160891-reshape-usage-limit-period';
import { AddLogoToConnectionProviderFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-39/2-39-instance-command-fast-1788542613404-add-logo-to-connection-provider';
import { AddReadabilityToObjectMetadataFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-39/2-39-instance-command-fast-1788548844925-add-readability-to-object-metadata';
+import { AddAuthFailedReasonToConnectedAccountFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-40/2-40-instance-command-fast-1788781233982-add-auth-failed-reason-to-connected-account';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -358,4 +359,5 @@ export const INSTANCE_COMMANDS = [
AddReadabilityToObjectMetadataFastInstanceCommand,
AddCommandMenuItemConditionalPinnedExpressionFastInstanceCommand,
AddCampaignDeliveryClaimTokenIndexFastInstanceCommand,
+ AddAuthFailedReasonToConnectedAccountFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
index 6033c8a6e48..08e3aaf6b54 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum.ts
@@ -8,6 +8,7 @@ export enum ConnectionProviderExceptionCode {
FORBIDDEN = 'FORBIDDEN',
INVALID_CONNECTION_PROVIDER_INPUT = 'INVALID_CONNECTION_PROVIDER_INPUT',
CONNECTION_PROVIDER_NOT_FOUND = 'CONNECTION_PROVIDER_NOT_FOUND',
+ CONNECTION_NOT_FOUND = 'CONNECTION_NOT_FOUND',
CONNECTION_PROVIDER_NAME_ALREADY_EXISTS = 'CONNECTION_PROVIDER_NAME_ALREADY_EXISTS',
ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND = 'ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND',
ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND = 'ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND',
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
index f002790a65f..6d96ad4c856 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service.ts
@@ -304,6 +304,7 @@ export class ConnectionProviderOAuthFlowService {
scopes: tokenResponse.scopes ?? provider.oauthConfig.scopes,
lastCredentialsRefreshedAt: new Date(),
authFailedAt: null,
+ authFailedReason: null,
visibility,
handle,
};
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
index 5a610576d2d..a450db2fce7 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.exception.ts
@@ -27,6 +27,8 @@ const getConnectionProviderExceptionUserFriendlyMessage = (
return msg`The connection-provider manifest is missing required fields.`;
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NOT_FOUND:
return msg`Connection provider not found.`;
+ case ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND:
+ return msg`Connection not found.`;
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
return msg`A connection provider with this name already exists for this application.`;
case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts
index 686b1006fdb..d515a610029 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.controller.ts
@@ -6,6 +6,7 @@ import {
HttpStatus,
Post,
Req,
+ UseFilters,
UseGuards,
UsePipes,
ValidationPipe,
@@ -19,6 +20,7 @@ import { type AppConnectionDto } from 'src/engine/core-modules/application/conne
import { GetAppConnectionDto } from 'src/engine/core-modules/application/connection-provider/connections/dtos/get-app-connection.dto';
import { ListAppConnectionsDto } from 'src/engine/core-modules/application/connection-provider/connections/dtos/list-app-connections.dto';
import { ApplicationConnectionsListService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service';
+import { ConnectionProviderRestApiExceptionFilter } from 'src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter';
import { JwtAuthGuard } from 'src/engine/guards/jwt-auth.guard';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
@@ -29,6 +31,7 @@ import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
* backward compatibility with already-deployed app runtimes. */
@Controller(`${ApiPath.Apps}/connections`)
@UseGuards(JwtAuthGuard, WorkspaceAuthGuard, NoPermissionGuard)
+@UseFilters(ConnectionProviderRestApiExceptionFilter)
@UsePipes(new ValidationPipe({ whitelist: true, forbidNonWhitelisted: true }))
export class ApplicationConnectionsController {
constructor(
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.module.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.module.ts
index 1984122ceb7..c8c2936bbee 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.module.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.module.ts
@@ -4,7 +4,9 @@ import { TypeOrmModule } from '@nestjs/typeorm';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { ApplicationConnectionsController } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.controller';
import { ApplicationConnectionsResolver } from 'src/engine/core-modules/application/connection-provider/connections/application-connections.resolver';
+import { ApplicationConnectionAuthFailureService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service';
import { ApplicationConnectionsListService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service';
+import { ConnectionProviderGraphqlApiExceptionInterceptor } from 'src/engine/core-modules/application/connection-provider/interceptors/connection-provider-graphql-api-exception.interceptor';
import { TokenModule } from 'src/engine/core-modules/auth/token/token.module';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
@@ -33,8 +35,10 @@ import { RefreshTokensManagerModule } from 'src/modules/connected-account/refres
ConnectedAccountTokenEncryptionModule,
],
providers: [
+ ApplicationConnectionAuthFailureService,
ApplicationConnectionsListService,
ApplicationConnectionsResolver,
+ ConnectionProviderGraphqlApiExceptionInterceptor,
],
controllers: [ApplicationConnectionsController],
exports: [ApplicationConnectionsListService],
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts
index 2ffbdaee108..3bbd0531b9a 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/application-connections.resolver.ts
@@ -1,23 +1,30 @@
-import { UseGuards } from '@nestjs/common';
-import { Args, ID, Query } from '@nestjs/graphql';
+import { UseGuards, UseInterceptors, UsePipes } from '@nestjs/common';
+import { Args, ID, Mutation, Query } from '@nestjs/graphql';
import { MetadataResolver } from 'src/engine/api/graphql/graphql-config/decorators/metadata-resolver.decorator';
+import { ConnectionProviderGraphqlApiExceptionInterceptor } from 'src/engine/core-modules/application/connection-provider/interceptors/connection-provider-graphql-api-exception.interceptor';
import { AppConnectionObjectDto } from 'src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object';
import { ListAppConnectionsInput } from 'src/engine/core-modules/application/connection-provider/connections/dtos/list-app-connections.input';
+import { ReportAppConnectionAuthFailureInput } from 'src/engine/core-modules/application/connection-provider/connections/dtos/report-app-connection-auth-failure.input';
+import { ApplicationConnectionAuthFailureService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service';
import { ApplicationConnectionsListService } from 'src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service';
import { type FlatApplication } from 'src/engine/core-modules/application/types/flat-application.type';
import { type FlatWorkspace } from 'src/engine/core-modules/workspace/types/flat-workspace.type';
import { AuthApplication } from 'src/engine/decorators/auth/auth-application.decorator';
import { AuthUserWorkspaceId } from 'src/engine/decorators/auth/auth-user-workspace-id.decorator';
+import { ResolverValidationPipe } from 'src/engine/core-modules/graphql/pipes/resolver-validation.pipe';
import { AuthWorkspace } from 'src/engine/decorators/auth/auth-workspace.decorator';
import { NoPermissionGuard } from 'src/engine/guards/no-permission.guard';
import { WorkspaceAuthGuard } from 'src/engine/guards/workspace-auth.guard';
@UseGuards(WorkspaceAuthGuard, NoPermissionGuard)
+@UseInterceptors(ConnectionProviderGraphqlApiExceptionInterceptor)
+@UsePipes(ResolverValidationPipe)
@MetadataResolver()
export class ApplicationConnectionsResolver {
constructor(
private readonly listService: ApplicationConnectionsListService,
+ private readonly authFailureService: ApplicationConnectionAuthFailureService,
) {}
@Query(() => [AppConnectionObjectDto])
@@ -51,4 +58,23 @@ export class ApplicationConnectionsResolver {
id,
});
}
+
+ @Mutation(() => Boolean)
+ async reportAppConnectionAuthFailure(
+ @AuthApplication() application: FlatApplication,
+ @AuthWorkspace() workspace: FlatWorkspace,
+ @AuthUserWorkspaceId({ allowUndefined: true })
+ userWorkspaceId: string | undefined,
+ @Args('input') input: ReportAppConnectionAuthFailureInput,
+ ): Promise<boolean> {
+ await this.authFailureService.reportAuthFailureOrThrow({
+ applicationId: application.id,
+ workspaceId: workspace.id,
+ requestUserWorkspaceId: userWorkspaceId ?? null,
+ id: input.id,
+ reason: input.reason ?? null,
+ });
+
+ return true;
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
index 81d3fa3cbe7..9384ba664ba 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.object.ts
@@ -33,4 +33,7 @@ export class AppConnectionObjectDto implements AppConnection {
@Field(() => String, { nullable: true })
authFailedAt: string | null;
+
+ @Field(() => String, { nullable: true })
+ authFailedReason: string | null;
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/report-app-connection-auth-failure.input.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/report-app-connection-auth-failure.input.ts
new file mode 100644
index 00000000000..b2438657c28
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/dtos/report-app-connection-auth-failure.input.ts
@@ -0,0 +1,16 @@
+import { Field, ID, InputType } from '@nestjs/graphql';
+
+import { IsOptional, IsString, IsUUID, MaxLength } from 'class-validator';
+
+@InputType('ReportAppConnectionAuthFailureInput')
+export class ReportAppConnectionAuthFailureInput {
+ @IsUUID()
+ @Field(() => ID)
+ id: string;
+
+ @IsString()
+ @IsOptional()
+ @MaxLength(1000)
+ @Field({ nullable: true })
+ reason?: string;
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts
new file mode 100644
index 00000000000..bc2f8e4ee84
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connection-auth-failure.service.ts
@@ -0,0 +1,88 @@
+import { Injectable } from '@nestjs/common';
+import { InjectRepository } from '@nestjs/typeorm';
+
+import { IsNull, Repository } from 'typeorm';
+
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+import { isDefined } from 'twenty-shared/utils';
+
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { isConnectionHiddenFromRequestUser } from 'src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util';
+import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+type ReportAuthFailureArgs = {
+ applicationId: string;
+ workspaceId: string;
+ requestUserWorkspaceId: string | null;
+ id: string;
+ reason: string | null;
+};
+
+@Injectable()
+export class ApplicationConnectionAuthFailureService {
+ constructor(
+ @InjectRepository(ConnectedAccountEntity)
+ private readonly connectedAccountRepository: Repository<ConnectedAccountEntity>,
+ ) {}
+
+ async reportAuthFailureOrThrow({
+ applicationId,
+ workspaceId,
+ requestUserWorkspaceId,
+ id,
+ reason,
+ }: ReportAuthFailureArgs): Promise<void> {
+ const scopedWhere = {
+ id,
+ applicationId,
+ workspaceId,
+ provider: ConnectedAccountProvider.APP,
+ archivedAt: IsNull(),
+ };
+
+ const account = await this.connectedAccountRepository.findOne({
+ where: scopedWhere,
+ });
+
+ if (
+ !isDefined(account) ||
+ isConnectionHiddenFromRequestUser({ account, requestUserWorkspaceId })
+ ) {
+ throw new ConnectionProviderException(
+ `Connection ${id} not found`,
+ ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND,
+ );
+ }
+
+ // Every reconnect rewrites lastCredentialsRefreshedAt, so matching on the
+ // value we read drops a report that describes an already-replaced token
+ // instead of resurrecting a failure the reconnect just cleared.
+ const updateResult = await this.connectedAccountRepository.update(
+ {
+ ...scopedWhere,
+ lastCredentialsRefreshedAt: isDefined(
+ account.lastCredentialsRefreshedAt,
+ )
+ ? account.lastCredentialsRefreshedAt
+ : IsNull(),
+ },
+ { authFailedAt: new Date(), authFailedReason: reason },
+ );
+
+ if (updateResult.affected === 0) {
+ const currentAccount = await this.connectedAccountRepository.findOne({
+ where: scopedWhere,
+ });
+
+ if (!isDefined(currentAccount)) {
+ throw new ConnectionProviderException(
+ `Connection ${id} not found`,
+ ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND,
+ );
+ }
+ // A reconnect superseded the report while it was in flight; the failure
+ // described the old credential, so dropping it is correct.
+ }
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
index d28a19834f5..8fcf8336bf2 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/services/application-connections-list.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Logger, NotFoundException } from '@nestjs/common';
+import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { type FindOptionsWhere, In, Repository } from 'typeorm';
@@ -6,8 +6,11 @@ import { type FindOptionsWhere, In, Repository } from 'typeorm';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
import { type AppConnectionDto } from 'src/engine/core-modules/application/connection-provider/connections/dtos/app-connection.dto';
+import { isConnectionHiddenFromRequestUser } from 'src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { resolveWorkspaceMemberId } from 'src/engine/core-modules/user-workspace/utils/resolve-workspace-member-id.util';
import { ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
@@ -129,23 +132,21 @@ export class ApplicationConnectionsListService {
},
});
- if (!isDefined(account)) {
- throw new NotFoundException(`Connection ${id} not found`);
- }
-
- // Same privacy rule as list(): a request-user can only see their own
- // user-visibility credentials. Workspace-shared ones are visible to
- // anyone in the workspace. Cron has no request user — sees all.
if (
- isDefined(requestUserWorkspaceId) &&
- account.visibility === 'user' &&
- account.userWorkspaceId !== requestUserWorkspaceId
+ !isDefined(account) ||
+ isConnectionHiddenFromRequestUser({ account, requestUserWorkspaceId })
) {
- throw new NotFoundException(`Connection ${id} not found`);
+ throw new ConnectionProviderException(
+ `Connection ${id} not found`,
+ ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND,
+ );
}
if (!isDefined(account.connectionProviderId)) {
- throw new NotFoundException(`Connection ${id} has no provider`);
+ throw new ConnectionProviderException(
+ `Connection ${id} has no provider`,
+ ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NOT_FOUND,
+ );
}
const provider = await this.oauthProviderRepository.findOneByOrFail({
@@ -166,8 +167,9 @@ export class ApplicationConnectionsListService {
);
if (!isDefined(dto)) {
- throw new NotFoundException(
+ throw new ConnectionProviderException(
`Connection ${id} could not be refreshed; ask the user to reconnect`,
+ ConnectionProviderExceptionCode.REFRESH_FAILED,
);
}
@@ -251,6 +253,7 @@ export class ApplicationConnectionsListService {
}),
scopes: account.scopes ?? provider.oauthConfig?.scopes ?? [],
authFailedAt: account.authFailedAt?.toISOString() ?? null,
+ authFailedReason: account.authFailedReason,
};
} catch (error) {
this.logger.warn(
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/__tests__/is-connection-hidden-from-request-user.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/__tests__/is-connection-hidden-from-request-user.util.spec.ts
new file mode 100644
index 00000000000..1e26d044e5a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/__tests__/is-connection-hidden-from-request-user.util.spec.ts
@@ -0,0 +1,39 @@
+import { isConnectionHiddenFromRequestUser } from 'src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util';
+
+describe('isConnectionHiddenFromRequestUser', () => {
+ it("hides another user's user-visibility connection from a request user", () => {
+ expect(
+ isConnectionHiddenFromRequestUser({
+ account: { visibility: 'user', userWorkspaceId: 'uw-owner' },
+ requestUserWorkspaceId: 'uw-someone-else',
+ }),
+ ).toBe(true);
+ });
+
+ it('shows a request user their own user-visibility connection', () => {
+ expect(
+ isConnectionHiddenFromRequestUser({
+ account: { visibility: 'user', userWorkspaceId: 'uw-owner' },
+ requestUserWorkspaceId: 'uw-owner',
+ }),
+ ).toBe(false);
+ });
+
+ it('shows workspace-shared connections to any request user', () => {
+ expect(
+ isConnectionHiddenFromRequestUser({
+ account: { visibility: 'workspace', userWorkspaceId: 'uw-owner' },
+ requestUserWorkspaceId: 'uw-someone-else',
+ }),
+ ).toBe(false);
+ });
+
+ it('hides nothing from background executions with no request user', () => {
+ expect(
+ isConnectionHiddenFromRequestUser({
+ account: { visibility: 'user', userWorkspaceId: 'uw-owner' },
+ requestUserWorkspaceId: null,
+ }),
+ ).toBe(false);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util.ts
new file mode 100644
index 00000000000..535c9822e66
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connections/utils/is-connection-hidden-from-request-user.util.ts
@@ -0,0 +1,15 @@
+import { isDefined } from 'twenty-shared/utils';
+
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+
+// Background executions carry no request user, so nothing is hidden from them.
+export const isConnectionHiddenFromRequestUser = ({
+ account,
+ requestUserWorkspaceId,
+}: {
+ account: Pick<ConnectedAccountEntity, 'visibility' | 'userWorkspaceId'>;
+ requestUserWorkspaceId: string | null;
+}): boolean =>
+ isDefined(requestUserWorkspaceId) &&
+ account.visibility === 'user' &&
+ account.userWorkspaceId !== requestUserWorkspaceId;
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
new file mode 100644
index 00000000000..9be57f759d3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/filters/connection-provider-rest-api-exception.filter.ts
@@ -0,0 +1,59 @@
+import {
+ type ArgumentsHost,
+ Catch,
+ type ExceptionFilter,
+ Injectable,
+} from '@nestjs/common';
+
+import { type Response } from 'express';
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+import { HttpExceptionHandlerService } from 'src/engine/core-modules/exception-handler/http-exception-handler.service';
+import { type CustomException } from 'src/utils/custom-exception';
+
+const connectionProviderExceptionCodeToHttpStatus = (
+ code: ConnectionProviderExceptionCode,
+): number => {
+ switch (code) {
+ case ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NOT_FOUND:
+ case ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND:
+ case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ return 404;
+ case ConnectionProviderExceptionCode.FORBIDDEN:
+ return 403;
+ case ConnectionProviderExceptionCode.INVALID_REQUEST:
+ case ConnectionProviderExceptionCode.INVALID_STATE:
+ case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
+ case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
+ return 400;
+ case ConnectionProviderExceptionCode.CLIENT_CREDENTIALS_NOT_CONFIGURED:
+ case ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED:
+ case ConnectionProviderExceptionCode.REFRESH_FAILED:
+ case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
+ return 500;
+ default:
+ return assertUnreachable(code);
+ }
+};
+
+@Injectable()
+@Catch(ConnectionProviderException)
+export class ConnectionProviderRestApiExceptionFilter implements ExceptionFilter {
+ constructor(
+ private readonly httpExceptionHandlerService: HttpExceptionHandlerService,
+ ) {}
+
+ catch(exception: ConnectionProviderException, host: ArgumentsHost) {
+ const response = host.switchToHttp().getResponse<Response>();
+
+ return this.httpExceptionHandlerService.handleError(
+ exception as CustomException,
+ response,
+ connectionProviderExceptionCodeToHttpStatus(exception.code),
+ );
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/interceptors/connection-provider-graphql-api-exception.interceptor.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/interceptors/connection-provider-graphql-api-exception.interceptor.ts
new file mode 100644
index 00000000000..781eb7bd098
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/interceptors/connection-provider-graphql-api-exception.interceptor.ts
@@ -0,0 +1,22 @@
+import {
+ type CallHandler,
+ type ExecutionContext,
+ Injectable,
+ type NestInterceptor,
+} from '@nestjs/common';
+
+import { type Observable, catchError } from 'rxjs';
+
+import { connectionProviderGraphqlApiExceptionHandler } from 'src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util';
+
+@Injectable()
+export class ConnectionProviderGraphqlApiExceptionInterceptor implements NestInterceptor {
+ intercept(
+ _context: ExecutionContext,
+ next: CallHandler,
+ ): Observable<unknown> {
+ return next
+ .handle()
+ .pipe(catchError(connectionProviderGraphqlApiExceptionHandler));
+ }
+}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
new file mode 100644
index 00000000000..6f0f224ad6a
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/connection-provider-graphql-api-exception-handler.util.ts
@@ -0,0 +1,40 @@
+import { assertUnreachable } from 'twenty-shared/utils';
+
+import {
+ ForbiddenError,
+ InternalServerError,
+ NotFoundError,
+ UserInputError,
+} from 'src/engine/core-modules/graphql/utils/graphql-errors.util';
+import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
+import { ConnectionProviderException } from 'src/engine/core-modules/application/connection-provider/connection-provider.exception';
+
+export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
+ if (error instanceof ConnectionProviderException) {
+ switch (error.code) {
+ case ConnectionProviderExceptionCode.CONNECTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NOT_FOUND:
+ case ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND:
+ case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ throw new NotFoundError(error);
+ case ConnectionProviderExceptionCode.FORBIDDEN:
+ throw new ForbiddenError(error);
+ case ConnectionProviderExceptionCode.INVALID_REQUEST:
+ case ConnectionProviderExceptionCode.INVALID_STATE:
+ case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
+ case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
+ throw new UserInputError(error);
+ case ConnectionProviderExceptionCode.CLIENT_CREDENTIALS_NOT_CONFIGURED:
+ case ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED:
+ case ConnectionProviderExceptionCode.REFRESH_FAILED:
+ case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
+ throw new InternalServerError(error);
+ default: {
+ return assertUnreachable(error.code);
+ }
+ }
+ }
+
+ throw error;
+};
diff --git a/packages/twenty-server/src/engine/core-modules/auth/services/update-connected-account-on-reconnect.service.ts b/packages/twenty-server/src/engine/core-modules/auth/services/update-connected-account-on-reconnect.service.ts
index 056c76d713e..48f3d18fdda 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/services/update-connected-account-on-reconnect.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/services/update-connected-account-on-reconnect.service.ts
@@ -60,6 +60,7 @@ export class UpdateConnectedAccountOnReconnectService {
refreshToken: encryptedRefreshToken,
scopes,
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
},
);
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account.dto.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account.dto.ts
index cd63f78d8bb..41ac2fd4365 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account.dto.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/dtos/connected-account.dto.ts
@@ -45,6 +45,11 @@ export class ConnectedAccountDTO {
@Field(() => Date, { nullable: true })
authFailedAt: Date | null;
+ @IsString()
+ @IsOptional()
+ @Field(() => String, { nullable: true })
+ authFailedReason: string | null;
+
// Set when the account is frozen after its owner is removed from the
// workspace: synced data is kept but the account is read-only.
@IsDateString()
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
index bfd2144fab6..6dcf8ba0089 100644
--- a/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/entities/connected-account.entity.ts
@@ -18,6 +18,7 @@ import { ApplicationEntity } from 'src/engine/core-modules/application/applicati
import { ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
import { type EncryptedImapSmtpCaldavParams } from 'src/engine/core-modules/imap-smtp-caldav-connection/types/imap-smtp-caldav-connection.type';
import { type EncryptedString } from 'src/engine/core-modules/secret-encryption/branded-strings/encrypted-string.type';
+import { WasIntroducedInUpgrade } from 'src/engine/core-modules/upgrade/decorators/was-introduced-in-upgrade.decorator';
import { type CalendarChannelEntity } from 'src/engine/metadata-modules/calendar-channel/entities/calendar-channel.entity';
import { type MessageChannelEntity } from 'src/engine/metadata-modules/message-channel/entities/message-channel.entity';
import { WorkspaceRelatedEntity } from 'src/engine/workspace-manager/types/workspace-related-entity';
@@ -66,6 +67,13 @@ export class ConnectedAccountEntity extends WorkspaceRelatedEntity {
@Column({ type: 'timestamptz', nullable: true })
authFailedAt: Date | null;
+ @Column({ type: 'varchar', nullable: true })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.40.0_AddAuthFailedReasonToConnectedAccountFastInstanceCommand_1788781233982',
+ })
+ authFailedReason: string | null;
+
@Column({ type: 'timestamptz', nullable: true })
archivedAt: Date | null;
diff --git a/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts b/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
index fe49aeab73c..2051861c17a 100644
--- a/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
+++ b/packages/twenty-server/src/modules/connected-account/services/imap-smtp-caldav-apis.service.ts
@@ -135,6 +135,7 @@ export class ImapSmtpCalDavApiService {
userWorkspaceId,
workspaceId,
authFailedAt: null,
+ authFailedReason: null,
archivedAt: null,
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts
new file mode 100644
index 00000000000..462431506c9
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/report-app-connection-auth-failure.integration-spec.ts
@@ -0,0 +1,344 @@
+import { gql } from 'graphql-tag';
+import { buildBaseManifest } from 'test/integration/metadata/suites/application/utils/build-base-manifest.util';
+import { cleanupApplicationAndAppRegistration } from 'test/integration/metadata/suites/application/utils/cleanup-application-and-app-registration.util';
+import { generateApplicationToken } from 'test/integration/metadata/suites/application/utils/generate-application-token.util';
+import { setupApplicationForSync } from 'test/integration/metadata/suites/application/utils/setup-application-for-sync.util';
+import { syncApplication } from 'test/integration/metadata/suites/application/utils/sync-application.util';
+import { findConnectionProvidersByApplication } from 'test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util';
+import { makeMetadataAPIRequest } from 'test/integration/metadata/suites/utils/make-metadata-api-request.util';
+import { type Manifest } from 'twenty-shared/application';
+import { ConnectedAccountProvider } from 'twenty-shared/types';
+import { v4 as uuidv4 } from 'uuid';
+
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const REPORT_AUTH_FAILURE_MUTATION = gql`
+ mutation ReportAppConnectionAuthFailure(
+ $input: ReportAppConnectionAuthFailureInput!
+ ) {
+ reportAppConnectionAuthFailure(input: $input)
+ }
+`;
+
+const OWNING_APP_ID = uuidv4();
+const OWNING_APP_ROLE_ID = uuidv4();
+const OWNING_APP_PROVIDER_ID = uuidv4();
+
+const OTHER_APP_ID = uuidv4();
+const OTHER_APP_ROLE_ID = uuidv4();
+const OTHER_APP_PROVIDER_ID = uuidv4();
+
+const buildManifestWithProvider = ({
+ appId,
+ roleId,
+ roleLabel,
+ providerId,
+}: {
+ appId: string;
+ roleId: string;
+ roleLabel: string;
+ providerId: string;
+}): Manifest =>
+ buildBaseManifest({
+ appId,
+ roleId,
+ overrides: {
+ roles: [
+ {
+ universalIdentifier: roleId,
+ label: roleLabel,
+ description: 'A test role',
+ },
+ ],
+ connectionProviders: [
+ {
+ universalIdentifier: providerId,
+ name: 'slack',
+ displayName: 'Slack',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint: 'https://slack.com/oauth/v2/authorize',
+ tokenEndpoint: 'https://slack.com/api/oauth.v2.access',
+ scopes: ['chat:write'],
+ clientIdVariable: 'SLACK_CLIENT_ID',
+ clientSecretVariable: 'SLACK_CLIENT_SECRET',
+ },
+ },
+ ],
+ },
+ });
+
+const findAuthFailure = async (
+ connectedAccountId: string,
+): Promise<{ authFailedAt: Date | null; authFailedReason: string | null }> => {
+ const [row] = await globalThis.testDataSource.query(
+ `SELECT "authFailedAt", "authFailedReason"
+ FROM core."connectedAccount" WHERE id = $1`,
+ [connectedAccountId],
+ );
+
+ return row;
+};
+
+describe('reportAppConnectionAuthFailure resolver (e2e)', () => {
+ let owningApplicationToken: string;
+ let adminUserWorkspaceId: string;
+ let owningApplicationDbId: string;
+ let owningProviderDbId: string;
+ let otherApplicationDbId: string;
+ let otherProviderDbId: string;
+
+ const insertAppConnection = async ({
+ id,
+ applicationId,
+ connectionProviderId,
+ visibility,
+ userWorkspaceId,
+ provider = ConnectedAccountProvider.APP,
+ }: {
+ id: string;
+ applicationId: string;
+ connectionProviderId: string;
+ visibility: 'user' | 'workspace';
+ userWorkspaceId: string;
+ provider?: ConnectedAccountProvider;
+ }): Promise<void> => {
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."connectedAccount"
+ (id, handle, provider, visibility, "workspaceId", "userWorkspaceId",
+ "applicationId", "connectionProviderId")
+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8)`,
+ [
+ id,
+ provider,
+ visibility,
+ SEED_APPLE_WORKSPACE_ID,
+ userWorkspaceId,
+ applicationId,
+ connectionProviderId,
+ ],
+ );
+ };
+
+ const reportAuthFailure = ({
+ id,
+ reason,
+ token = owningApplicationToken,
+ }: {
+ id: string;
+ reason?: string;
+ token?: string;
+ }) =>
+ makeMetadataAPIRequest(
+ {
+ query: REPORT_AUTH_FAILURE_MUTATION,
+ variables: { input: { id, reason } },
+ },
+ token,
+ );
+
+ beforeAll(async () => {
+ for (const { appId, roleId, providerId, sourcePath } of [
+ {
+ appId: OWNING_APP_ID,
+ roleId: OWNING_APP_ROLE_ID,
+ providerId: OWNING_APP_PROVIDER_ID,
+ sourcePath: 'test-report-auth-failure-owner',
+ },
+ {
+ appId: OTHER_APP_ID,
+ roleId: OTHER_APP_ROLE_ID,
+ providerId: OTHER_APP_PROVIDER_ID,
+ sourcePath: 'test-report-auth-failure-other',
+ },
+ ]) {
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: appId,
+ name: sourcePath,
+ description: 'App for testing auth-failure reporting',
+ sourcePath,
+ });
+
+ await syncApplication({
+ manifest: buildManifestWithProvider({
+ appId,
+ roleId,
+ roleLabel: `Test Role ${sourcePath}`,
+ providerId,
+ }),
+ expectToFail: false,
+ });
+ }
+
+ jest.useRealTimers();
+
+ const [owningProvider] =
+ await findConnectionProvidersByApplication(OWNING_APP_ID);
+ const [otherProvider] =
+ await findConnectionProvidersByApplication(OTHER_APP_ID);
+
+ owningApplicationDbId = owningProvider.applicationId;
+ owningProviderDbId = owningProvider.id;
+ otherApplicationDbId = otherProvider.applicationId;
+ otherProviderDbId = otherProvider.id;
+
+ const [userWorkspace] = await globalThis.testDataSource.query(
+ `SELECT id FROM core."userWorkspace" WHERE "workspaceId" = $1 LIMIT 1`,
+ [SEED_APPLE_WORKSPACE_ID],
+ );
+
+ adminUserWorkspaceId = userWorkspace.id;
+
+ // Minted with the admin token, so it carries that admin's userWorkspaceId
+ // alongside the owning applicationId.
+ const { data } = await generateApplicationToken({
+ applicationId: owningApplicationDbId,
+ expectToFail: false,
+ });
+
+ owningApplicationToken =
+ data.generateApplicationToken.applicationAccessToken.token;
+ }, 180000);
+
+ afterEach(async () => {
+ await globalThis.testDataSource.query(
+ `DELETE FROM core."connectedAccount" WHERE "workspaceId" = $1
+ AND "applicationId" IN ($2, $3)`,
+ [SEED_APPLE_WORKSPACE_ID, owningApplicationDbId, otherApplicationDbId],
+ );
+ });
+
+ afterAll(async () => {
+ for (const appId of [OWNING_APP_ID, OTHER_APP_ID]) {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: appId,
+ });
+ }
+ }, 120000);
+
+ it('marks the calling application own connection as auth-failed with the reason', async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: owningApplicationDbId,
+ connectionProviderId: owningProviderDbId,
+ visibility: 'workspace',
+ userWorkspaceId: adminUserWorkspaceId,
+ });
+
+ const response = await reportAuthFailure({
+ id: connectedAccountId,
+ reason: 'Slack rejected the stored token (invalid_auth)',
+ });
+
+ expect(response.body.errors).toBeUndefined();
+ expect(response.body.data.reportAppConnectionAuthFailure).toBe(true);
+
+ const { authFailedAt, authFailedReason } =
+ await findAuthFailure(connectedAccountId);
+
+ expect(authFailedAt).not.toBeNull();
+ expect(authFailedReason).toBe(
+ 'Slack rejected the stored token (invalid_auth)',
+ );
+ });
+
+ it('leaves the reason empty when the caller gives none', async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: owningApplicationDbId,
+ connectionProviderId: owningProviderDbId,
+ visibility: 'workspace',
+ userWorkspaceId: adminUserWorkspaceId,
+ });
+
+ const response = await reportAuthFailure({ id: connectedAccountId });
+
+ expect(response.body.errors).toBeUndefined();
+
+ const { authFailedAt, authFailedReason } =
+ await findAuthFailure(connectedAccountId);
+
+ expect(authFailedAt).not.toBeNull();
+ expect(authFailedReason).toBeNull();
+ });
+
+ it('refuses a connection owned by another application', async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: otherApplicationDbId,
+ connectionProviderId: otherProviderDbId,
+ visibility: 'workspace',
+ userWorkspaceId: adminUserWorkspaceId,
+ });
+
+ const response = await reportAuthFailure({
+ id: connectedAccountId,
+ reason: 'Should never be written',
+ });
+
+ expect(response.body.errors).toBeDefined();
+ expect(await findAuthFailure(connectedAccountId)).toEqual({
+ authFailedAt: null,
+ authFailedReason: null,
+ });
+ });
+
+ it("refuses another user's user-visibility connection", async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: owningApplicationDbId,
+ connectionProviderId: owningProviderDbId,
+ visibility: 'user',
+ userWorkspaceId: uuidv4(),
+ });
+
+ const response = await reportAuthFailure({
+ id: connectedAccountId,
+ reason: 'Should never be written',
+ });
+
+ expect(response.body.errors).toBeDefined();
+ expect(await findAuthFailure(connectedAccountId)).toEqual({
+ authFailedAt: null,
+ authFailedReason: null,
+ });
+ });
+
+ it('rejects a reason longer than 1000 characters without touching the row', async () => {
+ const connectedAccountId = uuidv4();
+
+ await insertAppConnection({
+ id: connectedAccountId,
+ applicationId: owningApplicationDbId,
+ connectionProviderId: owningProviderDbId,
+ visibility: 'workspace',
+ userWorkspaceId: adminUserWorkspaceId,
+ });
+
+ const response = await reportAuthFailure({
+ id: connectedAccountId,
+ reason: 'a'.repeat(1001),
+ });
+
+ expect(response.body.errors).toBeDefined();
+ expect(await findAuthFailure(connectedAccountId)).toEqual({
+ authFailedAt: null,
+ authFailedReason: null,
+ });
+ });
+
+ it('refuses an unknown connection id', async () => {
+ const response = await reportAuthFailure({ id: uuidv4() });
+
+ expect(response.body.errors).toBeDefined();
+ });
+});
diff --git a/packages/twenty-shared/src/application/appConnectionType.ts b/packages/twenty-shared/src/application/appConnectionType.ts
index 6735ff56a60..cdcd769c93a 100644
--- a/packages/twenty-shared/src/application/appConnectionType.ts
+++ b/packages/twenty-shared/src/application/appConnectionType.ts
@@ -37,7 +37,10 @@ export type AppConnection = {
// token issuance (may be a subset of what the app requested).
scopes: string[];
// Set when the most recent refresh attempt failed permanently
- // (4xx invalid_grant); the user must reconnect from the app's settings tab.
- // Apps should surface this so users know to take action.
+ // (4xx invalid_grant), or when the app reported the credential dead via
+ // `reportConnectionAuthFailure`; the user must reconnect from the app's
+ // settings tab. Apps should surface this so users know to take action.
authFailedAt: string | null;
+ // Human-readable explanation for `authFailedAt`, when the reporter gave one.
+ authFailedReason: string | null;
};