Skip to content

The open alternative to Salesforce, designed for AI.

Identify the upstream account before saving an app connection (#27954)

nitin7b714e0b2605
diff --git a/packages/twenty-agent-skills/references/develop-app/logic.md b/packages/twenty-agent-skills/references/develop-app/logic.md
index c3371b53d3b..980b2544c18 100644
--- a/packages/twenty-agent-skills/references/develop-app/logic.md
+++ b/packages/twenty-agent-skills/references/develop-app/logic.md
@@ -99,6 +99,7 @@ For third-party connections:
- Keep secrets out of source and public assets.
- Document required OAuth or API setup in the app README or listing.
- Verify failure states for expired or missing credentials.
+- When the provider can say which account a token belongs to (team, organization, user), declare `identifyAccountLogicFunction` so a reconnect that authorizes a different account is refused instead of overwriting the connection. Write the handler as one request to the provider's "who am I" endpoint, return the id as a string, and return `{ externalAccountId: null }` when there is no stable id.
## Post-Install Hooks
diff --git a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
index 892a87da755..0f5645f2ef5 100644
--- a/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
+++ b/packages/twenty-cli/src/app/manifest/__tests__/manifest-validate.spec.ts
@@ -336,7 +336,11 @@ describe('manifestValidate', () => {
);
});
- it.each(['onConnectLogicFunction', 'onDisconnectLogicFunction'] as const)(
+ it.each([
+ 'identifyAccountLogicFunction',
+ 'onConnectLogicFunction',
+ 'onDisconnectLogicFunction',
+ ] as const)(
'should not flag a connection provider referencing a logic function via %s as a duplicate',
(lifecycleHookKey) => {
const logicFunctionId = '550e8400-e29b-41d4-a716-446655440040';
diff --git a/packages/twenty-cli/src/app/manifest/manifest-validate.ts b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
index 838aaaa7b32..648921c5da5 100644
--- a/packages/twenty-cli/src/app/manifest/manifest-validate.ts
+++ b/packages/twenty-cli/src/app/manifest/manifest-validate.ts
@@ -66,6 +66,7 @@ const findUniversalIdentifiers = (obj: object): string[] => {
key === 'preInstallLogicFunction' ||
key === 'uninstallLogicFunction' ||
key === 'healthCheckLogicFunction' ||
+ key === 'identifyAccountLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
key === 'settingsFrontComponent'
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
index 3798f3cb7ee..43c60a4f2b1 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.graphql
@@ -290,6 +290,7 @@ type AppConnection {
accessToken: String!
authFailedAt: String
authFailedReason: String
+ externalAccountId: String
handle: String!
id: ID!
name: String!
diff --git a/packages/twenty-client-sdk/src/metadata/generated/schema.ts b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
index b66b12c1ea1..66226a019c5 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/schema.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/schema.ts
@@ -232,6 +232,7 @@ export interface AppConnection {
accessToken: Scalars['String']
authFailedAt?: Scalars['String']
authFailedReason?: Scalars['String']
+ externalAccountId?: Scalars['String']
handle: Scalars['String']
id: Scalars['ID']
name: Scalars['String']
@@ -4182,6 +4183,7 @@ export interface AppConnectionGenqlSelection{
accessToken?: boolean | number
authFailedAt?: boolean | number
authFailedReason?: boolean | number
+ externalAccountId?: boolean | number
handle?: boolean | number
id?: boolean | number
name?: boolean | number
diff --git a/packages/twenty-client-sdk/src/metadata/generated/types.ts b/packages/twenty-client-sdk/src/metadata/generated/types.ts
index e98e3894084..01ff653dbf8 100644
--- a/packages/twenty-client-sdk/src/metadata/generated/types.ts
+++ b/packages/twenty-client-sdk/src/metadata/generated/types.ts
@@ -654,6 +654,9 @@ export default {
"authFailedReason": [
1
],
+ "externalAccountId": [
+ 1
+ ],
"handle": [
1
],
diff --git a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
index 0b172d93c12..93ff377cdc1 100644
--- a/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
+++ b/packages/twenty-docs/developers/extend/apps/logic/connections.mdx
@@ -45,6 +45,10 @@ export default defineConnectionProvider({
// Optional: provider's RFC 7009 token revocation endpoint, called on disconnect.
// revokeEndpoint: 'https://example.com/oauth/revoke',
},
+ // Optional: a logic function in this app that returns a stable id for the
+ // upstream account, run before the tokens are saved. See "Identify the
+ // connected account".
+ // identifyAccountLogicFunction: { universalIdentifier: '2f1e0d9c-...-...' },
// Optional: a logic function in this app to run right after a connection is
// established. See "Run a logic function on connect".
// onConnectLogicFunction: { universalIdentifier: '3a2b1c0d-...-...' },
@@ -97,6 +101,100 @@ https://<your-twenty-server>/auth/apps/callback
</Accordion>
+<Accordion title="Identify the connected account" description="Stop a reconnect from silently switching upstream accounts">
+
+When a user clicks **Reconnect**, nothing stops them from authorizing a different upstream account than the one the connection was made with: Slack workspace B instead of workspace A, another GitHub organization, another Google account. Without a way to tell the two apart, Twenty would overwrite A's tokens with B's and everything your app built on that connection would quietly start talking to B.
+
+Set `identifyAccountLogicFunction` to a logic function in the same app that returns a stable id for the account behind the freshly issued token:
+
+```ts src/connection-providers/slack-connection.ts
+import { defineConnectionProvider } from 'twenty-sdk/define';
+
+import { SLACK_IDENTIFY_ACCOUNT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+
+export default defineConnectionProvider({
+ universalIdentifier: '...',
+ name: 'slack',
+ displayName: 'Slack',
+ type: 'oauth',
+ oauth: {
+ /* ... */
+ },
+ identifyAccountLogicFunction: {
+ universalIdentifier: SLACK_IDENTIFY_ACCOUNT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ },
+});
+```
+
+**When it runs.** Synchronously inside the OAuth callback, right after the authorization code is exchanged for tokens and **before** anything is saved. The user is waiting on the redirect, so when the app is installed or synced Twenty caps the function's `timeoutSeconds` at 10, whatever the manifest declares; keep it to a single request to the provider's "who am I" endpoint. The on-connect hook, if any, still runs afterwards, once the connection is saved.
+
+**Payload.** The handler receives the provisional access token. It has not been persisted yet, so `getConnection` cannot return it; use it directly and do not log it.
+
+```ts
+type IdentifyAccountPayload = {
+ connectionProviderId: string;
+ connectionProviderName: string; // e.g. 'slack'
+ accessToken: string;
+};
+```
+
+**Result.** Return the account's id, and optionally a handle to display:
+
+```ts
+type IdentifyAccountResult = {
+ externalAccountId: string | null; // non-empty, at most 512 characters; null opts out
+ handle?: string; // non-empty when present
+};
+```
+
+- `externalAccountId` must be stable for the life of the upstream account (a team id, an organization id, a user id), never a name the user can change. Twenty trims it and stores it on the connection on first connect.
+- `handle`, when returned, replaces the handle Twenty would otherwise derive (the OIDC `id_token` email, or the connecting user's email). Return something a user recognizes, such as the Slack workspace name.
+- Return `{ externalAccountId: null }` when the provider has no stable id to offer. Twenty then behaves as if no identify function were declared: no id is stored, a reconnect clears any id stored earlier, and reconnects are not checked. A bare `null` or a missing return is treated as an error, so a handler that forgets to return cannot silently disable the check.
+- If the function throws, times out, or returns anything else, the connection is **not** saved and the user lands back on the settings page with an error. Throw only when you genuinely cannot identify the account.
+
+**Reconnect refusal.** On a reconnect, Twenty compares the returned `externalAccountId` with the one stored on the connection. If they differ, the callback is refused before anything is written: the existing tokens, handle and visibility stay as they were, the on-connect hook does not run, and the user sees which account they authorized and which one the connection belongs to. Connections created before your app declared the function have no stored id yet; their next reconnect stores it.
+
+Twenty does not deduplicate on `externalAccountId`: connecting the same upstream account twice through **Add connection** creates two connections. The id is exposed on `listConnections` and `getConnection`, so an app that wants one connection per upstream account can detect duplicates itself (for instance in its on-connect hook).
+
+**Writing the function.** Most providers expose a single endpoint that describes the current token. For Slack that is `auth.test`, which returns the workspace (`team_id`, `team`) and the user behind the token:
+
+```ts src/logic-functions/slack-identify-account.ts
+import { defineLogicFunction } from 'twenty-sdk/define';
+import type {
+ IdentifyAccountPayload,
+ IdentifyAccountResult,
+} from 'twenty-sdk/logic-function';
+
+import { SLACK_IDENTIFY_ACCOUNT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER } from 'src/constants/universal-identifiers';
+
+export default defineLogicFunction({
+ universalIdentifier: SLACK_IDENTIFY_ACCOUNT_LOGIC_FUNCTION_UNIVERSAL_IDENTIFIER,
+ name: 'slack-identify-account',
+ timeoutSeconds: 10,
+ handler: async ({
+ accessToken,
+ }: IdentifyAccountPayload): Promise<IdentifyAccountResult> => {
+ const response = await fetch('https://slack.com/api/auth.test', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${accessToken}` },
+ });
+ const { ok, error, team_id, team } = await response.json();
+
+ if (!ok) {
+ throw new Error(`auth.test failed: ${error}`);
+ }
+
+ return { externalAccountId: team_id, handle: team };
+ },
+});
+```
+
+Other providers follow the same pattern, whether their "who am I" endpoint is REST or GraphQL. Throw when the provider rejects the token, and return the id as a string: convert numeric ids, such as GitHub user ids, with `String(id)`.
+
+Identification ships with Twenty 2.48.0. If your app relies on it, declare `"engines": { "twenty": ">=2.48.0" }` in its `package.json`.
+
+</Accordion>
+
<Accordion title="Run a logic function on connect" description="React the moment a connection is established">
Some providers hand you data at connect time that you need to persist before the connection is usable — the classic example is Slack, where the OAuth response identifies the workspace's `team_id` that inbound events will be keyed by. Set `onConnectLogicFunction` to reference a logic function in the same app (by its `universalIdentifier`), and it runs right after the `ConnectedAccount` is created.
@@ -225,7 +323,8 @@ Each connection has:
| `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 |
+| `handle` | The connected upstream account's label, refreshed on each reconnect: the `handle` returned by the identify function when there is one, otherwise the email from the OIDC `id_token` returned at token exchange, falling back to the connecting Twenty user's email |
+| `externalAccountId` | Stable id of the upstream account returned by the identify function, or `null` when the provider declares none or the connection predates it. Not unique: use it to deduplicate connections yourself |
| `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 |
diff --git a/packages/twenty-front/src/generated-metadata/graphql.ts b/packages/twenty-front/src/generated-metadata/graphql.ts
index 5fd43970dac..df533d80be4 100644
--- a/packages/twenty-front/src/generated-metadata/graphql.ts
+++ b/packages/twenty-front/src/generated-metadata/graphql.ts
@@ -330,6 +330,7 @@ export type AppConnection = {
accessToken: Scalars['String']['output'];
authFailedAt?: Maybe<Scalars['String']['output']>;
authFailedReason?: Maybe<Scalars['String']['output']>;
+ externalAccountId?: Maybe<Scalars['String']['output']>;
handle: Scalars['String']['output'];
id: Scalars['ID']['output'];
name: Scalars['String']['output'];
diff --git a/packages/twenty-sdk/package.json b/packages/twenty-sdk/package.json
index 5c9dfd679b6..cfd9f9b45de 100644
--- a/packages/twenty-sdk/package.json
+++ b/packages/twenty-sdk/package.json
@@ -115,7 +115,7 @@
"engines": {
"node": "^24.5.0",
"yarn": "^4.0.2",
- "twenty": ">=2.40.0"
+ "twenty": ">=2.48.0"
},
"typesVersions": {
"*": {
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
index 57f5137666a..f3fec4f718c 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/__tests__/manifest-validate.spec.ts
@@ -204,7 +204,11 @@ describe('manifestValidate', () => {
);
});
- it.each(['onConnectLogicFunction', 'onDisconnectLogicFunction'] as const)(
+ it.each([
+ 'identifyAccountLogicFunction',
+ 'onConnectLogicFunction',
+ 'onDisconnectLogicFunction',
+ ] as const)(
'should not flag a connection provider referencing a logic function via %s as a duplicate',
(lifecycleHookKey) => {
const logicFunctionId = '550e8400-e29b-41d4-a716-446655440040';
diff --git a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
index 1403f5eccda..10311b2398e 100644
--- a/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
+++ b/packages/twenty-sdk/src/cli/utilities/build/manifest/manifest-validate.ts
@@ -64,6 +64,7 @@ const findUniversalIdentifiers = (obj: object): string[] => {
key === 'preInstallLogicFunction' ||
key === 'uninstallLogicFunction' ||
key === 'healthCheckLogicFunction' ||
+ key === 'identifyAccountLogicFunction' ||
key === 'onConnectLogicFunction' ||
key === 'onDisconnectLogicFunction' ||
key === 'settingsFrontComponent'
diff --git a/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts b/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
index 7c956ad8050..2bb6933880b 100644
--- a/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
+++ b/packages/twenty-sdk/src/sdk/define/connection-providers/__tests__/define-connection-provider.spec.ts
@@ -84,6 +84,7 @@ describe('defineConnectionProvider', () => {
});
const lifecycleHookKeys = [
+ 'identifyAccountLogicFunction',
'onConnectLogicFunction',
'onDisconnectLogicFunction',
] as const;
diff --git a/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts b/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
index 4b1606b2f9d..aa3eb697120 100644
--- a/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
+++ b/packages/twenty-sdk/src/sdk/define/connection-providers/define-connection-provider.ts
@@ -7,15 +7,16 @@ import { isDefined } from 'twenty-shared/utils';
const PROVIDER_NAME_PATTERN = /^[a-z][a-z0-9-]*$/;
const SUPPORTED_TYPES = ['oauth'] as const;
-type ConnectionProviderLifecycleHookKey = Extract<
+type ConnectionProviderLogicFunctionKey = Extract<
keyof ConnectionProviderManifest,
- `on${string}LogicFunction`
+ `${string}LogicFunction`
>;
-const LIFECYCLE_HOOK_KEYS = [
+const LOGIC_FUNCTION_KEYS = [
+ 'identifyAccountLogicFunction',
'onConnectLogicFunction',
'onDisconnectLogicFunction',
-] as const satisfies readonly ConnectionProviderLifecycleHookKey[];
+] as const satisfies readonly ConnectionProviderLogicFunctionKey[];
export const defineConnectionProvider: DefineEntity<
ConnectionProviderManifest
@@ -42,12 +43,15 @@ export const defineConnectionProvider: DefineEntity<
errors.push('Connection provider must have a displayName');
}
- for (const hookKey of LIFECYCLE_HOOK_KEYS) {
- const hook = config[hookKey];
+ for (const logicFunctionKey of LOGIC_FUNCTION_KEYS) {
+ const logicFunction = config[logicFunctionKey];
- if (isDefined(hook) && !isValidPostgresUuid(hook.universalIdentifier)) {
+ if (
+ isDefined(logicFunction) &&
+ !isValidPostgresUuid(logicFunction.universalIdentifier)
+ ) {
errors.push(
- `Connection provider ${hookKey}.universalIdentifier "${hook.universalIdentifier}" must be the UUID universalIdentifier of a logic function in this app.`,
+ `Connection provider ${logicFunctionKey}.universalIdentifier "${logicFunction.universalIdentifier}" must be the UUID universalIdentifier of a logic function in this app.`,
);
}
}
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 80908ae49dd..f7f06c6db9e 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
@@ -10,6 +10,7 @@ const buildConnection = (
providerName: 'linear',
name: 'Linear #1',
handle: '[email protected]',
+ externalAccountId: null,
visibility: 'user',
userWorkspaceId: 'uws-me',
workspaceMemberId: 'wm-me',
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 39820122f54..9e2aa2f762d 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
@@ -19,6 +19,7 @@ const buildConnection = (
providerName: 'linear',
name: 'Linear #1',
handle: '[email protected]',
+ externalAccountId: null,
visibility: 'user',
userWorkspaceId: 'uws-me',
workspaceMemberId: 'wm-me',
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 3417d7089f3..bb5cdd683f3 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
@@ -9,6 +9,7 @@ const GET_APP_CONNECTION_QUERY = `
providerName
name
handle
+ externalAccountId
visibility
userWorkspaceId
workspaceMemberId
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 a71c2e841fa..f2edffd2d86 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
@@ -8,6 +8,7 @@ const LIST_APP_CONNECTIONS_QUERY = `
providerName
name
handle
+ externalAccountId
visibility
userWorkspaceId
workspaceMemberId
diff --git a/packages/twenty-sdk/src/sdk/logic-function/index.ts b/packages/twenty-sdk/src/sdk/logic-function/index.ts
index 77c0709d955..c27cf6f21f9 100644
--- a/packages/twenty-sdk/src/sdk/logic-function/index.ts
+++ b/packages/twenty-sdk/src/sdk/logic-function/index.ts
@@ -49,6 +49,10 @@ export { findConnectionForRequest } from '@/sdk/logic-function/connections/find-
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';
+export type {
+ IdentifyAccountPayload,
+ IdentifyAccountResult,
+} from 'twenty-shared/application';
export { createMessageChannel } from '@/sdk/logic-function/messaging/create-message-channel';
export type { CreateMessageChannelInput } from '@/sdk/logic-function/messaging/create-message-channel';
diff --git a/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1791975194413-add-identify-account-logic-function-and-external-account-id.ts b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1791975194413-add-identify-account-logic-function-and-external-account-id.ts
new file mode 100644
index 00000000000..4060a27a77e
--- /dev/null
+++ b/packages/twenty-server/src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1791975194413-add-identify-account-logic-function-and-external-account-id.ts
@@ -0,0 +1,25 @@
+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.48.0', 1791975194413)
+export class AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand implements FastInstanceCommand {
+ public async up(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectionProvider" ADD "identifyAccountLogicFunctionUniversalIdentifier" uuid',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" ADD "externalAccountId" character varying(512)',
+ );
+ }
+
+ public async down(queryRunner: QueryRunner): Promise<void> {
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectedAccount" DROP COLUMN "externalAccountId"',
+ );
+ await queryRunner.query(
+ 'ALTER TABLE "core"."connectionProvider" DROP COLUMN "identifyAccountLogicFunctionUniversalIdentifier"',
+ );
+ }
+}
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 e0aecfbfe38..efc50c84126 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
@@ -241,6 +241,7 @@ import { RestoreUsageLimitMeterCompatibilityFastInstanceCommand } from 'src/data
import { DropUsageLimitMeterFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-instance-command-fast-1791720497488-drop-usage-limit-meter';
import { SetWorkspaceEventLogRetentionDefaultFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-instance-command-fast-1791790299002-set-workspace-event-log-retention-default';
import { AddWidgetAvailabilityToFrontComponentFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-47/2-47-instance-command-fast-1791898075681-add-widget-availability-to-front-component';
+import { AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand } from 'src/database/commands/upgrade-version-command/2-48/2-48-instance-command-fast-1791975194413-add-identify-account-logic-function-and-external-account-id';
export const INSTANCE_COMMANDS = [
AddViewFieldGroupIdIndexOnViewFieldFastInstanceCommand,
@@ -484,4 +485,5 @@ export const INSTANCE_COMMANDS = [
DropUsageLimitMeterFastInstanceCommand,
SetWorkspaceEventLogRetentionDefaultFastInstanceCommand,
AddWidgetAvailabilityToFrontComponentFastInstanceCommand,
+ AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand,
];
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
index 64eda7d2681..c3f0657f749 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/application-manifest-migration.service.ts
@@ -12,6 +12,7 @@ import { preallocateWorkflowReferenceIds } from 'src/engine/core-modules/applica
import { buildAllFlatEntityOperationRecordByMetadataNameFromFromTo } from 'src/engine/core-modules/application/application-manifest/utils/build-all-flat-entity-operation-record-by-metadata-name-from-from-to.util';
import { buildFromToAllUniversalFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/build-from-to-all-universal-flat-entity-maps.util';
import { getApplicationSubAllFlatEntityMaps } from 'src/engine/core-modules/application/application-manifest/utils/get-application-sub-all-flat-entity-maps.util';
+import { assertConnectionProviderLogicFunctionsAreOwn } from 'src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util';
import { resolveApplicationReferenceIdOrThrow } from 'src/engine/core-modules/application/application-manifest/utils/resolve-application-reference-id-or-throw.util';
import {
ApplicationException,
@@ -211,6 +212,14 @@ export class ApplicationManifestMigrationService {
workspaceId,
});
+ assertConnectionProviderLogicFunctionsAreOwn({
+ manifest,
+ fromFlatLogicFunctionMaps: fromAllFlatEntityMaps.flatLogicFunctionMaps,
+ toFlatLogicFunctionMaps:
+ toAllUniversalFlatEntityMaps.flatLogicFunctionMaps,
+ inferDeletionFromMissingEntities,
+ });
+
const idByUniversalIdentifierByMetadataName =
(manifest.workflows ?? []).length > 0
? preallocateWorkflowReferenceIds({
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
index 2997484d6ae..6f5e48078d8 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-connection-provider-manifest-to-universal-flat-connection-provider.util.spec.ts
@@ -51,6 +51,7 @@ describe('fromConnectionProviderManifestToUniversalFlatConnectionProvider', () =
tokenRequestContentType: 'json',
usePkce: true,
},
+ identifyAccountLogicFunctionUniversalIdentifier: null,
onConnectLogicFunctionUniversalIdentifier: null,
onDisconnectLogicFunctionUniversalIdentifier: null,
createdAt: NOW,
@@ -71,6 +72,27 @@ describe('fromConnectionProviderManifestToUniversalFlatConnectionProvider', () =
expect(result.logo).toBe('public/linear-logomark.svg');
});
+ it('resolves the identifyAccountLogicFunction universalIdentifier into the flat field when provided', () => {
+ const identifyAccountLogicFunctionUniversalIdentifier =
+ 'e3e3e3e3-e3e3-4e3e-e3e3-e3e3e3e3e3e3';
+
+ const result =
+ fromConnectionProviderManifestToUniversalFlatConnectionProvider({
+ connectionProviderManifest: buildManifest({
+ identifyAccountLogicFunction: {
+ universalIdentifier:
+ identifyAccountLogicFunctionUniversalIdentifier,
+ },
+ }),
+ applicationUniversalIdentifier: APP_UID,
+ now: NOW,
+ });
+
+ expect(result.identifyAccountLogicFunctionUniversalIdentifier).toBe(
+ identifyAccountLogicFunctionUniversalIdentifier,
+ );
+ });
+
it('resolves the onConnectLogicFunction universalIdentifier into the flat field when provided', () => {
const onConnectLogicFunctionUniversalIdentifier =
'c1c1c1c1-c1c1-4c1c-c1c1-c1c1c1c1c1c1';
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
index dca8a318418..8eb84bef243 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/__tests__/from-logic-function-manifest-to-universal-flat-logic-function.util.spec.ts
@@ -2,6 +2,7 @@ import { type LogicFunctionManifest } from 'twenty-shared/application';
import { fromLogicFunctionManifestToUniversalFlatLogicFunction } from 'src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { IDENTIFY_ACCOUNT_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant';
import { createEmptyFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/constant/create-empty-flat-entity-maps.constant';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { LogicFunctionExecutionMode } from 'src/engine/metadata-modules/logic-function/logic-function.entity';
@@ -44,19 +45,58 @@ describe('fromLogicFunctionManifestToUniversalFlatLogicFunction', () => {
logicFunctionManifest = buildLogicFunctionManifest(),
applicationSourceType,
existingFlatLogicFunctionMaps = emptyFlatLogicFunctionMaps,
+ identifyAccountLogicFunctionUniversalIdentifiers = new Set<string>(),
}: {
logicFunctionManifest?: LogicFunctionManifest;
applicationSourceType: ApplicationRegistrationSourceType;
existingFlatLogicFunctionMaps?: AllFlatEntityMaps['flatLogicFunctionMaps'];
+ identifyAccountLogicFunctionUniversalIdentifiers?: Set<string>;
}) =>
fromLogicFunctionManifestToUniversalFlatLogicFunction({
logicFunctionManifest,
applicationUniversalIdentifier,
applicationSourceType,
existingFlatLogicFunctionMaps,
+ identifyAccountLogicFunctionUniversalIdentifiers,
now,
});
+ it('caps the timeout of a function a connection provider uses to identify accounts', () => {
+ const result = convert({
+ logicFunctionManifest: buildLogicFunctionManifest({
+ timeoutSeconds: 120,
+ }),
+ applicationSourceType: ApplicationRegistrationSourceType.LOCAL,
+ identifyAccountLogicFunctionUniversalIdentifiers: new Set([
+ logicFunctionUniversalIdentifier,
+ ]),
+ });
+
+ expect(result.timeoutSeconds).toBe(IDENTIFY_ACCOUNT_TIMEOUT_SECONDS);
+ });
+
+ it('keeps a shorter timeout on an identify function and the declared one elsewhere', () => {
+ expect(
+ convert({
+ logicFunctionManifest: buildLogicFunctionManifest({
+ timeoutSeconds: 5,
+ }),
+ applicationSourceType: ApplicationRegistrationSourceType.LOCAL,
+ identifyAccountLogicFunctionUniversalIdentifiers: new Set([
+ logicFunctionUniversalIdentifier,
+ ]),
+ }).timeoutSeconds,
+ ).toBe(5);
+ expect(
+ convert({
+ logicFunctionManifest: buildLogicFunctionManifest({
+ timeoutSeconds: 120,
+ }),
+ applicationSourceType: ApplicationRegistrationSourceType.LOCAL,
+ }).timeoutSeconds,
+ ).toBe(120);
+ });
+
it.each([
ApplicationRegistrationSourceType.TARBALL,
ApplicationRegistrationSourceType.NPM,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
index 9392cec27af..fa3fc9e411c 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-connection-provider-manifest-to-universal-flat-connection-provider.util.ts
@@ -44,6 +44,9 @@ export const fromConnectionProviderManifestToUniversalFlatConnectionProvider =
logo: connectionProviderManifest.logo ?? null,
type: connectionProviderManifest.type,
oauthConfig,
+ identifyAccountLogicFunctionUniversalIdentifier:
+ connectionProviderManifest.identifyAccountLogicFunction
+ ?.universalIdentifier ?? null,
onConnectLogicFunctionUniversalIdentifier:
connectionProviderManifest.onConnectLogicFunction
?.universalIdentifier ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
index e5b7698ec8e..13bb1203e70 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/converters/from-logic-function-manifest-to-universal-flat-logic-function.util.ts
@@ -5,6 +5,7 @@ import { type LogicFunctionManifest } from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { ApplicationRegistrationSourceType } from 'src/engine/core-modules/application/application-registration/enums/application-registration-source-type.enum';
+import { IDENTIFY_ACCOUNT_TIMEOUT_SECONDS } from 'src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant';
import { isPackagedApplicationSource } from 'src/engine/core-modules/application/application-registration/utils/is-packaged-application-source.util';
import { type AllFlatEntityMaps } from 'src/engine/metadata-modules/flat-entity/types/all-flat-entity-maps.type';
import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
@@ -55,24 +56,32 @@ export const fromLogicFunctionManifestToUniversalFlatLogicFunction = ({
applicationUniversalIdentifier,
applicationSourceType,
existingFlatLogicFunctionMaps,
+ identifyAccountLogicFunctionUniversalIdentifiers,
now,
}: {
logicFunctionManifest: LogicFunctionManifest;
applicationUniversalIdentifier: string;
applicationSourceType: ApplicationRegistrationSourceType;
existingFlatLogicFunctionMaps: AllFlatEntityMaps['flatLogicFunctionMaps'];
+ identifyAccountLogicFunctionUniversalIdentifiers: Set<string>;
now: string;
}): UniversalFlatLogicFunction => {
const name =
logicFunctionManifest.name ?? parse(logicFunctionManifest.handlerName).name;
+ const timeoutSeconds = logicFunctionManifest.timeoutSeconds ?? 300;
+
return {
universalIdentifier: logicFunctionManifest.universalIdentifier,
applicationUniversalIdentifier,
name,
description: logicFunctionManifest.description ?? null,
runtime: LogicFunctionRuntime.NODE22,
- timeoutSeconds: logicFunctionManifest.timeoutSeconds ?? 300,
+ timeoutSeconds: identifyAccountLogicFunctionUniversalIdentifiers.has(
+ logicFunctionManifest.universalIdentifier,
+ )
+ ? Math.min(timeoutSeconds, IDENTIFY_ACCOUNT_TIMEOUT_SECONDS)
+ : timeoutSeconds,
sourceHandlerPath: logicFunctionManifest.sourceHandlerPath,
builtHandlerPath: logicFunctionManifest.builtHandlerPath,
handlerName: logicFunctionManifest.handlerName,
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
index bcc0808f5c5..3e5e5c948db 100644
--- a/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/services/compute-application-manifest-all-universal-flat-entity-maps.service.ts
@@ -212,6 +212,16 @@ export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
});
}
+ const identifyAccountLogicFunctionUniversalIdentifiers = new Set(
+ (manifest.connectionProviders ?? [])
+ .map(
+ (connectionProviderManifest) =>
+ connectionProviderManifest.identifyAccountLogicFunction
+ ?.universalIdentifier,
+ )
+ .filter(isDefined),
+ );
+
for (const logicFunctionManifest of manifest.logicFunctions) {
addUniversalFlatEntityToUniversalFlatEntityMapsThroughMutationOrThrow({
universalFlatEntity:
@@ -221,6 +231,7 @@ export class ComputeApplicationManifestAllUniversalFlatEntityMapsService {
applicationSourceType,
existingFlatLogicFunctionMaps:
fromAllFlatEntityMaps.flatLogicFunctionMaps,
+ identifyAccountLogicFunctionUniversalIdentifiers,
now,
}),
universalFlatEntityMapsToMutate:
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts
new file mode 100644
index 00000000000..20728b73d74
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/__tests__/assert-connection-provider-logic-functions-are-own.util.spec.ts
@@ -0,0 +1,125 @@
+import { type ConnectionProviderManifest } from 'twenty-shared/application';
+
+import { ApplicationException } from 'src/engine/core-modules/application/application.exception';
+import { assertConnectionProviderLogicFunctionsAreOwn } from 'src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util';
+import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
+
+const MANIFEST_LOGIC_FUNCTION_IDENTIFIER = 'manifest-logic-function';
+const EXISTING_LOGIC_FUNCTION_IDENTIFIER = 'existing-logic-function';
+const UNKNOWN_LOGIC_FUNCTION_IDENTIFIER = 'unknown-logic-function';
+
+const buildFlatLogicFunctionMaps = (
+ universalIdentifier: string,
+): UniversalFlatEntityMaps<SyncableFlatEntity> => ({
+ byUniversalIdentifier: {
+ [universalIdentifier]: {
+ id: `${universalIdentifier}-id`,
+ universalIdentifier,
+ applicationId: 'application-id',
+ workspaceId: 'workspace-id',
+ },
+ },
+});
+
+const buildConnectionProvider = (
+ hooks: Pick<
+ ConnectionProviderManifest,
+ | 'identifyAccountLogicFunction'
+ | 'onConnectLogicFunction'
+ | 'onDisconnectLogicFunction'
+ >,
+): ConnectionProviderManifest => ({
+ universalIdentifier: 'connection-provider',
+ name: 'provider',
+ displayName: 'Provider',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint: 'https://provider.example.com/authorize',
+ tokenEndpoint: 'https://provider.example.com/token',
+ scopes: [],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ ...hooks,
+});
+
+const assertHooks = ({
+ hooks,
+ inferDeletionFromMissingEntities,
+}: {
+ hooks: Parameters<typeof buildConnectionProvider>[0];
+ inferDeletionFromMissingEntities: boolean;
+}) =>
+ assertConnectionProviderLogicFunctionsAreOwn({
+ manifest: { connectionProviders: [buildConnectionProvider(hooks)] },
+ fromFlatLogicFunctionMaps: buildFlatLogicFunctionMaps(
+ EXISTING_LOGIC_FUNCTION_IDENTIFIER,
+ ),
+ toFlatLogicFunctionMaps: buildFlatLogicFunctionMaps(
+ MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ ),
+ inferDeletionFromMissingEntities,
+ });
+
+describe('assertConnectionProviderLogicFunctionsAreOwn', () => {
+ it('accepts hooks that reference a logic function of the manifest', () => {
+ expect(() =>
+ assertHooks({
+ hooks: {
+ identifyAccountLogicFunction: {
+ universalIdentifier: MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ onConnectLogicFunction: {
+ universalIdentifier: MANIFEST_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ },
+ inferDeletionFromMissingEntities: true,
+ }),
+ ).not.toThrow();
+ });
+
+ it.each([
+ 'identifyAccountLogicFunction',
+ 'onConnectLogicFunction',
+ 'onDisconnectLogicFunction',
+ ] as const)(
+ 'rejects %s when it references a logic function outside the application',
+ (hook) => {
+ expect(() =>
+ assertHooks({
+ hooks: {
+ [hook]: { universalIdentifier: UNKNOWN_LOGIC_FUNCTION_IDENTIFIER },
+ },
+ inferDeletionFromMissingEntities: true,
+ }),
+ ).toThrow(ApplicationException);
+ },
+ );
+
+ it('accepts an existing logic function of the application on a partial sync', () => {
+ expect(() =>
+ assertHooks({
+ hooks: {
+ onDisconnectLogicFunction: {
+ universalIdentifier: EXISTING_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ },
+ inferDeletionFromMissingEntities: false,
+ }),
+ ).not.toThrow();
+ });
+
+ it('rejects an existing logic function the sync is about to delete', () => {
+ expect(() =>
+ assertHooks({
+ hooks: {
+ onDisconnectLogicFunction: {
+ universalIdentifier: EXISTING_LOGIC_FUNCTION_IDENTIFIER,
+ },
+ },
+ inferDeletionFromMissingEntities: true,
+ }),
+ ).toThrow(ApplicationException);
+ });
+});
diff --git a/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts
new file mode 100644
index 00000000000..92e6b2b95c3
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/application-manifest/utils/assert-connection-provider-logic-functions-are-own.util.ts
@@ -0,0 +1,59 @@
+import { type Manifest } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+
+import {
+ ApplicationException,
+ ApplicationExceptionCode,
+} from 'src/engine/core-modules/application/application.exception';
+import { type SyncableFlatEntity } from 'src/engine/metadata-modules/flat-entity/types/flat-entity-from.type';
+import { findFlatEntityByUniversalIdentifier } from 'src/engine/metadata-modules/flat-entity/utils/find-flat-entity-by-universal-identifier.util';
+import { type UniversalFlatEntityMaps } from 'src/engine/workspace-manager/workspace-migration/universal-flat-entity/types/universal-flat-entity-maps.type';
+
+export const assertConnectionProviderLogicFunctionsAreOwn = ({
+ manifest,
+ fromFlatLogicFunctionMaps,
+ toFlatLogicFunctionMaps,
+ inferDeletionFromMissingEntities,
+}: {
+ manifest: Pick<Manifest, 'connectionProviders'>;
+ fromFlatLogicFunctionMaps: UniversalFlatEntityMaps<SyncableFlatEntity>;
+ toFlatLogicFunctionMaps: UniversalFlatEntityMaps<SyncableFlatEntity>;
+ inferDeletionFromMissingEntities: boolean;
+}): void => {
+ for (const connectionProvider of manifest.connectionProviders ?? []) {
+ for (const [hook, logicFunctionReference] of Object.entries({
+ identifyAccount: connectionProvider.identifyAccountLogicFunction,
+ onConnect: connectionProvider.onConnectLogicFunction,
+ onDisconnect: connectionProvider.onDisconnectLogicFunction,
+ })) {
+ if (!isDefined(logicFunctionReference)) {
+ continue;
+ }
+
+ const { universalIdentifier } = logicFunctionReference;
+
+ // fromFlatLogicFunctionMaps only holds this application's functions, which a partial sync keeps.
+ const isOwnLogicFunction =
+ isDefined(
+ findFlatEntityByUniversalIdentifier({
+ flatEntityMaps: toFlatLogicFunctionMaps,
+ universalIdentifier,
+ }),
+ ) ||
+ (!inferDeletionFromMissingEntities &&
+ isDefined(
+ findFlatEntityByUniversalIdentifier({
+ flatEntityMaps: fromFlatLogicFunctionMaps,
+ universalIdentifier,
+ }),
+ ));
+
+ if (!isOwnLogicFunction) {
+ throw new ApplicationException(
+ `Failed to resolve ${hook} logic function of connection provider ${connectionProvider.name} for universalIdentifier ${universalIdentifier}`,
+ ApplicationExceptionCode.LOGIC_FUNCTION_NOT_FOUND,
+ );
+ }
+ }
+ }
+};
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 08e3aaf6b54..5c73924bd8f 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
@@ -13,4 +13,7 @@ export enum ConnectionProviderExceptionCode {
ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND = 'ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND',
ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND = 'ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND',
ON_DISCONNECT_LOGIC_FUNCTION_FAILED = 'ON_DISCONNECT_LOGIC_FUNCTION_FAILED',
+ IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND',
+ IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED = 'IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED',
+ RECONNECT_ACCOUNT_MISMATCH = 'RECONNECT_ACCOUNT_MISMATCH',
}
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
index 635f102d025..4d2d4782aff 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-lifecycle-hook.service.ts
@@ -1,12 +1,18 @@
import { Injectable } from '@nestjs/common';
+import {
+ type IdentifiedAccount,
+ type IdentifyAccountPayload,
+} from 'twenty-shared/application';
import { isDefined } from 'twenty-shared/utils';
import { ConnectionProviderExceptionCode } from 'src/engine/core-modules/application/connection-provider/connection-provider-exception-code.enum';
import { type 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 { ConnectionProviderService } from 'src/engine/core-modules/application/connection-provider/connection-provider.service';
+import { parseIdentifyAccountResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util';
import { ExceptionHandlerService } from 'src/engine/core-modules/exception-handler/exception-handler.service';
+import { type LogicFunctionExecuteResult } from 'src/engine/core-modules/logic-function/logic-function-drivers/interfaces/logic-function-driver.interface';
import { LogicFunctionExecutorService } from 'src/engine/core-modules/logic-function/logic-function-executor/logic-function-executor.service';
import { LOGIC_FUNCTION_QUEUE_RETRY_BACKOFF } from 'src/engine/core-modules/logic-function/logic-function-trigger/constants/logic-function-queue-retry-backoff.constant';
import {
@@ -17,18 +23,21 @@ import { InjectMessageQueue } from 'src/engine/core-modules/message-queue/decora
import { MessageQueue } from 'src/engine/core-modules/message-queue/message-queue.constants';
import { MessageQueueService } from 'src/engine/core-modules/message-queue/services/message-queue.service';
import { WorkspaceCacheService } from 'src/engine/workspace-cache/services/workspace-cache.service';
+import { CustomException } from 'src/utils/custom-exception';
-type ConnectionLifecycleHook = 'onConnect' | 'onDisconnect';
+type ConnectionLifecycleHook = 'identifyAccount' | 'onConnect' | 'onDisconnect';
type ConnectionLifecycleHookProvider = Pick<
ConnectionProviderEntity,
- 'id' | 'name'
+ 'id' | 'name' | 'applicationId'
>;
const MISSING_LOGIC_FUNCTION_EXCEPTION_CODE_BY_HOOK: Record<
ConnectionLifecycleHook,
ConnectionProviderExceptionCode
> = {
+ identifyAccount:
+ ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND,
onConnect:
ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND,
onDisconnect:
@@ -53,7 +62,10 @@ export class ConnectionProviderLifecycleHookService {
}: {
provider: Pick<
ConnectionProviderEntity,
- 'id' | 'name' | 'onConnectLogicFunctionUniversalIdentifier'
+ | 'id'
+ | 'name'
+ | 'applicationId'
+ | 'onConnectLogicFunctionUniversalIdentifier'
>;
workspaceId: string;
connectedAccountId: string;
@@ -86,6 +98,66 @@ export class ConnectionProviderLifecycleHookService {
});
}
+ // Unlike the other hooks, failures propagate: an account core could not identify must not be saved.
+ async runIdentifyAccount({
+ provider,
+ workspaceId,
+ accessToken,
+ }: {
+ provider: Pick<
+ ConnectionProviderEntity,
+ | 'id'
+ | 'name'
+ | 'applicationId'
+ | 'identifyAccountLogicFunctionUniversalIdentifier'
+ >;
+ workspaceId: string;
+ accessToken: string;
+ }): Promise<IdentifiedAccount | null> {
+ const logicFunctionId = await this.resolveLogicFunctionId({
+ hook: 'identifyAccount',
+ logicFunctionUniversalIdentifier:
+ provider.identifyAccountLogicFunctionUniversalIdentifier,
+ provider,
+ workspaceId,
+ });
+
+ if (!isDefined(logicFunctionId)) {
+ return null;
+ }
+
+ const payload: IdentifyAccountPayload = {
+ connectionProviderId: provider.id,
+ connectionProviderName: provider.name,
+ accessToken,
+ };
+
+ const executionResult = await this.executeIdentifyAccount({
+ provider,
+ logicFunctionId,
+ workspaceId,
+ payload,
+ });
+
+ if (isDefined(executionResult.error)) {
+ throw new ConnectionProviderException(
+ `identifyAccount logic function of connection provider ${provider.id} failed: ${executionResult.error.errorMessage}`,
+ ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
+ );
+ }
+
+ const parsedResult = parseIdentifyAccountResult(executionResult.data);
+
+ if (!parsedResult.isValid) {
+ throw new ConnectionProviderException(
+ `identifyAccount logic function of connection provider ${provider.id} returned an invalid result: ${parsedResult.reason}`,
+ ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
+ );
+ }
+
+ return parsedResult.identifiedAccount;
+ }
+
// Runs inline, before the connected account and its token are deleted, so the
// hook can still call the provider to release what onConnect set up remotely.
async runOnDisconnect({
@@ -130,6 +202,36 @@ export class ConnectionProviderLifecycleHookService {
});
}
+ private async executeIdentifyAccount({
+ provider,
+ logicFunctionId,
+ workspaceId,
+ payload,
+ }: {
+ provider: ConnectionLifecycleHookProvider;
+ logicFunctionId: string;
+ workspaceId: string;
+ payload: IdentifyAccountPayload;
+ }): Promise<LogicFunctionExecuteResult> {
+ try {
+ return await this.logicFunctionExecutorService.execute({
+ logicFunctionId,
+ workspaceId,
+ payload,
+ shouldEnforceUsageLimits: true,
+ });
+ } catch (error) {
+ if (error instanceof CustomException) {
+ throw error;
+ }
+
+ throw new ConnectionProviderException(
+ `identifyAccount logic function of connection provider ${provider.id} could not be executed: ${error instanceof Error ? error.message : String(error)}`,
+ ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED,
+ );
+ }
+ }
+
// Lifecycle hooks are best effort: a failing hook must never surface to the
// user connecting or disconnecting their account.
private async captureFailures(
@@ -186,10 +288,11 @@ export class ConnectionProviderLifecycleHookService {
if (
!isDefined(flatLogicFunction) ||
- isDefined(flatLogicFunction.deletedAt)
+ isDefined(flatLogicFunction.deletedAt) ||
+ flatLogicFunction.applicationId !== provider.applicationId
) {
throw new ConnectionProviderException(
- `Connection provider ${provider.id} references ${hook} logic function ${logicFunctionUniversalIdentifier}, which was not found in workspace ${workspaceId}.`,
+ `Connection provider ${provider.id} references ${hook} logic function ${logicFunctionUniversalIdentifier}, which was not found in its application.`,
MISSING_LOGIC_FUNCTION_EXCEPTION_CODE_BY_HOOK[hook],
);
}
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 941fccd9c85..683495354a3 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
@@ -1,8 +1,9 @@
import { Injectable, Logger } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
-import { Repository } from 'typeorm';
+import { IsNull, Repository } from 'typeorm';
+import { type IdentifiedAccount } from 'twenty-shared/application';
import { ConnectedAccountProvider } from 'twenty-shared/types';
import { isDefined } from 'twenty-shared/utils';
@@ -196,9 +197,17 @@ export class ConnectionProviderOAuthFlowService {
);
}
+ const identifiedAccount =
+ await this.connectionProviderLifecycleHookService.runIdentifyAccount({
+ provider,
+ workspaceId: statePayload.workspaceId,
+ accessToken: tokenResponse.accessToken,
+ });
+
const connectedAccount = await this.persistConnectedAccount({
provider,
tokenResponse,
+ identifiedAccount,
workspaceId: statePayload.workspaceId,
userId: statePayload.userId,
userWorkspaceId: statePayload.userWorkspaceId,
@@ -284,6 +293,7 @@ export class ConnectionProviderOAuthFlowService {
private async persistConnectedAccount({
provider,
tokenResponse,
+ identifiedAccount,
workspaceId,
userId,
userWorkspaceId,
@@ -292,6 +302,7 @@ export class ConnectionProviderOAuthFlowService {
}: {
provider: OAuthConnectionProvider;
tokenResponse: TokenExchangeResponse;
+ identifiedAccount: IdentifiedAccount | null;
workspaceId: string;
userId: string;
userWorkspaceId: string;
@@ -307,10 +318,12 @@ export class ConnectionProviderOAuthFlowService {
workspaceId,
});
- const handle = await this.resolveConnectedAccountHandle({
- tokenResponse,
- userId,
- });
+ const handle =
+ identifiedAccount?.handle ??
+ (await this.resolveConnectedAccountHandle({
+ tokenResponse,
+ userId,
+ }));
const sharedFields = {
accessToken: encryptedAccessToken,
@@ -321,18 +334,43 @@ export class ConnectionProviderOAuthFlowService {
authFailedReason: null,
visibility,
handle,
+ externalAccountId: identifiedAccount?.externalAccountId ?? null,
};
if (isDefined(reconnectingConnectedAccountId)) {
- await this.connectedAccountRepository.update(
- { id: reconnectingConnectedAccountId, workspaceId },
+ const reconnectTarget = {
+ id: reconnectingConnectedAccountId,
+ workspaceId,
+ };
+
+ // Compared and written in one statement so overlapping reconnects cannot pin different accounts.
+ const updateResult = await this.connectedAccountRepository.update(
+ isDefined(identifiedAccount)
+ ? [
+ { ...reconnectTarget, externalAccountId: IsNull() },
+ {
+ ...reconnectTarget,
+ externalAccountId: identifiedAccount.externalAccountId,
+ },
+ ]
+ : reconnectTarget,
{ ...sharedFields, userWorkspaceId },
);
- return this.connectedAccountRepository.findOneByOrFail({
- id: reconnectingConnectedAccountId,
- workspaceId,
- });
+ const connectedAccount =
+ await this.connectedAccountRepository.findOneByOrFail(reconnectTarget);
+
+ if (updateResult.affected === 0 && isDefined(identifiedAccount)) {
+ const authorizedAccountHandle =
+ identifiedAccount.handle ?? identifiedAccount.externalAccountId;
+
+ throw new ConnectionProviderException(
+ `You authorized ${authorizedAccountHandle}, but this connection belongs to ${connectedAccount.handle}. Reconnect with ${connectedAccount.handle}, or add a new connection for ${authorizedAccountHandle}.`,
+ ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH,
+ );
+ }
+
+ return connectedAccount;
}
const existingCount = await this.connectedAccountRepository.count({
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
index 6b01065eb65..5306eeddfca 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider.entity.ts
@@ -47,6 +47,13 @@ export class ConnectionProviderEntity
@Column({ nullable: true, type: 'jsonb' })
oauthConfig: StoredOAuthConnectionProviderConfig | null;
+ @Column({ nullable: true, type: 'uuid' })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.48.0_AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand_1791975194413',
+ })
+ identifyAccountLogicFunctionUniversalIdentifier: string | null;
+
@Column({ nullable: true, type: 'uuid' })
@WasIntroducedInUpgrade({
upgradeCommandName:
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 a450db2fce7..5de4e49f566 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
@@ -37,6 +37,12 @@ const getConnectionProviderExceptionUserFriendlyMessage = (
return msg`The logic function to run on disconnect was not found.`;
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
return msg`The logic function to run on disconnect failed.`;
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND:
+ return msg`The logic function that identifies the connected account was not found.`;
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED:
+ return msg`We could not identify the account you authorized. Please try again.`;
+ case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
+ return msg`You authorized a different account than the one this connection belongs to.`;
default:
assertUnreachable(code);
}
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 9384ba664ba..e65d7312aee 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
@@ -16,6 +16,9 @@ export class AppConnectionObjectDto implements AppConnection {
@Field()
handle: string;
+ @Field(() => String, { nullable: true })
+ externalAccountId: string | null;
+
@Field(() => String)
visibility: 'user' | 'workspace';
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 63012167377..a410672db88 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
@@ -245,6 +245,7 @@ export class ApplicationConnectionsListService {
providerName: provider.name,
name: account.name ?? account.handle,
handle: account.handle,
+ externalAccountId: account.externalAccountId,
visibility: account.visibility as 'user' | 'workspace',
userWorkspaceId: account.userWorkspaceId,
workspaceMemberId,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts
new file mode 100644
index 00000000000..175deaf7e37
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/constants/identify-account-timeout-seconds.constant.ts
@@ -0,0 +1,2 @@
+// identifyAccount runs inside the OAuth callback while the user waits on the redirect.
+export const IDENTIFY_ACCOUNT_TIMEOUT_SECONDS = 10;
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
index 9be57f759d3..a66df97b568 100644
--- 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
@@ -22,6 +22,7 @@ const connectionProviderExceptionCodeToHttpStatus = (
case ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND:
return 404;
case ConnectionProviderExceptionCode.FORBIDDEN:
return 403;
@@ -29,11 +30,13 @@ const connectionProviderExceptionCodeToHttpStatus = (
case ConnectionProviderExceptionCode.INVALID_STATE:
case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
+ case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
return 400;
case ConnectionProviderExceptionCode.CLIENT_CREDENTIALS_NOT_CONFIGURED:
case ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED:
case ConnectionProviderExceptionCode.REFRESH_FAILED:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_FAILED:
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED:
return 500;
default:
return assertUnreachable(code);
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-identify-account-result.util.spec.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-identify-account-result.util.spec.ts
new file mode 100644
index 00000000000..e7f2e9c7465
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/__tests__/parse-identify-account-result.util.spec.ts
@@ -0,0 +1,61 @@
+import { parseIdentifyAccountResult } from 'src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util';
+import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
+
+describe('parseIdentifyAccountResult', () => {
+ it('returns the trimmed id and handle', () => {
+ expect(
+ parseIdentifyAccountResult({
+ externalAccountId: ' team-a ',
+ handle: ' Team A ',
+ }),
+ ).toEqual({
+ isValid: true,
+ identifiedAccount: { externalAccountId: 'team-a', handle: 'Team A' },
+ });
+ });
+
+ it('leaves the handle out when it is absent or null', () => {
+ expect(
+ parseIdentifyAccountResult({ externalAccountId: 'team-a', handle: null }),
+ ).toEqual({
+ isValid: true,
+ identifiedAccount: { externalAccountId: 'team-a' },
+ });
+ });
+
+ it('treats a null id as the explicit opt-out', () => {
+ expect(parseIdentifyAccountResult({ externalAccountId: null })).toEqual({
+ isValid: true,
+ identifiedAccount: null,
+ });
+ });
+
+ it('accepts an id of exactly the maximum length', () => {
+ const externalAccountId = 'a'.repeat(EXTERNAL_ACCOUNT_ID_MAX_LENGTH);
+
+ expect(parseIdentifyAccountResult({ externalAccountId })).toEqual({
+ isValid: true,
+ identifiedAccount: { externalAccountId },
+ });
+ });
+
+ it.each([
+ ['a missing return', undefined],
+ ['a bare null', null],
+ ['a non-object', 'team-a'],
+ ['a missing id', {}],
+ ['an empty id', { externalAccountId: ' ' }],
+ ['a numeric id', { externalAccountId: 42 }],
+ [
+ 'an id over the maximum length',
+ { externalAccountId: 'a'.repeat(EXTERNAL_ACCOUNT_ID_MAX_LENGTH + 1) },
+ ],
+ ['an empty handle', { externalAccountId: 'team-a', handle: '' }],
+ ['a non-string handle', { externalAccountId: 'team-a', handle: 7 }],
+ ])('rejects %s', (_label, data) => {
+ const outcome = parseIdentifyAccountResult(data);
+
+ expect(outcome.isValid).toBe(false);
+ expect(outcome).toHaveProperty('reason', expect.any(String));
+ });
+});
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
index 6f0f224ad6a..ddc5be95088 100644
--- 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
@@ -17,6 +17,7 @@ export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
case ConnectionProviderExceptionCode.PROVIDER_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_CONNECT_LOGIC_FUNCTION_NOT_FOUND:
case ConnectionProviderExceptionCode.ON_DISCONNECT_LOGIC_FUNCTION_NOT_FOUND:
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_NOT_FOUND:
throw new NotFoundError(error);
case ConnectionProviderExceptionCode.FORBIDDEN:
throw new ForbiddenError(error);
@@ -24,11 +25,13 @@ export const connectionProviderGraphqlApiExceptionHandler = (error: Error) => {
case ConnectionProviderExceptionCode.INVALID_STATE:
case ConnectionProviderExceptionCode.INVALID_CONNECTION_PROVIDER_INPUT:
case ConnectionProviderExceptionCode.CONNECTION_PROVIDER_NAME_ALREADY_EXISTS:
+ case ConnectionProviderExceptionCode.RECONNECT_ACCOUNT_MISMATCH:
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:
+ case ConnectionProviderExceptionCode.IDENTIFY_ACCOUNT_LOGIC_FUNCTION_FAILED:
throw new InternalServerError(error);
default: {
return assertUnreachable(error.code);
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts
new file mode 100644
index 00000000000..e1a8a9f191f
--- /dev/null
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/utils/parse-identify-account-result.util.ts
@@ -0,0 +1,47 @@
+import { type IdentifiedAccount } from 'twenty-shared/application';
+import { isDefined } from 'twenty-shared/utils';
+import { z } from 'zod';
+
+import { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
+
+const identifyAccountResultSchema = z.object({
+ externalAccountId: z
+ .string()
+ .trim()
+ .min(1)
+ .max(EXTERNAL_ACCOUNT_ID_MAX_LENGTH)
+ .nullable(),
+ handle: z.string().trim().min(1).nullish(),
+});
+
+type ParseIdentifyAccountResultOutcome =
+ | { isValid: true; identifiedAccount: IdentifiedAccount | null }
+ | { isValid: false; reason: string };
+
+export const parseIdentifyAccountResult = (
+ data: unknown,
+): ParseIdentifyAccountResultOutcome => {
+ const parsed = identifyAccountResultSchema.safeParse(data);
+
+ if (!parsed.success) {
+ return {
+ isValid: false,
+ reason: parsed.error.issues
+ .map((issue) => `${issue.path.join('.') || 'result'}: ${issue.message}`)
+ .join('; '),
+ };
+ }
+
+ const { externalAccountId, handle } = parsed.data;
+
+ if (!isDefined(externalAccountId)) {
+ return { isValid: true, identifiedAccount: null };
+ }
+
+ return {
+ isValid: true,
+ identifiedAccount: isDefined(handle)
+ ? { externalAccountId, handle }
+ : { externalAccountId },
+ };
+};
diff --git a/packages/twenty-server/src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant.ts b/packages/twenty-server/src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant.ts
new file mode 100644
index 00000000000..78bb75bdac3
--- /dev/null
+++ b/packages/twenty-server/src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant.ts
@@ -0,0 +1 @@
+export const EXTERNAL_ACCOUNT_ID_MAX_LENGTH = 512;
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 3d3be49d7a4..985382ba6cf 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
@@ -20,6 +20,7 @@ import { type EncryptedImapSmtpCaldavParams } from 'src/engine/core-modules/imap
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 { EXTERNAL_ACCOUNT_ID_MAX_LENGTH } from 'src/engine/metadata-modules/connected-account/constants/external-account-id-max-length.constant';
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.type';
@@ -52,6 +53,17 @@ export class ConnectedAccountEntity extends WorkspaceRelatedEntity {
@Column({ type: 'varchar', nullable: false })
handle: string;
+ @Column({
+ type: 'varchar',
+ length: EXTERNAL_ACCOUNT_ID_MAX_LENGTH,
+ nullable: true,
+ })
+ @WasIntroducedInUpgrade({
+ upgradeCommandName:
+ '2.48.0_AddIdentifyAccountLogicFunctionAndExternalAccountIdFastInstanceCommand_1791975194413',
+ })
+ externalAccountId: string | null;
+
@Column({ type: 'varchar', nullable: false })
provider: ConnectedAccountProvider;
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
index bc63a80e256..7076c598cce 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/__tests__/__snapshots__/all-universal-flat-entity-properties-to-compare-and-stringify.constant.spec.ts.snap
@@ -69,6 +69,7 @@ exports[`ALL_UNIVERSAL_FLAT_ENTITY_PROPERTIES_TO_COMPARE_AND_STRINGIFY should ma
"logo",
"type",
"oauthConfig",
+ "identifyAccountLogicFunctionUniversalIdentifier",
"onConnectLogicFunctionUniversalIdentifier",
"onDisconnectLogicFunctionUniversalIdentifier",
],
diff --git a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
index d98fb6bed60..1e68108bf52 100644
--- a/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
+++ b/packages/twenty-server/src/engine/metadata-modules/flat-entity/constant/all-entity-properties-configuration-by-metadata-name.constant.ts
@@ -1917,6 +1917,11 @@ export const ALL_ENTITY_PROPERTIES_CONFIGURATION_BY_METADATA_NAME = {
toStringify: true,
universalProperty: undefined,
},
+ identifyAccountLogicFunctionUniversalIdentifier: {
+ toCompare: true,
+ toStringify: false,
+ universalProperty: undefined,
+ },
onConnectLogicFunctionUniversalIdentifier: {
toCompare: true,
toStringify: false,
diff --git a/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-connection-provider.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-connection-provider.integration-spec.ts
index 1815778bf01..faff598d525 100644
--- a/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-connection-provider.integration-spec.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/application/successful-manifest-update-connection-provider.integration-spec.ts
@@ -83,6 +83,7 @@ describe('Manifest update - connection providers', () => {
tokenRequestContentType: 'json',
usePkce: true,
},
+ identifyAccountLogicFunctionUniversalIdentifier: null,
onConnectLogicFunctionUniversalIdentifier: null,
onDisconnectLogicFunctionUniversalIdentifier: null,
});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
new file mode 100644
index 00000000000..2e9473bb571
--- /dev/null
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/app-connection-oauth-callback.integration-spec.ts
@@ -0,0 +1,562 @@
+import { createHash } from 'crypto';
+import { existsSync, mkdtempSync, readFileSync, rmSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import { http, HttpResponse } from 'msw';
+import request from 'supertest';
+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 { 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 { uploadApplicationFile } from 'test/integration/metadata/suites/application/utils/upload-application-file.util';
+import { generateTransientTokenResponse } from 'test/integration/utils/generate-transient-token.util';
+import { getAppProviderByClassName } from 'test/integration/utils/get-app-provider-by-class-name.util';
+import { setupHttpMock } from 'test/integration/utils/http-mock.util';
+import { waitForAllJobsToFinish } from 'test/integration/utils/wait-for-all-jobs-to-finish.util';
+import {
+ type LogicFunctionManifest,
+ type Manifest,
+} from 'twenty-shared/application';
+import { assertIsDefinedOrThrow } from 'twenty-shared/utils';
+import { v4 } from 'uuid';
+import { z } from 'zod';
+
+import { type ConnectionProviderEntity } from 'src/engine/core-modules/application/connection-provider/connection-provider.entity';
+import { plaintextStringSchema } from 'src/engine/core-modules/secret-encryption/branded-strings/plaintext-string.type';
+import { type SecretEncryptionService } from 'src/engine/core-modules/secret-encryption/secret-encryption.service';
+import { type ConnectedAccountEntity } from 'src/engine/metadata-modules/connected-account/entities/connected-account.entity';
+import { type ConnectedAccountTokenEncryptionService } from 'src/engine/metadata-modules/connected-account/services/connected-account-token-encryption.service';
+import { SEED_APPLE_WORKSPACE_ID } from 'src/engine/workspace-manager/dev-seeder/core/constants/seeder-workspaces.constant';
+
+const APPLICATION_IDENTIFIER = v4();
+const PROVIDER_IDENTIFIER = v4();
+const IDENTIFY_ACCOUNT_IDENTIFIER = v4();
+const ON_CONNECT_IDENTIFIER = v4();
+const TOKEN_ENDPOINT = 'https://connection-provider.example.com/token';
+
+// The token endpoint echoes the authorization code as the access token, and
+// the identify function reads the account from its "<account>:<suffix>" shape.
+const IDENTIFY_ACCOUNT_SOURCE = `export const handler = ({ accessToken }) => {
+ const [account] = accessToken.split(':');
+ if (account === 'unidentifiable') return { externalAccountId: null };
+ if (account === 'silent') return;
+ if (account === 'broken') throw new Error('upstream identity endpoint failed');
+ return { externalAccountId: account, handle: 'Handle ' + account };
+};`;
+
+describe('app connection OAuth callback', () => {
+ let provider: ConnectionProviderEntity;
+ let fixtureDirectory: string;
+ let onConnectExecutionsPath: string;
+ let tokenExchanges: string[];
+
+ setupHttpMock(
+ http.post(TOKEN_ENDPOINT, async ({ request: tokenRequest }) => {
+ const { code } = z
+ .object({ code: z.string().min(1) })
+ .parse(await tokenRequest.json());
+
+ tokenExchanges.push(code);
+
+ return HttpResponse.json({
+ access_token: code,
+ refresh_token: `refresh-${code}`,
+ token_type: 'Bearer',
+ scope: 'read',
+ });
+ }),
+ );
+
+ const readExecutions = (path: string): string[] =>
+ existsSync(path) ? readFileSync(path, 'utf8').trim().split('\n') : [];
+
+ const readAccounts = (): Promise<ConnectedAccountEntity[]> =>
+ globalThis.testDataSource.query(
+ 'SELECT * FROM core."connectedAccount" WHERE "connectionProviderId" = $1 ORDER BY "createdAt", id',
+ [provider.id],
+ );
+
+ const decryptAccessToken = (connectedAccount: ConnectedAccountEntity) => {
+ const encryption =
+ getAppProviderByClassName<ConnectedAccountTokenEncryptionService>(
+ 'ConnectedAccountTokenEncryptionService',
+ );
+
+ assertIsDefinedOrThrow(connectedAccount.accessToken);
+
+ return encryption.decrypt({
+ ciphertext: connectedAccount.accessToken,
+ workspaceId: SEED_APPLE_WORKSPACE_ID,
+ });
+ };
+
+ const authorize = async ({
+ reconnectingConnectedAccountId,
+ }: {
+ reconnectingConnectedAccountId?: string;
+ } = {}): Promise<string> => {
+ const transient = await generateTransientTokenResponse({
+ token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
+ });
+
+ expect(transient.errors).toBeUndefined();
+
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .get('/auth/apps/authorize')
+ .query({
+ applicationId: provider.applicationId,
+ providerName: provider.name,
+ transientToken:
+ transient.data.generateTransientToken.transientToken.token,
+ visibility: 'workspace',
+ reconnectingConnectedAccountId,
+ });
+
+ expect(response.status).toBe(302);
+ const authorizationUrl = new URL(response.headers.location);
+
+ expect(authorizationUrl.origin).toBe(
+ 'https://connection-provider.example.com',
+ );
+ const state = authorizationUrl.searchParams.get('state');
+
+ assertIsDefinedOrThrow(state);
+
+ return state;
+ };
+
+ const callback = async (state: string, code: string): Promise<URL> => {
+ const response = await request(`http://localhost:${APP_PORT}`)
+ .get('/auth/apps/callback')
+ .query({ state, code });
+
+ expect(response.status).toBe(302);
+ await waitForAllJobsToFinish();
+
+ return new URL(response.headers.location);
+ };
+
+ beforeAll(async () => {
+ fixtureDirectory = mkdtempSync(join(tmpdir(), 'app-connection-callback-'));
+ onConnectExecutionsPath = join(fixtureDirectory, 'on-connect-executions');
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ name: 'OAuth callback integration',
+ description: 'Callback account identification and onConnect execution',
+ sourcePath: 'oauth-callback-integration',
+ });
+ jest.useRealTimers();
+
+ const functions = [
+ {
+ universalIdentifier: IDENTIFY_ACCOUNT_IDENTIFIER,
+ name: 'identify-account',
+ source: IDENTIFY_ACCOUNT_SOURCE,
+ },
+ {
+ universalIdentifier: ON_CONNECT_IDENTIFIER,
+ name: 'on-connect',
+ source: `import { appendFileSync } from 'node:fs';
+export const handler = ({ connectedAccountId }) => {
+ appendFileSync(${JSON.stringify(onConnectExecutionsPath)}, connectedAccountId + '\\n');
+};`,
+ },
+ ];
+
+ for (const logicFunction of functions) {
+ const uploaded = await uploadApplicationFile({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: `dist/${logicFunction.name}.mjs`,
+ filename: `${logicFunction.name}.mjs`,
+ contentType: 'application/javascript',
+ fileBuffer: Buffer.from(logicFunction.source),
+ });
+
+ expect(uploaded.errors).toBeUndefined();
+ }
+
+ const { errors } = await syncApplication({
+ manifest: buildBaseManifest({
+ appId: APPLICATION_IDENTIFIER,
+ roleId: v4(),
+ overrides: {
+ logicFunctions: functions.map((logicFunction) => ({
+ universalIdentifier: logicFunction.universalIdentifier,
+ name: logicFunction.name,
+ handlerName: 'handler',
+ sourceHandlerPath: `src/${logicFunction.name}.ts`,
+ builtHandlerPath: `dist/${logicFunction.name}.mjs`,
+ builtHandlerChecksum: createHash('sha256')
+ .update(logicFunction.source)
+ .digest('hex'),
+ timeoutSeconds: 10,
+ })),
+ connectionProviders: [
+ {
+ universalIdentifier: PROVIDER_IDENTIFIER,
+ name: 'callback-provider',
+ displayName: 'Callback provider',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint:
+ 'https://connection-provider.example.com/authorize',
+ tokenEndpoint: TOKEN_ENDPOINT,
+ scopes: ['read'],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ identifyAccountLogicFunction: {
+ universalIdentifier: IDENTIFY_ACCOUNT_IDENTIFIER,
+ },
+ onConnectLogicFunction: {
+ universalIdentifier: ON_CONNECT_IDENTIFIER,
+ },
+ },
+ ],
+ },
+ }),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+ [provider] = await globalThis.testDataSource.query(
+ 'SELECT * FROM core."connectionProvider" WHERE "universalIdentifier" = $1',
+ [PROVIDER_IDENTIFIER],
+ );
+ const encryption = getAppProviderByClassName<SecretEncryptionService>(
+ 'SecretEncryptionService',
+ );
+
+ for (const key of ['CLIENT_ID', 'CLIENT_SECRET']) {
+ await globalThis.testDataSource.query(
+ `INSERT INTO core."applicationRegistrationVariable" (key, "encryptedValue", "applicationRegistrationId")
+ SELECT $1, $2, "applicationRegistrationId" FROM core.application WHERE id = $3`,
+ [
+ key,
+ encryption.encryptVersioned(
+ plaintextStringSchema.parse(`test-${key}`),
+ ),
+ provider.applicationId,
+ ],
+ );
+ }
+ }, 120000);
+
+ beforeEach(() => {
+ tokenExchanges = [];
+ rmSync(onConnectExecutionsPath, { force: true });
+ });
+
+ afterEach(async () => {
+ await globalThis.testDataSource.query(
+ 'DELETE FROM core."connectedAccount" WHERE "applicationId" = $1',
+ [provider.applicationId],
+ );
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: APPLICATION_IDENTIFIER,
+ });
+ rmSync(fixtureDirectory, { recursive: true, force: true });
+ });
+
+ it('stores the identified account on first connect and runs onConnect for it', async () => {
+ const redirect = await callback(await authorize(), 'team-a:first');
+ const [connection] = await readAccounts();
+
+ expect(redirect.searchParams.get('errorMessage')).toBeNull();
+ expect(connection).toMatchObject({
+ externalAccountId: 'team-a',
+ handle: 'Handle team-a',
+ });
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([connection.id]);
+ });
+
+ it('replaces credentials on the same connection when the reconnect resolves to the same account', async () => {
+ await callback(await authorize(), 'team-a:first');
+ const [original] = await readAccounts();
+
+ const redirect = await callback(
+ await authorize({ reconnectingConnectedAccountId: original.id }),
+ 'team-a:second',
+ );
+ const connections = await readAccounts();
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(connections).toHaveLength(1);
+ expect(connections[0]).toMatchObject({
+ id: original.id,
+ externalAccountId: 'team-a',
+ });
+ expect(decryptAccessToken(connections[0])).toBe('team-a:second');
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([
+ original.id,
+ original.id,
+ ]);
+ });
+
+ it('refuses a reconnect that resolves to a different account and leaves the connection untouched', async () => {
+ await callback(await authorize(), 'team-a:first');
+ const [original] = await readAccounts();
+
+ const redirect = await callback(
+ await authorize({ reconnectingConnectedAccountId: original.id }),
+ 'team-b:first',
+ );
+ const connections = await readAccounts();
+
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'Handle team-b',
+ );
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'Handle team-a',
+ );
+ expect(connections).toHaveLength(1);
+ expect(connections[0]).toMatchObject({
+ id: original.id,
+ externalAccountId: 'team-a',
+ handle: 'Handle team-a',
+ });
+ expect(decryptAccessToken(connections[0])).toBe('team-a:first');
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([original.id]);
+ });
+
+ it('pins the identified account on a reconnect target that predates identification', async () => {
+ await callback(await authorize(), 'team-a:first');
+ const [original] = await readAccounts();
+
+ await globalThis.testDataSource.query(
+ 'UPDATE core."connectedAccount" SET "externalAccountId" = NULL WHERE id = $1',
+ [original.id],
+ );
+
+ const redirect = await callback(
+ await authorize({ reconnectingConnectedAccountId: original.id }),
+ 'team-b:first',
+ );
+ const [reconnected] = await readAccounts();
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(reconnected).toMatchObject({
+ id: original.id,
+ externalAccountId: 'team-b',
+ });
+ });
+
+ it('keeps the previous behaviour when the identify function opts out', async () => {
+ const redirect = await callback(await authorize(), 'unidentifiable:first');
+ const [connection] = await readAccounts();
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(connection.externalAccountId).toBeNull();
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([connection.id]);
+ });
+
+ it('clears the stored account when a reconnect opts out', async () => {
+ await callback(await authorize(), 'team-a:first');
+ const [original] = await readAccounts();
+
+ const redirect = await callback(
+ await authorize({ reconnectingConnectedAccountId: original.id }),
+ 'unidentifiable:second',
+ );
+ const connections = await readAccounts();
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(connections).toHaveLength(1);
+ expect(connections[0]).toMatchObject({
+ id: original.id,
+ externalAccountId: null,
+ });
+ expect(decryptAccessToken(connections[0])).toBe('unidentifiable:second');
+ });
+
+ it('saves nothing and skips onConnect when the identify function returns nothing', async () => {
+ const redirect = await callback(await authorize(), 'silent:first');
+
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'invalid result',
+ );
+ expect(await readAccounts()).toEqual([]);
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ });
+
+ it('saves nothing and skips onConnect when the identify function fails', async () => {
+ const redirect = await callback(await authorize(), 'broken:first');
+
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'upstream identity endpoint failed',
+ );
+ expect(redirect.searchParams.get('errorMessage')).not.toContain(
+ 'broken:first',
+ );
+ expect(await readAccounts()).toEqual([]);
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ });
+
+ it('rejects tampered state before exchanging a code or executing the app', async () => {
+ const state = await authorize();
+ const redirect = await callback(`${state}invalid`, 'team-a:first');
+
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'invalid or expired',
+ );
+ expect(tokenExchanges).toEqual([]);
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ expect(await readAccounts()).toEqual([]);
+ });
+
+ describe('identify function owned by another application', () => {
+ const OTHER_APPLICATION_IDENTIFIER = v4();
+ const OTHER_IDENTIFY_ACCOUNT_IDENTIFIER = v4();
+ const OTHER_ROLE_IDENTIFIER = v4();
+ let otherIdentifyExecutionsPath: string;
+ let otherLogicFunctionManifest: LogicFunctionManifest;
+
+ const buildOtherApplicationManifest = (
+ connectionProviders: Manifest['connectionProviders'] = [],
+ ) =>
+ buildBaseManifest({
+ appId: OTHER_APPLICATION_IDENTIFIER,
+ roleId: OTHER_ROLE_IDENTIFIER,
+ overrides: {
+ roles: [
+ {
+ universalIdentifier: OTHER_ROLE_IDENTIFIER,
+ label: 'Other application role',
+ },
+ ],
+ logicFunctions: [otherLogicFunctionManifest],
+ connectionProviders,
+ },
+ });
+
+ beforeAll(async () => {
+ otherIdentifyExecutionsPath = join(
+ fixtureDirectory,
+ 'other-identify-executions',
+ );
+
+ const source = `import { appendFileSync } from 'node:fs';
+export const handler = () => {
+ appendFileSync(${JSON.stringify(otherIdentifyExecutionsPath)}, 'executed\\n');
+ return { externalAccountId: 'other-application' };
+};`;
+
+ await setupApplicationForSync({
+ applicationUniversalIdentifier: OTHER_APPLICATION_IDENTIFIER,
+ name: 'OAuth callback other application',
+ description: 'Owns a logic function another app tries to use',
+ sourcePath: 'oauth-callback-other-application',
+ });
+ jest.useRealTimers();
+
+ const uploaded = await uploadApplicationFile({
+ applicationUniversalIdentifier: OTHER_APPLICATION_IDENTIFIER,
+ fileFolder: 'BuiltLogicFunction',
+ filePath: 'dist/other-identify-account.mjs',
+ filename: 'other-identify-account.mjs',
+ contentType: 'application/javascript',
+ fileBuffer: Buffer.from(source),
+ });
+
+ expect(uploaded.errors).toBeUndefined();
+
+ otherLogicFunctionManifest = {
+ universalIdentifier: OTHER_IDENTIFY_ACCOUNT_IDENTIFIER,
+ name: 'other-identify-account',
+ handlerName: 'handler',
+ sourceHandlerPath: 'src/other-identify-account.ts',
+ builtHandlerPath: 'dist/other-identify-account.mjs',
+ builtHandlerChecksum: createHash('sha256').update(source).digest('hex'),
+ timeoutSeconds: 10,
+ };
+
+ const { errors } = await syncApplication({
+ manifest: buildOtherApplicationManifest(),
+ });
+
+ expect(errors).toBeUndefined();
+ jest.useRealTimers();
+ }, 120000);
+
+ beforeEach(() => {
+ rmSync(otherIdentifyExecutionsPath, { force: true });
+ });
+
+ afterAll(async () => {
+ await cleanupApplicationAndAppRegistration({
+ applicationUniversalIdentifier: OTHER_APPLICATION_IDENTIFIER,
+ });
+ });
+
+ it('refuses to install a provider that references it without writing anything', async () => {
+ const foreignProviderIdentifier = v4();
+ const manifest = buildOtherApplicationManifest([
+ {
+ universalIdentifier: foreignProviderIdentifier,
+ name: 'foreign-identify-provider',
+ displayName: 'Foreign identify provider',
+ type: 'oauth',
+ oauth: {
+ authorizationEndpoint:
+ 'https://connection-provider.example.com/authorize',
+ tokenEndpoint: TOKEN_ENDPOINT,
+ scopes: ['read'],
+ clientIdVariable: 'CLIENT_ID',
+ clientSecretVariable: 'CLIENT_SECRET',
+ },
+ identifyAccountLogicFunction: {
+ universalIdentifier: IDENTIFY_ACCOUNT_IDENTIFIER,
+ },
+ },
+ ]);
+
+ for (const dryRun of [true, false]) {
+ const { errors } = await syncApplication({
+ manifest,
+ dryRun,
+ expectToFail: true,
+ });
+
+ expect(errors?.[0]?.message).toContain(
+ 'identifyAccount logic function of connection provider foreign-identify-provider',
+ );
+ }
+
+ expect(
+ await globalThis.testDataSource.query(
+ 'SELECT id FROM core."connectionProvider" WHERE "universalIdentifier" = $1',
+ [foreignProviderIdentifier],
+ ),
+ ).toEqual([]);
+ });
+
+ it('does not run it for a provider that already references it', async () => {
+ await globalThis.testDataSource.query(
+ 'UPDATE core."connectionProvider" SET "identifyAccountLogicFunctionUniversalIdentifier" = $1 WHERE id = $2',
+ [OTHER_IDENTIFY_ACCOUNT_IDENTIFIER, provider.id],
+ );
+
+ try {
+ const redirect = await callback(await authorize(), 'team-a:first');
+
+ expect(redirect.searchParams.get('errorMessage')).toContain(
+ 'not found in its application',
+ );
+ expect(await readAccounts()).toEqual([]);
+ expect(readExecutions(otherIdentifyExecutionsPath)).toEqual([]);
+ expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
+ } finally {
+ await globalThis.testDataSource.query(
+ 'UPDATE core."connectionProvider" SET "identifyAccountLogicFunctionUniversalIdentifier" = $1 WHERE id = $2',
+ [IDENTIFY_ACCOUNT_IDENTIFIER, provider.id],
+ );
+ }
+ });
+ });
+});
diff --git a/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util.ts b/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util.ts
index 5d7817c70ed..79eb642f644 100644
--- a/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util.ts
+++ b/packages/twenty-server/test/integration/metadata/suites/connection-provider/utils/find-connection-providers-by-application.util.ts
@@ -9,6 +9,7 @@ type ConnectionProviderRow = {
displayName: string;
type: string;
oauthConfig: StoredOAuthConnectionProviderConfig | null;
+ identifyAccountLogicFunctionUniversalIdentifier: string | null;
onConnectLogicFunctionUniversalIdentifier: string | null;
onDisconnectLogicFunctionUniversalIdentifier: string | null;
};
@@ -19,7 +20,8 @@ export const findConnectionProvidersByApplication = async (
return globalThis.testDataSource.query(
`SELECT cp.id, cp."universalIdentifier", cp."applicationId",
cp."workspaceId", cp.name, cp."displayName", cp.type,
- cp."oauthConfig", cp."onConnectLogicFunctionUniversalIdentifier",
+ cp."oauthConfig", cp."identifyAccountLogicFunctionUniversalIdentifier",
+ cp."onConnectLogicFunctionUniversalIdentifier",
cp."onDisconnectLogicFunctionUniversalIdentifier"
FROM core."connectionProvider" cp
JOIN core."application" app ON app.id = cp."applicationId"
diff --git a/packages/twenty-shared/src/application/appConnectionType.ts b/packages/twenty-shared/src/application/appConnectionType.ts
index d49de4d96c3..811e83f7f21 100644
--- a/packages/twenty-shared/src/application/appConnectionType.ts
+++ b/packages/twenty-shared/src/application/appConnectionType.ts
@@ -18,6 +18,8 @@ export type AppConnection = {
// OAuth-derived identifier (typically email or login). Stays stable across
// reconnects of the same upstream account.
handle: string;
+ // Upstream account id from identifyAccountLogicFunction; not unique, apps dedupe on it themselves.
+ externalAccountId: string | null;
// Connection-row visibility:
// 'user' = visible only to the user who created it.
// 'workspace' = visible to every user in the workspace.
diff --git a/packages/twenty-shared/src/application/connectionProviderManifestType.ts b/packages/twenty-shared/src/application/connectionProviderManifestType.ts
index 331c9820a6d..0f77a9088a6 100644
--- a/packages/twenty-shared/src/application/connectionProviderManifestType.ts
+++ b/packages/twenty-shared/src/application/connectionProviderManifestType.ts
@@ -7,6 +7,7 @@ export type ConnectionProviderManifest = SyncableEntityOptions & {
logo?: string;
type: 'oauth';
oauth: OAuthConnectionProviderConfig;
+ identifyAccountLogicFunction?: SyncableEntityOptions;
onConnectLogicFunction?: SyncableEntityOptions;
onDisconnectLogicFunction?: SyncableEntityOptions;
};
diff --git a/packages/twenty-shared/src/application/identifyAccountType.ts b/packages/twenty-shared/src/application/identifyAccountType.ts
new file mode 100644
index 00000000000..6175480a7b6
--- /dev/null
+++ b/packages/twenty-shared/src/application/identifyAccountType.ts
@@ -0,0 +1,17 @@
+export type IdentifyAccountPayload = {
+ connectionProviderId: string;
+ connectionProviderName: string;
+ // Provisional token from the code exchange, persisted only once the account is accepted.
+ accessToken: string;
+};
+
+export type IdentifiedAccount = {
+ externalAccountId: string;
+ handle?: string;
+};
+
+// externalAccountId null is the explicit opt-out of providers without a stable id.
+export type IdentifyAccountResult = {
+ externalAccountId: string | null;
+ handle?: string;
+};
diff --git a/packages/twenty-shared/src/application/index.ts b/packages/twenty-shared/src/application/index.ts
index 09d17f18767..a841d23e0a2 100644
--- a/packages/twenty-shared/src/application/index.ts
+++ b/packages/twenty-shared/src/application/index.ts
@@ -179,6 +179,11 @@ export type {
} from './frontComponentManifestType';
export type { FrontComponentSharedDependenciesManifest } from './frontComponentSharedDependenciesManifestType';
export type { HealthCheckLogicFunctionApplicationManifest } from './healthCheckLogicFunctionApplicationType';
+export type {
+ IdentifyAccountPayload,
+ IdentifiedAccount,
+ IdentifyAccountResult,
+} from './identifyAccountType';
export type { IndexFieldManifest } from './indexFieldManifestType';
export type { IndexManifest } from './indexManifestType';
export type {