Skip to content

The open alternative to Salesforce, designed for AI.

Fix app OAuth recovery and return navigation (#28548)

nitin65354f9e1d04
diff --git a/packages/twenty-front/src/modules/error-handler/components/ErrorMessageEffect.tsx b/packages/twenty-front/src/modules/error-handler/components/ErrorMessageEffect.tsx
index 3b91c00f46f..ea010b4dc4f 100644
--- a/packages/twenty-front/src/modules/error-handler/components/ErrorMessageEffect.tsx
+++ b/packages/twenty-front/src/modules/error-handler/components/ErrorMessageEffect.tsx
@@ -1,12 +1,14 @@
import { useEffect } from 'react';
-import { useSearchParams } from 'react-router-dom';
+import { useLocation, useNavigate, useSearchParams } from 'react-router-dom';
import { isDefined } from 'twenty-shared/utils';
import { useToast } from 'twenty-ui/components/feedback';
export const ErrorMessageEffect = () => {
const { enqueueToast } = useToast();
- const [searchParams, setSearchParams] = useSearchParams();
+ const [searchParams] = useSearchParams();
+ const { hash } = useLocation();
+ const navigate = useNavigate();
const errorMessage = searchParams.get('errorMessage');
useEffect(() => {
@@ -18,9 +20,9 @@ export const ErrorMessageEffect = () => {
});
const newSearchParams = new URLSearchParams(searchParams);
newSearchParams.delete('errorMessage');
- setSearchParams(newSearchParams);
+ navigate({ search: newSearchParams.toString(), hash }, { replace: true });
}
- }, [enqueueToast, errorMessage, searchParams, setSearchParams]);
+ }, [enqueueToast, errorMessage, hash, navigate, searchParams]);
return <></>;
};
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 b71af434bfe..5b97ed2bd7c 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
@@ -285,6 +285,23 @@ export class ConnectionProviderOAuthFlowService {
});
}
+ async findErrorRedirectTargetFromState(state: string): Promise<{
+ workspaceId: string;
+ redirectLocation: string | null;
+ } | null> {
+ try {
+ const { workspaceId, redirectLocation } = await this.verifyState(state);
+
+ return { workspaceId, redirectLocation };
+ } catch (error) {
+ this.logger.warn(
+ `Could not read the OAuth state for the error redirect: ${error instanceof Error ? error.message : String(error)}`,
+ );
+
+ return null;
+ }
+ }
+
private async verifyState(state: string): Promise<AppOAuthStateJwtPayload> {
try {
const verified = (await this.jwtWrapperService.verifyJwtToken(
@@ -381,6 +398,7 @@ export class ConnectionProviderOAuthFlowService {
lastCredentialsRefreshedAt: new Date(),
authFailedAt: null,
authFailedReason: null,
+ archivedAt: null,
scope,
handle,
externalAccountId: identifiedAccount?.externalAccountId ?? null,
diff --git a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
index 6394feb8b02..a0f1bcce156 100644
--- a/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
+++ b/packages/twenty-server/src/engine/core-modules/application/connection-provider/connection-provider-oauth.controller.ts
@@ -1,9 +1,15 @@
import { Controller, Get, Logger, Query, Res, UseGuards } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
+import { isNonEmptyString } from '@sniptt/guards';
import { type Response } from 'express';
+import { SOURCE_LOCALE } from 'twenty-shared/translations';
import { ApiPath, SettingsPath } from 'twenty-shared/types';
-import { getSettingsPath, isDefined } from 'twenty-shared/utils';
+import {
+ getSettingsPath,
+ isDefined,
+ isSafeInternalPath,
+} from 'twenty-shared/utils';
import { Repository } from 'typeorm';
import { ConnectionProviderOAuthFlowService } from 'src/engine/core-modules/application/connection-provider/connection-provider-oauth-flow.service';
@@ -18,6 +24,7 @@ import { TransientTokenService } from 'src/engine/core-modules/auth/token/servic
import { parseRelativeUrl } from 'src/engine/core-modules/domain/domain-server-config/utils/parse-relative-url.util';
import { WorkspaceDomainsService } from 'src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service';
import { GuardRedirectService } from 'src/engine/core-modules/guard-redirect/services/guard-redirect.service';
+import { I18nService } from 'src/engine/core-modules/i18n/i18n.service';
import { TwentyConfigService } from 'src/engine/core-modules/twenty-config/twenty-config.service';
import { UserWorkspaceEntity } from 'src/engine/core-modules/user-workspace/user-workspace.entity';
import { WorkspaceEntity } from 'src/engine/core-modules/workspace/workspace.entity';
@@ -36,6 +43,7 @@ export class ConnectionProviderOAuthController {
private readonly workspaceDomainsService: WorkspaceDomainsService,
private readonly guardRedirectService: GuardRedirectService,
private readonly twentyConfigService: TwentyConfigService,
+ private readonly i18nService: I18nService,
@InjectRepository(WorkspaceEntity)
private readonly workspaceRepository: Repository<WorkspaceEntity>,
@InjectRepository(UserWorkspaceEntity)
@@ -129,7 +137,12 @@ export class ConnectionProviderOAuthController {
error instanceof Error ? error.stack : undefined,
);
- return this.redirectToError(res, error, workspace);
+ return this.redirectToError({
+ res,
+ error,
+ workspace,
+ redirectLocation: redirectLocation ?? null,
+ });
}
}
@@ -141,26 +154,24 @@ export class ConnectionProviderOAuthController {
@Query('error_description') errorDescription: string | undefined,
@Res() res: Response,
) {
- let workspace: WorkspaceEntity | null = null;
-
if (errorParam) {
- return this.redirectToError(
+ return this.redirectToErrorFromState({
res,
- new Error(
+ state,
+ error: new Error(
`OAuth provider returned error: ${errorParam}${errorDescription ? `: ${errorDescription}` : ''}`,
),
- workspace,
- );
+ });
}
if (!code || !state) {
- return this.redirectToError(
+ return this.redirectToErrorFromState({
res,
- new Error(
+ state,
+ error: new Error(
'OAuth callback is missing the `code` or `state` query parameter',
),
- workspace,
- );
+ });
}
try {
@@ -170,7 +181,7 @@ export class ConnectionProviderOAuthController {
state,
});
- workspace = await this.workspaceRepository.findOneBy({
+ const workspace = await this.workspaceRepository.findOneBy({
id: workspaceId,
});
@@ -181,10 +192,14 @@ export class ConnectionProviderOAuthController {
);
}
- const { pathname, searchParams, hash } = parseRelativeUrl(
- redirectLocation ||
- getSettingsPath(SettingsPath.ApplicationDetail, { applicationId }),
- );
+ const hasRedirectLocation = isNonEmptyString(redirectLocation);
+
+ const { pathname, searchParams, hash } = this.parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname: getSettingsPath(SettingsPath.ApplicationDetail, {
+ applicationId,
+ }),
+ });
const url = this.workspaceDomainsService.buildWorkspaceURL({
workspace,
@@ -194,21 +209,75 @@ export class ConnectionProviderOAuthController {
});
// Frontend tab list reads the URL hash to pick the active tab.
- if (!redirectLocation) {
+ if (!hasRedirectLocation) {
url.hash = 'settings';
}
return res.redirect(url.toString());
} catch (error) {
- return this.redirectToError(res, error, workspace);
+ return this.redirectToErrorFromState({ res, state, error });
}
}
- private redirectToError(
- res: Response,
- error: unknown,
- workspace: WorkspaceEntity | null,
- ) {
+ private async redirectToErrorFromState({
+ res,
+ state,
+ error,
+ }: {
+ res: Response;
+ state: string | undefined;
+ error: unknown;
+ }) {
+ const errorRedirectTarget = isNonEmptyString(state)
+ ? await this.oauthProviderFlowService.findErrorRedirectTargetFromState(
+ state,
+ )
+ : null;
+
+ const workspace = isDefined(errorRedirectTarget)
+ ? await this.workspaceRepository.findOneBy({
+ id: errorRedirectTarget.workspaceId,
+ })
+ : null;
+
+ return this.redirectToError({
+ res,
+ error,
+ workspace,
+ redirectLocation: errorRedirectTarget?.redirectLocation ?? null,
+ });
+ }
+
+ private parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname,
+ }: {
+ redirectLocation: string | null | undefined;
+ fallbackPathname: string;
+ }) {
+ return parseRelativeUrl(
+ isDefined(redirectLocation) && isSafeInternalPath(redirectLocation)
+ ? redirectLocation
+ : fallbackPathname,
+ );
+ }
+
+ private redirectToError({
+ res,
+ error,
+ workspace,
+ redirectLocation,
+ }: {
+ res: Response;
+ error: unknown;
+ workspace: WorkspaceEntity | null;
+ redirectLocation: string | null;
+ }) {
+ const { pathname, searchParams, hash } = this.parseRedirectLocation({
+ redirectLocation,
+ fallbackPathname: getSettingsPath(SettingsPath.Accounts),
+ });
+
return res.redirect(
this.guardRedirectService.getRedirectErrorUrlAndCaptureExceptions({
error: error instanceof Error ? error : new Error(String(error)),
@@ -218,9 +287,26 @@ export class ConnectionProviderOAuthController {
workspace?.subdomain ??
this.twentyConfigService.get('DEFAULT_SUBDOMAIN'),
customDomain: workspace?.customDomain ?? null,
+ isCustomDomainEnabled: workspace?.isCustomDomainEnabled ?? false,
},
- pathname: getSettingsPath(SettingsPath.Accounts),
+ pathname,
+ searchParams,
+ hash,
+ errorMessage: this.getTokenExchangeFailureMessage(error),
}),
);
}
+
+ private getTokenExchangeFailureMessage(error: unknown): string | undefined {
+ if (
+ !(error instanceof ConnectionProviderException) ||
+ error.code !== ConnectionProviderExceptionCode.TOKEN_EXCHANGE_FAILED
+ ) {
+ return undefined;
+ }
+
+ return this.i18nService
+ .getI18nInstance(SOURCE_LOCALE)
+ ._(error.userFriendlyMessage);
+ }
}
diff --git a/packages/twenty-server/src/engine/core-modules/auth/guards/google-apis-oauth-exchange-code-for-token.guard.ts b/packages/twenty-server/src/engine/core-modules/auth/guards/google-apis-oauth-exchange-code-for-token.guard.ts
index aa64a865963..b80643e188f 100644
--- a/packages/twenty-server/src/engine/core-modules/auth/guards/google-apis-oauth-exchange-code-for-token.guard.ts
+++ b/packages/twenty-server/src/engine/core-modules/auth/guards/google-apis-oauth-exchange-code-for-token.guard.ts
@@ -70,15 +70,16 @@ export class GoogleAPIsOauthExchangeCodeForTokenGuard extends AuthGuard(
);
const redirectErrorUrl =
- this.workspaceDomainsService.computeWorkspaceRedirectErrorUrl(
- 'We cannot connect to your Google account, please try again with more permissions, or a valid account',
- {
+ this.workspaceDomainsService.computeWorkspaceRedirectErrorUrl({
+ errorMessage:
+ 'We cannot connect to your Google account, please try again with more permissions, or a valid account',
+ workspace: {
subdomain: workspace.subdomain,
customDomain: workspace.customDomain,
isCustomDomainEnabled: workspace.isCustomDomainEnabled ?? false,
},
- '/settings/accounts',
- );
+ pathname: '/settings/accounts',
+ });
context.switchToHttp().getResponse().redirect(redirectErrorUrl);
diff --git a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
index 7f26cf3411a..248b88aeafb 100644
--- a/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/domain/workspace-domains/services/workspace-domains.service.ts
@@ -50,15 +50,24 @@ export class WorkspaceDomainsService {
return url;
}
- computeWorkspaceRedirectErrorUrl(
- errorMessage: string,
- workspace: WorkspaceDomainConfig,
- pathname: string,
- ) {
+ computeWorkspaceRedirectErrorUrl({
+ errorMessage,
+ workspace,
+ pathname,
+ searchParams,
+ hash,
+ }: {
+ errorMessage: string;
+ workspace: WorkspaceDomainConfig;
+ pathname: string;
+ searchParams?: Record<string, string>;
+ hash?: string;
+ }) {
const url = this.buildWorkspaceURL({
workspace,
pathname,
- searchParams: { errorMessage },
+ searchParams: { ...searchParams, errorMessage },
+ hash,
});
return url.toString();
diff --git a/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts b/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts
index 70fd8c8452a..2575518a3b5 100644
--- a/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts
+++ b/packages/twenty-server/src/engine/core-modules/guard-redirect/services/guard-redirect.service.ts
@@ -85,6 +85,9 @@ export class GuardRedirectService {
error,
workspace,
pathname,
+ searchParams,
+ hash,
+ errorMessage,
}: {
error: Error | AuthException;
workspace: {
@@ -94,22 +97,30 @@ export class GuardRedirectService {
isCustomDomainEnabled?: boolean;
};
pathname: string;
+ searchParams?: Record<string, string>;
+ hash?: string;
+ errorMessage?: string;
}) {
this.captureException(error, workspace.id);
- const errorMessage =
- error instanceof AuthException
- ? error.message
- : `Authentication error: ${error instanceof Error ? error.message : String(error)}`;
-
- return this.workspaceDomainsService.computeWorkspaceRedirectErrorUrl(
- errorMessage,
- {
+ return this.workspaceDomainsService.computeWorkspaceRedirectErrorUrl({
+ errorMessage: errorMessage ?? this.getDefaultRedirectErrorMessage(error),
+ workspace: {
subdomain: workspace.subdomain,
customDomain: workspace.customDomain,
isCustomDomainEnabled: workspace.isCustomDomainEnabled ?? false,
},
pathname,
- );
+ searchParams,
+ hash,
+ });
+ }
+
+ private getDefaultRedirectErrorMessage(error: Error | AuthException) {
+ if (error instanceof AuthException) {
+ return error.message;
+ }
+
+ return `Authentication error: ${error.message}`;
}
}
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
index 61a636f3351..d5fbaa0e93e 100644
--- 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
@@ -59,6 +59,13 @@ describe('app connection OAuth callback', () => {
tokenExchanges.push(code);
+ if (code.startsWith('rejected:')) {
+ return HttpResponse.json(
+ { error: 'invalid_client', error_description: 'Bad client secret' },
+ { status: 401 },
+ );
+ }
+
return HttpResponse.json({
access_token: code,
refresh_token: `refresh-${code}`,
@@ -91,11 +98,17 @@ describe('app connection OAuth callback', () => {
});
};
- const authorize = async ({
- reconnectingConnectedAccountId,
- }: {
+ type AuthorizeArgs = {
reconnectingConnectedAccountId?: string;
- } = {}): Promise<string> => {
+ redirectLocation?: string;
+ providerName?: string;
+ };
+
+ const requestAuthorization = async ({
+ reconnectingConnectedAccountId,
+ redirectLocation,
+ providerName = provider.name,
+ }: AuthorizeArgs = {}): Promise<URL> => {
const transient = await generateTransientTokenResponse({
token: APPLE_JANE_ADMIN_ACCESS_TOKEN,
});
@@ -106,14 +119,20 @@ describe('app connection OAuth callback', () => {
.get('/auth/apps/authorize')
.query({
applicationId: provider.applicationId,
- providerName: provider.name,
+ providerName,
transientToken:
transient.data.generateTransientToken.transientToken.token,
reconnectingConnectedAccountId,
+ redirectLocation,
});
expect(response.status).toBe(302);
- const authorizationUrl = new URL(response.headers.location);
+
+ return new URL(response.headers.location);
+ };
+
+ const authorize = async (args: AuthorizeArgs = {}): Promise<string> => {
+ const authorizationUrl = await requestAuthorization(args);
expect(authorizationUrl.origin).toBe(
'https://connection-provider.example.com',
@@ -298,6 +317,30 @@ export const handler = ({ connectedAccountId }) => {
]);
});
+ it('restores an archived connection when the reconnect resolves to the same account', async () => {
+ await callback(await authorize(), 'team-a:first');
+ const [original] = await readAccounts();
+
+ await globalThis.testDataSource.query(
+ 'UPDATE core."connectedAccount" SET "archivedAt" = NOW(), "authFailedAt" = NOW(), "accessToken" = NULL, "refreshToken" = NULL WHERE id = $1',
+ [original.id],
+ );
+
+ const redirect = await callback(
+ await authorize({ reconnectingConnectedAccountId: original.id }),
+ 'team-a:second',
+ );
+ const [reconnected] = await readAccounts();
+
+ expect(redirect.searchParams.has('errorMessage')).toBe(false);
+ expect(reconnected).toMatchObject({
+ id: original.id,
+ archivedAt: null,
+ authFailedAt: null,
+ });
+ expect(decryptAccessToken(reconnected)).toBe('team-a:second');
+ });
+
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();
@@ -397,6 +440,94 @@ export const handler = ({ connectedAccountId }) => {
expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
});
+ it('returns to where the flow started with a short message when the token exchange fails', async () => {
+ const redirectLocation = `/settings/accounts/applications/${provider.applicationId}#connections`;
+
+ const redirect = await callback(
+ await authorize({ redirectLocation }),
+ 'rejected:first',
+ );
+
+ expect(redirect.pathname).toBe(
+ `/settings/accounts/applications/${provider.applicationId}`,
+ );
+ expect(redirect.hash).toBe('#connections');
+ expect(redirect.searchParams.get('errorMessage')).toBe(
+ 'Failed to exchange the authorization code for an access token.',
+ );
+ expect(tokenExchanges).toEqual(['rejected:first']);
+ expect(await readAccounts()).toEqual([]);
+ });
+
+ describe('error redirect target on authorize', () => {
+ const UNKNOWN_PROVIDER_NAME = 'unknown-provider';
+
+ it.each(['https://evil.com/x', '//evil.com/x', '/\\evil.com'])(
+ 'stays on the workspace URL when redirectLocation is %s',
+ async (redirectLocation) => {
+ const fallbackRedirect = await requestAuthorization({
+ providerName: UNKNOWN_PROVIDER_NAME,
+ });
+ const redirect = await requestAuthorization({
+ providerName: UNKNOWN_PROVIDER_NAME,
+ redirectLocation,
+ });
+
+ expect(redirect.origin).toBe(fallbackRedirect.origin);
+ expect(redirect.hostname).not.toContain('evil.com');
+ expect(redirect.searchParams.get('errorMessage')).not.toBeNull();
+ },
+ );
+
+ it.each(['http://', '//'])(
+ 'falls back to the accounts page when redirectLocation is the malformed %s',
+ async (redirectLocation) => {
+ const fallbackRedirect = await requestAuthorization({
+ providerName: UNKNOWN_PROVIDER_NAME,
+ });
+ const redirect = await requestAuthorization({
+ providerName: UNKNOWN_PROVIDER_NAME,
+ redirectLocation,
+ });
+
+ expect(redirect.origin).toBe(fallbackRedirect.origin);
+ expect(redirect.pathname).toBe('/settings/accounts');
+ expect(redirect.searchParams.get('errorMessage')).not.toBeNull();
+ },
+ );
+
+ it('lands on the custom domain when the workspace has one enabled', async () => {
+ const customDomain = `oauth-${v4().slice(0, 8)}.example.com`;
+ const [original] = await globalThis.testDataSource.query(
+ 'SELECT "customDomain", "isCustomDomainEnabled" FROM core.workspace WHERE id = $1',
+ [SEED_APPLE_WORKSPACE_ID],
+ );
+
+ await globalThis.testDataSource.query(
+ 'UPDATE core.workspace SET "customDomain" = $1, "isCustomDomainEnabled" = true WHERE id = $2',
+ [customDomain, SEED_APPLE_WORKSPACE_ID],
+ );
+
+ try {
+ const redirect = await requestAuthorization({
+ providerName: UNKNOWN_PROVIDER_NAME,
+ });
+
+ expect(redirect.hostname).toBe(customDomain);
+ expect(redirect.searchParams.get('errorMessage')).not.toBeNull();
+ } finally {
+ await globalThis.testDataSource.query(
+ 'UPDATE core.workspace SET "customDomain" = $1, "isCustomDomainEnabled" = $2 WHERE id = $3',
+ [
+ original.customDomain,
+ original.isCustomDomainEnabled,
+ SEED_APPLE_WORKSPACE_ID,
+ ],
+ );
+ }
+ });
+ });
+
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');
@@ -404,6 +535,7 @@ export const handler = ({ connectedAccountId }) => {
expect(redirect.searchParams.get('errorMessage')).toContain(
'invalid or expired',
);
+ expect(redirect.pathname).toBe('/settings/accounts');
expect(tokenExchanges).toEqual([]);
expect(readExecutions(onConnectExecutionsPath)).toEqual([]);
expect(await readAccounts()).toEqual([]);