Skip to content

SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.

OAuth refactoring + shared config + security fixes

alaa-eddinee5c92b38577e
diff --git a/packages/app/src/backend/middlewares/oauthStrategy.mw.ts b/packages/app/src/backend/middlewares/oauthStrategy.mw.ts
index 5b8a5017..6dc25004 100644
--- a/packages/app/src/backend/middlewares/oauthStrategy.mw.ts
+++ b/packages/app/src/backend/middlewares/oauthStrategy.mw.ts
@@ -1,6 +1,7 @@
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import passport from 'passport';
-import { strategyConfig } from '../routes/oauth/helper/strategyConfig';
import { replaceTemplateVariablesOptimized } from '../routes/oauth/helper/oauthHelper';
+import { strategyConfig } from '../routes/oauth/helper/strategyConfig';
export const oauthStrategyInitialization = async (req, res, next) => {
const { service, scope } = req.body;
@@ -9,9 +10,9 @@ export const oauthStrategyInitialization = async (req, res, next) => {
return res.status(400).send({ error: 'Service is required.' });
}
try {
- // Determine if the strategy is OAuth1.0 or OAuth2.0 based on the service
- const isOAuth2 = ['google', 'linkedin', 'oauth2'].includes(service);
- const isOAuth1 = ['twitter', 'oauth1'].includes(service);
+ // Determine if the strategy is OAuth1.0 or OAuth2.0 based on the service using centralized configuration
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(service);
+ const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(service);
const strategy = isOAuth2 ? 'oauth2' : 'oauth';
req.session.strategyType = strategy;
req.session.scopes = scope ?? '';
@@ -29,27 +30,82 @@ export const oauthStrategyInitialization = async (req, res, next) => {
// Prepare the configuration
let config: any = { ...defaultConfig }; // Spread operator for shallow clone
- // Override default config with body parameters
- const updatedReqBody = await replaceTemplateVariablesOptimized(req).catch((error) => {
- console.log('error', error);
- return { error };
- });
-
- Object.entries(updatedReqBody).forEach(([key, value]) => {
- if (key === 'oauth1CallbackURL' || key === 'oauth2CallbackURL') {
- config['callbackURL'] = value;
- } else if (key in config) {
- config[key] = value;
- }
- });
+
+ // Use session-stored configuration instead of URL parameters
+ if (isOAuth2 && req.session.oauth2Config) {
+ const oauth2Config = req.session.oauth2Config;
+
+ // Handle template variables in session-stored config
+ const configToProcess = { ...oauth2Config };
+ const mockReq = {
+ body: configToProcess,
+ _team: req._team,
+ session: req.session,
+ };
+
+ const processedConfig = await replaceTemplateVariablesOptimized(mockReq).catch((error) => {
+ console.log('Template processing error for OAuth2:', error);
+ return configToProcess;
+ });
+
+ config.clientID = processedConfig.clientID;
+ config.clientSecret = processedConfig.clientSecret; // Safe from session + templates resolved
+ config.callbackURL = processedConfig.callbackURL;
+ if (processedConfig.authorizationURL)
+ config.authorizationURL = processedConfig.authorizationURL;
+ if (processedConfig.tokenURL) config.tokenURL = processedConfig.tokenURL;
+ } else if (isOAuth1 && req.session.oauth1Config) {
+ const oauth1Config = req.session.oauth1Config;
+
+ // Handle template variables in session-stored config
+ const configToProcess = { ...oauth1Config };
+ const mockReq = {
+ body: configToProcess,
+ _team: req._team,
+ session: req.session,
+ };
+
+ //TODO : do we really need to handle template variables for oauth
+ const processedConfig = await replaceTemplateVariablesOptimized(mockReq).catch((error) => {
+ console.log('Template processing error for OAuth1:', error);
+ return configToProcess;
+ });
+
+ config.consumerKey = processedConfig.consumerKey;
+ config.consumerSecret = processedConfig.consumerSecret; // Safe from session + templates resolved
+ config.callbackURL = processedConfig.callbackURL;
+ if (processedConfig.requestTokenURL) config.requestTokenURL = processedConfig.requestTokenURL;
+ if (processedConfig.accessTokenURL) config.accessTokenURL = processedConfig.accessTokenURL;
+ if (processedConfig.userAuthorizationURL)
+ config.userAuthorizationURL = processedConfig.userAuthorizationURL;
+ } else {
+ // Fallback to legacy URL parameter method (for backward compatibility)
+ //TODO : do we really need to handle template variables for oauth
+ const updatedReqBody = await replaceTemplateVariablesOptimized(req).catch((error) => {
+ console.log('error', error);
+ return { error };
+ });
+
+ Object.entries(updatedReqBody).forEach(([key, value]) => {
+ if (key === 'oauth1CallbackURL' || key === 'oauth2CallbackURL') {
+ config['callbackURL'] = value;
+ } else if (key in config) {
+ config[key] = value;
+ }
+ });
+ }
// Derive callback URL when missing
if (!config['callbackURL']) {
try {
const origin = req.headers?.origin || `${req.protocol}://${req.get('host')}`;
const internalService = String(service).toLowerCase();
- const isOAuth2 = ['google', 'linkedin', 'oauth2'].includes(internalService);
- const provider = isOAuth2 ? (internalService === 'oauth2' ? 'oauth2' : internalService) : 'oauth1';
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(internalService);
+ const provider = isOAuth2
+ ? internalService === 'oauth2'
+ ? 'oauth2'
+ : internalService
+ : 'oauth1';
config['callbackURL'] = `${origin}/oauth/${provider}/callback`;
} catch (e) {
// leave as undefined if cannot derive
@@ -57,13 +113,19 @@ export const oauthStrategyInitialization = async (req, res, next) => {
}
// Setup the callback function for the strategy
- let strategyCallback = null;
+ let strategyCallback: any = null;
if (isOAuth2) {
- strategyCallback = (accessToken, refreshToken, params, profile, done) =>
- processStrategy(accessToken, refreshToken, params, profile, done, service);
+ strategyCallback = (
+ accessToken: any,
+ refreshToken: any,
+ params: any,
+ profile: any,
+ done: any,
+ ) => processStrategy(accessToken, refreshToken, params, profile, done);
} else if (isOAuth1) {
- strategyCallback = (token, tokenSecret, profile, done) =>
- processStrategy(token, tokenSecret, profile, done, service);
+ strategyCallback = (token: any, tokenSecret: any, profile: any, done: any) =>
+ // @ts-ignore - OAuth1 processStrategy signature mismatch
+ processStrategy(token, tokenSecret, profile, done);
}
// Unuse the previous strategy if it was already used
@@ -72,7 +134,7 @@ export const oauthStrategyInitialization = async (req, res, next) => {
}
// Use the new strategy with updated configuration
- passport.use(strategy, new Strategy(config, strategyCallback));
+ passport.use(strategy, new (Strategy as any)(config, strategyCallback));
next();
} catch (error) {
diff --git a/packages/app/src/backend/routes/oauth/router.ts b/packages/app/src/backend/routes/oauth/router.ts
index e8cd6aac..437ec173 100644
--- a/packages/app/src/backend/routes/oauth/router.ts
+++ b/packages/app/src/backend/routes/oauth/router.ts
@@ -1,7 +1,9 @@
-import { mapStatusCodeToMessage } from '@src/shared/utils/oauth.utils';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
+import { mapStatusCodeToMessage } from '@src/shared/helpers/oauth/oauth.utils';
import axios from 'axios';
import crypto from 'crypto';
import express from 'express';
+import rateLimit from 'express-rate-limit';
import passport from 'passport';
import { includeTeamDetails } from '../../middlewares/auth.mw';
import { oauthStrategyInitialization } from '../../middlewares/oauthStrategy.mw';
@@ -9,7 +11,22 @@ import { getTeamSettingsObj, saveTeamSettingsObj } from '../../services/team-dat
import { replaceTemplateVariablesOptimized } from './helper/oauthHelper';
const router = express.Router();
+// Rate limiting for OAuth initialization
+const oauthInitLimit = rateLimit({
+ windowMs: 5 * 60 * 1000, // 5 minutes
+ max: 20, // Limit each IP to 20 OAuth init requests per windowMs
+ message: { error: 'Too many OAuth initialization attempts. Please try again later.' },
+ standardHeaders: true,
+ legacyHeaders: false,
+ // Skip rate limiting for trusted IPs (optional)
+ skip: (req) => {
+ const trustedIPs = process.env.TRUSTED_IPS?.split(',') || [];
+ return trustedIPs.includes(req.ip);
+ },
+});
+
// Websites that don't provide expires_in But estimated times in docs.
+//TODO : this need to be configured in oauth services json file
const PROVIDER_EXPIRATION_TIMES = {
'public-api.wordpress.com': {
expiresInSeconds: 14 * 24 * 60 * 60, // 14 days in seconds
@@ -98,90 +115,151 @@ router.post('/checkAuth', includeTeamDetails, async (req, res) => {
}
});
-router.post('/init', includeTeamDetails, oauthStrategyInitialization, async (req, res) => {
- // Store the frontend origin from the referer or origin header
- const referer = req.headers.referer || req.headers.referrer || req.headers.origin;
- if (referer && typeof referer === 'string') {
- try {
- const frontendOrigin = new URL(referer).origin;
- req.session.frontendOrigin = frontendOrigin;
- } catch (error) {
- console.error('[/oauth/init] Invalid referer/origin URL:', referer);
+router.post(
+ '/init',
+ oauthInitLimit,
+ includeTeamDetails,
+ oauthStrategyInitialization,
+ async (req, res) => {
+ // Validate and store frontend origin
+ const referer = req.headers.referer || req.headers.referrer || req.headers.origin;
+ if (referer && typeof referer === 'string') {
+ try {
+ const frontendOrigin = new URL(referer).origin;
+
+ // Validate against allowed origins (add your allowed origins to env)
+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || [frontendOrigin];
+ if (!allowedOrigins.includes(frontendOrigin)) {
+ console.warn(`[/oauth/init] Unauthorized origin: ${frontendOrigin}`);
+ return res.status(403).json({ error: 'Origin not allowed' });
+ }
+
+ req.session.frontendOrigin = frontendOrigin;
+ } catch (error) {
+ console.error('[/oauth/init] Invalid referer/origin URL:', referer);
+ return res.status(400).json({ error: 'Invalid origin' });
+ }
}
- }
- try {
- const {
- service,
- scope,
- clientID,
- clientSecret,
- authorizationURL,
- tokenURL,
- oauth2CallbackURL,
- // OAuth1 parameters
- consumerKey,
- consumerSecret,
- requestTokenURL,
- accessTokenURL,
- userAuthorizationURL,
- oauth1CallbackURL,
- } = req.body;
-
- let authUrl = `/oauth/${service}`;
-
- if (['google', 'linkedin', 'oauth2'].includes(service)) {
- // OAuth2 flow
- const oauthParams: any = {
- scopes: encodeURIComponent(scope),
- clientID: encodeURIComponent(clientID),
- clientSecret: encodeURIComponent(clientSecret),
- callbackURL: encodeURIComponent(oauth2CallbackURL),
- };
+ try {
+ const {
+ service,
+ scope,
+ clientID,
+ clientSecret,
+ authorizationURL,
+ tokenURL,
+ oauth2CallbackURL,
+ // OAuth1 parameters
+ consumerKey,
+ consumerSecret,
+ requestTokenURL,
+ accessTokenURL,
+ userAuthorizationURL,
+ oauth1CallbackURL,
+ } = req.body;
+
+ // Input validation
+ if (!service || typeof service !== 'string') {
+ return res.status(400).json({ error: 'Service is required and must be a string' });
+ }
- if (authorizationURL) oauthParams.authorizationURL = encodeURIComponent(authorizationURL);
- if (tokenURL) oauthParams.tokenURL = encodeURIComponent(tokenURL);
-
- authUrl +=
- '?' +
- Object.entries(oauthParams)
- .map(([key, value]) => `${key}=${value}`)
- .join('&');
- } else if (['oauth1', 'twitter'].includes(service)) {
- // OAuth1 flow
- const oauthParams: any = {
- scopes: encodeURIComponent(scope || ''),
- consumerKey: encodeURIComponent(consumerKey),
- consumerSecret: encodeURIComponent(consumerSecret),
- callbackURL: encodeURIComponent(oauth1CallbackURL),
+ // Validate URLs if provided
+ const validateURL = (url: string, fieldName: string) => {
+ if (!url) return;
+ try {
+ const parsed = new URL(url);
+ if (!['http:', 'https:'].includes(parsed.protocol)) {
+ throw new Error(`${fieldName} must use HTTP or HTTPS`);
+ }
+ } catch (error) {
+ throw new Error(`Invalid ${fieldName}: ${error.message}`);
+ }
};
- if (requestTokenURL) oauthParams.requestTokenURL = encodeURIComponent(requestTokenURL);
- if (accessTokenURL) oauthParams.accessTokenURL = encodeURIComponent(accessTokenURL);
- if (userAuthorizationURL) oauthParams.userAuthorizationURL = encodeURIComponent(userAuthorizationURL);
+ try {
+ if (authorizationURL) validateURL(authorizationURL, 'authorizationURL');
+ if (tokenURL) validateURL(tokenURL, 'tokenURL');
+ if (requestTokenURL) validateURL(requestTokenURL, 'requestTokenURL');
+ if (accessTokenURL) validateURL(accessTokenURL, 'accessTokenURL');
+ if (userAuthorizationURL) validateURL(userAuthorizationURL, 'userAuthorizationURL');
+ if (oauth2CallbackURL) validateURL(oauth2CallbackURL, 'oauth2CallbackURL');
+ if (oauth1CallbackURL) validateURL(oauth1CallbackURL, 'oauth1CallbackURL');
+ } catch (validationError) {
+ return res.status(400).json({ error: validationError.message });
+ }
+
+ if (OAuthServicesRegistry.isOAuth2Service(service) || service === 'oauth2') {
+ // OAuth2 flow - Store sensitive data in session, return clean URL
- authUrl +=
- '?' +
- Object.entries(oauthParams)
- .map(([key, value]) => `${key}=${value}`)
- .join('&');
- } else {
- // Unsupported service
- return res.status(400).json({ error: 'Invalid or unsupported service.' });
+ // Validate required OAuth2 fields
+ if (!clientID || !clientSecret) {
+ return res
+ .status(400)
+ .json({ error: 'clientID and clientSecret are required for OAuth2' });
+ }
+
+ // Store OAuth2 configuration in session (server-side only)
+ req.session.oauth2Config = {
+ service,
+ clientID,
+ //TODO: Do we need a stronger protection for this?
+ clientSecret, // Safe in session
+ authorizationURL,
+ tokenURL,
+ scope,
+ callbackURL: oauth2CallbackURL,
+ };
+
+ // Return internal URL that will trigger Passport (no secrets exposed)
+ // Let Passport handle state management internally
+ const authUrl = `/oauth/${service}`;
+
+ return res.json({ authUrl });
+ } else if (OAuthServicesRegistry.isOAuth1Service(service) || service === 'oauth1') {
+ // OAuth1 flow - Store sensitive data in session
+
+ // Validate required OAuth1 fields
+ if (!consumerKey || !consumerSecret) {
+ return res
+ .status(400)
+ .json({ error: 'consumerKey and consumerSecret are required for OAuth1' });
+ }
+
+ // Store OAuth1 configuration in session (server-side only)
+ req.session.oauth1Config = {
+ service,
+ consumerKey,
+ //TODO: Do we need a stronger protection for this?
+ consumerSecret, //Safe in session
+ requestTokenURL,
+ accessTokenURL,
+ userAuthorizationURL,
+ callbackURL: oauth1CallbackURL,
+ scope,
+ };
+
+ // Return internal URL that will trigger Passport (no secrets exposed)
+ // Let Passport handle state management internally
+ const authUrl = `/oauth/${service}`;
+
+ return res.json({ authUrl });
+ } else {
+ // Unsupported service
+ return res.status(400).json({ error: 'Invalid or unsupported service.' });
+ }
+ } catch (error) {
+ console.error('Error in /init route:', error);
+ res.status(500).json({ error: 'Failed to initialize authentication' });
}
- // console.log({ authUrl })
- res.json({ authUrl });
- } catch (error) {
- console.error('Error in /init route:', error);
- res.status(500).json({ error: 'Failed to initialize authentication' });
- }
-});
+ },
+);
router.get('/:provider', async (req, res, next) => {
try {
const scopes = req?.session?.scopes?.split(' ') || [];
const strategyOptions: any = {
- state: { beep: `${crypto.randomUUID()}` },
+ state: { beep: `${crypto.randomUUID()}` }, // Let Passport handle state internally
};
// Check if it's Twitter OAuth
@@ -272,8 +350,8 @@ function getCallbackOrigin(req: express.Request): string {
}
// For development, if running on localhost:4000 (backend), assume frontend is on 4002
- const callbackUrl = req.session?.oauth_info?.oauth2CallbackURL ||
- req.session?.oauth_info?.oauth1CallbackURL;
+ const callbackUrl =
+ req.session?.oauth_info?.oauth2CallbackURL || req.session?.oauth_info?.oauth1CallbackURL;
if (callbackUrl && callbackUrl.includes('localhost:4000')) {
return 'http://localhost:4002';
@@ -483,7 +561,12 @@ async function handleTokenStorage(session, oauthUser, req) {
}
}
-async function handleOAuthOperation(settingKey: string, entryId: string, newDataFromAuthFlow: any, req: express.Request) {
+async function handleOAuthOperation(
+ settingKey: string,
+ entryId: string,
+ newDataFromAuthFlow: any,
+ req: express.Request,
+) {
try {
const existingSettings = await getTeamSettingsObj(req, settingKey);
const existingEntryData = existingSettings?.[entryId] || {};
@@ -514,16 +597,20 @@ async function handleOAuthOperation(settingKey: string, entryId: string, newData
// Ensure oauth_info is merged correctly if it exists in both
if ((baseSettings as any).oauth_info && newSettingsFromAuthFlow.oauth_info) {
- mergedSettings.oauth_info = { ...(baseSettings as any).oauth_info, ...newSettingsFromAuthFlow.oauth_info };
+ mergedSettings.oauth_info = {
+ ...(baseSettings as any).oauth_info,
+ ...newSettingsFromAuthFlow.oauth_info,
+ };
}
// Preserve existing display metadata if missing in incoming data
- if ((baseSettings as any).name && !mergedSettings.name) mergedSettings.name = (baseSettings as any).name;
- if ((baseSettings as any).platform && !mergedSettings.platform) mergedSettings.platform = (baseSettings as any).platform;
+ if ((baseSettings as any).name && !mergedSettings.name)
+ mergedSettings.name = (baseSettings as any).name;
+ if ((baseSettings as any).platform && !mergedSettings.platform)
+ mergedSettings.platform = (baseSettings as any).platform;
// Ensure name key exists to classify as named (even if empty)
if (typeof mergedSettings.name === 'undefined') mergedSettings.name = '';
-
// Normalize
mergedSettings = normalizeAuthSettings(mergedSettings);
@@ -628,7 +715,9 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {
const settings = await getTeamSettingsObj(req, 'oauth');
if (!settings || !settings[entryId]) {
- return res.status(404).json({ error: 'No existing OAuth settings found for the provided prefix.' });
+ return res
+ .status(404)
+ .json({ error: 'No existing OAuth settings found for the provided prefix.' });
}
// Parse existing data if it's a string
@@ -666,7 +755,6 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {
if (updatedData.auth_data.expires_in === undefined) {
delete updatedData.auth_data.expires_in;
}
-
} else {
// Old structure: Clear tokens at the top level
updatedData = {
@@ -681,13 +769,16 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {
}
// If tokens were already empty, respond without saving (optional optimization)
- const currentPrimary = existingData.auth_data ? existingData.auth_data.primary : existingData.primary;
- const currentSecondary = existingData.auth_data ? existingData.auth_data.secondary : existingData.secondary;
+ const currentPrimary = existingData.auth_data
+ ? existingData.auth_data.primary
+ : existingData.primary;
+ const currentSecondary = existingData.auth_data
+ ? existingData.auth_data.secondary
+ : existingData.secondary;
if (currentPrimary === '' && currentSecondary === '') {
return res.json({ invalidate: true, message: 'Already signed out.' });
}
-
// Save the updated settings
const saveResult = await saveTeamSettingsObj({
req,
@@ -708,8 +799,6 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {
}
});
-
-
async function getClientCredentialToken({ clientID, clientSecret, tokenURL }) {
try {
// Sanity checks
diff --git a/packages/app/src/backend/routes/pages/builder-sidebar.ts b/packages/app/src/backend/routes/pages/builder-sidebar.ts
index 51c2540b..45766eb6 100644
--- a/packages/app/src/backend/routes/pages/builder-sidebar.ts
+++ b/packages/app/src/backend/routes/pages/builder-sidebar.ts
@@ -94,12 +94,14 @@ const baseMenu: Menu = {
{ name: 'VisionLLM', description: 'Vision LLM', label: 'Vision LLM' },
],
+ Triggers: [{ name: 'GmailTrigger', label: 'Gmail Trigger', description: '' }],
Integrations: [],
};
if (config.env.NODE_ENV === 'PROD') {
//remove memory section
delete baseMenu.Memory;
+ delete baseMenu.Triggers;
}
export const getBuilderSidebarMenu = () => {
diff --git a/packages/app/src/builder-ui/components/APICall.class.ts b/packages/app/src/builder-ui/components/APICall.class.ts
index acf3b754..76832394 100644
--- a/packages/app/src/builder-ui/components/APICall.class.ts
+++ b/packages/app/src/builder-ui/components/APICall.class.ts
@@ -1,23 +1,22 @@
import { errorToast, successToast } from '@src/shared/components/toast';
import { API_CALL_DATA_ENTRIES, SMYTHOS_DOCS_URL } from '@src/shared/constants/general'; // Adjust the path as necessary
import {
- deriveServiceFromOauthInfo,
+ //deriveServiceFromOauthInfo,
extractServiceFromConnection,
getConnectionOauthInfo,
- saveOAuthConnection
-} from '@src/shared/helpers/oauth-api.helper';
+ saveOAuthConnection,
+} from '@src/shared/helpers/oauth/oauth-api.helper';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import {
OAUTH_SERVICES,
extractPlatformFromUrl,
generateOAuthId,
mapInternalToServiceName,
- mapServiceNameToInternal
-} from '@src/shared/utils/oauth.utils';
+ mapServiceNameToInternal,
+} from '@src/shared/helpers/oauth/oauth.utils';
import { builderStore } from '../../shared/state_stores/builder/store';
import { COMP_NAMES } from '../config';
-import {
- generateOAuthModalHTML
-} from '../helpers/oauth-modal.helper';
+import { generateOAuthModalHTML } from '../helpers/oauth/oauth-modal.helper';
import { createBadge } from '../ui/badges'; // *** ADDED: Import createBadge ***
import { destroyCodeEditor, toggleMode } from '../ui/dom';
import { closeTwDialog, twEditValuesWithCallback } from '../ui/tw-dialogs';
@@ -53,9 +52,9 @@ export class APICall extends Component {
return getConnectionOauthInfo(connection, connectionId);
}
- private deriveServiceFromOauthInfo(oauthInfo: any): string {
- return deriveServiceFromOauthInfo(oauthInfo);
- }
+ // private deriveServiceFromOauthInfo(oauthInfo: any): string {
+ // return deriveServiceFromOauthInfo(oauthInfo);
+ // }
protected async prepare() {
try {
@@ -69,7 +68,11 @@ export class APICall extends Component {
const componentSpecificId = `OAUTH_${this.uid}_TOKENS`;
// Use the centralized buildOAuthSelectOptions method
- const options = this.buildOAuthSelectOptions(this.oauthConnections, componentSpecificId, '[APICall.prepare]');
+ const options = this.buildOAuthSelectOptions(
+ this.oauthConnections,
+ componentSpecificId,
+ '[APICall.prepare]',
+ );
// Add 'None' option at the start
options.unshift({ value: 'None', text: 'None', badge: '' });
@@ -487,14 +490,11 @@ export class APICall extends Component {
});
}
- const isOAuth2 = [
- 'Google',
- 'LinkedIn',
- 'Custom OAuth2.0',
- 'OAuth2 Client Credentials',
- ].includes(selectedValue);
+ const isOAuth2 =
+ OAuthServicesRegistry.isOAuth2Service(selectedValue) ||
+ OAuthServicesRegistry.isClientCredentialsService(selectedValue);
let fieldsToUse = isOAuth2 ? [...oauth2Fields] : oauth1Fields; // Use a copy of oauth2Fields to prevent modifying the original array
- if (selectedValue === 'OAuth2 Client Credentials') {
+ if (OAuthServicesRegistry.isClientCredentialsService(selectedValue)) {
// if value is 'OAuth2 Client Credentials',Remove 'authorizationURL', 'oauth2CallbackURL', and 'scope' from fieldsToUse, also hide oauth1Fields
fieldsToUse = fieldsToUse.filter(
(field) => !['authorizationURL', 'oauth2CallbackURL', 'scope'].includes(field),
@@ -568,7 +568,10 @@ export class APICall extends Component {
const selectedConnection = this.oauthConnections[selectedConnectionId];
// console.log('[OAuth Auth] Selected connection:', selectedConnection);
- const synthesizedOauthInfo = this.getConnectionOauthInfo(selectedConnection, selectedConnectionId);
+ const synthesizedOauthInfo = this.getConnectionOauthInfo(
+ selectedConnection,
+ selectedConnectionId,
+ );
// console.log('[OAuth Auth] Synthesized oauth_info:', synthesizedOauthInfo);
if (!selectedConnection || !synthesizedOauthInfo) {
@@ -577,7 +580,7 @@ export class APICall extends Component {
'Selected connection or its oauth_info not found for ID:',
selectedConnectionId,
'Connection:',
- selectedConnection
+ selectedConnection,
);
return;
}
@@ -585,7 +588,11 @@ export class APICall extends Component {
// Validate that required fields are present
if (!synthesizedOauthInfo.service) {
console.error('[OAuth Auth] Missing service field in oauth_info:', synthesizedOauthInfo);
- errorToast('OAuth connection is missing required service information. Please edit and save the connection again.', 'Error', 'alert');
+ errorToast(
+ 'OAuth connection is missing required service information. Please edit and save the connection again.',
+ 'Error',
+ 'alert',
+ );
return;
}
@@ -596,7 +603,8 @@ export class APICall extends Component {
// Normalize callback URLs to the current backend origin across envs (local/staging/prod)
const getDesiredBackendOrigin = () => {
// Prefer configured backend server when available
- const candidate = (this.workspace && (this.workspace as any).server) || window.location.origin;
+ const candidate =
+ (this.workspace && (this.workspace as any).server) || window.location.origin;
try {
const u = new URL(candidate);
return u.origin;
@@ -632,7 +640,11 @@ export class APICall extends Component {
const oauth1Path = `/oauth/${internalService === 'twitter' ? 'oauth1' : internalService}/callback`;
// Ensure correct origin for OAuth2 callbacks
- if (connectionType === 'oauth2' || internalService === 'google' || internalService === 'linkedin') {
+ if (
+ connectionType === 'oauth2' ||
+ internalService === 'google' ||
+ internalService === 'linkedin'
+ ) {
oauthInfoPayload.oauth2CallbackURL = normalizeCallbackOrigin(
oauthInfoPayload.oauth2CallbackURL,
oauth2Path,
@@ -640,7 +652,11 @@ export class APICall extends Component {
}
// Ensure correct origin for OAuth1 callbacks
- if (connectionType === 'oauth' || internalService === 'oauth1' || internalService === 'twitter') {
+ if (
+ connectionType === 'oauth' ||
+ internalService === 'oauth1' ||
+ internalService === 'twitter'
+ ) {
oauthInfoPayload.oauth1CallbackURL = normalizeCallbackOrigin(
oauthInfoPayload.oauth1CallbackURL,
oauth1Path,
@@ -661,18 +677,31 @@ export class APICall extends Component {
let isValid = true;
let missingFields = [];
- if (connectionType === 'oauth2' || isClientCredentials || derivedService === 'Google' || derivedService === 'LinkedIn') {
+ if (
+ connectionType === 'oauth2' ||
+ isClientCredentials ||
+ derivedService === 'Google' ||
+ derivedService === 'LinkedIn'
+ ) {
if (!oauthInfoPayload.tokenURL) missingFields.push('Token URL');
if (!oauthInfoPayload.clientID) missingFields.push('Client ID');
if (!oauthInfoPayload.clientSecret) missingFields.push('Client Secret');
if (
- (connectionType === 'oauth2' || derivedService === 'Google' || derivedService === 'LinkedIn') &&
+ (connectionType === 'oauth2' ||
+ derivedService === 'Google' ||
+ derivedService === 'LinkedIn') &&
!isClientCredentials &&
!oauthInfoPayload.authorizationURL
) {
missingFields.push('Auth URL');
}
- if ((connectionType === 'oauth2' || derivedService === 'Google' || derivedService === 'LinkedIn') && !isClientCredentials && !oauthInfoPayload.scope) {
+ if (
+ (connectionType === 'oauth2' ||
+ derivedService === 'Google' ||
+ derivedService === 'LinkedIn') &&
+ !isClientCredentials &&
+ !oauthInfoPayload.scope
+ ) {
missingFields.push('Scopes');
}
} else if (connectionType === 'oauth') {
@@ -746,7 +775,8 @@ export class APICall extends Component {
this.oauthConnections[selectedConnectionId].auth_data.secondary = data.secondary;
}
if (data.expires_in) {
- this.oauthConnections[selectedConnectionId].auth_data.expires_in = data.expires_in;
+ this.oauthConnections[selectedConnectionId].auth_data.expires_in =
+ data.expires_in;
}
} else {
// Legacy structure - store at root level
@@ -851,7 +881,9 @@ export class APICall extends Component {
if (currentId && this.oauthConnections[currentId] === undefined) {
// try to find a connection that has the same prefix but now exists only once
const prefix = (currentId || '').replace(/_TOKENS$/, '');
- const remapped = Object.keys(this.oauthConnections).find((k) => k.startsWith(prefix) && k.endsWith('_TOKENS'));
+ const remapped = Object.keys(this.oauthConnections).find(
+ (k) => k.startsWith(prefix) && k.endsWith('_TOKENS'),
+ );
if (remapped) {
this.data.oauth_con_id = remapped;
}
@@ -900,8 +932,8 @@ export class APICall extends Component {
}
/**
- * Checks the current authentication status for the selected connection.
- */
+ * Checks the current authentication status for the selected connection.
+ */
private async checkAuthentication(): Promise<boolean> {
const selectedValue = this.data.oauth_con_id;
@@ -988,7 +1020,12 @@ export class APICall extends Component {
// Derive oauth_keys_prefix if not found
let oauth_keys_prefix = oauthInfo?.oauth_keys_prefix;
- if (!oauth_keys_prefix && connectionId && connectionId.startsWith('OAUTH_') && connectionId.endsWith('_TOKENS')) {
+ if (
+ !oauth_keys_prefix &&
+ connectionId &&
+ connectionId.startsWith('OAUTH_') &&
+ connectionId.endsWith('_TOKENS')
+ ) {
oauth_keys_prefix = connectionId.replace('_TOKENS', '');
}
@@ -1012,9 +1049,7 @@ export class APICall extends Component {
});
if (!response.ok) {
- console.error(
- `Auth check failed for ${oauth_keys_prefix}: HTTP status ${response.status}`,
- );
+ console.error(`Auth check failed for ${oauth_keys_prefix}: HTTP status ${response.status}`);
return false;
}
@@ -1037,44 +1072,32 @@ export class APICall extends Component {
}
private updateConfiguration(selectedValue, sidebar) {
- if (selectedValue === 'OAuth2 Client Credentials') {
+ if (OAuthServicesRegistry.isClientCredentialsService(selectedValue)) {
return null;
}
const { cbUrl, key } = this.getOAuthCallbackDetails(selectedValue); // Get the callback details for the selected service
sidebar.querySelector(`[data-field-name="${key}"] span`).innerHTML = cbUrl; // Update callback URL in the sidebar dynamically based on OAuth version
- const configurations = {
- Google: {
- authorizationURL: 'https://accounts.google.com/o/oauth2/v2/auth',
- tokenURL: 'https://oauth2.googleapis.com/token',
- scope: 'https://www.googleapis.com/auth/gmail.readonly',
- oauth2CallbackURL: cbUrl,
- },
- Twitter: {
- requestTokenURL: 'https://api.twitter.com/oauth/request_token',
- accessTokenURL: 'https://api.twitter.com/oauth/access_token',
- userAuthorizationURL: 'https://api.twitter.com/oauth/authorize',
- oauth1CallbackURL: cbUrl,
- },
- LinkedIn: {
- authorizationURL: 'https://www.linkedin.com/oauth/v2/authorization',
- tokenURL: 'https://www.linkedin.com/oauth/v2/accessToken',
- scope: 'r_liteprofile r_emailaddress',
- oauth2CallbackURL: cbUrl,
- },
- };
- return configurations[selectedValue]; // Execute the function based on the selected value and get formData if available
+ // Get service defaults from centralized configuration
+ const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedValue);
+ if (!serviceDefaults || Object.keys(serviceDefaults).length === 0) {
+ return null;
+ }
+
+ // Add callback URL based on OAuth type
+ const configWithCallback: any = { ...serviceDefaults };
+ if (OAuthServicesRegistry.isOAuth2Service(selectedValue)) {
+ configWithCallback.oauth2CallbackURL = cbUrl;
+ } else if (OAuthServicesRegistry.isOAuth1Service(selectedValue)) {
+ configWithCallback.oauth1CallbackURL = cbUrl;
+ }
+
+ return configWithCallback;
}
private isOAuth1(selectedService) {
- const oauth1Services = [
- // Define the list of OAuth 1.0 services directly inside the function
- 'twitter', // Example OAuth 1.0 service
- // Add more OAuth 1.0 services as needed
- ];
- const serviceLower = selectedService?.toLowerCase();
- return oauth1Services.includes(serviceLower) || serviceLower.includes('oauth1.0'); // Check directly if serviceLower is an OAuth 1.0 service or contains "oauth1.0"
+ return OAuthServicesRegistry.isOAuth1Service(selectedService);
}
private getOAuthCallbackDetails(selectedValue) {
@@ -1432,7 +1455,6 @@ export class APICall extends Component {
// Update component messages
this.clearComponentMessages();
-
} else {
// Sign out failed
if (oauth_button) {
@@ -1575,7 +1597,8 @@ export class APICall extends Component {
// Get current connection if editing and determine structure
const currentConnectionRaw = !isNone ? this.oauthConnections[currentValue] : null;
- const isNewStructure = currentConnectionRaw && currentConnectionRaw.auth_data && currentConnectionRaw.auth_settings;
+ const isNewStructure =
+ currentConnectionRaw && currentConnectionRaw.auth_data && currentConnectionRaw.auth_settings;
// Extract the settings part based on structure
const currentSettings = isNewStructure
@@ -1603,7 +1626,7 @@ export class APICall extends Component {
currentName,
currentPlatform,
currentService,
- currentOauthInfo
+ currentOauthInfo,
);
// Show dialog using twEditValuesWithCallback, passing HTML content
@@ -1772,7 +1795,7 @@ export class APICall extends Component {
formData[key] = value as string;
});
- // --- Basic Validation ---
+ // --- Basic Validation ---
if (!formData.name || formData.name.trim() === '') {
errorToast('Name field is required.', 'Error', 'alert');
throw new Error('Validation failed: Name is required.'); // Throw to prevent dialog closing
@@ -1789,7 +1812,9 @@ export class APICall extends Component {
try {
const isCreating = isNone;
- const connectionId = isCreating ? `OAUTH_${generateOAuthId()}_TOKENS` : currentValue;
+ const connectionId = isCreating
+ ? `OAUTH_${generateOAuthId()}_TOKENS`
+ : currentValue;
const service = this.mapServiceNameToInternal(formData.oauthService);
const type = ['Custom OAuth1.0', 'Twitter'].includes(formData.oauthService)
? 'oauth'
@@ -1810,7 +1835,8 @@ export class APICall extends Component {
newOauthInfo.tokenURL = formData.tokenURL || '';
newOauthInfo.clientID = formData.clientID || '';
newOauthInfo.clientSecret = formData.clientSecret || '';
- if (type === 'oauth2') { // Only for full OAuth2
+ if (type === 'oauth2') {
+ // Only for full OAuth2
newOauthInfo.authorizationURL = formData.authorizationURL || '';
newOauthInfo.scope = formData.scope || '';
}
@@ -1827,7 +1853,10 @@ export class APICall extends Component {
const authSettingsToSave = {
name: newOauthInfo.name, // Use name from newOauthInfo
type: type,
- tokenURL: (type === 'oauth2' || type === 'oauth2_client_credentials') ? newOauthInfo.tokenURL : undefined,
+ tokenURL:
+ type === 'oauth2' || type === 'oauth2_client_credentials'
+ ? newOauthInfo.tokenURL
+ : undefined,
oauth_info: newOauthInfo, // Include the full oauth_info
};
// Clean up undefined tokenURL before saving
@@ -1876,8 +1905,6 @@ export class APICall extends Component {
);
}
-
-
// Build OAuth select options from connections with unified name detection and legacy fallback
private buildOAuthSelectOptions(
connections: Record<string, any>,
@@ -1897,7 +1924,7 @@ export class APICall extends Component {
options.push({
value: id,
text: connectionName,
- badge: ''
+ badge: '',
});
} else if (conn?.auth_data && conn?.auth_settings) {
// New structure but no name - treat as legacy to ensure visibility
@@ -1906,7 +1933,7 @@ export class APICall extends Component {
options.push({
value: id,
text: `${service} [${shortId}]`,
- badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1')
+ badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1'),
});
}
}
@@ -1914,7 +1941,11 @@ export class APICall extends Component {
// Second pass: add legacy connections that still exist AND oauthService is not 'None'
// This handles the case where legacy connections haven't been converted yet
- if (connections[componentSpecificId] && this.data.oauthService && this.data.oauthService !== 'None') {
+ if (
+ connections[componentSpecificId] &&
+ this.data.oauthService &&
+ this.data.oauthService !== 'None'
+ ) {
const conn = connections[componentSpecificId];
// Check if this connection has been converted to new structure
@@ -1922,19 +1953,21 @@ export class APICall extends Component {
if (!hasNewStructure) {
// Only add legacy connection if it hasn't been converted to new structure
- const serviceName = conn?.auth_settings?.oauth_info?.service ||
+ const serviceName =
+ conn?.auth_settings?.oauth_info?.service ||
conn?.oauth_info?.service ||
conn?.auth_settings?.type ||
- conn?.type || 'Unknown';
+ conn?.type ||
+ 'Unknown';
const shortId = componentSpecificId.replace('OAUTH_', '').replace('_TOKENS', '');
// Only add if not already in options (avoid duplicates)
- const alreadyExists = options.some(opt => opt.value === componentSpecificId);
+ const alreadyExists = options.some((opt) => opt.value === componentSpecificId);
if (!alreadyExists) {
options.push({
value: componentSpecificId,
text: `${serviceName} [${shortId}]`,
- badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1')
+ badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1'),
});
}
}
@@ -1966,7 +1999,11 @@ export class APICall extends Component {
const componentSpecificId = `OAUTH_${this.uid}_TOKENS`;
// Use the centralized buildOAuthSelectOptions method
- const options = this.buildOAuthSelectOptions(this.oauthConnections, componentSpecificId, '[APICall.updateOAuthConnectionOptions]');
+ const options = this.buildOAuthSelectOptions(
+ this.oauthConnections,
+ componentSpecificId,
+ '[APICall.updateOAuthConnectionOptions]',
+ );
// Add 'None' option at the start
options.unshift({ value: 'None', text: 'None', badge: '' });
@@ -2039,8 +2076,6 @@ export class APICall extends Component {
return map[internalName] || internalName;
}
-
-
/**
* Clears the authentication state for a specific connection
* @param connectionId - The ID of the connection to clear
diff --git a/packages/app/src/builder-ui/components/Component.class/index.ts b/packages/app/src/builder-ui/components/Component.class/index.ts
index 8288fe3e..b2316ca2 100644
--- a/packages/app/src/builder-ui/components/Component.class/index.ts
+++ b/packages/app/src/builder-ui/components/Component.class/index.ts
@@ -2217,7 +2217,7 @@ export class Component extends EventEmitter {
const inputsControl = document.createElement('div');
inputsControl.className = 'ep-control inputs px-2';
inputsControl.innerHTML = `<span>${
- this.drawSettings.addInputButtonLabel || this.drawSettings.addInputButton
+ this.drawSettings.addInputButtonLabel || this.drawSettings.addInputButton || ''
}</span>`;
div.appendChild(inputsControl);
@@ -2231,7 +2231,7 @@ export class Component extends EventEmitter {
inputsControl.appendChild(addInputButton);
const spanLabel = document.createElement('span');
spanLabel.innerHTML =
- this.drawSettings.addInputButtonLabel || this.drawSettings.addInputButton;
+ this.drawSettings.addInputButtonLabel || this.drawSettings.addInputButton || '';
inputsControl.appendChild(spanLabel);
//buttonContainer.appendChild(addInputButton);
addInputButton.onclick = (event) => {
@@ -2248,7 +2248,7 @@ export class Component extends EventEmitter {
const outputsControl = document.createElement('div');
outputsControl.className = 'ep-control outputs px-2';
outputsControl.innerHTML = `<span>${
- this.drawSettings.addOutputButtonLabel || this.drawSettings.addOutputButton
+ this.drawSettings.addOutputButtonLabel || this.drawSettings.addOutputButton || ''
}</span>`;
div.appendChild(outputsControl);
@@ -2263,7 +2263,7 @@ export class Component extends EventEmitter {
const spanLabel = document.createElement('span');
spanLabel.innerHTML =
- this.drawSettings.addOutputButtonLabel || this.drawSettings.addOutputButton;
+ this.drawSettings.addOutputButtonLabel || this.drawSettings.addOutputButton || '';
outputsControl.appendChild(spanLabel);
//buttonContainer.appendChild(addOutputButton);
diff --git a/packages/app/src/builder-ui/components/Triggers/GmailTrigger.class.ts b/packages/app/src/builder-ui/components/Triggers/GmailTrigger.class.ts
new file mode 100644
index 00000000..b8988af7
--- /dev/null
+++ b/packages/app/src/builder-ui/components/Triggers/GmailTrigger.class.ts
@@ -0,0 +1,61 @@
+import { oAuthSettings } from '../../helpers/oauth/oauth-settings.helper';
+import { Trigger } from './Trigger.class';
+
+declare var Metro;
+
+/**
+ * Gmail Trigger Component - Clean and Modular
+ *
+ * This component handles Gmail-based triggers with OAuth authentication.
+ * All OAuth logic has been extracted to the oAuthSettings() helper class
+ * for better separation of concerns and reusability.
+ */
+export class GmailTrigger extends Trigger {
+ private oauth: oAuthSettings | undefined;
+
+ protected async prepare(): Promise<boolean> {
+ try {
+ // Initialize OAuth settings helper
+ this.oauth = new oAuthSettings(this);
+ await this.oauth.initialize();
+ return true;
+ } catch (error) {
+ console.error('Error preparing Gmail trigger:', error);
+ return false;
+ }
+ }
+
+ protected async init(): Promise<void> {
+ await super.init();
+
+ // Set up component settings with OAuth configuration
+ this.settings = {
+ interval: {
+ type: 'range',
+ label: 'Interval',
+ min: 1,
+ max: 720,
+ value: 1,
+ step: 1,
+ validate: 'min=1 max=720',
+ validateMessage: 'Allowed range 1 to 720',
+ },
+ ...this.oauth?.configure(),
+ };
+
+ this.drawSettings.iconCSSClass = 'svg-icon ' + this.constructor.name;
+ this.drawSettings.color = '#ff00f2';
+ }
+
+ /**
+ * Clean up event listeners and resources
+ */
+ destroy(): void {
+ // Clean up OAuth helper
+ if (this.oauth) {
+ this.oauth.destroy();
+ }
+
+ super.destroy?.();
+ }
+}
diff --git a/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts b/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts
new file mode 100644
index 00000000..93f63f35
--- /dev/null
+++ b/packages/app/src/builder-ui/components/Triggers/Trigger.class.ts
@@ -0,0 +1,24 @@
+import { Component } from '../Component.class';
+
+export class Trigger extends Component {
+ protected async init() {
+ this.settings = {};
+
+ // #region [ I/O config ] ==================
+ this.properties.defaultOutputs = ['_'];
+ this.properties.defaultInputs = [];
+ // #endregion
+
+ // #region [ Draw config ] ==================
+
+ this.drawSettings.addOutputButton = null;
+ this.drawSettings.addInputButton = null;
+ this.drawSettings.addOutputButtonLabel = '';
+ this.drawSettings.addInputButtonLabel = '';
+ this.drawSettings.componentDescription = 'Trigger';
+
+ this.drawSettings.shortDescription = 'Trigger';
+ this.drawSettings.color = '#ff00f2';
+ // #endregion
+ }
+}
diff --git a/packages/app/src/builder-ui/components/index.ts b/packages/app/src/builder-ui/components/index.ts
index 42f115e4..cbd70cea 100644
--- a/packages/app/src/builder-ui/components/index.ts
+++ b/packages/app/src/builder-ui/components/index.ts
@@ -61,6 +61,8 @@ import { Twitter } from './Twitter.class';
import { VisionLLM } from './VisionLLM.class';
import { ZapierAction } from './ZapierAction.class';
+import { GmailTrigger } from './Triggers/GmailTrigger.class';
+
const baseComponents = {
Component,
Classifier,
@@ -128,6 +130,7 @@ const baseComponents = {
Inpainting,
AgentCard,
MCPClient,
+ GmailTrigger,
};
export const getBuilderComponents = () => {
diff --git a/packages/app/src/builder-ui/helpers/oauth-modal.helper.ts b/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
similarity index 86%
rename from packages/app/src/builder-ui/helpers/oauth-modal.helper.ts
rename to packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
index 2ab70f45..51b82627 100644
--- a/packages/app/src/builder-ui/helpers/oauth-modal.helper.ts
+++ b/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
@@ -1,4 +1,5 @@
-import { OAUTH_SERVICES, mapServiceNameToInternal } from '@src/shared/utils/oauth.utils';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
+import { OAUTH_SERVICES, mapServiceNameToInternal } from '@src/shared/helpers/oauth/oauth.utils';
/**
* Interface for OAuth connection form data
@@ -46,7 +47,7 @@ export function generateOAuthModalHTML(
currentName: string,
currentPlatform: string,
currentService: string,
- currentOauthInfo: OAuthConnectionInfo
+ currentOauthInfo: OAuthConnectionInfo,
): string {
const consumerKeyValue = currentOauthInfo.consumerKey || '';
const consumerSecretValue = currentOauthInfo.consumerSecret || '';
@@ -76,12 +77,10 @@ export function generateOAuthModalHTML(
<div class="col-span-3">
<select id="oauthService" name="oauthService" required
class="input flex items-center justify-between whitespace-nowrap rounded-md border border-input bg-transparent px-3 py-2 text-sm h-9 w-full outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500">
- ${OAUTH_SERVICES
- .map(
- (service) =>
- `<option value="${service}" ${service === currentService ? 'selected' : ''}>${service}</option>`,
- )
- .join('')}
+ ${OAUTH_SERVICES.map(
+ (service) =>
+ `<option value="${service}" ${service === currentService ? 'selected' : ''}>${service}</option>`,
+ ).join('')}
</select>
</div>
</div>
@@ -145,32 +144,24 @@ export function generateOAuthModalHTML(
/**
* Set prefill values for known OAuth services
*/
-export function setPrefillValuesForService(dialog: HTMLElement, selectedService: string, baseUrl: string) {
+export function setPrefillValuesForService(
+ dialog: HTMLElement,
+ selectedService: string,
+ baseUrl: string,
+) {
const service = mapServiceNameToInternal(selectedService);
const callbackUrl = `${baseUrl}/oauth/${service}/callback`;
- if (selectedService === 'Google') {
- (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
- 'https://accounts.google.com/o/oauth2/v2/auth';
- (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
- 'https://oauth2.googleapis.com/token';
- (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
- 'https://www.googleapis.com/auth/gmail.readonly';
- } else if (selectedService === 'LinkedIn') {
- (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
- 'https://www.linkedin.com/oauth/v2/authorization';
- (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
- 'https://www.linkedin.com/oauth/v2/accessToken';
- (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
- 'r_liteprofile r_emailaddress';
- } else if (selectedService === 'Twitter') {
- (dialog.querySelector('#requestTokenURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/request_token';
- (dialog.querySelector('#accessTokenURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/access_token';
- (dialog.querySelector('#userAuthorizationURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/authorize';
- }
+ // Get service defaults from centralized configuration
+ const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedService);
+
+ // Apply defaults to form fields
+ Object.entries(serviceDefaults).forEach(([field, value]) => {
+ const input = dialog.querySelector(`#${field}`) as HTMLInputElement | HTMLTextAreaElement;
+ if (input) {
+ input.value = value;
+ }
+ });
return callbackUrl;
}
@@ -181,15 +172,15 @@ export function setPrefillValuesForService(dialog: HTMLElement, selectedService:
export function updateOAuthFieldVisibility(
dialog: HTMLElement,
selectedValue: string,
- mapServiceFunc?: (service: string) => string
+ mapServiceFunc?: (service: string) => string,
) {
const oauth1Container = dialog.querySelector('#oauth1-fields');
const oauth2Container = dialog.querySelector('#oauth2-fields');
const callbackDisplayContainer = dialog.querySelector('#callback-url-display');
- const isOAuth2 = ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedValue);
- const isOAuth1 = ['Twitter', 'Custom OAuth1.0'].includes(selectedValue);
- const isClientCreds = selectedValue === 'OAuth2 Client Credentials';
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(selectedValue);
+ const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(selectedValue);
+ const isClientCreds = OAuthServicesRegistry.isClientCredentialsService(selectedValue);
// Show/hide main containers
oauth1Container?.classList.toggle('hidden', !isOAuth1);
@@ -207,10 +198,7 @@ export function updateOAuthFieldVisibility(
}
// Handle callback URL display
- callbackDisplayContainer?.classList.toggle(
- 'hidden',
- isClientCreds || (!isOAuth2 && !isOAuth1),
- );
+ callbackDisplayContainer?.classList.toggle('hidden', isClientCreds || (!isOAuth2 && !isOAuth1));
if (!callbackDisplayContainer?.classList.contains('hidden')) {
const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');
@@ -219,7 +207,9 @@ export function updateOAuthFieldVisibility(
try {
const baseUrl = window.location.origin;
- const serviceInternal = mapServiceFunc ? mapServiceFunc(service) : mapServiceNameToInternal(service);
+ const serviceInternal = mapServiceFunc
+ ? mapServiceFunc(service)
+ : mapServiceNameToInternal(service);
if (serviceInternal && serviceInternal !== 'none') {
callbackURL = `${baseUrl}/oauth/${serviceInternal}/callback`;
}
@@ -236,7 +226,10 @@ export function updateOAuthFieldVisibility(
/**
* Validate OAuth connection form data
*/
-export function validateOAuthFormData(formData: Record<string, string>): { isValid: boolean; error?: string } {
+export function validateOAuthFormData(formData: Record<string, string>): {
+ isValid: boolean;
+ error?: string;
+} {
if (!formData.name || formData.name.trim() === '') {
return { isValid: false, error: 'Name field is required.' };
}
@@ -255,7 +248,7 @@ export function validateOAuthFormData(formData: Record<string, string>): { isVal
export function buildOAuthSettingsForSave(
formData: Record<string, string>,
connectionId: string,
- type: 'oauth' | 'oauth2' | 'oauth2_client_credentials'
+ type: 'oauth' | 'oauth2' | 'oauth2_client_credentials',
) {
const service = mapServiceNameToInternal(formData.oauthService);
const oauthPrefix = connectionId.replace('_TOKENS', '');
diff --git a/packages/app/src/builder-ui/helpers/oauth/oauth-settings.helper.ts b/packages/app/src/builder-ui/helpers/oauth/oauth-settings.helper.ts
new file mode 100644
index 00000000..d597c8f6
--- /dev/null
+++ b/packages/app/src/builder-ui/helpers/oauth/oauth-settings.helper.ts
@@ -0,0 +1,365 @@
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { OAuthService } from './oauth.service';
+import type { SelectOption } from './oauth.types';
+import { UIHelper } from './ui.helper';
+
+/**
+ * OAuth Settings Helper Class
+ *
+ * This class encapsulates all OAuth-related logic and provides a clean interface
+ * for components to integrate OAuth functionality without cluttering the component code.
+ */
+export class oAuthSettings {
+ private component: any;
+ private oauthService: OAuthService | undefined;
+ private uiHelper: UIHelper | undefined;
+ private oauthConnectionNames: SelectOption[] = [];
+ private updateAuthButtonDebounceTimer: ReturnType<typeof setTimeout> | undefined;
+ private boundHandleFocusAfterAuth: () => Promise<void>;
+ private boundHandleAuthMessage: (event: MessageEvent) => void;
+
+ constructor(component: any) {
+ this.component = component;
+ this.boundHandleFocusAfterAuth = this.handleFocusAfterAuth.bind(this);
+ this.boundHandleAuthMessage = this.handleAuthMessage.bind(this);
+ }
+
+ /**
+ * Initialize OAuth services and load connections
+ */
+ async initialize(): Promise<void> {
+ try {
+ // Initialize services when workspace is fully available
+ if (!this.oauthService) {
+ this.oauthService = new OAuthService(this.component.workspace);
+ this.uiHelper = new UIHelper(this.component);
+ }
+
+ await this.oauthService.loadConnections();
+ this.oauthConnectionNames = this.oauthService.buildSelectOptions();
+ } catch (error) {
+ console.error('Error initializing OAuth settings:', error);
+ this.oauthConnectionNames = [{ value: 'None', text: 'None', badge: '' }];
+ }
+ }
+
+ /**
+ * Configure OAuth settings for component
+ */
+ configure(): Record<string, any> {
+ return {
+ oauth_con_id: {
+ type: 'select',
+ label: 'OAuth Connection',
+ section: 'OAuth',
+ options: this.oauthConnectionNames,
+ value: this.component.data.oauth_con_id || 'None',
+ events: {
+ change: (event: Event) =>
+ this.handleOAuthConnectionChange((event.target as HTMLSelectElement).value),
+ },
+ actions: [
+ {
+ label: 'Add New',
+ icon: 'fa-regular fa-lg fa-plus',
+ id: 'createOAuthConnection',
+ cls: 'mr-2 !mt-[-36px] !pt-[10px]',
+ visible: () => true,
+ events: {
+ click: () => {
+ this.component.data.oauth_con_id = 'None';
+ this.handleOAuthConnectionAction();
+ },
+ },
+ },
+ {
+ label: 'Edit',
+ icon: 'fa-regular fa-pen-to-square',
+ id: 'editOAuthConnection',
+ cls: 'mt-[7px] !mr-[24px] !pt-[10px]',
+ visible: () =>
+ this.component.data.oauth_con_id && this.component.data.oauth_con_id !== 'None',
+ events: {
+ click: () => this.handleOAuthConnectionAction(),
+ },
+ },
+ ],
+ },
+ authenticate: {
+ type: 'button',
+ label: 'Authenticate',
+ section: 'OAuth',
+ attributes: {},
+ events: {
+ click: (event: Event) => {
+ const target = event.target as HTMLButtonElement;
+ return target.innerText === 'Sign Out'
+ ? this.signOutFunction(target)
+ : this.collectAndConsoleOAuthValues(event);
+ },
+ },
+ },
+ };
+ }
+
+ /**
+ * Handles authentication messages from popup or redirected authentication flow
+ */
+ private handleAuthMessage(event: MessageEvent): void {
+ if (event?.origin !== window?.location?.origin) {
+ errorToast('Message origin does not match the current origin.');
+ return;
+ }
+
+ switch (event.data?.type) {
+ case 'oauth2':
+ case 'oauth':
+ this.handleAuthSuccess(event.data.type);
+ break;
+ case 'error':
+ if (event.data?.data?.message) {
+ errorToast(
+ `Authentication failed. Recheck your configuration. ${event.data.data.message}`,
+ 'Error',
+ 'alert',
+ );
+ }
+ break;
+ default:
+ console.warn('Unhandled message type:', event.data?.type);
+ break;
+ }
+ }
+
+ /**
+ * Handles successful authentication
+ */
+ private async handleAuthSuccess(type: string): Promise<void> {
+ successToast(`${type} authentication was successful`);
+ this.uiHelper?.updateSidebarForOAuth();
+ await this.updateOAuthConnectionOptions();
+ this.component.refreshSettingsSidebar();
+ this.uiHelper?.updateOAuthActionButtons(this.hasValidConnection());
+ await this.updateAuthenticationButtonState();
+ this.component.checkSettings();
+ window.removeEventListener('message', this.boundHandleAuthMessage);
+ }
+
+ private async handleFocusAfterAuth(): Promise<void> {
+ if (document.visibilityState === 'visible') {
+ await this.updateButtonAndRemoveFocusListener();
+ }
+ }
+
+ /**
+ * Updates OAuth connection options in settings
+ */
+ private async updateOAuthConnectionOptions(): Promise<void> {
+ if (!this.oauthService) return;
+
+ try {
+ await this.oauthService.loadConnections();
+ const options = this.oauthService.buildSelectOptions();
+
+ if (this.component.settings?.oauth_con_id) {
+ this.component.settings.oauth_con_id.options = options;
+ }
+ } catch (error) {
+ console.error('Error updating OAuth connection options:', error);
+ if (this.component.settings?.oauth_con_id) {
+ this.component.settings.oauth_con_id.options = [{ value: 'None', text: 'None' }];
+ }
+ }
+ }
+
+ /**
+ * Initiates OAuth authentication flow
+ */
+ private async collectAndConsoleOAuthValues(event: Event): Promise<void> {
+ if (!this.oauthService || !this.uiHelper) {
+ errorToast('OAuth service not initialized', 'Error', 'alert');
+ return;
+ }
+
+ const selectedConnectionId = this.component.data.oauth_con_id;
+ if (selectedConnectionId === 'None' || !selectedConnectionId) {
+ errorToast('Please select a valid OAuth Connection first', 'Error', 'alert');
+ return;
+ }
+
+ const button = event.target as HTMLButtonElement;
+ this.uiHelper.activateSpinner(button);
+ document.addEventListener('visibilitychange', this.boundHandleFocusAfterAuth);
+
+ try {
+ const success = await this.oauthService.authenticate(selectedConnectionId);
+
+ if (success) {
+ // If it's a popup flow, add message listener
+ window.addEventListener('message', this.boundHandleAuthMessage, false);
+ } else {
+ await this.updateButtonAndRemoveFocusListener();
+ }
+ } catch (error) {
+ console.error('Error during OAuth initiation:', error);
+ await this.updateButtonAndRemoveFocusListener();
+ }
+ }
+
+ private async updateAuthenticationButton(): Promise<void> {
+ await this.updateAuthenticationButtonState();
+
+ const isDataValid = await this.checkAuthentication();
+ const cptButton = this.component.domElement?.querySelector(
+ 'button.oauthButton',
+ ) as HTMLButtonElement;
+ if (cptButton) {
+ cptButton.disabled = false;
+ if (!isDataValid) {
+ cptButton.innerHTML =
+ '<div class="fa-solid fa-user-shield"></div><p class="">Authenticate</p>';
+ }
+ }
+ }
+
+ private async updateButtonAndRemoveFocusListener(): Promise<void> {
+ await this.updateAuthenticationButton();
+ document.removeEventListener('visibilitychange', this.boundHandleFocusAfterAuth);
+ }
+
+ /**
+ * Signs out from OAuth connection
+ */
+ private async signOutFunction(button: HTMLButtonElement): Promise<void> {
+ if (!this.oauthService || !this.uiHelper) {
+ errorToast('OAuth service not initialized', 'Error', 'alert');
+ return;
+ }
+
+ this.uiHelper.activateSpinner(button);
+
+ const success = await this.oauthService.signOut(this.component.data.oauth_con_id);
+
+ if (success) {
+ await this.uiHelper.updateAuthButtonState(false);
+ this.component.refreshSettingsSidebar();
+ this.component.clearComponentMessages();
+ } else {
+ await this.uiHelper.updateAuthButtonState(true);
+ }
+ }
+
+ /**
+ * Handles OAuth connection creation/editing
+ */
+ private async handleOAuthConnectionAction(): Promise<void> {
+ if (!this.oauthService || !this.uiHelper) {
+ errorToast('OAuth service not initialized', 'Error', 'alert');
+ return;
+ }
+
+ const currentValue = this.component.data.oauth_con_id;
+
+ try {
+ const connections = await this.oauthService.loadConnections();
+
+ await this.uiHelper.showConnectionModal(
+ currentValue,
+ connections,
+ async (formData, connectionId) => {
+ if (!this.oauthService || !this.uiHelper) return;
+
+ await this.oauthService.saveConnection(connectionId, formData);
+
+ // Update component state
+ this.component.data.oauth_con_id = connectionId;
+ await this.updateOAuthConnectionOptions();
+ this.component.refreshSettingsSidebar();
+ this.uiHelper.updateOAuthActionButtons(this.hasValidConnection());
+
+ // Skip authentication button update in callback to prevent hanging
+ // The auth button will be updated when the user interacts with it
+ },
+ );
+ } catch (error) {
+ console.error('Error handling OAuth connection action:', error);
+ errorToast('Error managing connection. Please try again.', 'Error', 'alert');
+ }
+ }
+
+ /**
+ * Handles OAuth connection selection change
+ */
+ private async handleOAuthConnectionChange(selectedValue: string): Promise<void> {
+ this.component.data.oauth_con_id = selectedValue;
+
+ if (!selectedValue || selectedValue === 'None') {
+ await this.uiHelper?.updateAuthButtonState(false);
+ } else {
+ await this.updateAuthenticationButtonState();
+ }
+
+ this.uiHelper?.updateOAuthActionButtons(this.hasValidConnection());
+ }
+
+ /**
+ * Updates authentication button state with debouncing
+ */
+ async updateAuthenticationButtonState(): Promise<void> {
+ if (this.updateAuthButtonDebounceTimer) {
+ clearTimeout(this.updateAuthButtonDebounceTimer);
+ }
+
+ return new Promise<void>((resolve) => {
+ this.updateAuthButtonDebounceTimer = setTimeout(async () => {
+ await this.performAuthButtonUpdate();
+ resolve();
+ }, 150);
+ });
+ }
+
+ /**
+ * Performs the actual authentication button update
+ */
+ private async performAuthButtonUpdate(): Promise<void> {
+ if (!this.uiHelper) return;
+
+ const authButton = this.uiHelper.getAuthButton();
+ if (!authButton) return;
+
+ this.uiHelper.activateSpinner(authButton);
+
+ const isAuthenticated =
+ this.component.data.oauth_con_id && this.component.data.oauth_con_id !== 'None'
+ ? await this.checkAuthentication()
+ : false;
+
+ await this.uiHelper.updateAuthButtonState(isAuthenticated);
+ }
+
+ /**
+ * Checks authentication status for current connection
+ */
+ private async checkAuthentication(): Promise<boolean> {
+ if (!this.oauthService) return false;
+ return this.oauthService.checkAuthentication(this.component.data.oauth_con_id);
+ }
+
+ /**
+ * Helper to check if current connection is valid
+ */
+ private hasValidConnection(): boolean {
+ return !!(this.component.data.oauth_con_id && this.component.data.oauth_con_id !== 'None');
+ }
+
+ /**
+ * Cleanup method to remove event listeners
+ */
+ destroy(): void {
+ if (this.updateAuthButtonDebounceTimer) {
+ clearTimeout(this.updateAuthButtonDebounceTimer);
+ }
+ window.removeEventListener('message', this.boundHandleAuthMessage);
+ document.removeEventListener('visibilitychange', this.boundHandleFocusAfterAuth);
+ }
+}
diff --git a/packages/app/src/builder-ui/helpers/oauth/oauth.service.ts b/packages/app/src/builder-ui/helpers/oauth/oauth.service.ts
new file mode 100644
index 00000000..724d5cc0
--- /dev/null
+++ b/packages/app/src/builder-ui/helpers/oauth/oauth.service.ts
@@ -0,0 +1,409 @@
+import { errorToast, successToast } from '@src/shared/components/toast';
+import {
+ getConnectionOauthInfo,
+ saveOAuthConnection,
+} from '@src/shared/helpers/oauth/oauth-api.helper';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
+import { mapInternalToServiceName } from '@src/shared/helpers/oauth/oauth.utils';
+import { builderStore } from '@src/shared/state_stores/builder/store';
+import type {
+ OAuthConnection,
+ OAuthInfo,
+ OAuthServiceType,
+ SelectOption,
+ ValidationResult,
+} from './oauth.types';
+
+export class OAuthService {
+ private authCheckPromises: Map<string, Promise<boolean>> = new Map();
+ private connections: Record<string, OAuthConnection> = {};
+
+ constructor(private workspace: any) {}
+
+ /**
+ * Load OAuth connections from workspace cache
+ */
+ async loadConnections(): Promise<Record<string, OAuthConnection>> {
+ try {
+ const data = await builderStore.getState().getOAuthConnections();
+ this.connections = data || {};
+ return this.connections;
+ } catch (error) {
+ console.error('[OAuthService] Failed to load connections:', error);
+ return {};
+ }
+ }
+
+ /**
+ * Build select options from connections
+ */
+ buildSelectOptions(): SelectOption[] {
+ const options: SelectOption[] = [];
+
+ for (const [id, conn] of Object.entries(this.connections)) {
+ const connectionName = conn?.auth_settings?.name;
+ if (connectionName) {
+ options.push({
+ value: id,
+ text: connectionName,
+ badge: '',
+ });
+ }
+ }
+
+ return [{ value: 'None', text: 'None', badge: '' }, ...options];
+ }
+
+ /**
+ * Validate OAuth payload
+ */
+ validatePayload(
+ payload: OAuthInfo,
+ connectionType: OAuthServiceType,
+ derivedService: string,
+ ): ValidationResult {
+ const missingFields: string[] = [];
+ const isClientCredentials =
+ connectionType === 'oauth2_client_credentials' ||
+ payload.service === 'oauth2_client_credentials';
+
+ if (
+ connectionType === 'oauth2' ||
+ isClientCredentials ||
+ ['Google', 'LinkedIn'].includes(derivedService)
+ ) {
+ if (!payload.tokenURL) missingFields.push('Token URL');
+ if (!payload.clientID) missingFields.push('Client ID');
+ if (!payload.clientSecret) missingFields.push('Client Secret');
+
+ if (!isClientCredentials) {
+ if (!payload.authorizationURL) missingFields.push('Auth URL');
+ if (!payload.scope) missingFields.push('Scopes');
+ }
+ } else if (connectionType === 'oauth') {
+ if (!payload.requestTokenURL) missingFields.push('Request Token URL');
+ if (!payload.accessTokenURL) missingFields.push('Access Token URL');
+ if (!payload.userAuthorizationURL) missingFields.push('User Auth URL');
+ if (!payload.consumerKey) missingFields.push('Consumer Key');
+ if (!payload.consumerSecret) missingFields.push('Consumer Secret');
+ }
+
+ return { valid: missingFields.length === 0, missingFields };
+ }
+
+ /**
+ * Normalize callback URL origin
+ */
+ normalizeCallbackOrigin(
+ cb: string | undefined,
+ providerPath: string | undefined,
+ ): string | undefined {
+ if (!providerPath) return cb;
+
+ const origin = this.getBackendOrigin();
+ try {
+ if (!cb) return `${origin}${providerPath}`;
+ const current = new URL(cb);
+ const desired = new URL(origin);
+ if (current.origin !== desired.origin) {
+ return `${desired.origin}${current.pathname}${current.search}${current.hash}`;
+ }
+ return cb;
+ } catch {
+ return `${origin}${providerPath}`;
+ }
+ }
+
+ /**
+ * Perform authentication
+ */
+ async authenticate(connectionId: string): Promise<boolean> {
+ const connection = this.connections[connectionId];
+ const oauthInfo = getConnectionOauthInfo(connection, connectionId) as OAuthInfo;
+
+ if (!connection || !oauthInfo?.service) {
+ errorToast('OAuth connection details not found.', 'Error', 'alert');
+ return false;
+ }
+
+ // Validate payload
+ const derivedService = mapInternalToServiceName(oauthInfo.service);
+ const validation = this.validatePayload(oauthInfo, oauthInfo.service, derivedService);
+
+ if (!validation.valid) {
+ errorToast(
+ `Missing required fields: ${validation.missingFields.join(', ')}`,
+ 'Error',
+ 'alert',
+ );
+ return false;
+ }
+
+ // Normalize callback URLs
+ this.normalizeCallbackUrls(oauthInfo);
+
+ const isClientCredentials = oauthInfo.service === 'oauth2_client_credentials';
+ const endpoint = isClientCredentials ? 'client_credentials' : 'init';
+ const url = `${this.workspace.server}/oauth/${endpoint}`;
+
+ try {
+ const response = await fetch(url, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(oauthInfo),
+ });
+
+ if (!response.ok) {
+ const errorData = await response.json().catch(() => ({}));
+ throw new Error(
+ errorData.message || `Authentication failed with status ${response.status}`,
+ );
+ }
+
+ const data = await response.json();
+
+ if (data.authUrl) {
+ window.open(data.authUrl, '_blank');
+ return true;
+ } else if ('success' in data) {
+ if (data.success) {
+ this.updateConnectionTokens(connectionId, data);
+ successToast(data.message);
+ } else {
+ this.clearConnectionTokens(connectionId);
+ errorToast(data.message, 'Error', 'alert');
+ }
+ return data.success;
+ }
+
+ throw new Error('Unexpected response from authentication server.');
+ } catch (error) {
+ errorToast(`Authentication Failed: ${error?.message || error}`, 'Error', 'alert');
+ this.clearConnectionTokens(connectionId);
+ return false;
+ }
+ }
+
+ /**
+ * Sign out from OAuth connection
+ */
+ async signOut(connectionId: string): Promise<boolean> {
+ try {
+ const response = await fetch(`${this.workspace.server}/oauth/signOut`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({
+ oauth_keys_prefix: connectionId,
+ invalidateAuthentication: true,
+ }),
+ });
+
+ if (!response.ok) {
+ throw new Error(`HTTP error! status: ${response.status}`);
+ }
+
+ const data = await response.json();
+
+ if (data.invalidate) {
+ this.clearConnectionAuthState(connectionId);
+ if (data.message) successToast(data.message);
+ return true;
+ } else {
+ errorToast(data.error, 'Error', 'alert');
+ return false;
+ }
+ } catch (error) {
+ errorToast(`Error during sign out: ${error.message}`, 'Error', 'alert');
+ return false;
+ }
+ }
+
+ /**
+ * Check authentication status
+ */
+ async checkAuthentication(connectionId: string): Promise<boolean> {
+ if (!connectionId || connectionId === 'None') return false;
+
+ // Use cached promise if available
+ const existingPromise = this.authCheckPromises.get(connectionId);
+ if (existingPromise) return existingPromise;
+
+ const authCheckPromise = this.performAuthCheck(connectionId);
+ this.authCheckPromises.set(connectionId, authCheckPromise);
+
+ // Clear cache after completion
+ authCheckPromise.finally(() => {
+ setTimeout(() => {
+ if (this.authCheckPromises.get(connectionId) === authCheckPromise) {
+ this.authCheckPromises.delete(connectionId);
+ }
+ }, 1000);
+ });
+
+ return authCheckPromise;
+ }
+
+ /**
+ * Save OAuth connection
+ */
+ async saveConnection(connectionId: string, formData: Record<string, string>): Promise<void> {
+ const service = this.mapServiceNameToInternal(formData.oauthService);
+ const type = this.getConnectionType(formData.oauthService);
+ const oauthPrefix = connectionId.replace('_TOKENS', '');
+
+ const oauthInfo: any = {
+ oauth_keys_prefix: oauthPrefix,
+ service,
+ name: formData.name.trim(),
+ platform: formData.platform.trim(),
+ };
+
+ // Add type-specific fields
+ if (type === 'oauth2' || type === 'oauth2_client_credentials') {
+ oauthInfo.tokenURL = formData.tokenURL || '';
+ oauthInfo.clientID = formData.clientID || '';
+ oauthInfo.clientSecret = formData.clientSecret || '';
+
+ if (type === 'oauth2') {
+ oauthInfo.authorizationURL = formData.authorizationURL || '';
+ oauthInfo.scope = formData.scope || '';
+ }
+ } else if (type === 'oauth') {
+ oauthInfo.requestTokenURL = formData.requestTokenURL || '';
+ oauthInfo.accessTokenURL = formData.accessTokenURL || '';
+ oauthInfo.userAuthorizationURL = formData.userAuthorizationURL || '';
+ oauthInfo.consumerKey = formData.consumerKey || '';
+ oauthInfo.consumerSecret = formData.consumerSecret || '';
+ }
+
+ const authSettings = {
+ name: oauthInfo.name,
+ type,
+ ...(oauthInfo.tokenURL && { tokenURL: oauthInfo.tokenURL }),
+ oauth_info: oauthInfo,
+ };
+
+ await saveOAuthConnection(connectionId, authSettings);
+
+ // Clear cache and reload connections
+ this.authCheckPromises.delete(connectionId);
+ builderStore.getState().invalidateOAuthConnectionsCache();
+ await this.loadConnections();
+ }
+
+ // Private helper methods
+ private getBackendOrigin(): string {
+ const candidate = this.workspace?.server || window.location.origin;
+ try {
+ return new URL(candidate).origin;
+ } catch {
+ return String(candidate).replace(/\/$/, '');
+ }
+ }
+
+ private normalizeCallbackUrls(oauthInfo: OAuthInfo): void {
+ const serviceType = oauthInfo.service.toLowerCase();
+
+ // Use centralized configuration to determine callback paths
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(serviceType);
+ const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(serviceType);
+
+ if (isOAuth2) {
+ // Get callback path from centralized configuration, fallback to legacy logic for compatibility
+ const callbackPath =
+ OAuthServicesRegistry.getCallbackPath(serviceType) ||
+ `/oauth/${['google', 'linkedin'].includes(serviceType) ? serviceType : 'oauth2'}/callback`;
+ oauthInfo.oauth2CallbackURL = this.normalizeCallbackOrigin(
+ oauthInfo.oauth2CallbackURL,
+ callbackPath,
+ );
+ }
+
+ if (isOAuth1) {
+ // Get callback path from centralized configuration, fallback to legacy logic for compatibility
+ const callbackPath =
+ OAuthServicesRegistry.getCallbackPath(serviceType) ||
+ `/oauth/${serviceType === 'twitter' ? 'oauth1' : serviceType}/callback`;
+ oauthInfo.oauth1CallbackURL = this.normalizeCallbackOrigin(
+ oauthInfo.oauth1CallbackURL,
+ callbackPath,
+ );
+ }
+ }
+
+ private async performAuthCheck(connectionId: string): Promise<boolean> {
+ const connection = this.connections[connectionId];
+ if (!connection) return false;
+
+ const oauthInfo = getConnectionOauthInfo(connection, connectionId) as OAuthInfo;
+ const oauth_keys_prefix = oauthInfo?.oauth_keys_prefix || connectionId.replace('_TOKENS', '');
+
+ if (!oauth_keys_prefix) return false;
+
+ try {
+ const response = await fetch(`${this.workspace.server}/oauth/checkAuth`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ oauth_keys_prefix }),
+ });
+
+ if (!response.ok) return false;
+
+ const data = await response.json();
+ const isAuthenticated = Boolean(data.success);
+
+ // Update local cache
+ if (this.connections[connectionId]) {
+ this.connections[connectionId].isAuthenticated = isAuthenticated;
+ }
+
+ return isAuthenticated;
+ } catch (error) {
+ console.error(`Error during auth check for ${oauth_keys_prefix}:`, error);
+ return false;
+ }
+ }
+
+ private updateConnectionTokens(connectionId: string, data: any): void {
+ const connection = this.connections[connectionId];
+ if (!connection || !data.primary) return;
+
+ connection.isAuthenticated = true;
+ if (!connection.auth_data) connection.auth_data = {};
+
+ connection.auth_data.primary = data.primary;
+ if (data.secondary) connection.auth_data.secondary = data.secondary;
+ if (data.expires_in) connection.auth_data.expires_in = data.expires_in;
+ }
+
+ private clearConnectionTokens(connectionId: string): void {
+ const connection = this.connections[connectionId];
+ if (!connection?.auth_data) return;
+
+ delete connection.auth_data.primary;
+ delete connection.auth_data.secondary;
+ delete connection.auth_data.expires_in;
+ }
+
+ private clearConnectionAuthState(connectionId: string): void {
+ const connection = this.connections[connectionId];
+ if (!connection) return;
+
+ connection.isAuthenticated = false;
+ this.clearConnectionTokens(connectionId);
+ this.authCheckPromises.delete(connectionId);
+ }
+
+ private mapServiceNameToInternal(serviceName: string): string {
+ return OAuthServicesRegistry.mapServiceNameToInternal(serviceName);
+ }
+
+ private getConnectionType(
+ oauthService: string,
+ ): 'oauth' | 'oauth2' | 'oauth2_client_credentials' {
+ if (OAuthServicesRegistry.isOAuth1Service(oauthService)) return 'oauth';
+ if (OAuthServicesRegistry.isClientCredentialsService(oauthService))
+ return 'oauth2_client_credentials';
+ return 'oauth2';
+ }
+}
diff --git a/packages/app/src/builder-ui/helpers/oauth/oauth.types.ts b/packages/app/src/builder-ui/helpers/oauth/oauth.types.ts
new file mode 100644
index 00000000..d9d4fc06
--- /dev/null
+++ b/packages/app/src/builder-ui/helpers/oauth/oauth.types.ts
@@ -0,0 +1,57 @@
+/**
+ * OAuth-related types and interfaces for Gmail Trigger
+ */
+
+export type OAuthServiceType = 'oauth' | 'oauth1' | 'oauth2' | 'oauth2_client_credentials' | string;
+
+export interface OAuthInfo {
+ oauth_keys_prefix?: string;
+ service: OAuthServiceType;
+ name?: string;
+ platform?: string;
+ // OAuth2
+ tokenURL?: string;
+ clientID?: string;
+ clientSecret?: string;
+ authorizationURL?: string;
+ scope?: string;
+ oauth2CallbackURL?: string;
+ // OAuth1
+ requestTokenURL?: string;
+ accessTokenURL?: string;
+ userAuthorizationURL?: string;
+ consumerKey?: string;
+ consumerSecret?: string;
+ oauth1CallbackURL?: string;
+}
+
+export interface OAuthAuthData {
+ primary?: string;
+ secondary?: string;
+ expires_in?: number;
+}
+
+export interface OAuthAuthSettings {
+ name: string;
+ type: 'oauth' | 'oauth2' | 'oauth2_client_credentials';
+ tokenURL?: string;
+ oauth_info: OAuthInfo;
+}
+
+export interface OAuthConnection {
+ auth_settings?: OAuthAuthSettings;
+ auth_data?: OAuthAuthData;
+ isAuthenticated?: boolean;
+ [key: string]: unknown;
+}
+
+export interface SelectOption {
+ value: string;
+ text: string;
+ badge?: string;
+}
+
+export interface ValidationResult {
+ valid: boolean;
+ missingFields: string[];
+}
diff --git a/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts b/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts
new file mode 100644
index 00000000..735d8974
--- /dev/null
+++ b/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts
@@ -0,0 +1,402 @@
+import { generateOAuthModalHTML } from '@src/builder-ui/helpers/oauth/oauth-modal.helper';
+import { twEditValuesWithCallback } from '@src/builder-ui/ui/tw-dialogs';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { getConnectionOauthInfo } from '@src/shared/helpers/oauth/oauth-api.helper';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
+import { generateOAuthId, mapInternalToServiceName } from '@src/shared/helpers/oauth/oauth.utils';
+import type { OAuthConnection } from './oauth.types';
+
+export class UIHelper {
+ constructor(private component: any) {}
+
+ /**
+ * Get sidebar element
+ */
+ getSidebarElement(): HTMLElement | null {
+ return this.component.getSettingsSidebar() as HTMLElement | null;
+ }
+
+ /**
+ * Get authentication button from sidebar
+ */
+ getAuthButton(): HTMLButtonElement | null {
+ const sidebar = this.getSidebarElement();
+ if (!sidebar) return null;
+ return sidebar.querySelector(
+ `[data-field-name='authenticate'] button`,
+ ) as HTMLButtonElement | null;
+ }
+
+ /**
+ * Update sidebar for OAuth success
+ */
+ updateSidebarForOAuth(): void {
+ const sidebar = this.getSidebarElement();
+ if (!sidebar) return;
+
+ const authButton = this.getAuthButton();
+ if (authButton) authButton.innerHTML = 'Sign Out';
+
+ const body = sidebar.querySelector('div[data-field-name="body"]');
+ if (body) {
+ this.removeExistingOAuthMessage(sidebar);
+ this.addOAuthSuccessMessage(body);
+ }
+
+ this.component.clearComponentMessages();
+ }
+
+ /**
+ * Update authentication button state
+ */
+ async updateAuthButtonState(isAuthenticated: boolean): Promise<void> {
+ const authButton = this.getAuthButton();
+ if (!authButton) return;
+
+ authButton.innerHTML = isAuthenticated ? 'Sign Out' : 'Authenticate';
+ authButton.disabled = false;
+ }
+
+ /**
+ * Show spinner on button
+ */
+ activateSpinner(button: HTMLButtonElement): void {
+ button.innerHTML = `<span class="oauth-spinner smyth-spinner"></span>&nbsp;&nbsp;In Progress ...`;
+ button.disabled = true;
+ }
+
+ /**
+ * Update OAuth action buttons visibility
+ */
+ updateOAuthActionButtons(hasConnection: boolean): void {
+ const sidebar = this.getSidebarElement();
+ if (!sidebar) return;
+
+ const createBtn = sidebar.querySelector('#createOAuthConnection') as HTMLElement;
+ const editBtn = sidebar.querySelector('#editOAuthConnection') as HTMLElement;
+
+ if (createBtn) createBtn.style.display = 'inline-block';
+ if (editBtn) editBtn.style.display = hasConnection ? 'inline-block' : 'none';
+
+ // Update edit button icon and tooltip
+ const icon = editBtn?.querySelector('i');
+ if (icon) {
+ icon.className = hasConnection ? 'fa-regular fa-pen-to-square' : 'fa-regular fa-plus';
+ }
+ editBtn?.setAttribute('title', hasConnection ? 'Edit' : 'Create');
+ }
+
+ /**
+ * Show OAuth connection modal
+ */
+ async showConnectionModal(
+ currentValue: string,
+ connections: Record<string, OAuthConnection>,
+ onSave: (formData: Record<string, string>, connectionId: string) => Promise<void>,
+ ): Promise<void> {
+ const isNone = !currentValue || currentValue === 'None';
+ const currentConnection = !isNone ? connections[currentValue] : null;
+ const currentSettings = currentConnection?.auth_settings;
+ const currentOauthInfo = getConnectionOauthInfo(currentSettings, currentValue) || {};
+ const currentName = currentSettings?.name || '';
+ const currentService = currentSettings
+ ? mapInternalToServiceName(currentOauthInfo.service)
+ : 'None';
+ const currentPlatform = currentOauthInfo.platform || '';
+
+ const formHTML = generateOAuthModalHTML(
+ currentName,
+ currentPlatform,
+ currentService,
+ currentOauthInfo,
+ );
+
+ await twEditValuesWithCallback(
+ {
+ title: isNone ? 'Add OAuth Connection' : 'Edit OAuth Connection',
+ content: formHTML,
+ onDOMReady: (dialog) => {
+ this.setupModalHandlers(dialog, currentOauthInfo);
+ },
+ actions: [
+ {
+ label: isNone ? 'Add Connection' : 'Save Changes',
+ cssClass:
+ 'bg-smythos-blue-500 text-white border-transparent hover:bg-smyth-blue ml-auto px-6 py-2 rounded shadow',
+ requiresValidation: true,
+ callback: async (result, dialogElm) => {
+ try {
+ const formData = this.extractFormData(dialogElm);
+
+ if (!this.validateFormData(formData)) {
+ console.log('[UIHelper] Validation failed, keeping dialog open');
+ return; // Don't close dialog on validation failure
+ }
+
+ const connectionId = isNone ? `OAUTH_${generateOAuthId()}_TOKENS` : currentValue;
+
+ await onSave(formData, connectionId);
+
+ // Show success message
+ successToast(
+ isNone ? 'Connection created successfully' : 'Connection updated successfully',
+ );
+ // Close dialog manually using the same logic as the internal closeDialog function
+ const dialogOverlay = dialogElm.querySelector('.__overlay');
+ const dialogDialog = dialogElm.querySelector('.__dialog');
+
+ if (dialogOverlay && dialogDialog) {
+ dialogOverlay.classList.remove('opacity-100');
+ dialogOverlay.classList.remove('opacity-0');
+ dialogDialog.classList.remove('scale-100');
+ dialogDialog.classList.add('scale-0');
+
+ // Remove dialog after animation
+ setTimeout(() => {
+ dialogElm.remove();
+ }, 300);
+ }
+
+ return;
+ } catch (error) {
+ console.error('Error saving OAuth connection:', error);
+ errorToast(`Error: ${error?.message || error}`, 'Error', 'alert');
+ // Don't close dialog on error - let user retry
+ }
+ },
+ },
+ ],
+ dialogClasses: 'smyth-modal-beautiful',
+ },
+ '',
+ '',
+ 'auto',
+ '600px',
+ '700px',
+ );
+ }
+
+ // Private helper methods
+ private removeExistingOAuthMessage(sidebar: HTMLElement): void {
+ const existingMessage = sidebar.querySelector('#oauthMessageSpan');
+ if (existingMessage) existingMessage.remove();
+ }
+
+ private addOAuthSuccessMessage(body: Element): void {
+ const messageSpan = document.createElement('small');
+ messageSpan.id = 'oauthMessageSpan';
+ messageSpan.className = 'p-2 mt-1 mb-0 text-green-500';
+ messageSpan.textContent = 'OAuth Enabled, Authentication headers will be injected at runtime.';
+ body.parentNode?.insertBefore(messageSpan, body.nextSibling);
+ }
+
+ private setupModalHandlers(dialog: HTMLElement, currentOauthInfo: any): void {
+ const serviceSelect = dialog.querySelector('#oauthService') as HTMLSelectElement;
+ const oauth1Container = dialog.querySelector('#oauth1-fields');
+ const oauth2Container = dialog.querySelector('#oauth2-fields');
+ const callbackDisplayContainer = dialog.querySelector('#callback-url-display');
+
+ // Set initial values
+ this.setInitialFormValues(dialog, currentOauthInfo);
+
+ // Setup field visibility handler
+ const updateFieldVisibility = (selectedValue: string) => {
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(selectedValue);
+ const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(selectedValue);
+ const isClientCreds = OAuthServicesRegistry.isClientCredentialsService(selectedValue);
+
+ oauth1Container?.classList.toggle('hidden', !isOAuth1);
+ oauth2Container?.classList.toggle('hidden', !(isOAuth2 || isClientCreds));
+
+ const scopeGroup = dialog.querySelector('[data-oauth-field="scope"]');
+ const authURLGroup = dialog.querySelector('#authorizationURL')?.closest('.form-group');
+
+ scopeGroup?.classList.toggle('hidden', isClientCreds || !isOAuth2);
+ authURLGroup?.classList.toggle('hidden', isClientCreds || !isOAuth2);
+
+ this.updateCallbackDisplay(
+ callbackDisplayContainer,
+ selectedValue,
+ isClientCreds,
+ isOAuth2,
+ isOAuth1,
+ );
+ };
+
+ // Apply initial visibility and setup change handler
+ updateFieldVisibility(serviceSelect?.value || 'None');
+ serviceSelect?.addEventListener('change', (e) => {
+ const target = e.target as HTMLSelectElement;
+ updateFieldVisibility(target.value);
+ this.prefillServiceDefaults(dialog, target.value, callbackDisplayContainer);
+ });
+ }
+
+ private setInitialFormValues(dialog: HTMLElement, currentOauthInfo: any): void {
+ const fields = [
+ { id: '#consumerKey', value: currentOauthInfo.consumerKey },
+ { id: '#consumerSecret', value: currentOauthInfo.consumerSecret },
+ { id: '#clientID', value: currentOauthInfo.clientID },
+ { id: '#clientSecret', value: currentOauthInfo.clientSecret },
+ { id: '#tokenURL', value: currentOauthInfo.tokenURL },
+ { id: '#authorizationURL', value: currentOauthInfo.authorizationURL },
+ { id: '#scope', value: currentOauthInfo.scope },
+ ];
+
+ fields.forEach(({ id, value }) => {
+ const input = dialog.querySelector(id) as HTMLInputElement | HTMLTextAreaElement;
+ if (input && value) input.value = value;
+ });
+ }
+
+ private updateCallbackDisplay(
+ container: Element | null,
+ selectedValue: string,
+ isClientCreds: boolean,
+ isOAuth2: boolean,
+ isOAuth1: boolean,
+ ): void {
+ if (!container) return;
+
+ container.classList.toggle('hidden', isClientCreds || (!isOAuth2 && !isOAuth1));
+
+ if (!container.classList.contains('hidden')) {
+ const callbackUrlDiv = container.querySelector('div.col-span-3');
+ if (callbackUrlDiv && selectedValue !== 'None') {
+ const serviceInternal = this.mapServiceNameToInternal(selectedValue);
+ const callbackURL =
+ serviceInternal !== 'none'
+ ? `${window.location.origin}/oauth/${serviceInternal}/callback`
+ : '';
+ callbackUrlDiv.textContent = callbackURL;
+ }
+ }
+ }
+
+ private prefillServiceDefaults(
+ dialog: HTMLElement,
+ selectedService: string,
+ callbackContainer: Element | null,
+ ): void {
+ const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedService);
+ if (!serviceDefaults || Object.keys(serviceDefaults).length === 0) return;
+
+ Object.entries(serviceDefaults).forEach(([field, value]) => {
+ const input = dialog.querySelector(`#${field}`) as HTMLInputElement | HTMLTextAreaElement;
+ if (input) input.value = value;
+ });
+
+ // Update callback URL
+ const callbackUrlDiv = callbackContainer?.querySelector('div.col-span-3');
+ if (callbackUrlDiv) {
+ const service = this.mapServiceNameToInternal(selectedService);
+ callbackUrlDiv.textContent = `${window.location.origin}/oauth/${service}/callback`;
+ }
+ }
+
+ private extractFormData(dialogElm: HTMLElement): Record<string, string> {
+ const formElement = dialogElm.querySelector('#oauth-connection-form') as HTMLFormElement;
+ if (!formElement) throw new Error('Form element not found');
+
+ const formDataRaw = new FormData(formElement);
+ const formData: Record<string, string> = {};
+ formDataRaw.forEach((value, key) => {
+ formData[key] = value as string;
+ });
+ return formData;
+ }
+
+ private validateFormData(formData: Record<string, string>): boolean {
+ // Basic required fields
+ const basicFields = [
+ { field: 'name', message: 'Name field is required.' },
+ { field: 'platform', message: 'Platform field is required.' },
+ { field: 'oauthService', message: 'Auth Service must be selected.', invalidValue: 'None' },
+ ];
+
+ for (const { field, message, invalidValue } of basicFields) {
+ const value = formData[field]?.trim();
+ if (!value || value === invalidValue) {
+ errorToast(message, 'Error', 'alert');
+ return false; // Don't throw, just return false
+ }
+ }
+
+ // OAuth service-specific validation
+ const oauthService = formData.oauthService;
+ if (oauthService && oauthService !== 'None') {
+ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(oauthService);
+ const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(oauthService);
+ const isClientCreds = OAuthServicesRegistry.isClientCredentialsService(oauthService);
+
+ if (isOAuth2) {
+ // OAuth2 validation
+ if (!formData.clientID?.trim()) {
+ errorToast('Client ID is required for OAuth2 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.clientSecret?.trim()) {
+ errorToast('Client Secret is required for OAuth2 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.tokenURL?.trim()) {
+ errorToast('Token URL is required for OAuth2 services.', 'Error', 'alert');
+ return false;
+ }
+
+ // Additional validation for non-client-credentials flows
+ if (!isClientCreds) {
+ if (!formData.authorizationURL?.trim()) {
+ errorToast(
+ 'Authorization URL is required for OAuth2 authorization flows.',
+ 'Error',
+ 'alert',
+ );
+ return false;
+ }
+ if (!formData.scope?.trim()) {
+ errorToast('Scope is required for OAuth2 authorization flows.', 'Error', 'alert');
+ return false;
+ }
+ }
+ } else if (isOAuth1) {
+ // OAuth1 validation
+ if (!formData.consumerKey?.trim()) {
+ errorToast('Consumer Key is required for OAuth1 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.consumerSecret?.trim()) {
+ errorToast('Consumer Secret is required for OAuth1 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.requestTokenURL?.trim()) {
+ errorToast('Request Token URL is required for OAuth1 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.accessTokenURL?.trim()) {
+ errorToast('Access Token URL is required for OAuth1 services.', 'Error', 'alert');
+ return false;
+ }
+ if (!formData.userAuthorizationURL?.trim()) {
+ errorToast('User Authorization URL is required for OAuth1 services.', 'Error', 'alert');
+ return false;
+ }
+ }
+ }
+
+ return true;
+ }
+
+ private mapServiceNameToInternal(serviceName: string): string {
+ const map: Record<string, string> = {
+ Google: 'google',
+ Twitter: 'twitter',
+ LinkedIn: 'linkedin',
+ 'Custom OAuth2.0': 'oauth2',
+ 'Custom OAuth1.0': 'oauth1',
+ 'OAuth2 Client Credentials': 'oauth2_client_credentials',
+ None: 'none',
+ };
+ return map[serviceName] || serviceName.toLowerCase();
+ }
+}
diff --git a/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx b/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
index a994e052..b0178bc8 100644
--- a/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
+++ b/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
@@ -17,12 +17,13 @@ import {
SelectValue,
} from '@src/react/shared/components/ui/select';
import { Textarea } from '@src/react/shared/components/ui/textarea';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import {
OAUTH_SERVICES,
deriveCallbackUrl,
mapInternalToServiceName,
mapServiceNameToInternal,
-} from '@src/shared/utils/oauth.utils';
+} from '@src/shared/helpers/oauth/oauth.utils';
import React, { useEffect, useMemo, useState } from 'react';
import type {
CreateOAuthConnectionModalProps,
@@ -138,56 +139,34 @@ export function CreateOAuthConnectionModal({
// Determine which fields to show based on selected service
const showOAuth2Fields = useMemo(
- () => ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedService),
+ () => OAuthServicesRegistry.isOAuth2Service(selectedService),
[selectedService],
);
const showOAuth1Fields = useMemo(
- () => ['Twitter', 'Custom OAuth1.0'].includes(selectedService),
+ () => OAuthServicesRegistry.isOAuth1Service(selectedService),
[selectedService],
- ); // Assuming Twitter uses 1.0a for simplicity here, might need adjustment
+ );
const showClientCredentialsFields = useMemo(
- () => selectedService === 'OAuth2 Client Credentials',
+ () => OAuthServicesRegistry.isClientCredentialsService(selectedService),
[selectedService],
);
const showScopeField = useMemo(
() =>
- !['Custom OAuth1.0', 'OAuth2 Client Credentials'].includes(selectedService) &&
+ !OAuthServicesRegistry.isOAuth1Service(selectedService) &&
+ !OAuthServicesRegistry.isClientCredentialsService(selectedService) &&
selectedService !== 'None',
[selectedService],
); // Scope not typically used in 1.0a or Client Credentials
- // Pre-fill URLs for known providers (similar logic to APICall.class)
+ // Pre-fill URLs for known providers using centralized configuration
useEffect(() => {
if (!isEditMode) {
// Only prefill when creating, not editing
- let defaults: Partial<OAuthConnectionFormData> = {};
- const baseCallbackUri = window.location.origin; // Simplistic assumption
+ const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedService);
- switch (selectedService) {
- case 'Google':
- defaults = {
- authorizationURL: 'https://accounts.google.com/o/oauth2/v2/auth',
- tokenURL: 'https://oauth2.googleapis.com/token',
- scope: 'https://www.googleapis.com/auth/gmail.readonly', // Example scope
- };
- break;
- case 'LinkedIn':
- defaults = {
- authorizationURL: 'https://www.linkedin.com/oauth/v2/authorization',
- tokenURL: 'https://www.linkedin.com/oauth/v2/accessToken',
- scope: 'r_liteprofile r_emailaddress', // Example scope (using OIDC)
- };
- break;
- case 'Twitter': // Assuming OAuth 1.0a for now based on APICall
- defaults = {
- requestTokenURL: 'https://api.twitter.com/oauth/request_token',
- accessTokenURL: 'https://api.twitter.com/oauth/access_token',
- userAuthorizationURL: 'https://api.twitter.com/oauth/authorize',
- };
- break;
- // Add cases for other predefined services if any
+ if (serviceDefaults && Object.keys(serviceDefaults).length > 0) {
+ setFormData((prev) => ({ ...prev, ...serviceDefaults }));
}
- setFormData((prev) => ({ ...prev, ...defaults }));
}
}, [selectedService, isEditMode]);
diff --git a/packages/app/src/react/features/vault/components/oauth-connections.tsx b/packages/app/src/react/features/vault/components/oauth-connections.tsx
index 21035f33..49da6870 100644
--- a/packages/app/src/react/features/vault/components/oauth-connections.tsx
+++ b/packages/app/src/react/features/vault/components/oauth-connections.tsx
@@ -6,7 +6,7 @@ import {
extractPlatformFromUrl,
getBackendOrigin,
mapOAuthTypeDisplay,
-} from '@src/shared/utils/oauth.utils';
+} from '@src/shared/helpers/oauth/oauth.utils';
import { useQueryClient } from '@tanstack/react-query'; // Import useQueryClient
import { Circle, CopyPlus, Pencil, PlusCircle, Trash2 } from 'lucide-react';
import React, { useCallback, useEffect, useState } from 'react';
diff --git a/packages/app/src/react/features/vault/components/use-vault-oauth.ts b/packages/app/src/react/features/vault/components/use-vault-oauth.ts
index 0c59ca84..bf7d7893 100644
--- a/packages/app/src/react/features/vault/components/use-vault-oauth.ts
+++ b/packages/app/src/react/features/vault/components/use-vault-oauth.ts
@@ -6,14 +6,15 @@ import {
fetchOAuthConnections as fetchOAuthConnectionsShared,
initiateOAuthFlow as initiateOAuthFlowShared,
saveOAuthConnection as saveOAuthConnectionShared,
- signOutOAuthConnection as signOutOAuthConnectionShared
-} from '@src/shared/helpers/oauth-api.helper';
+ signOutOAuthConnection as signOutOAuthConnectionShared,
+} from '@src/shared/helpers/oauth/oauth-api.helper';
+import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import {
generateOAuthId,
isOAuth1Service,
mapInternalToServiceName,
- mapServiceNameToInternal
-} from '@src/shared/utils/oauth.utils';
+ mapServiceNameToInternal,
+} from '@src/shared/helpers/oauth/oauth.utils';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import type {
AuthenticateOAuthPayload,
@@ -24,7 +25,7 @@ import type {
OAuthInfo,
OAuthSettings,
SignOutOAuthPayload,
- UpdateOAuthConnectionPayload
+ UpdateOAuthConnectionPayload,
} from '../types/oauth-connection';
export const OAUTH_QUERY_KEY = ['oauthConnections'];
@@ -63,7 +64,7 @@ function isTokenCurrentlyValid(expiresAtMs: number | null, bufferSeconds: number
* - oauth2: primary token present; if expiry provided, ensure not expired; otherwise unknown
* - oauth (OAuth1): require both primary and secondary (token + tokenSecret)
* Returns true/false when determinable from local data, otherwise undefined to trigger server check.
- *
+ *
* When tokens are redacted, we assume they're valid to prevent infinite auth check loops.
*/
function computeLocalAuthStatus(connection: Partial<OAuthConnection>): boolean | undefined {
@@ -101,10 +102,6 @@ function computeLocalAuthStatus(connection: Partial<OAuthConnection>): boolean |
return undefined;
}
-
-
-
-
/**
* Fetches all OAuth connection settings by calling the backend API.
* Assumes the backend endpoint GET /vault/oauth-connections uses getTeamSettingsObj(req, 'oauth').
@@ -133,7 +130,10 @@ const fetchOAuthConnections = async (): Promise<OAuthSettings> => {
try {
connectionData = JSON.parse(connectionData);
} catch (e) {
- console.warn(`[fetchOAuthConnections] Could not parse stringified connection for id=${id}:`, e);
+ console.warn(
+ `[fetchOAuthConnections] Could not parse stringified connection for id=${id}:`,
+ e,
+ );
return null;
}
}
@@ -148,7 +148,7 @@ const fetchOAuthConnections = async (): Promise<OAuthSettings> => {
let runtimeConnectionData: Partial<OAuthConnection> = {};
if (connectionData.auth_data && connectionData.auth_settings) {
runtimeConnectionData = {
- ...(connectionData.auth_settings),
+ ...connectionData.auth_settings,
primary: connectionData.auth_data.primary,
secondary: connectionData.auth_data.secondary,
expires_in: connectionData.auth_data.expires_in,
@@ -164,9 +164,19 @@ const fetchOAuthConnections = async (): Promise<OAuthSettings> => {
// Synthesize oauth_info for runtime consumers
const synthKeys = [
- 'oauth_keys_prefix', 'service', 'platform', 'scope', 'authorizationURL', 'tokenURL',
- 'clientID', 'clientSecret', 'requestTokenURL', 'accessTokenURL', 'userAuthorizationURL',
- 'consumerKey', 'consumerSecret'
+ 'oauth_keys_prefix',
+ 'service',
+ 'platform',
+ 'scope',
+ 'authorizationURL',
+ 'tokenURL',
+ 'clientID',
+ 'clientSecret',
+ 'requestTokenURL',
+ 'accessTokenURL',
+ 'userAuthorizationURL',
+ 'consumerKey',
+ 'consumerSecret',
];
const existingOauthInfo = (runtimeConnectionData as any).oauth_info;
const oauthInfoSynth: any = existingOauthInfo ? { ...existingOauthInfo } : {};
@@ -191,9 +201,7 @@ const fetchOAuthConnections = async (): Promise<OAuthSettings> => {
// Get the actual name value (could be empty string, but must exist)
const actualName =
- runtimeConnectionData.name ??
- connectionData.name ??
- connectionData.auth_settings?.name;
+ runtimeConnectionData.name ?? connectionData.name ?? connectionData.auth_settings?.name;
// Ensure name is a string (even if empty)
if (typeof actualName !== 'string') {
@@ -323,7 +331,10 @@ export function useOAuthConnections() {
// Helper function to get relevant CONFIGURATION fields for oauth_info based on type
// It now expects the form payload (`rest`) as input data.
-const getRelevantOAuthInfoFields = (type: 'oauth' | 'oauth2' | 'oauth2_client_credentials', formData: Record<string, any>): Partial<OAuthInfo> => {
+const getRelevantOAuthInfoFields = (
+ type: 'oauth' | 'oauth2' | 'oauth2_client_credentials',
+ formData: Record<string, any>,
+): Partial<OAuthInfo> => {
const relevantInfo: Partial<OAuthInfo> = {};
// *** ADDED: Always include platform if provided ***
@@ -334,18 +345,24 @@ const getRelevantOAuthInfoFields = (type: 'oauth' | 'oauth2' | 'oauth2_client_cr
if (type === 'oauth2') {
// OAuth2 specific config fields from the form
- ['authorizationURL', 'tokenURL', 'clientID', 'clientSecret'].forEach(key => {
+ ['authorizationURL', 'tokenURL', 'clientID', 'clientSecret'].forEach((key) => {
if (formData[key] !== undefined) relevantInfo[key] = formData[key];
});
// oauth2CallbackURL is derived, not directly from form data passed here
} else if (type === 'oauth2_client_credentials') {
// Client Credentials specific config fields from the form
- ['tokenURL', 'clientID', 'clientSecret'].forEach(key => {
+ ['tokenURL', 'clientID', 'clientSecret'].forEach((key) => {
if (formData[key] !== undefined) relevantInfo[key] = formData[key];
});
} else if (type === 'oauth') {
// OAuth 1.0a specific config fields from the form
- ['requestTokenURL', 'accessTokenURL', 'userAuthorizationURL', 'consumerKey', 'consumerSecret'].forEach(key => {
+ [
+ 'requestTokenURL',
+ 'accessTokenURL',
+ 'userAuthorizationURL',
+ 'consumerKey',
+ 'consumerSecret',
+ ].forEach((key) => {
if (formData[key] !== undefined) relevantInfo[key] = formData[key];
});
// oauth1CallbackURL is derived, not directly from form data passed here
@@ -364,10 +381,10 @@ export function useCreateOAuthConnection() {
const connectionId = `OAUTH_${generateOAuthId()}_TOKENS`;
const { oauthService, name, platform, ...rest } = payload;
- // Determine type and internal service name
- const type = ['Custom OAuth1.0', 'Twitter'].includes(oauthService)
+ // Determine type and internal service name using centralized configuration
+ const type = OAuthServicesRegistry.isOAuth1Service(oauthService)
? 'oauth'
- : oauthService === 'OAuth2 Client Credentials'
+ : OAuthServicesRegistry.isClientCredentialsService(oauthService)
? 'oauth2_client_credentials'
: 'oauth2';
const internalService = mapServiceNameToInternal(oauthService);
@@ -392,7 +409,10 @@ export function useCreateOAuthConnection() {
const authSettings = {
name: name,
type: type,
- tokenURL: (type === 'oauth2' || type === 'oauth2_client_credentials') ? oauthInfoData.tokenURL : undefined,
+ tokenURL:
+ type === 'oauth2' || type === 'oauth2_client_credentials'
+ ? oauthInfoData.tokenURL
+ : undefined,
oauth_info: oauthInfoData,
// team: undefined, // Team is typically added by the backend if needed
};
@@ -431,11 +451,11 @@ export function useUpdateOAuthConnection() {
? mapServiceNameToInternal(oauthService)
: currentData.oauth_info.service;
const finalType = oauthService
- ? (isOAuth1Service(finalInternalService)
+ ? isOAuth1Service(finalInternalService)
? 'oauth'
: finalInternalService === 'oauth2_client_credentials'
? 'oauth2_client_credentials'
- : 'oauth2')
+ : 'oauth2'
: currentData.type;
// Build the updated oauth_info object
@@ -499,7 +519,10 @@ export function useUpdateOAuthConnection() {
const updatedAuthSettings = {
name: updatedOAuthInfo.name, // Use the potentially updated name
type: finalType, // Use the potentially updated type
- tokenURL: (finalType === 'oauth2' || finalType === 'oauth2_client_credentials') ? updatedOAuthInfo.tokenURL : undefined,
+ tokenURL:
+ finalType === 'oauth2' || finalType === 'oauth2_client_credentials'
+ ? updatedOAuthInfo.tokenURL
+ : undefined,
oauth_info: updatedOAuthInfo, // Include the fully updated oauth_info
};
@@ -518,7 +541,7 @@ export function useUpdateOAuthConnection() {
},
onError: (error, variables) => {
console.error(`Error updating connection ${variables.connectionId}:`, error);
- }
+ },
});
}
@@ -585,7 +608,6 @@ export function useDuplicateOAuthConnection() {
});
}
-
/**
* Hook to initiate OAuth authentication flow.
* @returns Mutation object for initiating OAuth flow.
@@ -607,7 +629,7 @@ export function useInitiateOAuth() {
window.open(
data.authUrl,
'_blank',
- `width=${width},height=${height},top=${top},left=${left},resizable=yes,scrollbars=yes`
+ `width=${width},height=${height},top=${top},left=${left},resizable=yes,scrollbars=yes`,
);
// Add listener here or manage globally? Usually managed where the hook is called.
} else {
@@ -726,7 +748,9 @@ export function useSignOutOAuth() {
});
}
-const authenticateClientCredentials = async (payload: OAuthInfo): Promise<{ success: boolean; message: string }> => {
+const authenticateClientCredentials = async (
+ payload: OAuthInfo,
+): Promise<{ success: boolean; message: string }> => {
return authenticateClientCredentialsShared(payload);
};
@@ -742,4 +766,3 @@ export function useAuthenticateClientCredentials() {
},
});
}
-
diff --git a/packages/app/src/shared/helpers/oauth/README.md b/packages/app/src/shared/helpers/oauth/README.md
new file mode 100644
index 00000000..9613073e
--- /dev/null
+++ b/packages/app/src/shared/helpers/oauth/README.md
@@ -0,0 +1,338 @@
+# OAuth System Refactoring - Phase 1
+
+This document outlines the first phase of OAuth system refactoring that centralizes OAuth service configurations and eliminates hardcoded service type checks across the entire codebase.
+
+## 🚀 Adding a New OAuth Provider
+
+Thanks to our centralized configuration system, adding a new OAuth provider is now as simple as updating a single JSON file:
+
+### Step 1: Add Service Configuration
+
+Edit `oauth-services.json` and add your new service:
+
+```json
+{
+ "services": {
+ "Slack": {
+ "displayName": "Slack",
+ "internalName": "slack",
+ "type": "oauth2",
+ "category": "predefined",
+ "config": {
+ "authorizationURL": "https://slack.com/oauth/v2/authorize",
+ "tokenURL": "https://slack.com/api/oauth.v2.access",
+ "scope": "channels:read users:read"
+ },
+ "callbackPath": "/oauth/slack/callback",
+ "validation": {
+ "required": ["clientID", "clientSecret", "authorizationURL", "tokenURL", "scope"]
+ }
+ }
+ }
+}
+```
+
+### Step 2: That's It!
+
+The new service will automatically work across:
+
+- ✅ Frontend service type detection and validation
+- ✅ Backend OAuth routing and callback handling
+- ✅ React component dropdowns and form validation
+- ✅ Builder UI configuration and defaults
+- ✅ Callback URL generation and normalization
+
+## 🔧 Adding OAuth Authentication to a Component
+
+To add OAuth authentication functionality to a Builder UI component, follow this modular approach:
+
+### Step 1: Create OAuth Settings Helper
+
+Use the `oAuthSettings` helper class to handle all OAuth-related logic:
+
+```typescript
+import { oAuthSettings } from '../../helpers/oauth/oauth-settings.helper';
+import { Trigger } from './Trigger.class';
+
+export class GmailTrigger extends Trigger {
+ private oauth: oAuthSettings | undefined;
+ //...
+}
+```
+
+### Step 2: Initialize OAuth in prepare()
+
+Initialize the OAuth helper in your component's `prepare()` method:
+
+```typescript
+protected async prepare(): Promise<boolean> {
+ try {
+ // Initialize OAuth settings helper
+ this.oauth = new oAuthSettings(this);
+ await this.oauth.initialize();
+ return true;
+ } catch (error) {
+ console.error('Error preparing OAuth component:', error);
+ return false;
+ }
+}
+```
+
+### Step 3: Configure OAuth Settings
+
+Spread the OAuth configuration into your component's settings:
+
+```typescript
+protected async init(): Promise<void> {
+ await super.init();
+
+ // Set up component settings with OAuth configuration
+ this.settings = {
+ // Your component-specific settings
+ interval: {
+ type: 'range',
+ label: 'Interval',
+ min: 1,
+ max: 720,
+ value: 1,
+ },
+ // Spread OAuth settings (connection selector + auth button)
+ ...this.oauth?.configure(),
+ };
+}
+```
+
+### Step 4: Clean Up Resources
+
+Ensure proper cleanup in the `destroy()` method:
+
+```typescript
+destroy(): void {
+ // Clean up OAuth helper
+ if (this.oauth) {
+ this.oauth.destroy();
+ }
+
+ super.destroy?.();
+}
+```
+
+### What You Get Automatically:
+
+- ✅ **OAuth Connection Selector**: Dropdown with all available OAuth connections
+- ✅ **Add/Edit Connection Actions**: "Add New" and "Edit" options in the dropdown
+- ✅ **Authentication Button**: Shows connection status and allows sign-in/sign-out
+- ✅ **Connection Management**: Full CRUD operations for OAuth connections
+- ✅ **Service Type Detection**: Automatic handling of OAuth1, OAuth2, and Client Credentials
+- ✅ **Form Validation**: Service-specific field validation
+- ✅ **Error Handling**: Centralized error handling and user feedback
+
+### ⚠️ Special Note: APICall Component
+
+The `APICall.class.ts` component currently **does not** use the `oAuthSettings` helper approach described above. Instead, it implements OAuth functionality directly within the component itself.
+
+**Why?** The APICall component needs to handle:
+
+- **Legacy data formats** from existing workflows
+- **Backward compatibility** with older OAuth connection structures
+- **Complex field mapping** between different data formats
+- **Direct integration** with API call configurations
+
+**Migration Needed:** To improve maintainability, the APICall component should be migrated to use the `oAuthSettings` helper approach while maintaining backward compatibility. This would:
+
+- ✅ **Reduce code duplication** (currently ~200 lines of OAuth logic)
+- ✅ **Improve consistency** with other OAuth-enabled components
+- ✅ **Simplify maintenance** by centralizing OAuth logic
+- ✅ **Enhance testing** through better separation of concerns
+
+**Recommended Approach:**
+
+1. Create a specialized `APICallOAuthSettings` class that extends `oAuthSettings`
+2. Handle legacy data format conversion within this specialized class
+3. Gradually migrate APICall to use the helper while maintaining compatibility
+4. Add comprehensive tests for both legacy and new data formats
+
+### Configuration Options
+
+| Field | Description | Required |
+| --------------------- | ------------------------------------------------------------------------ | -------- |
+| `displayName` | User-facing service name | ✅ |
+| `internalName` | Internal service identifier | ✅ |
+| `type` | OAuth flow type: `oauth1`, `oauth2`, `oauth2_client_credentials`, `none` | ✅ |
+| `category` | Service category: `predefined`, `custom`, `system` | ✅ |
+| `config` | Default URLs and scopes (empty for custom services) | ✅ |
+| `callbackPath` | OAuth callback path pattern | ✅ |
+| `validation.required` | Required form fields for this service type | ✅ |
+
+## 📚 System Dependencies
+
+### Core Components
+
+#### `oauth-services.json`
+
+- **Purpose**: Single source of truth for all OAuth service configurations
+- **Contains**: Service definitions, default URLs, validation rules, callback paths
+- **Impact**: Changes here propagate automatically across the entire system
+
+#### `oauth-services.helper.ts` - `OAuthServicesRegistry`
+
+- **Purpose**: Centralized API for accessing OAuth service configurations
+- **Key Methods**:
+ - `isOAuth2Service()` / `isOAuth1Service()` / `isClientCredentialsService()` - Service type detection
+ - `getServiceDefaults()` - Get pre-configured URLs and scopes
+ - `getValidationRules()` - Get required fields for validation
+ - `mapServiceNameToInternal()` / `mapInternalToServiceName()` - Name mapping
+ - `getCallbackPath()` - Get OAuth callback paths
+
+#### `oauth.utils.ts`
+
+- **Purpose**: Shared OAuth utilities and helper functions
+- **Updated**: Now delegates to `OAuthServicesRegistry` instead of hardcoded logic
+- **Functions**: URL derivation, platform extraction, API response handling
+
+## 🏗️ Code Dependencies by Section
+
+### React Components (`src/react/features/vault/`)
+
+#### Components Using OAuth Logic:
+
+- **`create-oauth-connection-modal.tsx`**
+ - Service type detection for field visibility
+ - Pre-filling service defaults
+ - Form validation based on service type
+
+- **`use-vault-oauth.ts`**
+ - OAuth connection CRUD operations
+ - Service type determination for API calls
+ - Data format conversion between storage and UI
+
+#### Key Integration Points:
+
+```typescript
+// Service type checks
+const showOAuth2Fields = OAuthServicesRegistry.isOAuth2Service(selectedService);
+const showOAuth1Fields = OAuthServicesRegistry.isOAuth1Service(selectedService);
+
+// Service defaults
+const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedService);
+```
+
+### Builder UI (`src/builder-ui/`)
+
+#### Components Using OAuth Logic:
+
+- **`components/APICall.class.ts`**
+ - OAuth service configuration in API calls
+ - Service type detection for field visibility
+ - Default URL pre-filling
+
+- **`helpers/oauth/oauth.service.ts`**
+ - OAuth connection management
+ - Service name mapping
+ - Callback URL normalization
+
+- **`helpers/oauth/ui.helper.ts`**
+ - OAuth modal UI logic
+ - Form validation
+ - Service-specific field handling
+
+- **`helpers/oauth/oauth-modal.helper.ts`**
+ - OAuth modal HTML generation
+ - Service default pre-filling
+ - Field visibility management
+
+#### Key Integration Points:
+
+```typescript
+// Service configuration
+const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(selectedValue);
+const serviceDefaults = OAuthServicesRegistry.getServiceDefaults(selectedService);
+const callbackPath = OAuthServicesRegistry.getCallbackPath(serviceType);
+```
+
+### Backend (`src/backend/`)
+
+#### Components Using OAuth Logic:
+
+- **`middlewares/oauthStrategy.mw.ts`**
+ - OAuth strategy initialization
+ - Service type detection for routing
+ - Callback URL derivation
+
+- **`routes/oauth/router.ts`**
+ - OAuth flow routing (OAuth1 vs OAuth2)
+ - Authentication URL construction
+ - Service-specific parameter handling
+
+#### Key Integration Points:
+
+```typescript
+// Service type detection
+const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(service);
+const isOAuth1 = OAuthServicesRegistry.isOAuth1Service(service);
+
+// Flow routing
+if (OAuthServicesRegistry.isOAuth2Service(service) || service === 'oauth2') {
+ // OAuth2 flow
+} else if (OAuthServicesRegistry.isOAuth1Service(service) || service === 'oauth1') {
+ // OAuth1 flow
+}
+```
+
+## 🔄 What We Accomplished
+
+### Before Refactoring:
+
+- ❌ **8+ files** with hardcoded service arrays like `['Google', 'LinkedIn', 'Custom OAuth2.0']`
+- ❌ **Duplicated service defaults** across 6+ components
+- ❌ **Inconsistent service type checks** using different logic
+- ❌ **Manual synchronization** required when adding new services
+- ❌ **High maintenance risk** - easy to miss files when making changes
+
+### After Refactoring:
+
+- ✅ **1 centralized JSON file** (`oauth-services.json`) as single source of truth
+- ✅ **Consistent API** (`OAuthServicesRegistry`) used across all components
+- ✅ **Automatic propagation** - JSON changes apply everywhere instantly
+- ✅ **Type-safe service detection** with comprehensive validation
+- ✅ **Easy service addition** - just update JSON, no code changes needed
+
+### Files Refactored:
+
+- **Frontend**: `oauth.utils.ts`, `ui.helper.ts`, `oauth-modal.helper.ts`, `create-oauth-connection-modal.tsx`, `use-vault-oauth.ts`
+- **Builder UI**: `APICall.class.ts`, `oauth.service.ts`
+- **Backend**: `oauthStrategy.mw.ts`, `router.ts`
+
+## 🚧 Future Refactoring Needs
+
+While this phase significantly improved maintainability, the OAuth system still requires additional refactoring:
+
+### Remaining Technical Debt:
+
+1. **Data Format Inconsistencies**: Multiple OAuth data formats exist (nested vs flat) across different parts of the system
+2. **Complex Type Definitions**: OAuth type interfaces are scattered and sometimes duplicated
+3. **Legacy Compatibility Code**: Backward compatibility logic that could be simplified
+4. **Callback URL Logic**: Still contains some hardcoded callback path generation
+5. **Error Handling**: OAuth error handling could be more centralized and consistent
+6. **Testing**: OAuth flows need comprehensive test coverage
+
+### Recommended Next Steps:
+
+1. **Unify Data Formats**: Standardize on a single OAuth connection data format
+2. **Consolidate Type Definitions**: Create a single, comprehensive OAuth type system
+3. **Simplify Callback Logic**: Fully leverage centralized callback path configuration
+4. **Enhanced Error Handling**: Create centralized OAuth error handling and user feedback
+5. **Comprehensive Testing**: Add unit and integration tests for all OAuth flows
+6. **Documentation**: Create detailed OAuth flow documentation for developers
+
+### Benefits of Future Refactoring:
+
+- 🎯 **Reduced Complexity**: Simpler codebase with fewer edge cases
+- 🔧 **Easier Debugging**: Centralized error handling and logging
+- 🚀 **Better Performance**: Optimized OAuth flows with reduced redundancy
+- 📚 **Improved Developer Experience**: Clear patterns and comprehensive documentation
+- 🛡️ **Enhanced Security**: Standardized security practices across all OAuth flows
+
+---
+
+_This refactoring represents a significant step toward a more maintainable and scalable OAuth system. The centralized configuration approach provides a solid foundation for future improvements while immediately reducing the complexity of adding new OAuth providers._
diff --git a/packages/app/src/shared/helpers/oauth-api.helper.ts b/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
similarity index 62%
rename from packages/app/src/shared/helpers/oauth-api.helper.ts
rename to packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
index 102c8dc3..cbfe6d47 100644
--- a/packages/app/src/shared/helpers/oauth-api.helper.ts
+++ b/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
@@ -3,8 +3,7 @@ import {
handleApiResponse,
isOAuth1Service,
isOAuth2Service,
- mapInternalToServiceName
-} from '@src/shared/utils/oauth.utils';
+} from '@src/shared/helpers/oauth/oauth.utils';
/**
* Extract OAuth info from connection data supporting both old and new structures
@@ -25,13 +24,22 @@ export function getConnectionOauthInfo(connection: any, connectionId?: string):
// Backend has flattened oauth_info to auth_settings root, reconstruct it
const reconstructed: any = {};
const oauthFields = [
- 'oauth_keys_prefix', 'service', 'platform', 'scope',
- 'authorizationURL', 'tokenURL', 'clientID', 'clientSecret',
- 'requestTokenURL', 'accessTokenURL', 'userAuthorizationURL',
- 'consumerKey', 'consumerSecret'
+ 'oauth_keys_prefix',
+ 'service',
+ 'platform',
+ 'scope',
+ 'authorizationURL',
+ 'tokenURL',
+ 'clientID',
+ 'clientSecret',
+ 'requestTokenURL',
+ 'accessTokenURL',
+ 'userAuthorizationURL',
+ 'consumerKey',
+ 'consumerSecret',
];
- oauthFields.forEach(field => {
+ oauthFields.forEach((field) => {
if (connection.auth_settings[field] !== undefined) {
reconstructed[field] = connection.auth_settings[field];
}
@@ -54,13 +62,22 @@ export function getConnectionOauthInfo(connection: any, connectionId?: string):
// Legacy: construct oauth_info from flat fields
const oauthInfo: any = {};
const fields = [
- 'oauth_keys_prefix', 'service', 'platform', 'scope',
- 'authorizationURL', 'tokenURL', 'clientID', 'clientSecret',
- 'requestTokenURL', 'accessTokenURL', 'userAuthorizationURL',
- 'consumerKey', 'consumerSecret'
+ 'oauth_keys_prefix',
+ 'service',
+ 'platform',
+ 'scope',
+ 'authorizationURL',
+ 'tokenURL',
+ 'clientID',
+ 'clientSecret',
+ 'requestTokenURL',
+ 'accessTokenURL',
+ 'userAuthorizationURL',
+ 'consumerKey',
+ 'consumerSecret',
];
- fields.forEach(field => {
+ fields.forEach((field) => {
if (connection[field] !== undefined) {
oauthInfo[field] = connection[field];
}
@@ -84,102 +101,107 @@ export function extractServiceFromConnection(connection: any): string {
return oauthInfo?.service || '';
}
-/**
- * Derive service name from OAuth info URLs
- */
-export function deriveServiceFromOauthInfo(oauthInfo: any): string {
- if (!oauthInfo) return '';
-
- // Check authorization URL first
- if (oauthInfo.authorizationURL?.includes('google')) return 'Google';
- if (oauthInfo.authorizationURL?.includes('linkedin')) return 'LinkedIn';
- if (oauthInfo.authorizationURL?.includes('twitter') || oauthInfo.authorizationURL?.includes('x.com')) return 'Twitter/X';
-
- // Check other URLs
- if (oauthInfo.userAuthorizationURL?.includes('twitter') || oauthInfo.userAuthorizationURL?.includes('x.com')) return 'Twitter/X';
- if (oauthInfo.tokenURL?.includes('google')) return 'Google';
- if (oauthInfo.tokenURL?.includes('linkedin')) return 'LinkedIn';
-
- return '';
-}
-
-/**
- * Build OAuth select options from connections with unified name detection
- */
-export function buildOAuthSelectOptions(
- connections: Record<string, any>,
- componentSpecificId?: string,
- logPrefix?: string
-): Array<{ label: string; value: string }> {
- const connectionOptions: Array<{ label: string; value: string }> = [
- { label: 'None', value: 'None' }
- ];
-
- if (!connections || typeof connections !== 'object') {
- return connectionOptions;
- }
-
- for (const [id, connection] of Object.entries(connections)) {
- if (!id.startsWith('OAUTH_') || !id.endsWith('_TOKENS')) continue;
-
- try {
- // Parse if stringified
- const parsedConnection = typeof connection === 'string' ? JSON.parse(connection) : connection;
-
- // Support both new and old structures
- const isNewStructure = parsedConnection.auth_data && parsedConnection.auth_settings;
- const settingsPart = isNewStructure ? parsedConnection.auth_settings : parsedConnection;
-
- // Extract name with multiple fallback options
- let name = settingsPart?.name || '';
-
- if (!name) {
- // Try to derive from oauth_info
- const oauthInfo = getConnectionOauthInfo(parsedConnection, id);
- name = oauthInfo?.name || '';
-
- if (!name && oauthInfo?.service) {
- // Use service name as fallback
- const serviceName = mapInternalToServiceName(oauthInfo.service);
- name = serviceName !== oauthInfo.service ? serviceName : '';
- }
-
- if (!name) {
- // Try to derive from platform
- name = oauthInfo?.platform || deriveServiceFromOauthInfo(oauthInfo) || '';
- }
- }
-
- // Create label with ID prefix if needed
- const label = name ? `${name} (${id.substring(0, 15)}...)` : id;
-
- connectionOptions.push({
- label,
- value: id
- });
-
- if (logPrefix) {
- // console.log(`${logPrefix} Added option:`, { id, name, label });
- }
-
- } catch (error) {
- console.error(`Error processing connection ${id}:`, error);
- connectionOptions.push({
- label: id,
- value: id
- });
- }
- }
-
- return connectionOptions;
-}
+// /**
+// * Derive service name from OAuth info URLs
+// */
+// export function deriveServiceFromOauthInfo(oauthInfo: any): string {
+// if (!oauthInfo) return '';
+
+// // Check authorization URL first
+// if (oauthInfo.authorizationURL?.includes('google')) return 'Google';
+// if (oauthInfo.authorizationURL?.includes('linkedin')) return 'LinkedIn';
+// if (
+// oauthInfo.authorizationURL?.includes('twitter') ||
+// oauthInfo.authorizationURL?.includes('x.com')
+// )
+// return 'Twitter/X';
+
+// // Check other URLs
+// if (
+// oauthInfo.userAuthorizationURL?.includes('twitter') ||
+// oauthInfo.userAuthorizationURL?.includes('x.com')
+// )
+// return 'Twitter/X';
+// if (oauthInfo.tokenURL?.includes('google')) return 'Google';
+// if (oauthInfo.tokenURL?.includes('linkedin')) return 'LinkedIn';
+
+// return '';
+// }
+
+// /**
+// * Build OAuth select options from connections with unified name detection
+// */
+// export function buildOAuthSelectOptions(
+// connections: Record<string, any>,
+// componentSpecificId?: string,
+// logPrefix?: string,
+// ): Array<{ label: string; value: string }> {
+// const connectionOptions: Array<{ label: string; value: string }> = [
+// { label: 'None', value: 'None' },
+// ];
+
+// if (!connections || typeof connections !== 'object') {
+// return connectionOptions;
+// }
+
+// for (const [id, connection] of Object.entries(connections)) {
+// if (!id.startsWith('OAUTH_') || !id.endsWith('_TOKENS')) continue;
+
+// try {
+// // Parse if stringified
+// const parsedConnection = typeof connection === 'string' ? JSON.parse(connection) : connection;
+
+// // Support both new and old structures
+// const isNewStructure = parsedConnection.auth_data && parsedConnection.auth_settings;
+// const settingsPart = isNewStructure ? parsedConnection.auth_settings : parsedConnection;
+
+// // Extract name with multiple fallback options
+// let name = settingsPart?.name || '';
+
+// if (!name) {
+// // Try to derive from oauth_info
+// const oauthInfo = getConnectionOauthInfo(parsedConnection, id);
+// name = oauthInfo?.name || '';
+
+// if (!name && oauthInfo?.service) {
+// // Use service name as fallback
+// const serviceName = mapInternalToServiceName(oauthInfo.service);
+// name = serviceName !== oauthInfo.service ? serviceName : '';
+// }
+
+// if (!name) {
+// // Try to derive from platform
+// name = oauthInfo?.platform || deriveServiceFromOauthInfo(oauthInfo) || '';
+// }
+// }
+
+// // Create label with ID prefix if needed
+// const label = name ? `${name} (${id.substring(0, 15)}...)` : id;
+
+// connectionOptions.push({
+// label,
+// value: id,
+// });
+
+// if (logPrefix) {
+// // console.log(`${logPrefix} Added option:`, { id, name, label });
+// }
+// } catch (error) {
+// console.error(`Error processing connection ${id}:`, error);
+// connectionOptions.push({
+// label: id,
+// value: id,
+// });
+// }
+// }
+
+// return connectionOptions;
+// }
/**
* Check if an OAuth connection is authenticated
*/
-export async function checkOAuthAuthentication(
- oauthInfo: any
-): Promise<{ success: boolean }> {
+export async function checkOAuthAuthentication(oauthInfo: any): Promise<{ success: boolean }> {
try {
const response = await fetch('/oauth/checkAuth', {
method: 'POST',
@@ -205,7 +227,7 @@ export async function checkOAuthAuthentication(
*/
export async function initiateOAuthFlow(
oauthInfo: any,
- openPopup: boolean = true
+ openPopup: boolean = true,
): Promise<{ authUrl?: string }> {
// Enhance payload with callback URLs if needed
const service = oauthInfo.service;
@@ -242,7 +264,7 @@ export async function initiateOAuthFlow(
window.open(
data.authUrl,
'oauth_popup',
- `width=${width},height=${height},top=${top},left=${left},toolbar=no,menubar=no,scrollbars=yes,resizable=yes`
+ `width=${width},height=${height},top=${top},left=${left},toolbar=no,menubar=no,scrollbars=yes,resizable=yes`,
);
}
@@ -254,7 +276,7 @@ export async function initiateOAuthFlow(
*/
export async function signOutOAuthConnection(
connectionId: string,
- invalidateAuthentication: boolean = true
+ invalidateAuthentication: boolean = true,
): Promise<{ invalidate: boolean }> {
const response = await fetch('/oauth/signOut', {
method: 'POST',
@@ -281,10 +303,7 @@ export async function signOutOAuthConnection(
/**
* Save OAuth connection to backend
*/
-export async function saveOAuthConnection(
- connectionId: string,
- authSettings: any
-): Promise<void> {
+export async function saveOAuthConnection(connectionId: string, authSettings: any): Promise<void> {
const response = await fetch('/api/page/vault/oauth-connections', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
@@ -297,7 +316,7 @@ export async function saveOAuthConnection(
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
- errorData.error || `Failed to save OAuth connection (Status: ${response.status})`
+ errorData.error || `Failed to save OAuth connection (Status: ${response.status})`,
);
}
}
@@ -313,7 +332,7 @@ export async function deleteOAuthConnection(connectionId: string): Promise<void>
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
throw new Error(
- errorData.error || `Failed to delete OAuth connection (Status: ${response.status})`
+ errorData.error || `Failed to delete OAuth connection (Status: ${response.status})`,
);
}
}
@@ -350,7 +369,9 @@ export async function fetchOAuthConnections(): Promise<Record<string, any>> {
/**
* Authenticate OAuth2 Client Credentials
*/
-export async function authenticateClientCredentials(oauthInfo: any): Promise<{ success: boolean; message: string }> {
+export async function authenticateClientCredentials(
+ oauthInfo: any,
+): Promise<{ success: boolean; message: string }> {
const response = await fetch('/oauth/client_credentials', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
diff --git a/packages/app/src/shared/helpers/oauth/oauth-services.helper.ts b/packages/app/src/shared/helpers/oauth/oauth-services.helper.ts
new file mode 100644
index 00000000..00774678
--- /dev/null
+++ b/packages/app/src/shared/helpers/oauth/oauth-services.helper.ts
@@ -0,0 +1,233 @@
+// Centralized OAuth Services Registry
+// This file provides a unified interface for OAuth service configurations
+// eliminating duplication across React and Builder UI components
+
+import oauthServicesConfig from './oauth-services.json';
+
+export interface OAuthServiceConfig {
+ displayName: string;
+ internalName: string;
+ type: 'oauth1' | 'oauth2' | 'oauth2_client_credentials' | 'none';
+ category: 'predefined' | 'custom' | 'system';
+ config: Record<string, string>;
+ callbackPath: string;
+ validation: {
+ required: string[];
+ };
+}
+
+export interface OAuthServiceDefaults {
+ authorizationURL?: string;
+ tokenURL?: string;
+ scope?: string;
+ requestTokenURL?: string;
+ accessTokenURL?: string;
+ userAuthorizationURL?: string;
+}
+
+/**
+ * Centralized OAuth Services Registry
+ *
+ * This class provides a single source of truth for OAuth service configurations,
+ * replacing hardcoded service definitions scattered across the codebase.
+ *
+ * @example
+ * // Check service type
+ * const isOAuth2 = OAuthServicesRegistry.isOAuth2Service('Google');
+ *
+ * // Get service defaults
+ * const defaults = OAuthServicesRegistry.getServiceDefaults('Google');
+ *
+ * // Get validation rules
+ * const required = OAuthServicesRegistry.getValidationRules('Google');
+ */
+export class OAuthServicesRegistry {
+ private static services = oauthServicesConfig.services as Record<string, OAuthServiceConfig>;
+
+ /**
+ * Get service configuration by display name
+ * @param displayName - The user-facing service name (e.g., 'Google', 'LinkedIn')
+ * @returns Service configuration or null if not found
+ */
+ static getServiceConfig(displayName: string): OAuthServiceConfig | null {
+ return this.services[displayName] || null;
+ }
+
+ /**
+ * Get service configuration by internal name
+ * @param internalName - The internal service identifier (e.g., 'google', 'linkedin')
+ * @returns Service configuration or null if not found
+ */
+ static getServiceByInternalName(internalName: string): OAuthServiceConfig | null {
+ return Object.values(this.services).find((s) => s.internalName === internalName) || null;
+ }
+
+ /**
+ * Get all services of a specific type
+ * @param type - OAuth service type
+ * @returns Array of service configurations
+ */
+ static getServicesByType(type: string): OAuthServiceConfig[] {
+ return Object.values(this.services).filter((s) => s.type === type);
+ }
+
+ /**
+ * Get predefined service defaults (URLs, scopes, etc.)
+ * @param displayName - The user-facing service name
+ * @returns Default configuration values
+ */
+ static getServiceDefaults(displayName: string): OAuthServiceDefaults {
+ const service = this.getServiceConfig(displayName);
+ return service?.config || {};
+ }
+
+ /**
+ * Check if service uses OAuth1.0/1.0a
+ * @param serviceName - Service name (display or internal)
+ * @returns True if OAuth1 service
+ */
+ static isOAuth1Service(serviceName: string): boolean {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+ return service?.type === 'oauth1';
+ }
+
+ /**
+ * Check if service uses OAuth2.0
+ * @param serviceName - Service name (display or internal)
+ * @returns True if OAuth2 service
+ */
+ static isOAuth2Service(serviceName: string): boolean {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+ return service?.type === 'oauth2';
+ }
+
+ /**
+ * Check if service uses OAuth2 Client Credentials flow
+ * @param serviceName - Service name (display or internal)
+ * @returns True if Client Credentials service
+ */
+ static isClientCredentialsService(serviceName: string): boolean {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+ return service?.type === 'oauth2_client_credentials';
+ }
+
+ /**
+ * Get callback path for service
+ * @param serviceName - Service name (display or internal)
+ * @returns Callback path for OAuth flow
+ */
+ static getCallbackPath(serviceName: string): string {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+ return service?.callbackPath || '/oauth/oauth2/callback';
+ }
+
+ /**
+ * Get validation rules for service
+ * @param serviceName - Service name (display or internal)
+ * @returns Array of required field names
+ */
+ static getValidationRules(serviceName: string): string[] {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+ return service?.validation.required || [];
+ }
+
+ /**
+ * Map display name to internal name
+ * @param displayName - User-facing service name
+ * @returns Internal service identifier
+ */
+ static mapServiceNameToInternal(displayName: string): string {
+ const service = this.getServiceConfig(displayName);
+ return service?.internalName || displayName.toLowerCase();
+ }
+
+ /**
+ * Map internal name to display name
+ * @param internalName - Internal service identifier
+ * @returns User-facing service name
+ */
+ static mapInternalToServiceName(internalName: string): string {
+ const service = this.getServiceByInternalName(internalName);
+ return service?.displayName || internalName;
+ }
+
+ /**
+ * Get all service display names
+ * @returns Array of all available service names
+ */
+ static getAllServiceNames(): string[] {
+ return Object.keys(this.services);
+ }
+
+ /**
+ * Get services by category
+ * @param category - Service category
+ * @returns Array of service configurations in the category
+ */
+ static getServicesByCategory(category: 'predefined' | 'custom' | 'system'): OAuthServiceConfig[] {
+ return Object.values(this.services).filter((s) => s.category === category);
+ }
+
+ /**
+ * Get OAuth flow type for service (used for routing)
+ * @param serviceName - Service name (display or internal)
+ * @returns OAuth flow type
+ */
+ static getOAuthFlowType(
+ serviceName: string,
+ ): 'oauth' | 'oauth2' | 'oauth2_client_credentials' | 'none' {
+ const service =
+ this.getServiceConfig(serviceName) || this.getServiceByInternalName(serviceName);
+
+ if (!service) return 'oauth2'; // Default fallback
+
+ switch (service.type) {
+ case 'oauth1':
+ return 'oauth';
+ case 'oauth2':
+ return 'oauth2';
+ case 'oauth2_client_credentials':
+ return 'oauth2_client_credentials';
+ case 'none':
+ return 'none';
+ default:
+ return 'oauth2';
+ }
+ }
+
+ /**
+ * Check if service requires specific callback handling
+ * @param serviceName - Service name (display or internal)
+ * @returns True if service needs special callback handling
+ */
+ static requiresSpecialCallbackHandling(serviceName: string): boolean {
+ const internalName = this.mapServiceNameToInternal(serviceName);
+ // Twitter and other OAuth1 services need special handling
+ return ['twitter', 'oauth1'].includes(internalName);
+ }
+
+ /**
+ * Get service list for dropdowns/selects (excluding 'None')
+ * @returns Array of service names suitable for UI dropdowns
+ */
+ static getSelectableServiceNames(): string[] {
+ return Object.keys(this.services).filter((name) => name !== 'None');
+ }
+
+ /**
+ * Validate if a service name is supported
+ * @param serviceName - Service name to validate
+ * @returns True if service is supported
+ */
+ static isValidService(serviceName: string): boolean {
+ return (
+ this.getServiceConfig(serviceName) !== null ||
+ this.getServiceByInternalName(serviceName) !== null
+ );
+ }
+}
diff --git a/packages/app/src/shared/helpers/oauth/oauth-services.json b/packages/app/src/shared/helpers/oauth/oauth-services.json
new file mode 100644
index 00000000..366e4907
--- /dev/null
+++ b/packages/app/src/shared/helpers/oauth/oauth-services.json
@@ -0,0 +1,119 @@
+{
+ "services": {
+ "Google": {
+ "displayName": "Google",
+ "internalName": "google",
+ "type": "oauth2",
+ "category": "predefined",
+ "config": {
+ "authorizationURL": "https://accounts.google.com/o/oauth2/v2/auth",
+ "tokenURL": "https://oauth2.googleapis.com/token",
+ "scope": "https://www.googleapis.com/auth/gmail.readonly"
+ },
+ "callbackPath": "/oauth/google/callback",
+ "validation": {
+ "required": ["clientID", "clientSecret", "authorizationURL", "tokenURL", "scope"]
+ }
+ },
+ "LinkedIn": {
+ "displayName": "LinkedIn",
+ "internalName": "linkedin",
+ "type": "oauth2",
+ "category": "predefined",
+ "config": {
+ "authorizationURL": "https://www.linkedin.com/oauth/v2/authorization",
+ "tokenURL": "https://www.linkedin.com/oauth/v2/accessToken",
+ "scope": "r_liteprofile r_emailaddress"
+ },
+ "callbackPath": "/oauth/linkedin/callback",
+ "validation": {
+ "required": ["clientID", "clientSecret", "authorizationURL", "tokenURL", "scope"]
+ }
+ },
+ "Twitter": {
+ "displayName": "Twitter",
+ "internalName": "twitter",
+ "type": "oauth1",
+ "category": "predefined",
+ "config": {
+ "requestTokenURL": "https://api.twitter.com/oauth/request_token",
+ "accessTokenURL": "https://api.twitter.com/oauth/access_token",
+ "userAuthorizationURL": "https://api.twitter.com/oauth/authorize"
+ },
+ "callbackPath": "/oauth/oauth1/callback",
+ "validation": {
+ "required": [
+ "consumerKey",
+ "consumerSecret",
+ "requestTokenURL",
+ "accessTokenURL",
+ "userAuthorizationURL"
+ ]
+ }
+ },
+ "Custom OAuth2.0": {
+ "displayName": "Custom OAuth2.0",
+ "internalName": "oauth2",
+ "type": "oauth2",
+ "category": "custom",
+ "config": {},
+ "callbackPath": "/oauth/oauth2/callback",
+ "validation": {
+ "required": ["clientID", "clientSecret", "authorizationURL", "tokenURL", "scope"]
+ }
+ },
+ "Custom OAuth1.0": {
+ "displayName": "Custom OAuth1.0",
+ "internalName": "oauth1",
+ "type": "oauth1",
+ "category": "custom",
+ "config": {},
+ "callbackPath": "/oauth/oauth1/callback",
+ "validation": {
+ "required": [
+ "consumerKey",
+ "consumerSecret",
+ "requestTokenURL",
+ "accessTokenURL",
+ "userAuthorizationURL"
+ ]
+ }
+ },
+ "OAuth2 Client Credentials": {
+ "displayName": "OAuth2 Client Credentials",
+ "internalName": "oauth2_client_credentials",
+ "type": "oauth2_client_credentials",
+ "category": "custom",
+ "config": {},
+ "callbackPath": "/oauth/oauth2/callback",
+ "validation": {
+ "required": ["clientID", "clientSecret", "tokenURL"]
+ }
+ },
+ "None": {
+ "displayName": "None",
+ "internalName": "none",
+ "type": "none",
+ "category": "system",
+ "config": {},
+ "callbackPath": "",
+ "validation": {
+ "required": []
+ }
+ }
+ },
+ "categories": {
+ "predefined": {
+ "label": "Popular Services",
+ "description": "Pre-configured OAuth services"
+ },
+ "custom": {
+ "label": "Custom OAuth",
+ "description": "Custom OAuth configurations"
+ },
+ "system": {
+ "label": "System",
+ "description": "System options"
+ }
+ }
+}
diff --git a/packages/app/src/shared/utils/oauth.utils.ts b/packages/app/src/shared/helpers/oauth/oauth.utils.ts
similarity index 71%
rename from packages/app/src/shared/utils/oauth.utils.ts
rename to packages/app/src/shared/helpers/oauth/oauth.utils.ts
index b834e044..e34544ee 100644
--- a/packages/app/src/shared/utils/oauth.utils.ts
+++ b/packages/app/src/shared/helpers/oauth/oauth.utils.ts
@@ -1,4 +1,7 @@
// Shared OAuth helpers used across Builder UI and React Vault
+// Updated to use centralized OAuth services configuration
+
+import { OAuthServicesRegistry } from './oauth-services.helper';
export interface OAuthInfoLike {
authorizationURL?: string;
@@ -8,48 +11,19 @@ export interface OAuthInfoLike {
tokenURL?: string;
}
-// OAuth Service Constants
-export const OAUTH_SERVICES = [
- 'None',
- 'Google',
- 'Twitter',
- 'LinkedIn',
- 'Custom OAuth2.0',
- 'Custom OAuth1.0',
- 'OAuth2 Client Credentials',
-] as const;
-
-export type OAuthServiceType = typeof OAUTH_SERVICES[number];
-
-// Service name mappings
-const SERVICE_TO_INTERNAL_MAP: Record<string, string> = {
- 'Google': 'google',
- 'Twitter': 'twitter',
- 'LinkedIn': 'linkedin',
- 'Custom OAuth2.0': 'oauth2',
- 'Custom OAuth1.0': 'oauth1',
- 'OAuth2 Client Credentials': 'oauth2_client_credentials',
- 'None': 'none',
-};
-
-const INTERNAL_TO_SERVICE_MAP: Record<string, string> = {
- 'google': 'Google',
- 'twitter': 'Twitter',
- 'linkedin': 'LinkedIn',
- 'oauth2': 'Custom OAuth2.0',
- 'oauth1': 'Custom OAuth1.0',
- 'oauth2_client_credentials': 'OAuth2 Client Credentials',
- 'none': 'None',
-};
+// OAuth Service Constants - now derived from centralized configuration
+export const OAUTH_SERVICES = OAuthServicesRegistry.getAllServiceNames() as readonly string[];
+
+export type OAuthServiceType = (typeof OAUTH_SERVICES)[number];
// Maps the user-facing service name to the internal service identifier
export function mapServiceNameToInternal(serviceName: string): string {
- return SERVICE_TO_INTERNAL_MAP[serviceName] || serviceName.toLowerCase();
+ return OAuthServicesRegistry.mapServiceNameToInternal(serviceName);
}
// Maps the internal service identifier back to the user-facing service name
export function mapInternalToServiceName(internalName: string): string {
- return INTERNAL_TO_SERVICE_MAP[internalName] || internalName;
+ return OAuthServicesRegistry.mapInternalToServiceName(internalName);
}
// Gets the backend origin for OAuth callbacks
@@ -67,10 +41,7 @@ export function getBackendOrigin(): string {
}
// Derives the callback URL based on service and OAuth type
-export function deriveCallbackUrl(
- service: string,
- type: 'oauth' | 'oauth2'
-): string | undefined {
+export function deriveCallbackUrl(service: string, type: 'oauth' | 'oauth2'): string | undefined {
if (service === 'none') return undefined;
const baseUrl = getBackendOrigin();
@@ -85,42 +56,25 @@ export function deriveCallbackUrl(
}
// Determines OAuth type from service name
-export function getOAuthTypeFromService(service: string): 'oauth' | 'oauth2' | 'oauth2_client_credentials' | 'none' {
- const internalService = typeof SERVICE_TO_INTERNAL_MAP[service] !== 'undefined'
- ? SERVICE_TO_INTERNAL_MAP[service]
- : service;
-
- if (['oauth1', 'twitter'].includes(internalService)) return 'oauth';
- if (internalService === 'oauth2_client_credentials') return 'oauth2_client_credentials';
- if (['google', 'linkedin', 'oauth2'].includes(internalService)) return 'oauth2';
- if (internalService === 'none') return 'none';
-
- // Default fallback
- return 'oauth2';
+export function getOAuthTypeFromService(
+ service: string,
+): 'oauth' | 'oauth2' | 'oauth2_client_credentials' | 'none' {
+ return OAuthServicesRegistry.getOAuthFlowType(service);
}
// Check if service uses OAuth1
export function isOAuth1Service(service: string): boolean {
- const internalService = typeof SERVICE_TO_INTERNAL_MAP[service] !== 'undefined'
- ? SERVICE_TO_INTERNAL_MAP[service]
- : service;
- return ['oauth1', 'twitter', 'oauth'].includes(internalService);
+ return OAuthServicesRegistry.isOAuth1Service(service);
}
// Check if service uses OAuth2
export function isOAuth2Service(service: string): boolean {
- const internalService = typeof SERVICE_TO_INTERNAL_MAP[service] !== 'undefined'
- ? SERVICE_TO_INTERNAL_MAP[service]
- : service;
- return ['google', 'linkedin', 'oauth2'].includes(internalService);
+ return OAuthServicesRegistry.isOAuth2Service(service);
}
// Check if service uses Client Credentials
export function isClientCredentialsService(service: string): boolean {
- const internalService = typeof SERVICE_TO_INTERNAL_MAP[service] !== 'undefined'
- ? SERVICE_TO_INTERNAL_MAP[service]
- : service;
- return internalService === 'oauth2_client_credentials';
+ return OAuthServicesRegistry.isClientCredentialsService(service);
}
// Attempts to extract a provider/service name from a URL's hostname
@@ -239,5 +193,3 @@ export function mapStatusCodeToMessage(statusCode: number): string {
return 'An unexpected error occurred. Please try again.';
}
}
-
-