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.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
add new implementation for oauth1/oauth2 (#63)
samme-abdula5b5d710063f
diff --git a/packages/app/src/backend/middlewares/dynamicStrategy.mw.ts b/packages/app/src/backend/middlewares/oauthStrategy.mw.tssimilarity index 80%rename from packages/app/src/backend/middlewares/dynamicStrategy.mw.tsrename to packages/app/src/backend/middlewares/oauthStrategy.mw.tsindex 76cc512e..5b8a5017 100644--- a/packages/app/src/backend/middlewares/dynamicStrategy.mw.ts+++ b/packages/app/src/backend/middlewares/oauthStrategy.mw.ts@@ -2,7 +2,7 @@ import passport from 'passport';import { strategyConfig } from '../routes/oauth/helper/strategyConfig';import { replaceTemplateVariablesOptimized } from '../routes/oauth/helper/oauthHelper';-export const dynamicStrategyInitialization = async (req, res, next) => {+export const oauthStrategyInitialization = async (req, res, next) => {const { service, scope } = req.body;//console.log(service,callbackURL)if (!service) {@@ -43,6 +43,19 @@ export const dynamicStrategyInitialization = async (req, res, next) => {}});+ // 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';+ config['callbackURL'] = `${origin}/oauth/${provider}/callback`;+ } catch (e) {+ // leave as undefined if cannot derive+ }+ }+// Setup the callback function for the strategylet strategyCallback = null;if (isOAuth2) {diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.tsindex c8816c31..d8f4c61c 100644--- a/packages/app/src/backend/routes/api/page/vault.ts+++ b/packages/app/src/backend/routes/api/page/vault.ts@@ -23,6 +23,83 @@ import { getVaultKeys, setVaultKey } from '../../router.utils';const router = express.Router();const vault = new Vault();+const OAUTH_SETTING_KEY = 'oauth';++// ------------------------------+// Internal helpers (pure, no side-effects)+// ------------------------------++/**+ * Flattens legacy auth_settings.oauth_info into auth_settings (new structure),+ * removes disallowed fields, and guarantees the presence of a name key.+ */+function normalizeAuthSettingsObject(authSettings: any): any {+ if (!authSettings || typeof authSettings !== 'object') return authSettings;++ // Remove disallowed fields+ if (authSettings.team) delete authSettings.team;++ // Flatten oauth_info if present (legacy)+ if (authSettings.oauth_info && typeof authSettings.oauth_info === 'object') {+ const legacyInfo = authSettings.oauth_info;+ const keysToFlatten = [+ 'oauth_keys_prefix',+ 'service',+ 'platform',+ 'scope',+ 'authorizationURL',+ 'tokenURL',+ 'clientID',+ 'clientSecret',+ 'requestTokenURL',+ 'accessTokenURL',+ 'userAuthorizationURL',+ 'consumerKey',+ 'consumerSecret',+ ];+ for (const k of keysToFlatten) {+ // Always use value from oauth_info if it exists (overwrite existing)+ if (legacyInfo[k] !== undefined) {+ authSettings[k] = legacyInfo[k];+ }+ }+ delete authSettings.oauth_info;+ }++ // Ensure a name key exists to classify as named connection (even if empty)+ if (typeof authSettings.name === 'undefined') authSettings.name = '';++ return authSettings;+}++/**+ * Merges new settings into existing settings with legacy compatibility.+ * - Existing auth_settings (if present) are the base; otherwise old flat entry is used (sans tokens)+ * - Deep-merges oauth_info (legacy), then flattens and sanitizes to new shape+ */+function mergeAuthSettings(existingEntry: any, incomingNewSettings: any): any {+ // Determine existing settings base+ let existingAuthSettings = {} as any;+ if (existingEntry?.auth_settings) {+ existingAuthSettings = existingEntry.auth_settings;+ } else if (existingEntry && Object.keys(existingEntry).length > 0 && !existingEntry.auth_data) {+ // Old structure: remove likely token fields+ const { primary: _p, secondary: _s, expires_in: _e, ...oldSettings } = existingEntry;+ existingAuthSettings = oldSettings;+ }++ // Merge incoming+ let merged = { ...existingAuthSettings, ...(incomingNewSettings || {}) } as any;++ // Deep-merge oauth_info if present+ if (existingAuthSettings?.oauth_info && incomingNewSettings?.oauth_info) {+ merged.oauth_info = { ...existingAuthSettings.oauth_info, ...incomingNewSettings.oauth_info };+ }++ // Normalize to new shape (flatten & sanitize)+ merged = normalizeAuthSettingsObject(merged);+ return merged;+}/*some endpoints are duplicated in /page/builder.ts, the concept is we require it to handle page specific ACLs@@ -120,6 +197,213 @@ router.delete('/keys/:keyId', includeTeamDetails, async (req, res) => {res.send({ success: true, data: { keyId } });});+/**+ * Sanitizes OAuth connections by replacing sensitive fields with placeholders.+ * Replaces tokens and expiration info with [REDACTED] to prevent exposure.+ */+function sanitizeOAuthConnections(connections: any): any {+ if (!connections || typeof connections !== 'object') return connections;++ const sanitized = {};++ for (const [key, value] of Object.entries(connections)) {+ if (!value || typeof value !== 'object') {+ sanitized[key] = value;+ continue;+ }++ // Deep clone the connection object+ const sanitizedConnection = JSON.parse(JSON.stringify(value));++ // Helper to sanitize sensitive fields+ const sanitizeTokenFields = (obj: any, location: string = '') => {+ if (!obj || typeof obj !== 'object') return;++ // List of sensitive field names to sanitize+ const sensitiveFields = ['primary', 'secondary', 'expires_in', 'refresh_token',+ 'access_token', 'accessToken', 'refreshToken', 'token',+ 'tokenSecret', 'accessTokenSecret'];++ for (const field of sensitiveFields) {+ if (obj[field] && typeof obj[field] === 'string' && obj[field] !== '[REDACTED]') {+ obj[field] = '[REDACTED]';+ }+ }++ // Also check for any field that looks like a token (JWT pattern or long string)+ // Exclude fields that are meant to be visible like clientID, clientSecret, consumerKey, etc.+ const excludedFields = ['clientID', 'clientSecret', 'consumerKey', 'consumerSecret',+ 'oauth_keys_prefix', 'name', 'platform', 'service', 'type',+ 'scope', 'authorizationURL', 'tokenURL', 'requestTokenURL',+ 'accessTokenURL', 'userAuthorizationURL'];++ for (const [fieldName, fieldValue] of Object.entries(obj)) {+ if (typeof fieldValue === 'string' &&+ fieldValue.length > 40 &&+ !excludedFields.includes(fieldName) &&+ fieldValue !== '[REDACTED]') {+ // This might be a token - check for JWT pattern or OAuth token pattern+ const looksLikeToken = fieldValue.includes('.') || // JWT (has dots)+ fieldValue.match(/^[A-Za-z0-9_-]{40,}$/); // OAuth token pattern+ if (looksLikeToken) {+ obj[fieldName] = '[REDACTED]';+ }+ }+ }+ };++ // Sanitize auth_data (new structure)+ if (sanitizedConnection.auth_data && typeof sanitizedConnection.auth_data === 'object') {+ sanitizeTokenFields(sanitizedConnection.auth_data, 'auth_data');+ }++ // Sanitize auth_settings (might exist in legacy or contain misplaced tokens)+ if (sanitizedConnection.auth_settings && typeof sanitizedConnection.auth_settings === 'object') {+ sanitizeTokenFields(sanitizedConnection.auth_settings, 'auth_settings');+ }++ // Sanitize root level (legacy structure)+ sanitizeTokenFields(sanitizedConnection, 'root');++ sanitized[key] = sanitizedConnection;+ }++ return sanitized;+}++router.get('/oauth-connections', includeTeamDetails, async (req, res) => {+ try {+ const settings = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);+ if (settings === null) {+ console.error('Failed to get OAuth settings due to an internal error.');+ return res.status(500).json({ success: false, error: 'Failed to retrieve OAuth connections.' });+ }++ // Parse any stringified entries before sanitization+ const parsedSettings = {};+ if (settings && typeof settings === 'object') {+ for (const [key, value] of Object.entries(settings)) {+ if (typeof value === 'string') {+ try {+ parsedSettings[key] = JSON.parse(value);+ } catch (e) {+ // If parsing fails, keep as is+ parsedSettings[key] = value;+ }+ } else {+ parsedSettings[key] = value;+ // Log warning if tokens are exposed (for security monitoring)+ if (value && typeof value === 'object') {+ const hasExposedTokens =+ (value.auth_data?.primary && value.auth_data.primary !== '[REDACTED]') ||+ (value.primary && value.primary !== '[REDACTED]');+ if (hasExposedTokens) {+ console.warn(`[OAuth Security] Connection ${key} has unsanitized tokens - will be sanitized before sending to frontend`);+ }+ }+ }+ }+ }++ // Sanitize the settings before sending to frontend+ const sanitizedSettings = sanitizeOAuthConnections(parsedSettings);+ res.json(sanitizedSettings);+ } catch (error) {+ console.error('Error fetching OAuth connections:', error);+ res.status(500).json({ success: false, error: 'An unexpected error occurred while fetching OAuth connections.' });+ }+});++router.put('/oauth-connections', includeTeamDetails, async (req, res) => {+ const { entryId, data: newSettings } = req.body;++ // Validate entryId format+ if (!entryId || typeof entryId !== 'string' || !entryId.startsWith('OAUTH_') || !entryId.endsWith('_TOKENS')) {+ return res.status(400).json({ success: false, error: 'Invalid or missing entryId.' });+ }+ // Validate incoming settings data (basic check)+ if (!newSettings || typeof newSettings !== 'object' || Array.isArray(newSettings)) {+ return res.status(400).json({ success: false, error: 'Invalid or missing connection settings data.' });+ }++ try {+ // 1. Fetch all existing OAuth settings for the team+ const existingSettingsMap = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);+ if (existingSettingsMap === null) {+ // Handle case where fetching settings failed (getTeamSettingsObj handles internal errors)+ return res.status(500).json({ success: false, error: 'Failed to retrieve existing OAuth settings.' });+ }++ // 2. Get the specific entry being updated, or default to an empty object+ const existingEntry = existingSettingsMap[entryId] || {};+ // 3. Preserve existing auth_data (if it exists) OR migrate from old structure+ let preservedAuthData = existingEntry.auth_data || {}; // Keep existing tokens++ // If auth_data is empty but tokens exist at root level (old structure), migrate them+ if ((!preservedAuthData.primary && !preservedAuthData.secondary) &&+ (existingEntry.primary || existingEntry.secondary)) {+ // console.log('[OAuth Edit] Migrating tokens from old structure to new auth_data');+ preservedAuthData = {+ primary: existingEntry.primary || '',+ secondary: existingEntry.secondary || '',+ expires_in: existingEntry.expires_in || ''+ };+ }++ // 4-5. Merge and normalize the settings using helper+ const mergedAuthSettings = mergeAuthSettings(existingEntry, newSettings);++ // 6. Construct the final data object with the new structure+ const finalDataToSave = {+ auth_data: preservedAuthData, // Preserved tokens+ auth_settings: mergedAuthSettings, // Merged configuration+ };++ // 7. Save the updated entry back using saveTeamSettingsObj+ const result = await saveTeamSettingsObj({+ req,+ settingKey: OAUTH_SETTING_KEY,+ entryId: entryId,+ data: finalDataToSave,+ });++ // 8. Handle save result+ if (!result.success) {+ console.error(`[PUT /oauth-connections] Failed to save settings for ${entryId}:`, result.error);+ return res.status(500).json({ success: false, error: result.error || 'Failed to save OAuth connection.' });+ }++ // Respond with success and potentially the saved data (or just success status)+ // Returning the saved data might be useful for the client+ res.json({ success: true, data: finalDataToSave }); // Respond with the data that was saved++ } catch (error) {+ console.error(`[PUT /oauth-connections] Error processing request for ${entryId}:`, error);+ res.status(500).json({ success: false, error: 'An unexpected error occurred while saving the OAuth connection.' });+ }+});++router.delete('/oauth-connections/:connectionId', includeTeamDetails, async (req, res) => {+ const { connectionId } = req.params;++ if (!connectionId || typeof connectionId !== 'string' || !connectionId.startsWith('OAUTH_') || !connectionId.endsWith('_TOKENS')) {+ return res.status(400).json({ success: false, error: 'Invalid or missing connectionId parameter.' });+ }++ try {+ const result = await deleteTeamSettingsObj(req, OAUTH_SETTING_KEY, connectionId);++ if (!result.success) {+ return res.status(500).json({ success: false, error: result.error || 'Failed to delete OAuth connection.' });+ }++ res.status(200).json({ success: true });+ } catch (error) {+ console.error(`Error deleting OAuth connection ${connectionId}:`, error);+ res.status(500).json({ success: false, error: 'An unexpected error occurred while deleting the OAuth connection.' });+ }+});+async function getRecommendedModels(req) {let recommendedModels = (await getTeamSettingsObj(req, SMYTH_LLM_PROVIDERS_SETTINGS_KEY)) || {};diff --git a/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts b/packages/app/src/backend/routes/oauth/helper/oauthHelper.tsindex 3f406dad..08c20039 100644--- a/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts+++ b/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts@@ -1,5 +1,4 @@import { getTeamSettingsObj } from '../../../services/team-data.service';-import { getVaultKeys } from '../../router.utils';export const isKeyTemplateVariable = (str: string): boolean => {if (!str) return false;@@ -36,8 +35,7 @@ export const replaceTemplateVariablesOptimized = async (req) => {const reqBody = req.body;// Fetch all team settings- // const allKeys = await getTeamSettingsObj(req, 'vault'); // ! Newly added keys are not accessible using this approach.- const allKeys = await getVaultKeys(req);+ const allKeys = await getTeamSettingsObj(req, 'vault');// Fetch template variables and their corresponding valuesconst templateValues = fetchTemplateValues(reqBody, allKeys, keysToCheck, req._team?.id);diff --git a/packages/app/src/backend/routes/oauth/router.ts b/packages/app/src/backend/routes/oauth/router.tsindex fb23385e..e8cd6aac 100644--- a/packages/app/src/backend/routes/oauth/router.ts+++ b/packages/app/src/backend/routes/oauth/router.ts@@ -1,13 +1,13 @@+import { mapStatusCodeToMessage } from '@src/shared/utils/oauth.utils';+import axios from 'axios';+import crypto from 'crypto';import express from 'express';import passport from 'passport';-import { dynamicStrategyInitialization } from '../../middlewares/dynamicStrategy.mw';import { includeTeamDetails } from '../../middlewares/auth.mw';+import { oauthStrategyInitialization } from '../../middlewares/oauthStrategy.mw';import { getTeamSettingsObj, saveTeamSettingsObj } from '../../services/team-data.service';-const router = express.Router();-import config from '../../../backend/config';import { replaceTemplateVariablesOptimized } from './helper/oauthHelper';-import crypto from 'crypto';-import axios from 'axios';+const router = express.Router();// Websites that don't provide expires_in But estimated times in docs.const PROVIDER_EXPIRATION_TIMES = {@@ -19,6 +19,67 @@ const PROVIDER_EXPIRATION_TIMES = {// 'api.example.com': { expiresInSeconds: X, bufferInSeconds: Y }};+/**+ * Returns the provider configuration object to compare against request body.+ * Supports both legacy (settings.oauth_info) and new flat settings structures.+ */+function getConfigForCompare(settings: any) {+ return settings?.oauth_info && typeof settings.oauth_info === 'object'+ ? settings.oauth_info+ : settings;+}++/**+ * Returns true if a valid primary token exists either in auth_data (new) or+ * mis-saved on settings (legacy/top-level).+ */+function hasPrimaryToken(authData: any, settings: any): boolean {+ if (authData && typeof authData.primary === 'string' && authData.primary !== '') return true;+ if (settings && typeof settings.primary === 'string' && settings.primary !== '') return true;+ return false;+}++/**+ * Flattens legacy settings.oauth_info into auth_settings (new shape), removes disallowed keys.+ */+function normalizeAuthSettings(mergedSettings: any): any {+ if (!mergedSettings || typeof mergedSettings !== 'object') return mergedSettings;++ // Do not persist disallowed fields+ if (mergedSettings.team) delete mergedSettings.team;++ // Flatten oauth_info if present+ if (mergedSettings.oauth_info && typeof mergedSettings.oauth_info === 'object') {+ const legacyInfo = mergedSettings.oauth_info;+ const keysToFlatten = [+ 'oauth_keys_prefix',+ 'service',+ 'platform',+ 'scope',+ 'authorizationURL',+ 'tokenURL',+ 'clientID',+ 'clientSecret',+ 'requestTokenURL',+ 'accessTokenURL',+ 'userAuthorizationURL',+ 'consumerKey',+ 'consumerSecret',+ ];+ for (const k of keysToFlatten) {+ if (mergedSettings[k] === undefined && legacyInfo[k] !== undefined) {+ mergedSettings[k] = legacyInfo[k];+ }+ }+ delete mergedSettings.oauth_info;+ }++ // Ensure a name key exists to classify as named connection (even if empty)+ if (typeof mergedSettings.name === 'undefined') mergedSettings.name = '';++ return mergedSettings;+}+router.post('/checkAuth', includeTeamDetails, async (req, res) => {try {const existing = await getTeamSettingsObj(req, 'oauth');@@ -37,7 +98,18 @@ router.post('/checkAuth', includeTeamDetails, async (req, res) => {}});-router.post('/init', includeTeamDetails, dynamicStrategyInitialization, 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);+ }+ }+try {const {service,@@ -47,11 +119,19 @@ router.post('/init', includeTeamDetails, dynamicStrategyInitialization, async (rauthorizationURL,tokenURL,oauth2CallbackURL,+ // OAuth1 parameters+ consumerKey,+ consumerSecret,+ requestTokenURL,+ accessTokenURL,+ userAuthorizationURL,+ oauth1CallbackURL,} = req.body;let authUrl = `/oauth/${service}`;if (['google', 'linkedin', 'oauth2'].includes(service)) {+ // OAuth2 flowconst oauthParams: any = {scopes: encodeURIComponent(scope),clientID: encodeURIComponent(clientID),@@ -67,8 +147,29 @@ router.post('/init', includeTeamDetails, dynamicStrategyInitialization, async (rObject.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),+ };++ if (requestTokenURL) oauthParams.requestTokenURL = encodeURIComponent(requestTokenURL);+ if (accessTokenURL) oauthParams.accessTokenURL = encodeURIComponent(accessTokenURL);+ if (userAuthorizationURL) oauthParams.userAuthorizationURL = encodeURIComponent(userAuthorizationURL);+ authUrl +=+ '?' ++ Object.entries(oauthParams)+ .map(([key, value]) => `${key}=${value}`)+ .join('&');+ } else {+ // Unsupported service+ return res.status(400).json({ error: 'Invalid or unsupported service.' });+ }+ // console.log({ authUrl })res.json({ authUrl });} catch (error) {console.error('Error in /init route:', error);@@ -145,6 +246,53 @@ router.get('/:provider', async (req, res, next) => {}});+/**+ * Extracts the origin from the OAuth callback URL in the session.+ * Falls back to an empty string if not available or invalid.+ */+function getCallbackOrigin(req: express.Request): string {+ // For OAuth flows initiated from the React app at localhost:4002,+ // we need to send the message back to the frontend, not the backend callback URL++ // Check if we have a stored frontend origin in the session+ const frontendOrigin = req.session?.frontendOrigin;+ if (frontendOrigin) {+ return frontendOrigin;+ }++ // Check referer header to determine where the request came from+ const referer = req.headers.referer || req.headers.referrer;+ if (referer && typeof referer === 'string') {+ try {+ const refererOrigin = new URL(referer).origin;+ return refererOrigin;+ } catch (error) {+ console.error('Invalid referer URL:', referer);+ }+ }++ // 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;++ if (callbackUrl && callbackUrl.includes('localhost:4000')) {+ return 'http://localhost:4002';+ }++ // Fallback to extracting from callback URL (for production)+ if (typeof callbackUrl === 'string') {+ try {+ const origin = new URL(callbackUrl).origin;+ return origin;+ } catch (error) {+ console.error('Invalid callback URL:', callbackUrl);+ return '';+ }+ }++ return '';+}+router.get('/:provider/callback', async (req, res, next) => {const { state, code } = req.query;@@ -163,7 +311,7 @@ router.get('/:provider/callback', async (req, res, next) => {window.opener.postMessage({type: 'error',data: { message: 'Invalid state parameter. Possible CSRF attack.' }- }, '${config.env.UI_SERVER}');+ }, '${getCallbackOrigin(req)}');window.close();</script>`);}@@ -203,12 +351,13 @@ router.get('/:provider/callback', async (req, res, next) => {handleSuccessfulAuthentication(req.session.strategyType, res);} catch (error) {console.error('Error exchanging code for tokens:', error);- return res.status(500).send(`+ const origin = getCallbackOrigin(req);+ res.send(`<script>window.opener.postMessage({type: 'error',data: { message: 'Failed to exchange authorization code for tokens.' }- }, '${config.env.UI_SERVER}');+ }, '${origin}');window.close();</script>`);}@@ -253,12 +402,13 @@ router.get('/:provider/callback', async (req, res, next) => {} catch (error) {console.error('Error in callback route:', error);const errorMessage = `${error.message || 'Unknown error'}.`;+ const origin = getCallbackOrigin(req);const errorScript = `<script>window.opener.postMessage({type: 'error',data: { message: '${errorMessage.replace(/'/g, "\\'")}' }- }, '${config.env.UI_SERVER}');+ }, '${origin}');window.close();</script>`;res.send(errorScript);@@ -333,17 +483,60 @@ async function handleTokenStorage(session, oauthUser, req) {}}-async function handleOAuthOperation(settingKey, entryId, data, req) {+async function handleOAuthOperation(settingKey: string, entryId: string, newDataFromAuthFlow: any, req: express.Request) {try {- const existing = await getTeamSettingsObj(req, settingKey);- console.log(- existing && existing[entryId]- ? 'overwriting existing oauth values'- : 'creating new oauth values',- );- await saveTeamSettingsObj({ req, settingKey, entryId, data });+ const existingSettings = await getTeamSettingsObj(req, settingKey);+ const existingEntryData = existingSettings?.[entryId] || {};++ // 1. Separate new token data from new settings data+ const { primary, secondary, expires_in, ...newSettingsFromAuthFlowRaw } = newDataFromAuthFlow;+ // Remove fields that must not be persisted inside auth_settings (e.g., team)+ const { team: _omitTeam, ...newSettingsFromAuthFlow } = newSettingsFromAuthFlowRaw;+ const newAuthData = { primary, secondary, expires_in };++ // 2. Determine the base settings (existing or new)+ // If existing entry has auth_settings, use that as base, otherwise use the whole existing entry (old structure) or an empty object.+ let baseSettings = {};+ if (existingEntryData.auth_settings) {+ baseSettings = existingEntryData.auth_settings;+ } else if (Object.keys(existingEntryData).length > 0 && !existingEntryData.auth_data) {+ // Handle old structure: extract settings from top level, excluding potential old token fields+ // eslint-disable-next-line @typescript-eslint/no-unused-vars+ const { primary: _p, secondary: _s, expires_in: _e, ...oldSettings } = existingEntryData;+ baseSettings = oldSettings;+ }++ // 3. Merge new settings from auth flow into base settings and normalize+ let mergedSettings: any = {+ ...(baseSettings as any),+ ...newSettingsFromAuthFlow,+ };++ // 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 };+ }++ // 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;+ // Ensure name key exists to classify as named (even if empty)+ if (typeof mergedSettings.name === 'undefined') mergedSettings.name = '';+++ // Normalize+ mergedSettings = normalizeAuthSettings(mergedSettings);++ // 4. Construct the final data object with the new structure+ const finalDataToSave = {+ auth_data: newAuthData, // Always use the fresh tokens+ auth_settings: mergedSettings, // Use the merged settings+ };++ // 5. Save the final data object+ await saveTeamSettingsObj({ req, settingKey, entryId, data: finalDataToSave });} catch (error) {- console.error(`Error handling OAuth operation for ${entryId}:`, error);+ console.error(`[handleOAuthOperation] Error handling OAuth operation for ${entryId}:`, error);throw error; // Re-throw the error for higher-level handling}}@@ -352,13 +545,33 @@ function handleSuccessfulAuthentication(strategyType, res) {try {const messageType = strategyType === 'oauth' ? 'oauth' : 'oauth2';const messageData = { message: 'Authentication successful' };+ const origin = getCallbackOrigin(res.req);+ // If no origin found, try to use a wildcard or the opener's origin+ const targetOrigin = origin || '*';res.send(`<script>- window.opener.postMessage({- type: '${messageType}',- data: ${JSON.stringify(messageData)}- }, '${config.env.UI_SERVER}');- window.close();++ if (window.opener) {+ // Try sending to specific origin first, then fallback to wildcard if needed+ try {+ window.opener.postMessage({+ type: '${messageType}',+ data: ${JSON.stringify(messageData)}+ }, '${targetOrigin}');+ } catch (e) {+ console.error('[OAuth Callback] Failed to send to specific origin, trying wildcard:', e);+ window.opener.postMessage({+ type: '${messageType}',+ data: ${JSON.stringify(messageData)}+ }, '*');+ }+ } else {+ console.error('[OAuth Callback] window.opener is null - cannot send message');+ }++ setTimeout(() => {+ window.close();+ }, 500);</script>`);} catch (error) {console.error('Error in handleSuccessfulAuthentication:', error);@@ -367,86 +580,127 @@ function handleSuccessfulAuthentication(strategyType, res) {}// Modify the existing compareOAuthDetails function to include template variable replacement.-async function compareOAuthDetails(existing, req) {- // Attempt to replace template variables in requestBody before the comparison.+async function compareOAuthDetails(existing: Record<string, any>, req: express.Request) {const updatedRequestBody = await replaceTemplateVariablesOptimized(req);-const { oauth_keys_prefix } = updatedRequestBody;const entryId = `${oauth_keys_prefix}_TOKENS`;- // Proceed with the rest of your compareOAuthDetails function.- const targetObject = existing[entryId];- let current_oauth_object;++ const entryData = existing[entryId];+ let connectionData: any;try {- current_oauth_object =- typeof targetObject === 'string' ? JSON?.parse(targetObject) : targetObject;+ connectionData = typeof entryData === 'string' ? JSON.parse(entryData) : entryData;} catch (error) {console.error('Error parsing target object:', error);return false;}- if (!current_oauth_object || typeof current_oauth_object !== 'object') {+ if (!connectionData || typeof connectionData !== 'object') {return false;}++ // Determine where the settings and auth data reside (new vs old structure)+ const settings = connectionData.auth_settings || connectionData; // Use auth_settings if exists, else assume old structure+ let authData = connectionData.auth_data || connectionData; // Use auth_data if exists, else assume old structure++ // New structure has no oauth_info; prefer oauth_info if present (legacy), else compare with flat settings+ const configToCompare: any = getConfigForCompare(settings);++ // Compare request body against provider configfor (const [key, value] of Object.entries(updatedRequestBody)) {- if (current_oauth_object?.oauth_info?.[key] !== value) {+ if (configToCompare[key] !== value) {return false;}}- if ('primary' in current_oauth_object && current_oauth_object['primary'] === '') {- return false; // The property exists and is an empty string- } else if (current_oauth_object['primary']) {- return true; // The property exists and has a truthy value (not empty, not null, etc.)- }+ // Robust token presence check: support mis-saved tokens under auth_settings+ if (!hasPrimaryToken(authData, settings)) return false;- return true;+ return true; // All checks passed}router.post('/signOut', includeTeamDetails, async (req, res) => {try {- const { invalidateAuthentication, oauth_keys_prefix: entryId } = req.body;+ // Accept either prefix (OAUTH_XXX) or full id (OAUTH_XXX_TOKENS)+ const raw = String(req.body.oauth_keys_prefix || '');+ const entryId = raw.endsWith('_TOKENS') ? raw : `${raw}_TOKENS`;+ const { invalidateAuthentication } = req.body; // invalidateAuthentication flag is still used+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.' });+ }- // Parse existing if it's a string- let existing = settings[entryId];+ // Parse existing data if it's a string+ let existingData = settings[entryId];try {- existing = typeof existing === 'string' ? JSON?.parse(existing) : existing;+ existingData = typeof existingData === 'string' ? JSON.parse(existingData) : existingData;} catch (error) {console.error('Error parsing existing settings:', error);return res.status(500).json({ error: 'Invalid settings format' });}- if (!settings || !existing) {- return res.status(404).json({ error: 'No existing OAuth settings found.' });- }-if (invalidateAuthentication !== true) {return res.status(400).json({ error: 'Invalid request. Missing or invalid "invalidateAuthentication" flag.' });}- // Clear properties if they exist- for (let prop of ['primary', 'secondary']) {- if (prop in existing && existing[prop] === '') {- return res.json({ invalidate: true, message: '' }); // send empty message with true, and stop if the property exists and is an empty string- } else if (prop in existing) {- existing[prop] = ''; // Set the property to an empty string if it exists and is not already empty++ // Prepare the updated data structure+ let updatedData;++ // Check if the existing data uses the new structure+ if (existingData.auth_data && existingData.auth_settings) {+ // New structure: Clear tokens within auth_data+ updatedData = {+ ...existingData,+ auth_data: {+ ...existingData.auth_data,+ primary: '',+ secondary: '',+ // Optionally clear expires_in or leave it? Clearing for consistency.+ expires_in: undefined, // or '' or null depending on desired state+ },+ };+ // Remove undefined expires_in if set that way+ if (updatedData.auth_data.expires_in === undefined) {+ delete updatedData.auth_data.expires_in;+ }++ } else {+ // Old structure: Clear tokens at the top level+ updatedData = {+ ...existingData,+ primary: '',+ secondary: '',+ expires_in: undefined, // or '' or null+ };+ if (updatedData.expires_in === undefined) {+ delete updatedData.expires_in;}}++ // 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;+ if (currentPrimary === '' && currentSecondary === '') {+ return res.json({ invalidate: true, message: 'Already signed out.' });+ }++// Save the updated settingsconst saveResult = await saveTeamSettingsObj({req,settingKey: 'oauth',entryId,- data: existing,+ data: updatedData, // Save the structure with cleared tokens});- // Check the result of saveTeamSettingsObj+if (!saveResult.success) {- // Handle failure according to your application's needs- console.error('Failed to save team settings:', saveResult.error);+ console.error('Failed to save team settings during sign out:', saveResult.error);return res.status(500).json({ error: saveResult.error || 'Failed to process Sign out.' });}+return res.json({ invalidate: true, message: 'Signed out successfully.' });} catch (error) {console.error('Error during sign out:', error);@@ -454,23 +708,7 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {}});-// This function maps HTTP status codes to user-friendly error messages-function mapStatusCodeToMessage(statusCode) {- switch (statusCode) {- case 400:- return 'Bad Request. Please verify your request and try again.';- case 401:- return 'Unauthorized. Please ensure you are logged in and have the necessary permissions.';- case 403:- return 'Forbidden. Access is denied.';- case 404:- return 'Not Found. The requested resource was not found.';- case 500:- return 'Internal Server Error. Something went wrong on our end.';- default:- return 'An unexpected error occurred. Please try again.';- }-}+async function getClientCredentialToken({ clientID, clientSecret, tokenURL }) {try {diff --git a/packages/app/src/builder-ui/components/APICall.class.ts b/packages/app/src/builder-ui/components/APICall.class.tsindex bf3d84e3..e3aadf62 100644--- a/packages/app/src/builder-ui/components/APICall.class.ts+++ b/packages/app/src/builder-ui/components/APICall.class.ts@@ -1,7 +1,26 @@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,+ extractServiceFromConnection,+ getConnectionOauthInfo,+ saveOAuthConnection+} from '@src/shared/helpers/oauth-api.helper';+import {+ OAUTH_SERVICES,+ extractPlatformFromUrl,+ generateOAuthId,+ mapInternalToServiceName,+ mapServiceNameToInternal+} from '@src/shared/utils/oauth.utils';+import { builderStore } from '../../shared/state_stores/builder/store';import { COMP_NAMES } from '../config';+import {+ generateOAuthModalHTML+} from '../helpers/oauth-modal.helper';+import { createBadge } from '../ui/badges'; // *** ADDED: Import createBadge ***import { destroyCodeEditor, toggleMode } from '../ui/dom';+import { closeTwDialog, twEditValuesWithCallback } from '../ui/tw-dialogs';import { delay, getVaultData, handleKvFieldEditBtn, handleKvFieldEditBtnForParams } from '../utils';import { Workspace } from '../workspace/Workspace.class';import { Component } from './Component.class';@@ -16,6 +35,54 @@ export class APICall extends Component {public eventTriggersActually = false;private boundHandleAuthMessage = this.handleAuthMessage.bind(this);private boundHandleFocusAfterAuth = this.handleFocusAfterAuth.bind(this);+ private oauthConnections: any = null;+ private oauthConnectionNames: any = null;+ private authCheckPromises: Map<string, Promise<boolean>> = new Map();+ private updateAuthButtonDebounceTimer: any = null;++ // Wrapper methods to use helper functions+ private extractPlatformFromUrl(url?: string): string {+ return extractPlatformFromUrl(url);+ }++ private extractServiceFromConnection(connection: any): string {+ return extractServiceFromConnection(connection);+ }++ private getConnectionOauthInfo(connection: any, connectionId?: string): any {+ return getConnectionOauthInfo(connection, connectionId);+ }++ private deriveServiceFromOauthInfo(oauthInfo: any): string {+ return deriveServiceFromOauthInfo(oauthInfo);+ }++ protected async prepare() {+ try {+ // console.log('[APICall.prepare] Getting OAuth connections from workspace cache...');++ // Get OAuth connections from workspace cache+ const oauthConnectionsData = await builderStore.getState().getOAuthConnections();+ // console.log('[APICall.prepare] OAuth connections retrieved from cache:', oauthConnectionsData);++ this.oauthConnections = oauthConnectionsData || {};+ const componentSpecificId = `OAUTH_${this.uid}_TOKENS`;++ // Use the centralized buildOAuthSelectOptions method+ const options = this.buildOAuthSelectOptions(this.oauthConnections, componentSpecificId, '[APICall.prepare]');++ // Add 'None' option at the start+ options.unshift({ value: 'None', text: 'None', badge: '' });++ // console.log('[APICall.prepare] Final options for select:', options);+ this.oauthConnectionNames = options;+ } catch (error) {+ console.error('[APICall.prepare] Exception:', error);+ this.oauthConnectionNames = [{ value: 'None', text: 'None', badge: '' }];+ }+ return true;+ }+protected async init() {this.settings = {method: {@@ -60,7 +127,7 @@ export class APICall extends Component {type: 'textarea',label: 'Headers',readonly: true,- help: `Headers pass essential metadata like Content-Type and authentication details. <br />Edit them in the API component settings to match your API’s requirements. <br /><a style="color: #3b82f6;text-decoration: underline;" href="${SMYTHOS_DOCS_URL}/agent-studio/components/advanced/api-call" target="_blank">See headers guide →</a>`,+ help: `Headers pass essential metadata like Content-Type and authentication details. <br />Edit them in the API component settings to match your API's requirements. <br /><a style="color: #3b82f6;text-decoration: underline;" href="${SMYTHOS_DOCS_URL}/agent-studio/components/advanced/api-call" target="_blank">See headers guide →</a>`,tooltipClasses: 'w-64',arrowClasses: '-ml-13',validate: `custom=isValidJson`,@@ -120,62 +187,91 @@ export class APICall extends Component {},],},- oauthService: {+ oauth_con_id: {type: 'select',+ label: 'OAuth Connection',+ section: 'OAuth',+ options: this.oauthConnectionNames,+ value: this.data.oauth_con_id || 'None',+ events: {+ change: (event) => this.handleOAuthConnectionChange(event.target.value),+ },+ actions: [+ // Always show "Create New" button+ {+ label: 'Add New',+ icon: 'fa-regular fa-lg fa-plus',+ id: 'createOAuthConnection',+ cls: 'mr-2 !mt-[-36px] !pt-[10px]',+ visible: () => true, // Always visible+ events: {+ click: () => {+ this.data.oauth_con_id = 'None';+ this.handleOAuthConnectionAction();+ },+ },+ },+ // Only show "Edit" button if a valid connection is selected+ {+ label: 'Edit',+ icon: 'fa-regular fa-pen-to-square',+ id: 'editOAuthConnection',+ cls: 'mt-[7px] !mr-[24px] !pt-[10px]',+ visible: () => this.data.oauth_con_id && this.data.oauth_con_id !== 'None',+ events: {+ click: () => this.handleOAuthConnectionAction(),+ },+ },+ ],+ },+ oauthService: {+ type: 'hidden',label: 'Authentication Service',section: 'OAuth',sectionHelp:'SmythOS supports OAuth 2.0 with OpenID Connect (OIDC) for secure user authentication and authorization.',sectionTooltipClasses: 'w-64 ml-12',sectionArrowClasses: '-ml-11',- options: [- 'None',- 'Google',- 'Twitter',- 'LinkedIn',- 'Custom OAuth2.0',- 'Custom OAuth1.0',- 'OAuth2 Client Credentials',- ],+ options: [...OAUTH_SERVICES],value: 'None',events: {change: (event) => this.handleServiceChange(event.target.value),},},scope: {- type: 'textarea',+ type: 'hidden',label: 'Scopes *',section: 'OAuth',value: '', // Default empty, can be pre-filled based on service selection},authorizationURL: {- type: 'input',+ type: 'hidden',label: 'Authorization URL (OAuth2.0) *',section: 'OAuth',value: '', // Default empty, can be pre-filled based on service selection},tokenURL: {- type: 'input',+ type: 'hidden',label: 'Token URL (OAuth2.0) *',section: 'OAuth',value: '',},clientID: {- type: 'input',+ type: 'hidden',label: 'Client ID *',section: 'OAuth',value: '',attributes: { 'data-vault': `${COMP_NAMES.apiCall},All` },},clientSecret: {- type: 'input',+ type: 'hidden',label: 'Client Secret *',section: 'OAuth',value: '',attributes: { 'data-vault': `${COMP_NAMES.apiCall},All` },},oauth2CallbackURL: {- type: 'div',+ type: 'hidden',html: `Callback URL (OAuth2.0)<br /><br /><span></span>`,label: 'Callback URL (OAuth2.0)',section: 'OAuth',@@ -184,32 +280,32 @@ export class APICall extends Component {// OAuth1.0 InputsrequestTokenURL: {- type: 'input',+ type: 'hidden',label: 'Request Token URL (OAuth1.0) *',section: 'OAuth',value: '',},accessTokenURL: {- type: 'input',+ type: 'hidden',label: 'Access Token URL (OAuth1.0) *',section: 'OAuth',value: '',},userAuthorizationURL: {- type: 'input',+ type: 'hidden',label: 'User Authorization URL (OAuth1.0) *',section: 'OAuth',value: '',},consumerKey: {- type: 'input',+ type: 'hidden',label: 'Consumer Key (OAuth1.0) *',section: 'OAuth',value: '',attributes: { 'data-vault': `${COMP_NAMES.apiCall},All` },},consumerSecret: {- type: 'input',+ type: 'hidden',label: 'Consumer Secret (OAuth1.0) *',section: 'OAuth',value: '',@@ -217,7 +313,7 @@ export class APICall extends Component {},oauth1CallbackURL: {// Renamed to avoid conflict with OAuth2.0 callback URL- type: 'div',+ type: 'hidden',html: 'Callback URL (OAuth1.0)<br /><br /><span></span>',label: 'Callback URL (OAuth1.0)',section: 'OAuth',@@ -250,6 +346,13 @@ export class APICall extends Component {},};+ // Handle backward compatibility for existing components+ if (!this.data.oauth_con_id && this.data.oauthService && this.data.oauthService !== 'None') {+ // If there's an existing OAuth service but no oauth_con_id,+ // set oauth_con_id to the component's default OAuth connection ID+ this.data.oauth_con_id = `OAUTH_${this.uid}_TOKENS`;+ }+for (let item of API_CALL_DATA_ENTRIES) {if (typeof this.data[item] === 'undefined') this.data[item] = this.settings[item]?.value;}@@ -439,126 +542,170 @@ export class APICall extends Component {* @returns {string} The internal service name corresponding to the selected service.*/private mapSelectedService(service) {- const serviceMap = {- 'OAuth2 Client Credentials': 'oauth2_client_credentials',- 'Custom OAuth1.0': 'oauth1',- 'Custom OAuth2.0': 'oauth2',- Google: 'google',- LinkedIn: 'linkedin',- Twitter: 'twitter',- };- return serviceMap[service] || service.toLowerCase();+ return mapServiceNameToInternal(service);}/**- * Collects current OAuth values from the right sidebar, constructs a request payload, and sends it to- * the server for checking or initializing OAuth authentication. Opens the authentication URL if provided.- * @param {Event} event - The event object, not used in this function.+ * Collects the OAuth configuration from the *selected connection*+ * and initiates the authentication flow.+ * @param {Event} event - The click event object.*/private async collectAndConsoleOAuthValues(event) {- const selectedService = this.data.oauthService;- if (selectedService === 'None') {- errorToast('You did not select any Authentication Service');- return console.log('No OAuth service selected.');+ const selectedConnectionId = this.data.oauth_con_id;+ if (selectedConnectionId === 'None' || !selectedConnectionId) {+ errorToast('Please select a valid OAuth Connection first', 'Error', 'alert');+ return;}- // Validate configuration before proceeding- const { isValid, missingFields } = await this.validateOAuthConfiguration();- if (!isValid) {- // Convert camelCase field names to readable format with spaces before capital letters- // Example: "clientId" becomes "client id", but "URL" stays as "url"- const camelCasePattern = /([a-z])([A-Z])/g; // Only matches capital letters preceded by lowercase+ // Ensure connections are loaded (they should be by the time this is clicked)+ if (!this.oauthConnections) {+ errorToast('OAuth connections not loaded. Please wait or refresh.', 'Error', 'alert');+ console.error('OAuth connections not loaded.');+ return;+ }++ // Find the selected connection object using the ID+ const selectedConnection = this.oauthConnections[selectedConnectionId];+ // console.log('[OAuth Auth] Selected connection:', selectedConnection);- const formattedFields = missingFields- .map((field) => field.replace(camelCasePattern, '$1 $2').toLowerCase())- .join(', ');+ const synthesizedOauthInfo = this.getConnectionOauthInfo(selectedConnection, selectedConnectionId);+ // console.log('[OAuth Auth] Synthesized oauth_info:', synthesizedOauthInfo);- errorToast(`Please configure the following fields: ${formattedFields}`);+ if (!selectedConnection || !synthesizedOauthInfo) {+ errorToast('Selected OAuth connection details not found.', 'Error', 'alert');+ console.error(+ 'Selected connection or its oauth_info not found for ID:',+ selectedConnectionId,+ 'Connection:',+ selectedConnection+ );return;}- const { cbUrl, service, key, isOAuth1 } = this.getOAuthCallbackDetails(selectedService);- let fieldsToCollect = [- ...(isOAuth1- ? [- 'requestTokenURL',- 'accessTokenURL',- 'userAuthorizationURL',- 'consumerKey',- 'consumerSecret',- 'oauth1CallbackURL',- ]- : []),- ...(!isOAuth1- ? ['authorizationURL', 'tokenURL', 'clientID', 'clientSecret', 'oauth2CallbackURL']- : []),- 'scope',- ];- if (selectedService === 'OAuth2 Client Credentials') {- // Remove 'authorizationURL', 'oauth2CallbackURL', and 'scope' from fieldsToUse- fieldsToCollect = fieldsToCollect.filter(- (field) => !['authorizationURL', 'oauth2CallbackURL', 'scope'].includes(field),- );+ // 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');+ return;}- let emptyFields = [];- let invalidUrls = [];- let values: any = fieldsToCollect?.reduce((acc, field) => {- // Collect current OAuth values from saved data.- const value = this.data[field];- if (!value) emptyFields?.push(field); // Check for empty fields and collect names of empty fields- if (- ['requestTokenURL', 'accessTokenURL', 'userAuthorizationURL', 'authorizationURL'].includes(- field,- ) &&- value &&- !this.isValidUrl(value)- ) {- invalidUrls.push(field);++ // --- Use synthesized oauth_info from the selected connection (supports old/new structures) ---+ const oauthInfoPayload = synthesizedOauthInfo;+ //console.log(oauthInfoPayload);+ const connectionType = oauthInfoPayload?.service; // 'oauth', 'oauth2', or 'oauth2_client_credentials'+ // 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;+ try {+ const u = new URL(candidate);+ return u.origin;+ } catch {+ return String(candidate).replace(/\/$/, '');}- return { ...acc, [field]: value };- }, {});-- if (emptyFields.length > 0) {- // for empty fields, except scpoe (for oauth1) and callbackurl (oauth1 and oauth1), show error message and return- const isSingleOAuth1Scope =- isOAuth1 && emptyFields.length === 1 && emptyFields[0] === 'scope';- const isSingleCallbackField =- emptyFields.length === 1 &&- (emptyFields.includes('oauth2CallbackURL') || emptyFields.includes('oauth1CallbackURL'));- if (!isSingleOAuth1Scope && !isSingleCallbackField) {- const exclusions = [- 'oauth2CallbackURL',- 'oauth1CallbackURL',- ...(isOAuth1 ? ['scope'] : []),- ];- const formattedFieldNames = emptyFields- .filter((field) => !exclusions.includes(field))- .join(', ');- if (formattedFieldNames) {- // Proceed only if there's something to show- errorToast(`Please fill in the following fields: ${formattedFieldNames}`);- return console.log(`Error: The following fields are empty: ${formattedFieldNames}`);+ };+ const desiredBackendOrigin = getDesiredBackendOrigin();+ const normalizeCallbackOrigin = (cb?: string, providerPath?: string) => {+ if (!providerPath) return cb;+ try {+ if (!cb) return `${desiredBackendOrigin}${providerPath}`;+ const current = new URL(cb);+ const desired = new URL(desiredBackendOrigin);+ if (current.origin !== desired.origin) {+ return `${desired.origin}${current.pathname}${current.search}${current.hash}`;}+ return cb;+ } catch {+ return `${desiredBackendOrigin}${providerPath}`;+ }+ };+ // --- Basic Payload Validation (on the fetched payload) ---+ //console.log(oauthInfoPayload);++ // Get connection type information from both sources+ const serviceType = oauthInfoPayload.service; // 'google', 'oauth1', 'oauth2', etc.++ // Ensure callback URL exists for the current flow (derive when missing)+ try {+ const internalService = (serviceType || connectionType || '').toLowerCase();+ const oauth2Path = `/oauth/${internalService === 'google' || internalService === 'linkedin' ? internalService : 'oauth2'}/callback`;+ const oauth1Path = `/oauth/${internalService === 'twitter' ? 'oauth1' : internalService}/callback`;++ // Ensure correct origin for OAuth2 callbacks+ if (connectionType === 'oauth2' || internalService === 'google' || internalService === 'linkedin') {+ oauthInfoPayload.oauth2CallbackURL = normalizeCallbackOrigin(+ oauthInfoPayload.oauth2CallbackURL,+ oauth2Path,+ );+ }++ // Ensure correct origin for OAuth1 callbacks+ if (connectionType === 'oauth' || internalService === 'oauth1' || internalService === 'twitter') {+ oauthInfoPayload.oauth1CallbackURL = normalizeCallbackOrigin(+ oauthInfoPayload.oauth1CallbackURL,+ oauth1Path,+ );}+ } catch (e) {+ console.warn('Could not normalize callback URL origin', e);}- if (invalidUrls.length > 0) {- // Handle invalid URLs- const formattedInvalidUrls = invalidUrls.join(', ');- errorToast(`The following fields do not contain valid URLs: ${formattedInvalidUrls}`);- return console.log(`Error: The following fields have invalid URLs: ${formattedInvalidUrls}`);+ // Determine if this is a client credentials flow+ const isClientCredentials =+ connectionType === 'oauth2_client_credentials' || serviceType === 'oauth2_client_credentials';++ // Derive human-friendly service for UI checks+ const derivedService = mapInternalToServiceName(serviceType || connectionType || '');++ // --- Basic Payload Validation (on the fetched payload) ---+ let isValid = true;+ let missingFields = [];++ 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') &&+ !isClientCredentials &&+ !oauthInfoPayload.authorizationURL+ ) {+ missingFields.push('Auth URL');+ }+ if ((connectionType === 'oauth2' || derivedService === 'Google' || derivedService === 'LinkedIn') && !isClientCredentials && !oauthInfoPayload.scope) {+ missingFields.push('Scopes');+ }+ } else if (connectionType === 'oauth') {+ // OAuth 1.0 validation remains the same+ if (!oauthInfoPayload.requestTokenURL) missingFields.push('Request Token URL');+ if (!oauthInfoPayload.accessTokenURL) missingFields.push('Access Token URL');+ if (!oauthInfoPayload.userAuthorizationURL) missingFields.push('User Auth URL');+ if (!oauthInfoPayload.consumerKey) missingFields.push('Consumer Key');+ if (!oauthInfoPayload.consumerSecret) missingFields.push('Consumer Secret');+ }+ //console.log(missingFields);+ if (missingFields.length > 0) {+ isValid = false;}- if (selectedService !== 'OAuth2 Client Credentials') {- values[key] = cbUrl;+ if (!isValid) {+ errorToast(+ `Selected connection is missing required fields: ${missingFields.join(', ')}`,+ 'Error',+ 'alert',+ );+ return;}- const url = `${this.workspace.server}/oauth/${- selectedService === 'OAuth2 Client Credentials' ? 'client_credentials' : 'init'- }`;- const authData = { oauth_keys_prefix: `OAUTH_${this.uid}`, service, ...values };+ // --- End Basic Validation ---++ // Determine the correct backend endpoint based on connection type+ const endpoint = isClientCredentials ? 'client_credentials' : 'init';+ const url = `${this.workspace.server}/oauth/${endpoint}`;- this.activateSpinner(event.target);- /* The 'visibilitychange' event listener is set up to handle focus once the authentication tab/window is closed. */+ // The payload *is* the oauth_info from the selected connection+ const authData = { ...oauthInfoPayload }; // Send a copy+ //console.log('payload', authData);+ this.activateSpinner(event.target); // Assumes event.target is the buttondocument.addEventListener('visibilitychange', this.boundHandleFocusAfterAuth);try {@@ -567,27 +714,108 @@ export class APICall extends Component {headers: { 'Content-Type': 'application/json' },body: JSON.stringify(authData),});++ // Check if response is OK before parsing JSON+ if (!response.ok) {+ const errorData = await response.json().catch(() => ({})); // Try to parse error+ throw new Error(+ errorData.message || `Authentication request failed with status ${response.status}`,+ );+ }+const data = await response.json();+if (data.authUrl) {+ // Standard OAuth flow requiring popupwindow.open(data.authUrl, '_blank');window.addEventListener('message', this.boundHandleAuthMessage, false);} else if ('success' in data) {+ // Direct success/failure (e.g., client credentials)+ successToast(data.message, data.success ? '' : 'Error', data.success ? '' : 'alert');if (data.success) {- successToast(data.message);+ // Manually update the local state for the connection to reflect success+ if (this.oauthConnections[selectedConnectionId]) {+ this.oauthConnections[selectedConnectionId].isAuthenticated = true;+ // Store tokens if returned (primarily for client_credentials)+ if (data.primary) {+ // Check if connection has new structure+ if (this.oauthConnections[selectedConnectionId].auth_data) {+ // New structure - store in auth_data+ this.oauthConnections[selectedConnectionId].auth_data.primary = data.primary;+ if (data.secondary) {+ this.oauthConnections[selectedConnectionId].auth_data.secondary = data.secondary;+ }+ if (data.expires_in) {+ this.oauthConnections[selectedConnectionId].auth_data.expires_in = data.expires_in;+ }+ } else {+ // Legacy structure - store at root level+ this.oauthConnections[selectedConnectionId].primary = data.primary;+ if (data.secondary) {+ this.oauthConnections[selectedConnectionId].secondary = data.secondary;+ }+ if (data.expires_in) {+ this.oauthConnections[selectedConnectionId].expires_in = data.expires_in;+ }+ }+ }+ }+ this.updateSidebarForOAuth(); // Update button text etc.+ await this.updateOAuthConnectionOptions(); // Refresh options to replace legacy entry+ this.refreshSettingsSidebar(); // Refresh the sidebar to show updated name+ this.updateOAuthActionButton(); // Update action button state+ // Note: updateAuthenticationButtonState not needed here as the button was already+ // set to "Sign Out" in updateSidebarForOAuth and we know it's authenticated++ // Update component's button state+ this.checkSettings();} else {- errorToast(data.message);+ // Update local state to reflect failure+ if (this.oauthConnections[selectedConnectionId]) {+ this.oauthConnections[selectedConnectionId].isAuthenticated = false;+ // Clear tokens from both structures on failure+ if (this.oauthConnections[selectedConnectionId].auth_data) {+ // New structure+ delete this.oauthConnections[selectedConnectionId].auth_data.primary;+ delete this.oauthConnections[selectedConnectionId].auth_data.secondary;+ delete this.oauthConnections[selectedConnectionId].auth_data.expires_in;+ }+ // Legacy structure+ delete this.oauthConnections[selectedConnectionId].primary;+ delete this.oauthConnections[selectedConnectionId].secondary;+ delete this.oauthConnections[selectedConnectionId].expires_in;+ }+ // Refresh sidebar to reflect failed authentication state+ this.refreshSettingsSidebar();+ // Note: updateAuthenticationButtonState will be called through refreshSettingsSidebar if needed}- if (data.success) this.updateSidebarForOAuth();- await this.updateButtonAndRemoveFocusListener();+ await this.updateButtonAndRemoveFocusListener(); // Restore button state} else {- console.error('Authentication URL was not returned from the server.');- errorToast('Authentication URL was not returned from the server.');- await this.updateButtonAndRemoveFocusListener();+ console.error('Unexpected response from authentication server:', data);+ throw new Error('Unexpected response from authentication server.');}} catch (error) {- errorToast(`Authentication Failed: ${error?.message || error}`);- console.error('Error:', error);- await this.updateButtonAndRemoveFocusListener();+ errorToast(`Authentication Failed: ${error?.message || error}`, 'Error', 'alert');+ console.error('Error during OAuth initiation:', error);+ // Update local state to reflect failure+ if (this.oauthConnections[selectedConnectionId]) {+ this.oauthConnections[selectedConnectionId].isAuthenticated = false;+ // Clear tokens from both structures on failure+ if (this.oauthConnections[selectedConnectionId].auth_data) {+ // New structure+ delete this.oauthConnections[selectedConnectionId].auth_data.primary;+ delete this.oauthConnections[selectedConnectionId].auth_data.secondary;+ delete this.oauthConnections[selectedConnectionId].auth_data.expires_in;+ }+ // Legacy structure+ delete this.oauthConnections[selectedConnectionId].primary;+ delete this.oauthConnections[selectedConnectionId].secondary;+ delete this.oauthConnections[selectedConnectionId].expires_in;+ }+ // Refresh sidebar to reflect failed authentication state+ this.refreshSettingsSidebar();+ // Note: updateAuthenticationButtonState will be called through refreshSettingsSidebar if needed+ await this.updateButtonAndRemoveFocusListener(); // Restore button state}}@@ -607,9 +835,35 @@ export class APICall extends Component {switch (event.data?.type) {case 'oauth2':case 'oauth':- console.log('Authentication was successful');+ // console.log('Authentication was successful');successToast(`${event.data.type} authentication was successful`);++ // Clear auth check cache for the current connection after successful auth+ if (this.data.oauth_con_id) {+ this.authCheckPromises.delete(this.data.oauth_con_id);+ }+this.updateSidebarForOAuth();+ // Refresh options from server to replace any legacy entry with its named/unnamed converted form+ this.updateOAuthConnectionOptions().then(async () => {+ // If the previously selected id was legacy component-specific id, remap to the converted id if necessary+ const currentId = this.data.oauth_con_id;+ 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'));+ if (remapped) {+ this.data.oauth_con_id = remapped;+ }+ }+ this.refreshSettingsSidebar();+ this.updateOAuthActionButton();+ // Update authentication button state after sidebar refresh+ await this.updateAuthenticationButtonState();++ // Update component's button state+ this.checkSettings();+ });window.removeEventListener('message', this.boundHandleAuthMessage);break;@@ -618,6 +872,8 @@ export class APICall extends Component {if (event.data?.data?.message) {errorToast(`Authentication failed. Recheck your configuration. ${event?.data?.data?.message}`,+ 'Error',+ 'alert',);}break;@@ -644,71 +900,142 @@ export class APICall extends Component {}/**- * Checks the current authentication setup by collecting form oauth values, sending them to the server, comparing the saved and current,- * and evaluating the success response. Also includes error handling for the request and response parsing.+ * Checks the current authentication status for the selected connection.+ */+ private async checkAuthentication(): Promise<boolean> {+ const selectedValue = this.data.oauth_con_id;++ // If 'None' or no value is selected, it's not authenticated for this component.+ if (selectedValue === 'None' || !selectedValue) {+ return false;+ }++ // Check if we already have a pending auth check for this connection+ const existingPromise = this.authCheckPromises.get(selectedValue);+ if (existingPromise) {+ // console.log(`[checkAuth] Reusing existing auth check promise for: ${selectedValue}`);+ return existingPromise;+ }++ // console.log(`[checkAuth] Creating new auth check promise for: ${selectedValue}`);+ // Create new auth check promise+ const authCheckPromise = this.performAuthCheck(selectedValue);++ // Store the promise in the cache+ this.authCheckPromises.set(selectedValue, authCheckPromise);++ // Keep the cache for longer to handle rapid successive calls+ // We'll clear it after 1 second to allow all related UI updates to complete+ authCheckPromise.finally(() => {+ setTimeout(() => {+ // Only clear if it's still the same promise (not replaced by a newer one)+ if (this.authCheckPromises.get(selectedValue) === authCheckPromise) {+ this.authCheckPromises.delete(selectedValue);+ }+ }, 1000); // Keep cache for 1 second after completion+ });++ // Also set a timeout to clear stale promises (increase to 5 seconds)+ setTimeout(() => {+ // Only clear if it's still the same promise+ if (this.authCheckPromises.get(selectedValue) === authCheckPromise) {+ this.authCheckPromises.delete(selectedValue);+ }+ }, 5000); // Clear after 5 seconds max++ return authCheckPromise;+ }++ /**+ * Performs the actual authentication check (separated for caching)*/- private async checkAuthentication() {- const currentAuthProvider = this.data.oauthService; // Fetch the current value of the auth provider from data.- if (currentAuthProvider === 'None') {- // Case 1: If the auth provider is 'None', directly return true.- return true;+ private async performAuthCheck(selectedValue: string): Promise<boolean> {+ // Ensure connections are loaded.+ if (!this.oauthConnections) {+ console.warn('Attempted to check auth status, but oauthConnections is not loaded.');+ return false;}- const { cbUrl, key, service, isOAuth1 } = this.getOAuthCallbackDetails(currentAuthProvider);- let fieldsToCollect = [- ...(isOAuth1- ? [- 'requestTokenURL',- 'accessTokenURL',- 'userAuthorizationURL',- 'consumerKey',- 'consumerSecret',- 'oauth1CallbackURL',- ]- : []),- ...(!isOAuth1- ? ['authorizationURL', 'tokenURL', 'clientID', 'clientSecret', 'oauth2CallbackURL']- : []),- 'scope',- ];- if (currentAuthProvider === 'OAuth2 Client Credentials') {- // Remove 'authorizationURL', 'oauth2CallbackURL', and 'scope' from fieldsToUse- fieldsToCollect = fieldsToCollect.filter(- (field) => !['authorizationURL', 'oauth2CallbackURL', 'scope'].includes(field),++ let connectionId: string | null = null;+ let selectedConnection: any = null;++ // Determine the actual connection ID. It could be the ID directly or the name.+ if (selectedValue.startsWith('OAUTH_') && selectedValue.endsWith('_TOKENS')) {+ // Value looks like an ID+ connectionId = selectedValue;+ selectedConnection = this.oauthConnections[connectionId];+ } else {+ // Value might be a name, try to find the corresponding ID+ const foundEntry = Object.entries(this.oauthConnections).find(+ ([id, conn]: [string, any]) => conn?.auth_settings?.name === selectedValue,+ );+ if (foundEntry) {+ connectionId = foundEntry[0];+ selectedConnection = foundEntry[1];+ }+ }++ // If no valid connection was found by ID or name+ if (!connectionId || !selectedConnection) {+ console.warn(+ `Attempted to check auth status, but connection data is missing or invalid for selection: ${selectedValue}`,);+ return false;}- let values = fieldsToCollect.reduce((acc, field) => {- // Collect current OAuth values from the saved data. Reduce the fields to an object with their current values inside data.- const value = this.data[field];- return { ...acc, [field]: value };- }, {});-- currentAuthProvider === 'OAuth2 Client Credentials'- ? (values[`service`] = 'oauth2_client_credentials')- : (values[key] = cbUrl);- const authData = { oauth_keys_prefix: `OAUTH_${this.uid}`, ...values };++ // Get OAuth info from either new or old structure+ const oauthInfo = this.getConnectionOauthInfo(selectedConnection, connectionId);++ // 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')) {+ oauth_keys_prefix = connectionId.replace('_TOKENS', '');+ }++ if (!oauth_keys_prefix) {+ console.warn(`Cannot determine oauth_keys_prefix for connection: ${connectionId}`);+ return false;+ }++ // Call backend checkAuth to get actual authentication status+ const authCheckPayload = {+ oauth_keys_prefix: oauth_keys_prefix,+ };++ // console.log(`[checkAuth] Sending auth check request for ${connectionId}`);+try {const response = await fetch(`${this.workspace.server}/oauth/checkAuth`, {method: 'POST',headers: { 'Content-Type': 'application/json' },- body: JSON.stringify(authData),+ body: JSON.stringify(authCheckPayload),});if (!response.ok) {- throw new Error(`HTTP error! status: ${response.status}`);+ console.error(+ `Auth check failed for ${oauth_keys_prefix}: HTTP status ${response.status}`,+ );+ return false;}- try {- const data = await response.json();- return data.success; // 'data.success' is a boolean indicating the authentication check result.- } catch (e) {- console.error('Failed to parse JSON response:', e); // If there is an error parsing JSON- return false;+ const data = await response.json();++ // Backend response is the source of truth+ const isAuthenticated = Boolean(data.success);++ // Update local cache with backend result+ if (this.oauthConnections[connectionId]) {+ this.oauthConnections[connectionId].isAuthenticated = isAuthenticated;}++ // console.log(`[checkAuth] Connection ${connectionId}: authenticated=${isAuthenticated}`);+ return isAuthenticated;} catch (error) {- console.error('Error during fetching or network issue:', error);- return false; // Return false if there's a network issue or the fetch fails.+ console.error(`Error during auth check for ${oauth_keys_prefix}:`, error);+ return false;}}+private updateConfiguration(selectedValue, sidebar) {if (selectedValue === 'OAuth2 Client Credentials') {return null;@@ -763,9 +1090,17 @@ export class APICall extends Component {protected async run() {this.addEventListener('settingsOpened', async (sidebar, component) => {if (component != this) return; //check if the sidebar is for this component+this.eventTriggersActually = false;this.handleBodyEditButtons(sidebar);await this.addRightSidebarFunction(sidebar);++ // Update the OAuth action button when sidebar opens+ // Note: updateAuthenticationButtonState is already called in addRightSidebarFunction -> setCallbackUrl+ // So we only need to update the action button here+ setTimeout(() => {+ this.updateOAuthActionButton();+ }, 100);});}@@ -848,25 +1183,32 @@ export class APICall extends Component {private async setCallbackUrl(sidebar) {const oauthService = sidebar?.querySelector('div[data-name="OAuth"]');if (oauthService) {- const selectedService = this?.data?.oauthService;- if (selectedService && this.data.oauthService !== 'None') {- if (this.data.oauthService !== 'OAuth2 Client Credentials') {+ const selectedConnectionId = this?.data?.oauth_con_id;+ if (selectedConnectionId && selectedConnectionId !== 'None') {+ // Display callback URL for relevant OAuth types+ const selectedService = this?.data?.oauthService;+ if (selectedService && selectedService !== 'OAuth2 Client Credentials') {const { cbUrl, key } = this.getOAuthCallbackDetails(selectedService);- const callbackURLSpan = sidebar.querySelector(`[data-field-name="${key}"] span`); // Combine the querySelector and innerHTML setting to minimize DOM queries+ const callbackURLSpan = sidebar.querySelector(`[data-field-name="${key}"] span`);if (callbackURLSpan) {callbackURLSpan.innerHTML = cbUrl;}}- const isDataValid = await this.checkAuthentication();- if (isDataValid) {- const oauth_button: any = sidebar?.querySelector(- `[data-field-name="authenticate"] button`,- );- if (oauth_button) oauth_button.innerHTML = 'Sign Out';++ // Update authentication button state (will check backend)+ // This will be debounced and use cached results+ await this.updateAuthenticationButtonState();+ } else {+ // No OAuth connection selected, show default state (Authenticate)+ const oauth_button: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);+ if (oauth_button) {+ oauth_button.innerHTML = 'Authenticate';+ oauth_button.disabled = false;}}} else {- setTimeout(this.setCallbackUrl, 20);+ // If sidebar element is not found, retry after a short delay+ setTimeout(() => this.setCallbackUrl(sidebar), 20);}}@@ -953,7 +1295,7 @@ export class APICall extends Component {isValid: boolean;missingFields: string[];}> {- const selectedService = this.data.oauthService;+ const selectedService = this.data.oauth_con_id;if (selectedService === 'None') {return { isValid: true, missingFields: [] };}@@ -1008,24 +1350,23 @@ export class APICall extends Component {const authCheck = await this.checkAuthentication();await super.checkSettings();- // Only show the builder button if both authentication check fails AND all fields are properly configured- const { isValid } = await this.validateOAuthConfiguration();- const existingButton = this.domElement?.querySelector('button.oauthButton');-- // We only show the authenticate button if:- // 1. Not authenticated (authCheck is false)- // 2. All required fields are configured (isValid is true)- // 3. A service is selected (this.data.oauthService !== 'None')- if (!authCheck && isValid && this.data.oauthService !== 'None' && !existingButton) {- this.addComponentButton(- `<div class="fa-solid fa-user-shield"></div><p class="">Authenticate</p>`,- 'warning',- {- class: 'oauthButton',- },- this.collectAndConsoleOAuthValues.bind(this),- );+ // Replace temporary status with the final state+ this.clearComponentMessages();++ if (this.data.oauth_con_id && this.data.oauth_con_id !== 'None') {+ if (!authCheck) {+ this.addComponentButton(+ `<div class="fa-solid fa-user-shield"></div><p class="">Authenticate</p>`,+ 'warning',+ { class: 'oauthButton' },+ this.collectAndConsoleOAuthValues.bind(this),+ );+ }}++ // Note: updateAuthenticationButtonState is not needed here since we already called checkAuthentication+ // which uses the same cached promise that updateAuthenticationButtonState would use+ // The sidebar button will be updated through other paths if needed}// remove tokens to invalidate authentication@@ -1034,10 +1375,13 @@ export class APICall extends Component {const sidebar = this.getSettingsSidebar();if (!sidebar) return '';const oauth_button: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);++ // Accept both id and prefix; backend normalizesconst authData = {- oauth_keys_prefix: `OAUTH_${this.uid}_TOKENS`,+ oauth_keys_prefix: this.data.oauth_con_id,invalidateAuthentication: true,};+try {const response = await fetch(`${this.workspace.server}/oauth/signOut`, {method: 'POST',@@ -1050,34 +1394,69 @@ export class APICall extends Component {}const data = await response.json();- if (oauth_button) {- button.disabled = false;- if (data.invalidate) {- // Check if the sign out was successful. 'data.invalidate' indicates successful sign-out- oauth_button.innerHTML = 'Authenticate'; // Update the button's text to 'Authenticate' after signing out- const body = sidebar?.querySelector('div[data-field-name="body"]');- if (body) {- const messageId = 'oauthMessageSpan';- let existingMessageSpan = sidebar?.querySelector(`#${messageId}`);- if (existingMessageSpan) existingMessageSpan.remove();- }- if (data.message && data.message !== '') successToast(`${data.message}`);- } else {- oauth_button.innerHTML = 'Sign Out'; // Update the button's text to 'Authenticate' after signing out- errorToast(`${data.error}`);++ // IMPORTANT: Update local state immediately after successful sign out+ if (data.invalidate) {+ // Update local connection state to reflect sign out+ if (this.oauthConnections && this.data.oauth_con_id) {+ this.clearConnectionAuthenticationState(this.data.oauth_con_id);+ }++ // Clear any legacy authentication state+ this.data.oauthService = 'None';++ // Update button state immediately+ if (oauth_button) {+ oauth_button.innerHTML = 'Authenticate';+ oauth_button.disabled = false;}++ // Remove OAuth message if present+ const body = sidebar?.querySelector('div[data-field-name="body"]');+ if (body) {+ const messageId = 'oauthMessageSpan';+ let existingMessageSpan = sidebar?.querySelector(`#${messageId}`);+ if (existingMessageSpan) existingMessageSpan.remove();+ }++ // Show success message+ if (data.message && data.message !== '') {+ successToast(`${data.message}`);+ }++ // Force refresh the sidebar to ensure all states are updated+ this.refreshSettingsSidebar();++ // Note: The authentication button was already updated to "Authenticate" above+ // No need to call updateAuthenticationButtonState again++ // Update component messages+ this.clearComponentMessages();++ } else {+ // Sign out failed+ if (oauth_button) {+ oauth_button.innerHTML = 'Sign Out';+ oauth_button.disabled = false;+ }+ errorToast(`${data.error}`, 'Error', 'alert');}} catch (error) {- errorToast(`Error during fetching or network issue`);- console.error('Error during fetching or network issue:', error);- oauth_button.innerHTML = 'Sign Out';- button.disabled = false;+ errorToast(`Error during sign out: ${error.message}`, 'Error', 'alert');+ console.error('Error during sign out:', error);++ // Reset button state on error+ if (oauth_button) {+ oauth_button.innerHTML = 'Sign Out';+ oauth_button.disabled = false;+ }}}private updateSidebarForOAuth() {- this.checkSettings();+ // Note: Removed checkSettings() call here to avoid duplicate auth checks+ // The component messages will be updated through other pathsconst sidebar = this.getSettingsSidebar();- if (!sidebar) return '';+ if (!sidebar) return;const body = sidebar?.querySelector('div[data-field-name="body"]');const oauth_button: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);if (oauth_button) oauth_button.innerHTML = 'Sign Out';@@ -1094,21 +1473,17 @@ export class APICall extends Component {// Insert the new message span after the body divbody.parentNode.insertBefore(messageSpan, body.nextSibling);}++ // Update component messages separately+ this.clearComponentMessages();}private async updateAuthenticationButton() {- const sidebar = this.getSettingsSidebar();+ // This function is now just a wrapper that calls updateAuthenticationButtonState+ // to leverage the debouncing and caching mechanisms+ await this.updateAuthenticationButtonState();++ // Also update the component button if neededconst isDataValid = await this.checkAuthentication();- if (sidebar) {- const oauthButton: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);- if (oauthButton) {- oauthButton.disabled = false;- if (isDataValid) {- oauthButton.innerHTML = 'Sign Out';- } else {- oauthButton.innerHTML = 'Authenticate';- }- }- }const cptButton: any = this.domElement?.querySelector('button.oauthButton');if (cptButton) {cptButton.disabled = false;@@ -1134,4 +1509,610 @@ export class APICall extends Component {button.innerHTML = `<span class="oauth-spinner smyth-spinner"></span> In Progress ...`; // Insert spinner HTML with hidden spacesbutton.disabled = true;}+ private async handleOAuthConnectionChange(selectedValue: string) {+ const sidebar = this.getSettingsSidebar();+ const previousValue = this.data.oauth_con_id;++ // Clear auth check cache when changing connections+ if (previousValue) {+ this.authCheckPromises.delete(previousValue);+ }++ // First handle the selection change+ if (!selectedValue || selectedValue === 'None') {+ // Clear OAuth-related fields+ this.data.oauth_con_id = 'None';+ const oauth_button: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);+ if (oauth_button) {+ oauth_button.innerHTML = 'Authenticate';+ }+ } else {+ // Set the oauth_con_id in the component's data+ this.data.oauth_con_id = selectedValue;++ // Always synchronize the component's legacy field (oauthService) with the selected connection+ // to avoid stale/broken state across legacy/new structures.+ const selectedConn = this.oauthConnections[selectedValue];+ const selectedOauthInfo = this.getConnectionOauthInfo(selectedConn, selectedValue);+ if (selectedOauthInfo?.service) {+ // Store a user-friendly value for legacy consumers+ this.data.oauthService = mapInternalToServiceName(selectedOauthInfo.service);+ } else {+ this.data.oauthService = 'None';+ }++ // If the selection has changed, check authentication status and update button+ if (selectedValue !== previousValue) {+ // Update button state (this will check backend)+ await this.updateAuthenticationButtonState();+ }+ }++ // Update the action button icon and tooltip+ this.updateOAuthActionButton();+ }++ private async handleOAuthConnectionAction() {+ const currentValue = this.data.oauth_con_id;+ const isNone = !currentValue || currentValue === 'None';+ // console.log('[OAuth Edit] Action started. Current Value:', currentValue, 'Is None:', isNone);+ // Fetch existing OAuth connections ONLY when editing to avoid modal delay on "Add New"+ if (!isNone) {+ try {+ // console.log('[OAuth Edit] Getting OAuth connections from workspace cache for editing...');+ this.oauthConnections = await builderStore.getState().getOAuthConnections();+ // console.log('[OAuth Edit] Retrieved connections for editing:', this.oauthConnections);+ } catch (error) {+ console.error('Error fetching OAuth connections:', error);+ errorToast('Error fetching connections. Please try again.', 'Error', 'alert');+ return;+ }+ } else {+ // Ensure the object exists to avoid any downstream checks+ this.oauthConnections = this.oauthConnections || {};+ // console.log('[OAuth Edit] Creating new connection, using existing connections:', this.oauthConnections);+ }++ // Get current connection if editing and determine structure+ const currentConnectionRaw = !isNone ? this.oauthConnections[currentValue] : null;+ const isNewStructure = currentConnectionRaw && currentConnectionRaw.auth_data && currentConnectionRaw.auth_settings;++ // Extract the settings part based on structure+ const currentSettings = isNewStructure+ ? currentConnectionRaw.auth_settings+ : currentConnectionRaw; // Assume old structure if new one isn't present++ const currentOauthInfo = this.getConnectionOauthInfo(currentSettings, currentValue) || {}; // Support both structures+ const currentName = currentSettings?.name || ''; // Get name from the settings part++ //console.log('[OAuth Edit] Identified Current Connection Settings:', currentSettings);+ //console.log('[OAuth Edit] Identified Current OAuth Info:', currentOauthInfo);++ // Determine service name and platform from the extracted settings+ const currentService = currentSettings+ ? mapInternalToServiceName(currentOauthInfo.service)+ : 'None';+ const currentPlatform = currentOauthInfo.platform || '';++ // Extract values needed for later use in onDOMReady+ const consumerKeyValue = currentOauthInfo.consumerKey || '';+ const consumerSecretValue = currentOauthInfo.consumerSecret || '';++ // Generate form HTML using helper function+ const formHTML = generateOAuthModalHTML(+ currentName,+ currentPlatform,+ currentService,+ currentOauthInfo+ );++ // Show dialog using twEditValuesWithCallback, passing HTML content+ await twEditValuesWithCallback(+ {+ title: isNone ? 'Add OAuth Connection' : 'Edit OAuth Connection',+ content: formHTML,+ onDOMReady: (dialog) => {+ // Get all containers+ const oauth1Container = dialog.querySelector('#oauth1-fields');+ const oauth2Container = dialog.querySelector('#oauth2-fields');+ const callbackDisplayContainer = dialog.querySelector('#callback-url-display');+ const serviceSelect = dialog.querySelector('#oauthService') as HTMLSelectElement;+ const initialServiceValue = serviceSelect?.value || 'None';++ // Force-set OAuth1 fields (our working fix)+ const consumerKeyInput = dialog.querySelector('#consumerKey') as HTMLInputElement;+ const consumerSecretInput = dialog.querySelector('#consumerSecret') as HTMLInputElement;+ if (consumerKeyInput && consumerKeyValue) {+ consumerKeyInput.value = consumerKeyValue;+ }+ if (consumerSecretInput && consumerSecretValue) {+ consumerSecretInput.value = consumerSecretValue;+ }++ // Force-set OAuth2 fields the same way+ const clientIDInput = dialog.querySelector('#clientID') as HTMLInputElement;+ const clientSecretInput = dialog.querySelector('#clientSecret') as HTMLInputElement;+ const tokenURLInput = dialog.querySelector('#tokenURL') as HTMLInputElement;+ const authURLInput = dialog.querySelector('#authorizationURL') as HTMLInputElement;+ const scopeInput = dialog.querySelector('#scope') as HTMLTextAreaElement;++ if (clientIDInput && currentOauthInfo.clientID) {+ clientIDInput.value = currentOauthInfo.clientID;+ }+ if (clientSecretInput && currentOauthInfo.clientSecret) {+ clientSecretInput.value = currentOauthInfo.clientSecret;+ }+ if (tokenURLInput && currentOauthInfo.tokenURL) {+ tokenURLInput.value = currentOauthInfo.tokenURL;+ }+ if (authURLInput && currentOauthInfo.authorizationURL) {+ authURLInput.value = currentOauthInfo.authorizationURL;+ }+ if (scopeInput && currentOauthInfo.scope) {+ scopeInput.value = currentOauthInfo.scope;+ }++ // Comprehensive update field visibility function+ const updateFieldVisibility = (selectedValue: string) => {+ const isOAuth2 = ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedValue);+ const isOAuth1 = ['Twitter', 'Custom OAuth1.0'].includes(selectedValue);+ const isClientCreds = selectedValue === 'OAuth2 Client Credentials';++ // Show/hide main containers+ oauth1Container?.classList.toggle('hidden', !isOAuth1);+ oauth2Container?.classList.toggle('hidden', !(isOAuth2 || isClientCreds));++ // Toggle specific fields within OAuth2+ const scopeGroup = dialog.querySelector('[data-oauth-field="scope"]');+ const authURLGroup = dialog.querySelector('#authorizationURL')?.closest('.form-group');++ if (scopeGroup) {+ scopeGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);+ }+ if (authURLGroup) {+ authURLGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);+ }++ // Handle callback URL display+ callbackDisplayContainer?.classList.toggle(+ 'hidden',+ isClientCreds || (!isOAuth2 && !isOAuth1),+ );+ if (!callbackDisplayContainer?.classList.contains('hidden')) {+ const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');+ const service = selectedValue === 'None' ? '' : selectedValue;+ let callbackURL = '';++ try {+ const baseUrl = window.location.origin;+ const serviceInternal = APICall.prototype.mapServiceNameToInternal.call(+ this,+ service,+ );+ if (serviceInternal && serviceInternal !== 'none') {+ callbackURL = `${baseUrl}/oauth/${serviceInternal}/callback`;+ }+ } catch (e) {+ console.error('Error creating callback URL:', e);+ }++ if (callbackUrlDiv) {+ callbackUrlDiv.textContent = callbackURL;+ }+ }+ };++ // Apply initial visibility+ updateFieldVisibility(initialServiceValue);++ // Re-add change handler+ if (serviceSelect) {+ serviceSelect.addEventListener('change', (e) => {+ const target = e.target as HTMLSelectElement;+ updateFieldVisibility(target.value);++ // Add this code to prefill values when service changes+ const selectedService = target.value;+ if (['Google', 'Twitter', 'LinkedIn'].includes(selectedService)) {+ // Get default configuration for selected service+ const baseUrl = window.location.origin;+ const service = this.mapServiceNameToInternal(selectedService);+ const callbackUrl = `${baseUrl}/oauth/${service}/callback`;++ // Set default values based on service+ 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';+ }++ // Update callback URL display+ const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');+ if (callbackUrlDiv) {+ callbackUrlDiv.textContent = callbackUrl;+ }+ }+ });+ }+ },+ 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) => {+ // Read form data directly from the static form+ const formElement = dialogElm.querySelector(+ '#oauth-connection-form',+ ) as HTMLFormElement;+ if (!formElement) throw new Error('Form element not found');++ const formDataRaw = new FormData(formElement);+ // Ensure all keys exist, even if empty, consistent with how forms work+ const formData: Record<string, string> = {};+ formDataRaw.forEach((value, key) => {+ formData[key] = value as string;+ });++ // --- 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+ }+ if (!formData.platform || formData.platform.trim() === '') {+ errorToast('Platform field is required.', 'Error', 'alert');+ throw new Error('Validation failed: Platform is required.');+ }+ if (!formData.oauthService || formData.oauthService === 'None') {+ errorToast('Auth Service must be selected.', 'Error', 'alert');+ throw new Error('Validation failed: Auth Service is required.');+ }+ // ------------------------++ try {+ const isCreating = isNone;+ const connectionId = isCreating ? `OAUTH_${generateOAuthId()}_TOKENS` : currentValue;+ const service = this.mapServiceNameToInternal(formData.oauthService);+ const type = ['Custom OAuth1.0', 'Twitter'].includes(formData.oauthService)+ ? 'oauth'+ : formData.oauthService === 'OAuth2 Client Credentials'+ ? 'oauth2_client_credentials'+ : 'oauth2';+ const oauthPrefix = connectionId.replace('_TOKENS', '');++ // 1. Build the new oauth_info object from the form data+ const newOauthInfo: any = {+ oauth_keys_prefix: oauthPrefix,+ service,+ name: formData.name.trim(),+ platform: formData.platform.trim(),+ };+ // Add type-specific fields from formData to newOauthInfo+ if (type === 'oauth2' || type === 'oauth2_client_credentials') {+ newOauthInfo.tokenURL = formData.tokenURL || '';+ newOauthInfo.clientID = formData.clientID || '';+ newOauthInfo.clientSecret = formData.clientSecret || '';+ if (type === 'oauth2') { // Only for full OAuth2+ newOauthInfo.authorizationURL = formData.authorizationURL || '';+ newOauthInfo.scope = formData.scope || '';+ }+ } else if (type === 'oauth') {+ newOauthInfo.requestTokenURL = formData.requestTokenURL || '';+ newOauthInfo.accessTokenURL = formData.accessTokenURL || '';+ newOauthInfo.userAuthorizationURL = formData.userAuthorizationURL || '';+ newOauthInfo.consumerKey = formData.consumerKey || '';+ newOauthInfo.consumerSecret = formData.consumerSecret || '';+ }+ // Note: Callback URLs are not explicitly saved, they are derived.++ // 2. Build the auth_settings object to be saved+ const authSettingsToSave = {+ name: newOauthInfo.name, // Use name from newOauthInfo+ type: type,+ tokenURL: (type === 'oauth2' || type === 'oauth2_client_credentials') ? newOauthInfo.tokenURL : undefined,+ oauth_info: newOauthInfo, // Include the full oauth_info+ };+ // Clean up undefined tokenURL before saving+ if (authSettingsToSave.tokenURL === undefined) delete authSettingsToSave.tokenURL;++ // --- Prepare final connectionData (REMOVED as we only send settings) ---+ // let finalConnectionData: any; ... (Removed old logic)+ // --- End Prepare final connectionData ---++ // 3. Save only the constructed auth_settings+ //console.log('[APICall Save] Saving connection settings:', JSON.stringify(authSettingsToSave, null, 2));+ await saveOAuthConnection(connectionId, authSettingsToSave);+ closeTwDialog(dialogElm); // Manually close dialog on success+ successToast(+ isNone ? 'Connection created successfully' : 'Connection updated successfully',+ );++ // Clear auth check cache for the edited/created connection+ this.authCheckPromises.delete(connectionId);++ // Invalidate workspace cache and update connection options+ builderStore.getState().invalidateOAuthConnectionsCache();+ await this.updateOAuthConnectionOptions();++ // Update component data and refresh UI elements+ this.data.oauth_con_id = connectionId;+ this.refreshSettingsSidebar();+ this.updateOAuthActionButton(); // Update the edit/add button icon+ // Update authentication button state after sidebar refresh+ await this.updateAuthenticationButtonState();+ } catch (error) {+ console.error('Error saving OAuth connection:', error);+ errorToast(`Error: ${error.message}`, 'Error', 'alert');+ throw error; // Do not close the dialog, throw error to signal failure+ }+ },+ },+ ],+ dialogClasses: 'smyth-modal-beautiful',+ },+ '', // dialogHeight+ '', // minContentHeight+ 'auto', // overflowY+ '600px', // minWidth+ '700px', // maxWidth+ );+ }++++ // Build OAuth select options from connections with unified name detection and legacy fallback+ private buildOAuthSelectOptions(+ connections: Record<string, any>,+ componentSpecificId: string,+ logPrefix: string,+ ) {+ const options = [];++ // First pass: add ALL connections that have a name property under auth_data (new structure)+ for (const [id, conn] of Object.entries(connections)) {+ if (conn && typeof conn === 'object') {+ // Check for name in the new structure: auth_settings.name+ const connectionName = conn?.auth_settings?.name;++ if (connectionName) {+ // Has a real name+ options.push({+ value: id,+ text: connectionName,+ badge: ''+ });+ } else if (conn?.auth_data && conn?.auth_settings) {+ // New structure but no name - treat as legacy to ensure visibility+ const service = conn?.auth_settings?.service || conn?.auth_settings?.type || 'Unknown';+ const shortId = id.replace('OAUTH_', '').replace('_TOKENS', '');+ options.push({+ value: id,+ text: `${service} [${shortId}]`,+ badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1')+ });+ }+ }+ }++ // 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') {+ const conn = connections[componentSpecificId];++ // Check if this connection has been converted to new structure+ const hasNewStructure = conn?.auth_data && conn?.auth_settings;++ if (!hasNewStructure) {+ // Only add legacy connection if it hasn't been converted to new structure+ const serviceName = conn?.auth_settings?.oauth_info?.service ||+ conn?.oauth_info?.service ||+ conn?.auth_settings?.type ||+ 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);+ if (!alreadyExists) {+ options.push({+ value: componentSpecificId,+ text: `${serviceName} [${shortId}]`,+ badge: createBadge('Legacy', 'text-orange-500 border-orange-500 ml-1')+ });+ }+ }+ }++ // console.log(`${logPrefix} Built options:`, {+ // namedConnections: options.filter(opt => !opt.badge).length,+ // legacyConnections: options.filter(opt => opt.badge).length,+ // totalOptions: options.length,+ // hasNewStructure: connections[componentSpecificId]?.auth_data ? 'yes' : 'no',+ // breakdown: {+ // withNames: options.filter(opt => !opt.badge).length,+ // newStructureNoName: options.filter(opt => opt.badge && opt.text.includes('[')).length,+ // oldLegacy: options.filter(opt => opt.badge && opt.value === componentSpecificId).length+ // }+ // });++ return options;+ }++ /**+ * Fetches the latest OAuth connections and updates the options in this.settings.+ */+ private async updateOAuthConnectionOptions() {+ try {+ // Force refresh to get latest connections+ this.oauthConnections = await builderStore.getState().getOAuthConnections();++ const componentSpecificId = `OAUTH_${this.uid}_TOKENS`;++ // Use the centralized buildOAuthSelectOptions method+ const options = this.buildOAuthSelectOptions(this.oauthConnections, componentSpecificId, '[APICall.updateOAuthConnectionOptions]');++ // Add 'None' option at the start+ options.unshift({ value: 'None', text: 'None', badge: '' });++ // --- Update the options with badges ---+ if (this.settings?.oauth_con_id) {+ this.settings.oauth_con_id.options = options;+ // console.log('Updated settings.oauth_con_id.options:', this.settings.oauth_con_id.options);+ } else {+ console.warn('Could not find oauth_con_id in settings to update options.');+ }+ } catch (error) {+ console.error('Error updating OAuth connection options:', error);+ if (this.settings?.oauth_con_id) {+ this.settings.oauth_con_id.options = [{ value: 'None', text: 'None' }];+ }+ }+ }++ private updateOAuthActionButton() {+ const sidebar: any = this.getSettingsSidebar();+ if (!sidebar) return;++ // Find or create the action buttons+ const createBtn: any = sidebar.querySelector('#createOAuthConnection');+ const editBtn: any = sidebar.querySelector('#editOAuthConnection');+ const isNone: boolean = !this.data.oauth_con_id || this.data.oauth_con_id === 'None';++ if (createBtn) createBtn.style.display = 'inline-block';+ if (editBtn) editBtn.style.display = isNone ? 'none' : 'inline-block';++ const actionButton: any = sidebar.querySelector('#editOAuthConnection');+ if (!actionButton) return;++ // Update icon and tooltip+ const icon = actionButton.querySelector('i');+ if (icon) {+ icon.className = isNone+ ? 'fa-regular fa-plus' // Create icon+ : 'fa-regular fa-pen-to-square'; // Edit icon+ }++ // Update tooltip/title+ actionButton.setAttribute('title', isNone ? 'Create' : 'Edit');+ }++ 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();+ }++ private mapInternalToServiceName(internalName: string): string {+ const 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',+ };+ return map[internalName] || internalName;+ }++++ /**+ * Clears the authentication state for a specific connection+ * @param connectionId - The ID of the connection to clear+ */+ private clearConnectionAuthenticationState(connectionId: string) {+ if (this.oauthConnections && this.oauthConnections[connectionId]) {+ const connection = this.oauthConnections[connectionId];++ // Mark as not authenticated+ connection.isAuthenticated = false;++ // Clear tokens from both structures+ if (connection.auth_data) {+ // New structure+ delete connection.auth_data.primary;+ delete connection.auth_data.secondary;+ delete connection.auth_data.expires_in;+ }++ // Legacy structure+ delete connection.primary;+ delete connection.secondary;+ delete connection.expires_in;++ // Clear any cached auth check promises for this connection+ this.authCheckPromises.delete(connectionId);++ // console.log(`Cleared authentication state for connection: ${connectionId}`);+ }+ }++ /**+ * Updates the authentication button state based on current connection status+ */+ private async updateAuthenticationButtonState() {+ // Clear any existing debounce timer+ if (this.updateAuthButtonDebounceTimer) {+ clearTimeout(this.updateAuthButtonDebounceTimer);+ }++ // Debounce the actual update to prevent rapid successive calls+ return new Promise<void>((resolve) => {+ this.updateAuthButtonDebounceTimer = setTimeout(async () => {+ await this.performAuthButtonUpdate();+ resolve();+ }, 150); // Increased to 150ms debounce to better group rapid calls+ });+ }++ /**+ * Performs the actual authentication button state update+ */+ private async performAuthButtonUpdate() {+ const sidebar = this.getSettingsSidebar();+ if (!sidebar) return;++ const oauth_button: any = sidebar?.querySelector(`[data-field-name="authenticate"] button`);+ if (!oauth_button) return;++ // console.log(`[performAuthButtonUpdate] Updating button for connection: ${this.data.oauth_con_id}`);++ // Show loading state while checking+ this.activateSpinner(oauth_button);++ // Check authentication status with backend for accurate state+ let isAuthenticated = false;+ if (this.data.oauth_con_id && this.data.oauth_con_id !== 'None') {+ // Always verify with backend to ensure accurate state+ isAuthenticated = await this.checkAuthentication();+ }++ oauth_button.innerHTML = isAuthenticated ? 'Sign Out' : 'Authenticate';+ oauth_button.disabled = false;+ }}diff --git a/packages/app/src/builder-ui/helpers/oauth-modal.helper.ts b/packages/app/src/builder-ui/helpers/oauth-modal.helper.tsnew file mode 100644index 00000000..2ab70f45--- /dev/null+++ b/packages/app/src/builder-ui/helpers/oauth-modal.helper.ts@@ -0,0 +1,308 @@+import { OAUTH_SERVICES, mapServiceNameToInternal } from '@src/shared/utils/oauth.utils';++/**+ * Interface for OAuth connection form data+ */+export interface OAuthConnectionFormData {+ name: string;+ platform: string;+ oauthService: string;+ authorizationURL?: string;+ tokenURL?: string;+ clientID?: string;+ clientSecret?: string;+ scope?: string;+ requestTokenURL?: string;+ accessTokenURL?: string;+ userAuthorizationURL?: string;+ consumerKey?: string;+ consumerSecret?: string;+}++/**+ * Interface for OAuth connection info+ */+export interface OAuthConnectionInfo {+ oauth_keys_prefix?: string;+ service?: string;+ name?: string;+ platform?: string;+ authorizationURL?: string;+ tokenURL?: string;+ clientID?: string;+ clientSecret?: string;+ scope?: string;+ requestTokenURL?: string;+ accessTokenURL?: string;+ userAuthorizationURL?: string;+ consumerKey?: string;+ consumerSecret?: string;+}++/**+ * Generate OAuth connection modal HTML+ */+export function generateOAuthModalHTML(+ currentName: string,+ currentPlatform: string,+ currentService: string,+ currentOauthInfo: OAuthConnectionInfo+): string {+ const consumerKeyValue = currentOauthInfo.consumerKey || '';+ const consumerSecretValue = currentOauthInfo.consumerSecret || '';++ return `+ <form id="oauth-connection-form" class="grid gap-4 py-4">+ <!-- Name Field -->+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="name" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Name <span class="text-red-500">*</span></label>+ <div class="col-span-3">+ <input type="text" id="name" name="name" value="${currentName}" required+ class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" />+ </div>+ </div>+ <!-- Platform Field -->+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="platform" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Platform <span class="text-red-500">*</span></label>+ <div class="col-span-3">+ <input type="text" id="platform" name="platform" value="${currentPlatform}" required+ placeholder="e.g., Google Mail, HubSpot CRM"+ class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" />+ </div>+ </div>+ <!-- OAuth Service Selector -->+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="oauthService" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Auth Service <span class="text-red-500">*</span></label>+ <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('')}+ </select>+ </div>+ </div>+ <!-- OAuth 2.0 Fields Container -->+ <div id="oauth2-fields" class="contents hidden">+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="authorizationURL" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Auth URL</label>+ <div class="col-span-3"><input type="text" id="authorizationURL" name="authorizationURL" value="${currentOauthInfo.authorizationURL || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="tokenURL" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Token URL</label>+ <div class="col-span-3"><input type="text" id="tokenURL" name="tokenURL" value="${currentOauthInfo.tokenURL || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="clientID" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Client ID</label>+ <div class="col-span-3"><input type="text" id="clientID" name="clientID" value="${currentOauthInfo.clientID || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="clientSecret" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Client Secret</label>+ <div class="col-span-3"><input type="password" id="clientSecret" name="clientSecret" value="${currentOauthInfo.clientSecret || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group" data-oauth-field="scope">+ <label for="scope" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Scopes</label>+ <div class="col-span-3"><textarea id="scope" name="scope" class="input w-full bg-white border text-gray-900 rounded block outline-none focus:outline-none focus:ring-0 text-sm px-3 py-2 border-gray-300 focus:border-b-2 focus:border-b-blue-500 min-h-[70px] resize-none">${currentOauthInfo.scope || ''}</textarea></div>+ </div>+ </div>++ <!-- OAuth 1.0a Fields Container -->+ <div id="oauth1-fields" class="contents hidden">+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="requestTokenURL" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Request Token URL</label>+ <div class="col-span-3"><input type="text" id="requestTokenURL" name="requestTokenURL" value="${currentOauthInfo.requestTokenURL || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="accessTokenURL" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Access Token URL</label>+ <div class="col-span-3"><input type="text" id="accessTokenURL" name="accessTokenURL" value="${currentOauthInfo.accessTokenURL || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="userAuthorizationURL" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">User Auth URL</label>+ <div class="col-span-3"><input type="text" id="userAuthorizationURL" name="userAuthorizationURL" value="${currentOauthInfo.userAuthorizationURL || ''}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="consumerKey" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Consumer Key</label>+ <div class="col-span-3"><input type="text" id="consumerKey" name="consumerKey" value="${consumerKeyValue}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ <div class="grid grid-cols-4 items-center gap-4 form-group">+ <label for="consumerSecret" class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Consumer Secret</label>+ <div class="col-span-3"><input type="password" id="consumerSecret" name="consumerSecret" value="${consumerSecretValue}" class="input bg-white border border-gray-300 text-gray-900 rounded block w-full h-9 px-3 py-2 text-sm outline-none focus:outline-none focus:ring-0 focus:border-b-2 focus:border-b-blue-500" /></div>+ </div>+ </div>++ <!-- Callback URL Display Container -->+ <div id="callback-url-display" class="grid grid-cols-4 items-center gap-4 hidden">+ <label class="text-sm font-medium peer-disabled:cursor-not-allowed peer-disabled:opacity-70">Callback URL</label>+ <div class="col-span-3 text-sm text-gray-500 break-all"></div>+ </div>+ </form>+ `;+}++/**+ * Set prefill values for known OAuth services+ */+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';+ }++ return callbackUrl;+}++/**+ * Update field visibility based on selected OAuth service+ */+export function updateOAuthFieldVisibility(+ dialog: HTMLElement,+ selectedValue: 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';++ // Show/hide main containers+ oauth1Container?.classList.toggle('hidden', !isOAuth1);+ oauth2Container?.classList.toggle('hidden', !(isOAuth2 || isClientCreds));++ // Toggle specific fields within OAuth2+ const scopeGroup = dialog.querySelector('[data-oauth-field="scope"]');+ const authURLGroup = dialog.querySelector('#authorizationURL')?.closest('.form-group');++ if (scopeGroup) {+ scopeGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);+ }+ if (authURLGroup) {+ authURLGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);+ }++ // Handle callback URL display+ callbackDisplayContainer?.classList.toggle(+ 'hidden',+ isClientCreds || (!isOAuth2 && !isOAuth1),+ );++ if (!callbackDisplayContainer?.classList.contains('hidden')) {+ const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');+ const service = selectedValue === 'None' ? '' : selectedValue;+ let callbackURL = '';++ try {+ const baseUrl = window.location.origin;+ const serviceInternal = mapServiceFunc ? mapServiceFunc(service) : mapServiceNameToInternal(service);+ if (serviceInternal && serviceInternal !== 'none') {+ callbackURL = `${baseUrl}/oauth/${serviceInternal}/callback`;+ }+ } catch (e) {+ console.error('Error creating callback URL:', e);+ }++ if (callbackUrlDiv) {+ callbackUrlDiv.textContent = callbackURL;+ }+ }+}++/**+ * Validate OAuth connection form data+ */+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.' };+ }+ if (!formData.platform || formData.platform.trim() === '') {+ return { isValid: false, error: 'Platform field is required.' };+ }+ if (!formData.oauthService || formData.oauthService === 'None') {+ return { isValid: false, error: 'Auth Service must be selected.' };+ }+ return { isValid: true };+}++/**+ * Build OAuth settings object for saving+ */+export function buildOAuthSettingsForSave(+ formData: Record<string, string>,+ connectionId: string,+ type: 'oauth' | 'oauth2' | 'oauth2_client_credentials'+) {+ const service = mapServiceNameToInternal(formData.oauthService);+ const oauthPrefix = connectionId.replace('_TOKENS', '');++ // Build the new oauth_info object from the form data+ const newOauthInfo: any = {+ oauth_keys_prefix: oauthPrefix,+ service,+ name: formData.name.trim(),+ platform: formData.platform.trim(),+ };++ // Add type-specific fields from formData to newOauthInfo+ if (type === 'oauth2' || type === 'oauth2_client_credentials') {+ newOauthInfo.tokenURL = formData.tokenURL || '';+ newOauthInfo.clientID = formData.clientID || '';+ newOauthInfo.clientSecret = formData.clientSecret || '';+ if (type === 'oauth2') {+ newOauthInfo.authorizationURL = formData.authorizationURL || '';+ newOauthInfo.scope = formData.scope || '';+ }+ } else if (type === 'oauth') {+ newOauthInfo.requestTokenURL = formData.requestTokenURL || '';+ newOauthInfo.accessTokenURL = formData.accessTokenURL || '';+ newOauthInfo.userAuthorizationURL = formData.userAuthorizationURL || '';+ newOauthInfo.consumerKey = formData.consumerKey || '';+ newOauthInfo.consumerSecret = formData.consumerSecret || '';+ }++ // Build the auth_settings object to be saved+ const authSettingsToSave: any = {+ name: newOauthInfo.name,+ type: type,+ oauth_info: newOauthInfo,+ };++ // Add tokenURL for OAuth2 types+ if (type === 'oauth2' || type === 'oauth2_client_credentials') {+ authSettingsToSave.tokenURL = newOauthInfo.tokenURL;+ }++ return authSettingsToSave;+}++/**+ * Generate a unique ID for OAuth connections+ */+export function generateOAuthConnectionId(): string {+ return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();+}diff --git a/packages/app/src/builder-ui/pages/builder/preload-data.ts b/packages/app/src/builder-ui/pages/builder/preload-data.tsindex 502212d7..10107a76 100644--- a/packages/app/src/builder-ui/pages/builder/preload-data.ts+++ b/packages/app/src/builder-ui/pages/builder/preload-data.ts@@ -1,5 +1,6 @@import { lsCache } from '../../../shared/Cache.class';import { MOCK_DATA_CACHE_KEY, VAULT_DATA_CACHE_KEY } from '../../../shared/constants/general';+import { builderStore } from '../../../shared/state_stores/builder/store';import { Workspace } from '../../workspace/Workspace.class';export async function preloadDataScripts(workspace: Workspace) {@@ -14,6 +15,16 @@ export async function preloadDataScripts(workspace: Workspace) {});//#endregion+ //#region preload OAuth connections+ builderStore.getState().getOAuthConnections()+ .then(() => {+ // console.log('[PreloadData] OAuth connections preloaded successfully');+ })+ .catch((error) => {+ console.error('[PreloadData] Failed to preload OAuth connections:', error);+ });+ //#endregion+//#region preload mock data// workspace?.agent?.id is not available here// Extract agent ID from URL path@@ -29,6 +40,6 @@ export async function preloadDataScripts(workspace: Workspace) {});//#endregion} catch {- console.log('Preloading vault data failed.');+ // console.log('Preloading vault data failed.');}}diff --git a/packages/app/src/builder-ui/workspace/Workspace.class.ts b/packages/app/src/builder-ui/workspace/Workspace.class.tsindex c0dc54b2..e7c19da4 100644--- a/packages/app/src/builder-ui/workspace/Workspace.class.ts+++ b/packages/app/src/builder-ui/workspace/Workspace.class.ts@@ -96,6 +96,8 @@ export class Workspace extends EventEmitter {private pendingAddComponent: any = null;public deployments: any = {};public domainData: any = {};+ public oauthConnections: any = null;+ public oauthConnectionsPromise: Promise<any> | null = null;public componentTemplates: any = {};public ACL = {};@@ -121,6 +123,12 @@ export class Workspace extends EventEmitter {this.emit('deploymentsUpdated', result);});}++ // Invalidate OAuth connections cache when they're updated from React+ if (event.detail.queryKey.includes('oauthConnections')) {+ // console.log('[Workspace] OAuth connections updated, invalidating cache');+ this.invalidateOAuthConnectionsCache();+ }});this.jsPlumbInstance.setContainer(this.domElement);@@ -162,7 +170,7 @@ export class Workspace extends EventEmitter {});this.jsPlumbInstance.bind('beforeDrop', (info) => {- console.log('beforeDrop: ', info);+ // console.log('beforeDrop: ', info);if (this.collapsed) return false;if (this.locked) return false;// Check if a connection already exists between the source and target@@ -364,6 +372,80 @@ export class Workspace extends EventEmitter {return result;}+ /**+ * Fetches OAuth connections and caches them+ * Returns cached data if already fetched+ */+ public async getOAuthConnections(forceRefresh: boolean = false): Promise<any> {+ // If we're forcing a refresh, clear the cache+ if (forceRefresh) {+ this.oauthConnections = null;+ this.oauthConnectionsPromise = null;+ }++ // Return cached data if available+ if (this.oauthConnections !== null) {+ return this.oauthConnections;+ }++ // If a fetch is already in progress, return that promise+ if (this.oauthConnectionsPromise !== null) {+ return this.oauthConnectionsPromise;+ }++ // Fetch OAuth connections+ this.oauthConnectionsPromise = fetch(`${this.server}/api/page/vault/oauth-connections`, {+ method: 'GET',+ headers: {+ 'Content-Type': 'application/json',+ credentials: 'include',+ },+ })+ .then(async (response) => {+ if (!response.ok) {+ console.error('[Workspace.getOAuthConnections] Error fetching OAuth connections:', response.status);+ throw new Error(`Failed to fetch OAuth connections: ${response.status}`);+ }+ const data = await response.json();+ this.oauthConnections = data || {};++ // Normalize: parse string values+ Object.keys(this.oauthConnections).forEach((id) => {+ const value = this.oauthConnections[id];+ if (typeof value === 'string') {+ try {+ this.oauthConnections[id] = JSON.parse(value);+ } catch (e) {+ console.warn(+ `[Workspace.getOAuthConnections] Could not parse stringified connection for id=${id}:`,+ e,+ );+ }+ }+ });++ // console.log('[Workspace.getOAuthConnections] OAuth connections cached:', this.oauthConnections);+ return this.oauthConnections;+ })+ .catch((error) => {+ console.error('[Workspace.getOAuthConnections] Failed to fetch OAuth connections:', error);+ this.oauthConnectionsPromise = null; // Reset promise on error+ throw error;+ });++ return this.oauthConnectionsPromise;+ }++ /**+ * Invalidates the OAuth connections cache+ * Call this when OAuth connections are updated+ */+ public invalidateOAuthConnectionsCache(): void {+ // console.log('[Workspace] Invalidating OAuth connections cache');+ this.oauthConnections = null;+ this.oauthConnectionsPromise = null;+ }+private _suspendConnectionRestyle = false;public updateConnectionStyle(_connection) {if (this._suspendConnectionRestyle) return;@@ -385,7 +467,7 @@ export class Workspace extends EventEmitter {if (sourceBR.right > targetBR.left) {const cornerRadius =sourceComponentBR.left - targetComponentBR.left > 100 &&- sourceComponentBR.top - targetComponentBR.bottom > 100+ sourceComponentBR.top - targetComponentBR.bottom > 100? 80: 30;@@ -609,7 +691,7 @@ export class Workspace extends EventEmitter {scheme: scheme,},});- console.log('Populated shared state');+ // console.log('Populated shared state');}async loadUserSubscription() {@@ -747,7 +829,7 @@ export class Workspace extends EventEmitter {try {const result = await this.agent.delete(id);- console.log('Agent Delete result', result);+ // console.log('Agent Delete result', result);if (result.error || !result?.success) {return false;} else {@@ -886,7 +968,7 @@ export class Workspace extends EventEmitter {smoothScroll: true,duration: 300,easing: 'ease-out',- handleStartEvent(e) {},+ handleStartEvent(e) { },});const parent = zoom.parentElement;@@ -1092,7 +1174,7 @@ export class Workspace extends EventEmitter {components.forEach((component) => {try {this.componentTemplates[component.id] = JSON.parse(component.data);- } catch (error) {}+ } catch (error) { }});}private async initServerData() {@@ -1698,7 +1780,7 @@ export class Workspace extends EventEmitter {properties.top = configuration.ui.agentCard.top;} else {const skills = configuration?.components?.filter((c) => c.name === 'APIEndpoint');- console.log('skills to compare', skills);+ // console.log('skills to compare', skills);if (skills.length > 0) {// get the skill with the least Y and place the card above it to the left. x - agent_card_width, y - agent_card_height / 2@@ -1756,7 +1838,7 @@ export class Workspace extends EventEmitter {});}public lock(options?: { showViewOnlyMsg?: boolean }) {- console.log('Locking Workspace');+ // console.log('Locking Workspace');this.locked = true;document.querySelector('#builder-container')?.classList.remove('locked');if (options?.showViewOnlyMsg) this.toggleViewOnlyModeMsg(true);@@ -1778,7 +1860,7 @@ export class Workspace extends EventEmitter {}public unlock() {- console.log('Unlocking Workspace');+ // console.log('Unlocking Workspace');this.locked = false;document.querySelector('#builder-container')?.classList.remove('locked');this.toggleViewOnlyModeMsg(false);@@ -1821,7 +1903,7 @@ export class Workspace extends EventEmitter {}});this.agent.addEventListener('lock', (prevStatus) => {- console.log('lock', prevStatus);+ // console.log('lock', prevStatus);if (prevStatus?.startsWith('unlock') || !prevStatus) {this.lock({ showViewOnlyMsg: false });}@@ -2230,7 +2312,7 @@ export class Workspace extends EventEmitter {* Initialize the monitor*/private initMonitor(): void {- console.log('INIT MONITOR');+ // console.log('INIT MONITOR');// Close existing monitor if anyif (this.monitor) {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.tsxnew file mode 100644index 00000000..a994e052--- /dev/null+++ b/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx@@ -0,0 +1,485 @@+// src/webappv2/pages/vault/create-oauth-connection-modal.tsx+import {+ Dialog,+ DialogContent,+ DialogFooter,+ DialogHeader,+ DialogTitle,+} from '@src/react/shared/components/ui/dialog';+import { Input } from '@src/react/shared/components/ui/input';+import { Label } from '@src/react/shared/components/ui/label';+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button'; // Your custom button+import {+ Select,+ SelectContent,+ SelectItem,+ SelectTrigger,+ SelectValue,+} from '@src/react/shared/components/ui/select';+import { Textarea } from '@src/react/shared/components/ui/textarea';+import {+ OAUTH_SERVICES,+ deriveCallbackUrl,+ mapInternalToServiceName,+ mapServiceNameToInternal,+} from '@src/shared/utils/oauth.utils';+import React, { useEffect, useMemo, useState } from 'react';+import type {+ CreateOAuthConnectionModalProps,+ OAuthConnectionFormData,+} from '../types/oauth-connection';++export function CreateOAuthConnectionModal({+ isOpen,+ onClose,+ onSubmit,+ editConnection,+ isProcessing,+}: CreateOAuthConnectionModalProps) {+ const [formData, setFormData] = useState<Partial<OAuthConnectionFormData>>({});+ const [selectedService, setSelectedService] = useState<string>('None');++ // Determine if it's an edit operation+ const isEditMode = !!editConnection;++ // Initialize form data when opening in edit mode or when editConnection changes+ useEffect(() => {+ if (isOpen && isEditMode && editConnection?.oauth_info) {+ // Map OAuthConnection back to form data structure+ const serviceName = mapInternalToServiceName(editConnection.oauth_info.service);+ setFormData({+ name: editConnection.name,+ platform: editConnection.oauth_info.platform,+ oauthService: serviceName,+ scope: editConnection.oauth_info.scope,+ authorizationURL: editConnection.oauth_info.authorizationURL,+ tokenURL: editConnection.oauth_info.tokenURL,+ clientID: editConnection.oauth_info.clientID,+ clientSecret: editConnection.oauth_info.clientSecret,+ requestTokenURL: editConnection.oauth_info.requestTokenURL,+ accessTokenURL: editConnection.oauth_info.accessTokenURL,+ userAuthorizationURL: editConnection.oauth_info.userAuthorizationURL,+ consumerKey: editConnection.oauth_info.consumerKey,+ consumerSecret: editConnection.oauth_info.consumerSecret,+ });+ setSelectedService(serviceName);+ } else if (isOpen && !isEditMode) {+ // Reset form for creating new connection+ setFormData({ name: '', platform: '', oauthService: 'None' });+ setSelectedService('None');+ }+ }, [isOpen, isEditMode, editConnection]);++ // Handle input changes+ const handleChange = (+ e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>,+ ) => {+ const { name, value } = e.target;+ setFormData((prev) => ({ ...prev, [name]: value }));+ };++ // Handle select changes (specifically for oauthService)+ const handleSelectChange = (value: string) => {+ // Only reset OAuth fields if it's a new connection or if the service type actually changes+ const prevService = formData.oauthService;+ const isServiceTypeChange = prevService !== value;++ if (!isEditMode || isServiceTypeChange) {+ // In create mode or when service type changes, reset OAuth-specific fields+ setFormData((prev) => ({+ ...prev,+ oauthService: value,+ // Reset fields that depend on the service type when service changes+ authorizationURL: isServiceTypeChange ? '' : prev.authorizationURL,+ tokenURL: isServiceTypeChange ? '' : prev.tokenURL,+ clientID: isServiceTypeChange ? '' : prev.clientID,+ clientSecret: isServiceTypeChange ? '' : prev.clientSecret,+ scope: isServiceTypeChange ? '' : prev.scope,+ requestTokenURL: isServiceTypeChange ? '' : prev.requestTokenURL,+ accessTokenURL: isServiceTypeChange ? '' : prev.accessTokenURL,+ userAuthorizationURL: isServiceTypeChange ? '' : prev.userAuthorizationURL,+ consumerKey: isServiceTypeChange ? '' : prev.consumerKey,+ consumerSecret: isServiceTypeChange ? '' : prev.consumerSecret,+ // Keep name and platform+ name: prev.name,+ platform: prev.platform,+ }));+ } else {+ // In edit mode without service type change, just update the service+ setFormData((prev) => ({+ ...prev,+ oauthService: value,+ }));+ }+ setSelectedService(value);+ };++ // Handle form submission+ const handleSubmit = (e: React.FormEvent) => {+ e.preventDefault();+ if (!isProcessing) {+ // Basic validation: Ensure name, platform and service are selected+ if (!formData.name) {+ alert('Please enter a name for the connection.');+ return;+ }+ if (!formData.platform) {+ alert('Please enter the platform name (e.g., Google Mail, HubSpot).');+ return;+ }+ if (!formData.oauthService || formData.oauthService === 'None') {+ alert('Please select an Authentication Service.');+ return;+ }+ // Add more specific field validation based on selectedService if needed here+ onSubmit(formData as OAuthConnectionFormData); // Cast as formData should be complete by now+ }+ };++ // Determine which fields to show based on selected service+ const showOAuth2Fields = useMemo(+ () => ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedService),+ [selectedService],+ );+ const showOAuth1Fields = useMemo(+ () => ['Twitter', 'Custom OAuth1.0'].includes(selectedService),+ [selectedService],+ ); // Assuming Twitter uses 1.0a for simplicity here, might need adjustment+ const showClientCredentialsFields = useMemo(+ () => selectedService === 'OAuth2 Client Credentials',+ [selectedService],+ );+ const showScopeField = useMemo(+ () =>+ !['Custom OAuth1.0', 'OAuth2 Client Credentials'].includes(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)+ useEffect(() => {+ if (!isEditMode) {+ // Only prefill when creating, not editing+ let defaults: Partial<OAuthConnectionFormData> = {};+ const baseCallbackUri = window.location.origin; // Simplistic assumption++ 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+ }+ setFormData((prev) => ({ ...prev, ...defaults }));+ }+ }, [selectedService, isEditMode]);++ // Derived Callback URLs (display only)+ const oauth2CallbackURL = useMemo(() => {+ const internalService = mapServiceNameToInternal(selectedService);+ return deriveCallbackUrl(internalService, 'oauth2');+ }, [selectedService]);++ const oauth1CallbackURL = useMemo(() => {+ const internalService = mapServiceNameToInternal(selectedService);+ return deriveCallbackUrl(internalService, 'oauth');+ }, [selectedService]);++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-[600px] max-h-[80vh] overflow-y-auto">+ <DialogHeader>+ <DialogTitle>{isEditMode ? 'Edit OAuth Connection' : 'Add OAuth Connection'}</DialogTitle>+ </DialogHeader>+ <form onSubmit={handleSubmit}>+ <div className="grid gap-4 py-4">+ {/* Name Field */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="name">+ Name <span className="text-red-500">*</span>+ </Label>+ <div className="col-span-3">+ <Input+ id="name"+ name="name"+ value={formData.name || ''}+ onChange={handleChange}+ placeholder="e.g., My Google Connection"+ required+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>++ {/* Platform Field */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="platform">+ Platform <span className="text-red-500">*</span>+ </Label>+ <div className="col-span-3">+ <Input+ id="platform"+ name="platform"+ value={formData.platform || ''}+ onChange={handleChange}+ placeholder="e.g., Google Mail, HubSpot CRM"+ required+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>++ {/* OAuth Service Selector */}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="oauthService">+ Auth Service <span className="text-red-500">*</span>+ </Label>+ <div className="col-span-3">+ <Select+ name="oauthService"+ value={selectedService}+ onValueChange={handleSelectChange}+ required+ disabled={isProcessing}+ >+ <SelectTrigger className="h-9 w-full">+ <SelectValue placeholder="Select a service" />+ </SelectTrigger>+ <SelectContent>+ {OAUTH_SERVICES.map((service) => (+ <SelectItem key={service} value={service}>+ {service}+ </SelectItem>+ ))}+ </SelectContent>+ </Select>+ </div>+ </div>++ {/* Conditional Fields based on selectedService */}+ {selectedService !== 'None' && (+ <>+ {/* OAuth 2.0 Fields */}+ {(showOAuth2Fields || showClientCredentialsFields) && (+ <>+ {showOAuth2Fields && ( // Auth URL only for standard OAuth2+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="authorizationURL">Auth URL</Label>+ <div className="col-span-3">+ <Input+ id="authorizationURL"+ name="authorizationURL"+ value={formData.authorizationURL || ''}+ onChange={handleChange}+ placeholder="Authorization Endpoint URL"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ )}+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="tokenURL">Token URL</Label>+ <div className="col-span-3">+ <Input+ id="tokenURL"+ name="tokenURL"+ value={formData.tokenURL || ''}+ onChange={handleChange}+ placeholder="Token Endpoint URL"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="clientID">Client ID</Label>+ <div className="col-span-3">+ <Input+ id="clientID"+ name="clientID"+ value={formData.clientID || ''}+ onChange={handleChange}+ placeholder="OAuth Client ID"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="clientSecret">Client Secret</Label>+ <div className="col-span-3">+ <Input+ id="clientSecret"+ name="clientSecret"+ type="password"+ value={formData.clientSecret || ''}+ onChange={handleChange}+ placeholder="OAuth Client Secret"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ {showOAuth2Fields &&+ oauth2CallbackURL && ( // Callback URL Display (OAuth2)+ <div className="grid grid-cols-4 items-center gap-4">+ <Label>Callback URL</Label>+ <div className="col-span-3 text-sm text-gray-500 break-all">+ {oauth2CallbackURL}+ </div>+ </div>+ )}+ </>+ )}++ {/* OAuth 1.0a Fields */}+ {showOAuth1Fields && (+ <>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="requestTokenURL">Request Token URL</Label>+ <div className="col-span-3">+ <Input+ id="requestTokenURL"+ name="requestTokenURL"+ value={formData.requestTokenURL || ''}+ onChange={handleChange}+ placeholder="Request Token URL"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="accessTokenURL">Access Token URL</Label>+ <div className="col-span-3">+ <Input+ id="accessTokenURL"+ name="accessTokenURL"+ value={formData.accessTokenURL || ''}+ onChange={handleChange}+ placeholder="Access Token URL"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="userAuthorizationURL">User Auth URL</Label>+ <div className="col-span-3">+ <Input+ id="userAuthorizationURL"+ name="userAuthorizationURL"+ value={formData.userAuthorizationURL || ''}+ onChange={handleChange}+ placeholder="User Authorization URL"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="consumerKey">Consumer Key</Label>+ <div className="col-span-3">+ <Input+ id="consumerKey"+ name="consumerKey"+ value={formData.consumerKey || ''}+ onChange={handleChange}+ placeholder="OAuth Consumer Key"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="consumerSecret">Consumer Secret</Label>+ <div className="col-span-3">+ <Input+ id="consumerSecret"+ name="consumerSecret"+ type="password"+ value={formData.consumerSecret || ''}+ onChange={handleChange}+ placeholder="OAuth Consumer Secret"+ disabled={isProcessing}+ fullWidth+ />+ </div>+ </div>+ {oauth1CallbackURL && ( // Callback URL Display (OAuth1)+ <div className="grid grid-cols-4 items-center gap-4">+ <Label>Callback URL</Label>+ <div className="col-span-3 text-sm text-gray-500 break-all">+ {oauth1CallbackURL}+ </div>+ </div>+ )}+ </>+ )}++ {/* Scope Field (Common for most OAuth2 flows) */}+ {showScopeField && (+ <div className="grid grid-cols-4 items-center gap-4">+ <Label htmlFor="scope">Scopes</Label>+ <div className="col-span-3">+ <Textarea+ id="scope"+ name="scope"+ value={formData.scope || ''}+ onChange={handleChange}+ className="min-h-[70px] h-[70px] resize-none"+ placeholder="Enter scopes separated by space"+ disabled={isProcessing}+ fullWidth={true}+ />+ </div>+ </div>+ )}+ </>+ )}+ </div>+ <DialogFooter>+ {/* <DialogClose asChild>+ <CustomButton+ variant="primary"+ type="button"+ handleClick={onClose}+ disabled={isProcessing}+ label="Cancel"+ />+ </DialogClose> */}+ <CustomButton+ variant="primary"+ type="submit"+ loading={isProcessing}+ disabled={+ isProcessing || selectedService === 'None' || !formData.name || !formData.platform+ }+ label={isEditMode ? 'Save Changes' : 'Add Connection'}+ />+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ );+}diff --git a/packages/app/src/react/features/vault/components/delete-oauth-connection-modal.tsx b/packages/app/src/react/features/vault/components/delete-oauth-connection-modal.tsxnew file mode 100644index 00000000..7ada1fb2--- /dev/null+++ b/packages/app/src/react/features/vault/components/delete-oauth-connection-modal.tsx@@ -0,0 +1,54 @@+// src/webappv2/pages/vault/delete-oauth-connection-modal.tsx+import React from 'react';+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogDescription,+ DialogFooter,+ DialogClose+} from '@src/react/shared/components/ui/dialog';+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';+import type { DeleteOAuthConnectionModalProps } from '../types/oauth-connection';++export function DeleteOAuthConnectionModal({+ isOpen,+ onClose,+ connection,+ onConfirm,+ isProcessing,+}: DeleteOAuthConnectionModalProps) {+ const handleConfirm = () => {+ if (connection && !isProcessing) {+ onConfirm(connection);+ }+ };++ return (+ <Dialog open={isOpen} onOpenChange={onClose}>+ <DialogContent className="sm:max-w-[425px]">+ <DialogHeader>+ <DialogTitle>Delete OAuth Connection</DialogTitle>+ <DialogDescription>+ Are you sure you want to delete the connection{' '}+ <span className="font-semibold">{connection?.name || 'this connection'}</span>? This+ action cannot be undone.+ </DialogDescription>+ </DialogHeader>+ <DialogFooter>+ <DialogClose asChild>+ <CustomButton variant="secondary" type="button" handleClick={onClose} disabled={isProcessing} label="Cancel" />+ </DialogClose>+ <CustomButton+ variant="primary" // Use destructive variant for delete actions+ handleClick={handleConfirm}+ loading={isProcessing}+ disabled={isProcessing}+ label="Delete Connection"+ />+ </DialogFooter>+ </DialogContent>+ </Dialog>+ );+}\ No newline at end of filediff --git a/packages/app/src/react/features/vault/components/oauth-connections.tsx b/packages/app/src/react/features/vault/components/oauth-connections.tsxnew file mode 100644index 00000000..53d6e5a4--- /dev/null+++ b/packages/app/src/react/features/vault/components/oauth-connections.tsx@@ -0,0 +1,554 @@+// src/webappv2/pages/vault/oauth-connections.tsx+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button'; // Your custom button+import { errorToast, successToast } from '@src/shared/components/toast';+import {+ extractPlatformFromUrl,+ getBackendOrigin,+ mapOAuthTypeDisplay,+} from '@src/shared/utils/oauth.utils';+import { useQueryClient } from '@tanstack/react-query'; // Import useQueryClient+import { Circle, Copy, Pencil, PlusCircle, Trash2 } from 'lucide-react';+import React, { useCallback, useEffect, useState } from 'react';+import {+ OAUTH_QUERY_KEY, // Import the query key+ useAuthenticateClientCredentials,+ useCheckAuthStatus,+ useCreateOAuthConnection,+ useDeleteOAuthConnection,+ useDuplicateOAuthConnection,+ useInitiateOAuth,+ useOAuthConnections,+ useSignOutOAuth,+ useUpdateOAuthConnection,+} from '../components/use-vault-oauth';+import type { OAuthConnection, OAuthConnectionFormData } from '../types/oauth-connection';+import { CreateOAuthConnectionModal } from './create-oauth-connection-modal';+import { DeleteOAuthConnectionModal } from './delete-oauth-connection-modal';+//import { Skeleton } from '@/components/ui/skeleton'; // For loading state++export function OAuthConnections() {+ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);+ const [editingConnection, setEditingConnection] = useState<OAuthConnection | undefined>();+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false);+ const [connectionToDelete, setConnectionToDelete] = useState<OAuthConnection | undefined>();+ const [isProcessing, setIsProcessing] = useState(false); // General processing state++ const queryClient = useQueryClient(); // Get query client instance++ // --- React Query Hooks ---+ const { data: connectionsData, isLoading, error: fetchError } = useOAuthConnections();+ // console.log('[OAuthConnections] useOAuthConnections hook result:', {+ // connectionsData,+ // isLoading,+ // fetchError,+ // });+ const createMutation = useCreateOAuthConnection();+ const updateMutation = useUpdateOAuthConnection();+ const deleteMutation = useDeleteOAuthConnection();+ const duplicateMutation = useDuplicateOAuthConnection();+ const initiateAuthMutation = useInitiateOAuth();+ const checkAuthMutation = useCheckAuthStatus();+ const signOutMutation = useSignOutOAuth();+ const authenticateClientCredsMutation = useAuthenticateClientCredentials();++ // Derived state: convert connectionsData object to array for mapping+ const connections = React.useMemo(() => {+ // console.log('[OAuthConnections] Processing connectionsData:', connectionsData);+ if (!connectionsData) return [];+ const arr = Object.values(connectionsData);+ const sorted = arr.sort((a, b) =>+ (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),+ );+ // console.log('[OAuthConnections] Sorted connections array:', sorted);+ return sorted;+ }, [connectionsData]);++ // --- Authentication Message Handling ---+ const handleAuthMessage = useCallback(+ (event: MessageEvent) => {+ // console.log('[OAuthConnections] handleAuthMessage received event:', event.data);+ // Environment-aware origin check+ const allowedOrigins = new Set<string>([+ window.location.origin, // frontend origin+ getBackendOrigin(), // backend origin+ ]);++ if (!allowedOrigins.has(event.origin)) {+ console.warn('Message received from unexpected origin:', event.origin);+ return; // Reject messages from unknown origins+ }++ const { type, data } = event.data || {};++ if (type === 'oauth' || type === 'oauth2') {+ // console.log('[handleAuthMessage] Authentication successful for type:', type);+ successToast('Authentication successful!');+ // Invalidate the query cache to refetch data AFTER successful auth+ // console.log('[handleAuthMessage] Invalidating OAuth queries to refetch data');+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ } else if (type === 'error') {+ // console.log('[handleAuthMessage] Authentication error:', data);+ errorToast(+ `Authentication Error: ${data?.message || 'An unknown error occurred during authentication.'}`,+ );+ }+ // Keep the listener persistent so multiple auth attempts are handled+ // If you need per-attempt correlation, include a state param and filter here.+ },+ [queryClient], // Add queryClient to dependencies+ );++ // Effect to add/remove the global message listener+ useEffect(() => {+ // Add listener when the component mounts or when auth is initiated+ // Remove listener when the component unmounts+ // Note: This simple approach might have issues if multiple auth flows are triggered.+ // A more robust solution might involve passing a unique state to the OAuth flow+ // and listening for messages matching that state.+ window.addEventListener('message', handleAuthMessage);+ return () => {+ window.removeEventListener('message', handleAuthMessage);+ };+ }, [handleAuthMessage]);++ // Effect to check authentication status for connections when data changes+ useEffect(() => {+ // console.log('[OAuthConnections] Effect triggered - connectionsData changed:', connectionsData);+ if (!connectionsData) return;++ // Prevent duplicate concurrent checks per prefix+ const pending = new Set<string>();++ Object.values(connectionsData).forEach((conn) => {+ // Skip client credentials: we derive locally+ if (conn.type === 'oauth2_client_credentials') return;++ // Skip when already known locally (true/false)+ if (typeof conn.isAuthenticated === 'boolean') return;++ const prefix = conn.oauth_info?.oauth_keys_prefix;+ if (!prefix || pending.has(prefix)) return;++ pending.add(prefix);+ // console.log(+ // '[OAuthConnections] Checking auth status for connection:',+ // conn.name,+ // 'prefix:',+ // prefix,+ // );+ checkAuthMutation.mutate(conn.oauth_info);+ });+ }, [connectionsData, checkAuthMutation]);++ // --- CRUD Handlers ---++ const handleSaveConnection = async (formData: OAuthConnectionFormData) => {+ // console.log('[OAuthConnections] handleSaveConnection called with formData:', formData);+ setIsProcessing(true);+ try {+ if (editingConnection) {+ // Update existing connection+ // console.log('[OAuthConnections] Updating existing connection:', editingConnection.id);+ await updateMutation.mutateAsync({+ connectionId: editingConnection.id,+ updatedFields: formData,+ });+ successToast('OAuth connection updated.');+ } else {+ // Create new connection+ // console.log('[OAuthConnections] Creating new connection');+ await createMutation.mutateAsync(formData);+ successToast('OAuth connection created.');+ // After creating, proactively initiate auth for oauth/oauth2 (not client creds)+ const service = formData.oauthService;+ if (service && service !== 'OAuth2 Client Credentials') {+ // console.log(+ // '[OAuthConnections] Initiating auth for newly created connection with service:',+ // service,+ // );+ // The list will be refetched; to get the new item, delay slightly then initiate+ setTimeout(() => {+ // Find the newly created connection in the cache and trigger auth popup+ const latest =+ queryClient.getQueryData<Record<string, OAuthConnection>>(OAUTH_QUERY_KEY);+ // console.log('[OAuthConnections] Latest query data for auth initiation:', latest);+ if (latest) {+ const created = Object.values(latest)+ .filter((c) => c.name === formData.name)+ .sort((a, b) => (a.id > b.id ? -1 : 1))[0];+ // console.log('[OAuthConnections] Found newly created connection for auth:', created);+ if (created?.oauth_info) {+ initiateAuthMutation.mutate(created.oauth_info);+ }+ }+ }, 350);+ }+ }+ setIsCreateModalOpen(false);+ setEditingConnection(undefined);+ } catch (err: any) {+ console.error('Error saving connection:', err);+ errorToast(+ `Failed to ${editingConnection ? 'update' : 'create'} connection: ${err.message || 'Unknown error'}`,+ );+ } finally {+ setIsProcessing(false);+ }+ };++ const handleEditClick = (connection: OAuthConnection) => {+ setEditingConnection(connection);+ setIsCreateModalOpen(true);+ };++ const handleDeleteClick = (connection: OAuthConnection) => {+ setConnectionToDelete(connection);+ setIsDeleteModalOpen(true);+ };++ const handleDeleteConfirm = async (connection: OAuthConnection) => {+ // console.log(+ // '[OAuthConnections] handleDeleteConfirm called for connection:',+ // connection.id,+ // connection.name,+ // );+ setIsProcessing(true);+ try {+ await deleteMutation.mutateAsync({ connectionId: connection.id });+ successToast('OAuth connection deleted.');+ // Close modal and clear state *after* successful deletion+ setIsDeleteModalOpen(false);+ setConnectionToDelete(undefined);+ } catch (err: any) {+ console.error('Error deleting connection:', err);+ errorToast(`Failed to delete connection: ${err.message || 'Unknown error'}`);+ // Keep modal open on error? Or close? For now, we only close on success.+ } finally {+ // console.log('Finished handleDeleteConfirm.');+ setIsProcessing(false);+ }+ };++ const handleDuplicateClick = async (connection: OAuthConnection) => {+ // console.log(+ // '[OAuthConnections] handleDuplicateClick called for connection:',+ // connection.id,+ // connection.name,+ // );+ setIsProcessing(true);+ try {+ await duplicateMutation.mutateAsync({ connectionToDuplicate: connection });+ successToast(`Connection "${connection.name}" duplicated.`);+ } catch (err: any) {+ console.error('Error duplicating connection:', err);+ errorToast(`Failed to duplicate connection: ${err.message || 'Unknown error'}`);+ } finally {+ // console.log('Finished handleDuplicateClick.');+ setIsProcessing(false);+ }+ };++ // --- Authentication Handlers ---++ const handleAuthenticateClick = async (connection: OAuthConnection) => {+ // console.log(+ // '[OAuthConnections] handleAuthenticateClick called for connection:',+ // connection.id,+ // connection.name,+ // connection.type,+ // );++ try {+ // Fix: Check oauth_info.service instead of connection.type+ if (connection.oauth_info?.service === 'oauth2_client_credentials') {+ // console.log(+ // '[OAuthConnections] Using client credentials authentication for:',+ // connection.name,+ // );+ await authenticateClientCredsMutation.mutateAsync(connection.oauth_info);+ successToast('Authenticated! Client Credentials authentication was successful.');+ // Reflect status in UI immediately+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ } else {+ // console.log('[OAuthConnections] Using OAuth flow authentication for:', connection.name);+ await initiateAuthMutation.mutateAsync(connection.oauth_info);+ }+ } catch (err: any) {+ console.error('Error initiating authentication:', err);+ errorToast(`Could not start authentication: ${err.message || 'Unknown error'}`);+ }+ };++ const handleSignOutClick = async (connection: OAuthConnection) => {+ // console.log(+ // '[OAuthConnections] handleSignOutClick called for connection:',+ // connection.id,+ // connection.name,+ // );+ setIsProcessing(true);+ try {+ await signOutMutation.mutateAsync({+ connectionId: connection.id,+ });+ successToast('Successfully signed out.');+ // No need to manually close modal or clear state here as it's an inline action+ } catch (err: any) {+ console.error('Error signing out:', err);+ errorToast(`Failed to sign out: ${err.message || 'Unknown error'}`);+ } finally {+ // console.log('Finished handleSignOutClick.');+ setIsProcessing(false);+ }+ };++ // --- Helper Functions ---++ // Function to determine the platform display value+ const getPlatformDisplay = (conn: OAuthConnection): string => {+ // 1. Use explicitly set platform if available+ if (conn.oauth_info.platform && conn.oauth_info.platform.trim() !== '') {+ return conn.oauth_info.platform;+ }++ // 2. Use predefined names for known services+ const service = conn.oauth_info.service;+ if (service === 'google') return 'Google';+ if (service === 'linkedin') return 'LinkedIn';+ if (service === 'twitter') return 'Twitter/X'; // Handle twitter/x case++ // 3. Try extracting from URL+ const urlToParse = conn.oauth_info.authorizationURL || conn.oauth_info.userAuthorizationURL;+ if (urlToParse) {+ const extracted = extractPlatformFromUrl(urlToParse);+ // Avoid showing 'unknown' or 'invalid_url' directly if possible+ return extracted !== 'unknown' && extracted !== 'invalid_url' ? extracted : '';+ }++ // 4. Fallback to empty string if nothing else works+ return '';+ };++ // --- Render Logic ---++ if (fetchError) {+ return (+ <div className="rounded-lg bg-white text-gray-800 border border-solid border-gray-200 shadow-sm p-6">+ <div className="text-red-500">Error loading OAuth connections: {fetchError.message}</div>+ </div>+ );+ }++ return (+ <div className="w-full p-6 rounded-lg border border-solid border-[#d9d9d9] flex-col justify-start items-start gap-6 flex">+ <div className="self-stretch text-[#1e1e1e] text-lg font-semibold font-['Inter'] leading-snug">+ OAuth Connections+ </div>+ <div className="w-full">+ {' '}+ {/* Container for the table and button */}+ {isLoading ? (+ <div>Loading connections...</div>+ ) : connections.length === 0 ? (+ <div className="py-4 text-center text-gray-500">No OAuth connections found</div>+ ) : (+ <table className="w-full text-sm text-left text-gray-500">+ <thead className="text-xs text-gray-700 uppercase bg-gray-50">+ <tr>+ <th scope="col" className="px-4 py-3">+ Platform+ </th>+ <th scope="col" className="px-4 py-3">+ Connection Name+ </th>+ <th scope="col" className="px-4 py-3">+ Type+ </th>+ <th scope="col" className="px-4 py-3">+ Status+ </th>+ <th scope="col" className="px-4 py-3 text-right">+ Actions+ </th>+ </tr>+ </thead>+ <tbody>+ {connections.map((conn) => {+ const isCheckingStatus =+ checkAuthMutation.isLoading &&+ checkAuthMutation.variables?.oauth_keys_prefix ===+ conn.oauth_info.oauth_keys_prefix;++ // Derive local active state when server status is unknown+ const isClientCreds = conn.type === 'oauth2_client_credentials';+ const isActive = Boolean(+ (typeof conn.isAuthenticated === 'boolean' ? conn.isAuthenticated : false) ||+ (isClientCreds && conn.primary),+ );+ const isProcessingAny =+ isProcessing ||+ duplicateMutation.isLoading ||+ deleteMutation.isLoading ||+ signOutMutation.isLoading ||+ initiateAuthMutation.isLoading;+ const isDisabled = isProcessingAny || isCheckingStatus;+ const platformDisplay = getPlatformDisplay(conn);++ return (+ <tr key={conn.id} className="bg-white border-b hover:bg-gray-50">+ {/* Platform Column */}+ <td className="px-4 py-3 truncate max-w-[150px]" title={platformDisplay}>+ {platformDisplay || '-'} {/* Show hyphen if empty */}+ </td>+ {/* Name Column */}+ <td+ className="px-4 py-3 font-medium text-gray-900 whitespace-nowrap truncate max-w-[200px]"+ title={conn.name}+ >+ {conn.name}+ </td>+ {/* Type Column */}+ <td className="px-4 py-3">+ <span+ className="inline-flex h-5 items-center justify-center rounded-md bg-[#f3f4f6] px-2 text-xs font-medium text-[#6b7280]"+ title={conn.type}+ >+ {mapOAuthTypeDisplay(conn.type)}+ </span>+ </td>+ {/* Status Column */}+ <td className="px-4 py-3">+ <div+ className="flex items-center justify-start"+ title={isActive ? 'Active' : 'Inactive'}+ >+ {isCheckingStatus ? (+ <div+ className="animate-spin rounded-full h-3 w-3 border-t-2 border-b-2 border-gray-400"+ title="Checking..."+ ></div>+ ) : (+ <Circle+ className={`h-3 w-3 ${+ isActive+ ? 'fill-green-500 text-green-500'+ : 'fill-gray-400 text-gray-400'+ }`}+ />+ )}+ {/* Removed status text as requested */}+ </div>+ </td>+ {/* Actions Column */}+ <td className="px-4 py-3">+ <div className="flex items-center justify-end gap-1">+ {/* Authentication Buttons */}+ {conn.oauth_info &&+ (conn.isAuthenticated ||+ (conn.type === 'oauth2_client_credentials' && conn.primary) ? (+ <button+ type="button"+ onClick={() => handleSignOutClick(conn)}+ disabled={+ signOutMutation.isLoading || isProcessing || isCheckingStatus+ }+ className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-xs font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-8 px-3"+ >+ Sign Out+ </button>+ ) : (+ <button+ type="button"+ onClick={() => handleAuthenticateClick(conn)}+ disabled={+ initiateAuthMutation.isLoading || isProcessing || isCheckingStatus+ }+ className="inline-flex items-center justify-center whitespace-nowrap rounded-md text-xs font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 border border-input bg-background hover:bg-accent hover:text-accent-foreground h-8 px-3"+ >+ Authenticate+ </button>+ ))}++ {/* Duplicate Button */}+ <button+ type="button"+ onClick={() => handleDuplicateClick(conn)}+ className="h-8 w-8 p-0 flex items-center justify-center text-gray-500 hover:text-gray-700 disabled:opacity-50"+ title="Duplicate"+ disabled={isDisabled}+ >+ <Copy className="h-4 w-4" />+ </button>++ {/* Edit Button */}+ <button+ type="button"+ onClick={() => handleEditClick(conn)}+ className="h-8 w-8 p-0 flex items-center justify-center text-gray-500 hover:text-gray-700 disabled:opacity-50"+ title="Edit"+ disabled={isDisabled}+ >+ <Pencil className="h-4 w-4" />+ </button>++ {/* Delete Button */}+ <button+ type="button"+ onClick={() => handleDeleteClick(conn)}+ className="h-8 w-8 p-0 flex items-center justify-center text-gray-500 hover:text-red-500 disabled:opacity-50"+ title="Delete"+ disabled={isDisabled}+ >+ <Trash2 className="h-4 w-4" />+ </button>+ </div>+ </td>+ </tr>+ );+ })}+ </tbody>+ </table>+ )}+ {/* Add Button - Placed below the table */}+ <div className="w-full flex justify-center mt-4">+ <CustomButton+ variant="secondary"+ addIcon+ Icon={<PlusCircle className="mr-2 h-4 w-4" />}+ handleClick={() => {+ setEditingConnection(undefined);+ setIsCreateModalOpen(true);+ }}+ label="Add OAuth Connection"+ disabled={isLoading}+ />+ </div>+ </div>++ {/* Modals */}+ <CreateOAuthConnectionModal+ isOpen={isCreateModalOpen}+ onClose={() => {+ if (!isProcessing && !createMutation.isLoading && !updateMutation.isLoading) {+ setIsCreateModalOpen(false);+ setEditingConnection(undefined);+ }+ }}+ onSubmit={handleSaveConnection}+ editConnection={editingConnection}+ isProcessing={isProcessing || createMutation.isLoading || updateMutation.isLoading}+ />+ <DeleteOAuthConnectionModal+ isOpen={isDeleteModalOpen}+ onClose={() => {+ if (!deleteMutation.isLoading) {+ setIsDeleteModalOpen(false);+ setConnectionToDelete(undefined);+ }+ }}+ connection={connectionToDelete}+ onConfirm={handleDeleteConfirm}+ isProcessing={deleteMutation.isLoading || isProcessing}+ />+ </div>+ );+}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.tsnew file mode 100644index 00000000..0c59ca84--- /dev/null+++ b/packages/app/src/react/features/vault/components/use-vault-oauth.ts@@ -0,0 +1,745 @@+// src/webappv2/pages/vault/use-vault-oauth.ts+import {+ authenticateClientCredentials as authenticateClientCredentialsShared,+ checkOAuthAuthentication as checkOAuthAuthenticationShared,+ deleteOAuthConnection as deleteOAuthConnectionShared,+ fetchOAuthConnections as fetchOAuthConnectionsShared,+ initiateOAuthFlow as initiateOAuthFlowShared,+ saveOAuthConnection as saveOAuthConnectionShared,+ signOutOAuthConnection as signOutOAuthConnectionShared+} from '@src/shared/helpers/oauth-api.helper';+import {+ generateOAuthId,+ isOAuth1Service,+ mapInternalToServiceName,+ mapServiceNameToInternal+} from '@src/shared/utils/oauth.utils';+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';+import type {+ AuthenticateOAuthPayload,+ CheckAuthStatusPayload,+ CreateOAuthConnectionPayload,+ DeleteOAuthConnectionPayload,+ OAuthConnection,+ OAuthInfo,+ OAuthSettings,+ SignOutOAuthPayload,+ UpdateOAuthConnectionPayload+} from '../types/oauth-connection';++export const OAUTH_QUERY_KEY = ['oauthConnections'];++// ============================================================================+// Local Auth Status Derivation Helpers+// ============================================================================++/**+ * Parses an expiration timestamp provided as string or number into a number (ms since epoch).+ * Returns null for undefined, redacted, or invalid values.+ */+function parseExpirationTimestamp(expiresIn?: string | number): number | null {+ if (expiresIn === undefined || expiresIn === '[REDACTED]') return null;+ if (typeof expiresIn === 'number' && Number.isFinite(expiresIn)) return expiresIn;+ if (typeof expiresIn === 'string') {+ const numeric = Number(expiresIn);+ if (Number.isFinite(numeric)) return numeric;+ }+ return null;+}++/**+ * Returns true if token is NOT expired, considering a small safety buffer.+ */+function isTokenCurrentlyValid(expiresAtMs: number | null, bufferSeconds: number = 60): boolean {+ if (expiresAtMs === null) return true; // if no expiry data, assume valid until server proves otherwise+ const now = Date.now();+ const bufferedNow = now + bufferSeconds * 1000;+ return expiresAtMs > bufferedNow;+}++/**+ * Best-effort local auth status evaluation to reduce server checks.+ * - oauth2_client_credentials: require primary token and non-expired (if expiry present)+ * - 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 {+ const type = connection.type;+ const primary = connection.primary;+ const secondary = connection.secondary;+ const expiresAt = parseExpirationTimestamp(connection.expires_in);++ // Check if tokens exist (either actual values or [REDACTED] placeholders)+ const hasPrimary = primary && primary !== '';+ const hasSecondary = secondary && secondary !== '';++ if (type === 'oauth2_client_credentials') {+ if (!hasPrimary) return false;+ // If expires_in is redacted but token exists, assume valid (server will verify on actual API calls)+ if (connection.expires_in === '[REDACTED]') return true;+ return isTokenCurrentlyValid(expiresAt);+ }++ if (type === 'oauth2') {+ if (!hasPrimary) return false;+ // If expires_in is redacted but token exists, assume valid (server will verify on actual API calls)+ if (connection.expires_in === '[REDACTED]') return true;+ // If we know expiry, respect it. If not, leave unknown to allow precise server validation.+ if (expiresAt !== null) return isTokenCurrentlyValid(expiresAt);+ return undefined;+ }++ if (type === 'oauth') {+ // OAuth 1.0a typically has no expiry; both tokens must exist+ if (hasPrimary && hasSecondary) return true;+ return false;+ }++ return undefined;+}++++++/**+ * Fetches all OAuth connection settings by calling the backend API.+ * Assumes the backend endpoint GET /vault/oauth-connections uses getTeamSettingsObj(req, 'oauth').+ * @returns {Promise<OAuthSettings>} A promise resolving to the OAuth settings object.+ */+/**+ * Fetches all OAuth connection settings by calling the backend API.+ * Assumes the backend endpoint GET /vault/oauth-connections uses getTeamSettingsObj(req, 'oauth').+ * Filters the results to only include connections that have a 'name' property.+ * @returns {Promise<OAuthSettings>} A promise resolving to the filtered OAuth settings object.+ */+const fetchOAuthConnections = async (): Promise<OAuthSettings> => {+ const rawData = await fetchOAuthConnectionsShared();++ const normalizedSettings: OAuthSettings = {};++ // Helper: safe hasOwnProperty+ const hasOwn = (obj: any, key: string) => Object.prototype.hasOwnProperty.call(obj ?? {}, key);++ // Helper: normalize one stored entry into a runtime OAuthConnection+ const normalizeEntry = (id: string, entry: any): OAuthConnection | null => {+ let connectionData = entry;++ // Parse if stringified+ if (typeof connectionData === 'string') {+ try {+ connectionData = JSON.parse(connectionData);+ } catch (e) {+ console.warn(`[fetchOAuthConnections] Could not parse stringified connection for id=${id}:`, e);+ return null;+ }+ }++ // Must be an object+ if (typeof connectionData !== 'object' || connectionData === null) {+ console.warn(`[fetchOAuthConnections] Invalid data type for id=${id} after parsing.`);+ return null;+ }++ // Flatten new structure or use old as-is+ let runtimeConnectionData: Partial<OAuthConnection> = {};+ if (connectionData.auth_data && connectionData.auth_settings) {+ runtimeConnectionData = {+ ...(connectionData.auth_settings),+ primary: connectionData.auth_data.primary,+ secondary: connectionData.auth_data.secondary,+ expires_in: connectionData.auth_data.expires_in,+ };+ } else {+ runtimeConnectionData = { ...connectionData };+ }++ // Remove forbidden fields+ if (runtimeConnectionData && (runtimeConnectionData as any).team) {+ delete (runtimeConnectionData as any).team;+ }++ // Synthesize oauth_info for runtime consumers+ const synthKeys = [+ '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 } : {};+ for (const k of synthKeys) {+ if (oauthInfoSynth[k] === undefined && (runtimeConnectionData as any)[k] !== undefined) {+ oauthInfoSynth[k] = (runtimeConnectionData as any)[k];+ }+ }+ (runtimeConnectionData as any).oauth_info = oauthInfoSynth;++ // Check if connection has an original name property (not synthetic)+ const hasOriginalName =+ hasOwn(runtimeConnectionData, 'name') ||+ hasOwn(connectionData, 'name') ||+ (connectionData.auth_settings && hasOwn(connectionData.auth_settings, 'name'));++ // If no original name property exists, skip this connection+ if (!hasOriginalName) {+ // console.log(`[fetchOAuthConnections] Skipping connection ${id} - no original name property`);+ return null;+ }++ // Get the actual name value (could be empty string, but must exist)+ const actualName =+ runtimeConnectionData.name ??+ connectionData.name ??+ connectionData.auth_settings?.name;++ // Ensure name is a string (even if empty)+ if (typeof actualName !== 'string') {+ console.warn(`[fetchOAuthConnections] Connection ${id} has non-string name:`, actualName);+ return null;+ }++ const provisional: OAuthConnection = {+ ...(runtimeConnectionData as any),+ id: id,+ name: actualName, // Use the actual name, even if empty+ isAuthenticated: undefined,+ } as OAuthConnection;++ // Derive local status when determinable+ const locallyDerived = computeLocalAuthStatus(provisional);+ if (typeof locallyDerived === 'boolean') {+ provisional.isAuthenticated = locallyDerived;+ }++ return provisional;+ };++ for (const id in rawData) {+ // Basic validation for the entry+ if (+ Object.prototype.hasOwnProperty.call(rawData, id) &&+ id.startsWith('OAUTH_') &&+ id.endsWith('_TOKENS')+ ) {+ // console.log(`[fetchOAuthConnections] Processing connection ${id}:`, rawData[id]);+ const normalized = normalizeEntry(id, rawData[id]);+ if (normalized) {+ // console.log(`[fetchOAuthConnections] Including connection ${id} with name: "${normalized.name}"`);+ normalizedSettings[id] = normalized;+ } else {+ // console.log(`[fetchOAuthConnections] Filtered out connection ${id} - no original name property`);+ }+ }+ }++ return normalizedSettings; // Return the normalized data+};++/**+ * Saves (creates or updates) OAuth connection *settings* by calling the backend API.+ * Assumes the backend endpoint PUT /vault/oauth-connections handles merging settings+ * and preserving existing token data (auth_data).+ * @param {object} payload - The payload containing connection ID and settings data.+ * @param {string} payload.connectionId - The ID (OAUTH_{UUID}_TOKENS) of the connection.+ * @param {Record<string, any>} payload.settingsData - The connection settings data (expected to be the auth_settings part).+ * @returns {Promise<unknown>} A promise resolving with the API response.+ */+const saveOAuthConnectionSettings = async ({+ connectionId,+ settingsData, // Renamed from 'data' to reflect it only contains settings+}: {+ connectionId: string;+ settingsData: Record<string, any>; // Type appropriately, expecting the auth_settings structure+}): Promise<unknown> => {+ return saveOAuthConnectionShared(connectionId, settingsData);+};++/**+ * Deletes an OAuth connection setting by calling the backend API.+ * Assumes the backend endpoint DELETE /vault/oauth-connections/:connectionId uses deleteTeamSettingsObj.+ * @param {DeleteOAuthConnectionPayload} payload - Contains the connectionId to delete.+ * @returns {Promise<any>} A promise resolving with the API response.+ */+const deleteOAuthConnection = async ({+ connectionId,+}: DeleteOAuthConnectionPayload): Promise<any> => {+ await deleteOAuthConnectionShared(connectionId);+ return { success: true };+};++/**+ * Initiates the OAuth authentication flow using fetch.+ * @param {AuthenticateOAuthPayload} payload - Contains OAuth configuration details.+ * @returns {Promise<{ authUrl: string }>} A promise resolving to the authentication URL.+ */+const initiateOAuth = async (payload: AuthenticateOAuthPayload): Promise<{ authUrl: string }> => {+ const result = await initiateOAuthFlowShared(payload, false); // false to not auto-open popup+ if (!result.authUrl) {+ throw new Error('No authentication URL received');+ }+ return { authUrl: result.authUrl };+};++/**+ * Checks the authentication status of an OAuth connection using fetch.+ * @param {CheckAuthStatusPayload} payload - Contains OAuth configuration details for checking.+ * @returns {Promise<{ success: boolean }>} A promise resolving to the authentication status.+ */+const checkAuthStatus = async (payload: CheckAuthStatusPayload): Promise<{ success: boolean }> => {+ try {+ return await checkOAuthAuthenticationShared(payload);+ } catch (error) {+ console.error('API: checkAuthStatus - Error:', error);+ throw error;+ }+};++/**+ * Signs out an OAuth connection by invalidating its tokens using fetch.+ * @param {SignOutOAuthPayload} payload - Contains the connectionId to sign out.+ * @returns {Promise<any>} A promise resolving with the API response.+ */+const signOutOAuth = async ({ connectionId }: SignOutOAuthPayload): Promise<any> => {+ return signOutOAuthConnectionShared(connectionId, true);+};++// ============================================================================+// React Query Hooks+// ============================================================================++/**+ * Hook to fetch OAuth connections.+ */+export function useOAuthConnections() {+ return useQuery<OAuthSettings, Error>({+ queryKey: OAUTH_QUERY_KEY,+ queryFn: fetchOAuthConnections, // Uses the fetch function calling the backend API+ // staleTime: 5 * 60 * 1000, // Optional: 5 minutes+ });+}++// 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 relevantInfo: Partial<OAuthInfo> = {};++ // *** ADDED: Always include platform if provided ***+ if (formData['platform'] !== undefined) relevantInfo['platform'] = formData['platform'];++ // Always include scope if provided, regardless of type (it might be used conceptually)+ if (formData['scope'] !== undefined) relevantInfo['scope'] = formData['scope'];++ if (type === 'oauth2') {+ // OAuth2 specific config fields from the form+ ['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 => {+ 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 => {+ if (formData[key] !== undefined) relevantInfo[key] = formData[key];+ });+ // oauth1CallbackURL is derived, not directly from form data passed here+ }+ return relevantInfo;+};++/**+ * Hook to create a new OAuth connection.+ */+export function useCreateOAuthConnection() {+ const queryClient = useQueryClient();++ return useMutation<unknown, Error, CreateOAuthConnectionPayload>({+ mutationFn: async (payload: CreateOAuthConnectionPayload) => {+ 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)+ ? 'oauth'+ : oauthService === 'OAuth2 Client Credentials'+ ? 'oauth2_client_credentials'+ : 'oauth2';+ const internalService = mapServiceNameToInternal(oauthService);+ const oauthPrefix = connectionId.replace('_TOKENS', '');++ // Build the oauth_info part which contains all configuration+ const relevantConfigFields = getRelevantOAuthInfoFields(type, payload);+ const oauthInfoData: OAuthInfo = {+ oauth_keys_prefix: oauthPrefix,+ service: internalService,+ name: name,+ platform: platform,+ ...relevantConfigFields,+ // Note: Callback URLs are derived but not strictly part of the *saved* settings+ // They might be added here for completeness if needed elsewhere, but won't be saved directly.+ // oauth2CallbackURL: (type === 'oauth2') ? deriveCallbackUrl(...) : undefined,+ // oauth1CallbackURL: (type === 'oauth') ? deriveCallbackUrl(...) : undefined,+ };++ // Build the auth_settings object+ // This includes name, type, tokenURL (if applicable), and the detailed oauth_info+ const authSettings = {+ name: name,+ type: type,+ tokenURL: (type === 'oauth2' || type === 'oauth2_client_credentials') ? oauthInfoData.tokenURL : undefined,+ oauth_info: oauthInfoData,+ // team: undefined, // Team is typically added by the backend if needed+ };++ // Clean up undefined tokenURL before saving+ if (authSettings.tokenURL === undefined) delete authSettings.tokenURL;+ // Call the helper to save only the settings+ return saveOAuthConnectionSettings({ connectionId, settingsData: authSettings });+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ },+ });+}++/**+ * Hook to update an existing OAuth connection.+ */+export function useUpdateOAuthConnection() {+ const queryClient = useQueryClient();++ return useMutation<unknown, Error, UpdateOAuthConnectionPayload>({+ mutationFn: async (payload: UpdateOAuthConnectionPayload) => {+ const { connectionId, updatedFields } = payload;+ const { oauthService, name, platform, ...rest } = updatedFields;++ // Fetch existing connection data (normalized to old structure by fetcher)+ const currentSettings = queryClient.getQueryData<OAuthSettings>(OAUTH_QUERY_KEY) || {};+ const currentData = currentSettings[connectionId];+ if (!currentData) {+ throw new Error(`Connection with ID ${connectionId} not found in cache.`);+ }++ // Determine the final type and service name after update+ const finalInternalService = oauthService+ ? mapServiceNameToInternal(oauthService)+ : currentData.oauth_info.service;+ const finalType = oauthService+ ? (isOAuth1Service(finalInternalService)+ ? 'oauth'+ : finalInternalService === 'oauth2_client_credentials'+ ? 'oauth2_client_credentials'+ : 'oauth2')+ : currentData.type;++ // Build the updated oauth_info object+ // Start with ALL existing oauth_info fields, then selectively update+ const updatedOAuthInfo: OAuthInfo = {+ // Preserve ALL existing oauth_info fields first+ ...currentData.oauth_info,+ // Then update specific fields+ oauth_keys_prefix: currentData.oauth_info.oauth_keys_prefix, // Never change+ service: finalInternalService,+ name: 'name' in updatedFields ? name : currentData.name,+ platform: 'platform' in updatedFields ? platform : currentData.oauth_info.platform,+ };++ // Now selectively update OAuth-specific fields based on type+ // Only update fields that have actually been provided with new values+ if (finalType === 'oauth2' || finalType === 'oauth2_client_credentials') {+ // Update OAuth2 fields only if explicitly provided in updatedFields+ if ('tokenURL' in updatedFields) {+ updatedOAuthInfo.tokenURL = updatedFields.tokenURL;+ }+ if ('clientID' in updatedFields) {+ updatedOAuthInfo.clientID = updatedFields.clientID;+ }+ if ('clientSecret' in updatedFields) {+ updatedOAuthInfo.clientSecret = updatedFields.clientSecret;+ }+ if (finalType === 'oauth2') {+ if ('authorizationURL' in updatedFields) {+ updatedOAuthInfo.authorizationURL = updatedFields.authorizationURL;+ }+ if ('scope' in updatedFields) {+ updatedOAuthInfo.scope = updatedFields.scope;+ }+ }+ // For client credentials, ensure auth URL and scope are removed+ if (finalType === 'oauth2_client_credentials') {+ delete updatedOAuthInfo.authorizationURL;+ delete updatedOAuthInfo.scope;+ }+ } else if (finalType === 'oauth') {+ // Update OAuth1 fields only if explicitly provided in updatedFields+ if ('requestTokenURL' in updatedFields) {+ updatedOAuthInfo.requestTokenURL = updatedFields.requestTokenURL;+ }+ if ('accessTokenURL' in updatedFields) {+ updatedOAuthInfo.accessTokenURL = updatedFields.accessTokenURL;+ }+ if ('userAuthorizationURL' in updatedFields) {+ updatedOAuthInfo.userAuthorizationURL = updatedFields.userAuthorizationURL;+ }+ if ('consumerKey' in updatedFields) {+ updatedOAuthInfo.consumerKey = updatedFields.consumerKey;+ }+ if ('consumerSecret' in updatedFields) {+ updatedOAuthInfo.consumerSecret = updatedFields.consumerSecret;+ }+ }++ // Build the updated auth_settings object to send to the backend+ 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,+ oauth_info: updatedOAuthInfo, // Include the fully updated oauth_info+ };++ // Clean up undefined tokenURL+ if (updatedAuthSettings.tokenURL === undefined) delete updatedAuthSettings.tokenURL;++ // Call the helper to save only the updated settings+ // The backend PUT handler is responsible for merging these settings+ // with the existing entry and preserving auth_data.+ await saveOAuthConnectionSettings({ connectionId, settingsData: updatedAuthSettings });++ return { success: true }; // Indicate success+ },+ onSuccess: (data: unknown, variables) => {+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ },+ onError: (error, variables) => {+ console.error(`Error updating connection ${variables.connectionId}:`, error);+ }+ });+}++/**+ * Hook to delete an OAuth connection.+ * @returns Mutation object for deleting an OAuth connection.+ */+export function useDeleteOAuthConnection() {+ const queryClient = useQueryClient();++ return useMutation<any, Error, DeleteOAuthConnectionPayload>({+ mutationFn: deleteOAuthConnection,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ },+ // Consider optimistic update for better UX+ // onMutate: async (deletePayload) => { ... },+ // onError: (err, deletePayload, context) => { ... },+ // onSettled: () => { ... },+ });+}++/**+ * Hook to duplicate an OAuth connection.+ * @returns Mutation object for duplicating an OAuth connection.+ */+export function useDuplicateOAuthConnection() {+ const queryClient = useQueryClient();+ const createMutation = useCreateOAuthConnection(); // Use the create hook++ return useMutation<any, Error, { connectionToDuplicate: OAuthConnection }>({+ mutationFn: async ({ connectionToDuplicate }) => {+ if (!connectionToDuplicate) {+ throw new Error('No connection provided for duplication.');+ }++ const newName = `${connectionToDuplicate.name} (Copy)`;++ // Prepare payload similar to create, but using existing oauth_info+ // Exclude token fields (primary, secondary, expires_in)+ const createPayload: CreateOAuthConnectionPayload = {+ name: newName,+ oauthService: mapInternalToServiceName(connectionToDuplicate.oauth_info.service), // Map internal service name back to display name+ // Copy relevant fields from oauth_info+ scope: connectionToDuplicate.oauth_info.scope,+ authorizationURL: connectionToDuplicate.oauth_info.authorizationURL,+ tokenURL: connectionToDuplicate.oauth_info.tokenURL,+ clientID: connectionToDuplicate.oauth_info.clientID,+ clientSecret: connectionToDuplicate.oauth_info.clientSecret,+ requestTokenURL: connectionToDuplicate.oauth_info.requestTokenURL,+ accessTokenURL: connectionToDuplicate.oauth_info.accessTokenURL,+ userAuthorizationURL: connectionToDuplicate.oauth_info.userAuthorizationURL,+ consumerKey: connectionToDuplicate.oauth_info.consumerKey,+ consumerSecret: connectionToDuplicate.oauth_info.consumerSecret,+ platform: connectionToDuplicate.oauth_info.platform, // <-- Fix: include platform+ };++ // Call the create mutation function+ return createMutation.mutateAsync(createPayload);+ },+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ },+ });+}+++/**+ * Hook to initiate OAuth authentication flow.+ * @returns Mutation object for initiating OAuth flow.+ */+export function useInitiateOAuth() {+ const queryClient = useQueryClient();+ // This mutation doesn't directly change server state in our list,+ // but triggers an external flow. Success means the popup opened.+ return useMutation<{ authUrl: string }, Error, AuthenticateOAuthPayload>({+ mutationFn: initiateOAuth,+ onSuccess: (data, variables) => {+ // Open the popup window+ if (data.authUrl) {+ const width = 600;+ const height = 700;+ const left = window.screen.width / 2 - width / 2;+ const top = window.screen.height / 2 - height / 2;++ window.open(+ data.authUrl,+ '_blank',+ `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 {+ console.error('Authentication URL was not returned from the server.');+ // Optionally show a toast message to the user+ // toast({ title: 'Error', description: 'Could not start authentication.', variant: 'destructive' });+ }+ },+ onError: (error) => {+ console.error('Failed to initiate OAuth:', error);+ // Optionally show a toast message to the user+ // toast({ title: 'Error', description: `Authentication failed: ${error.message}`, variant: 'destructive' });+ },+ });+}++/**+ * Hook to check the authentication status of a connection.+ * This might be used for manually refreshing the status indicator.+ * @returns Mutation object for checking auth status.+ */+export function useCheckAuthStatus() {+ const queryClient = useQueryClient();++ return useMutation<{ success: boolean }, Error, CheckAuthStatusPayload>({+ mutationFn: checkAuthStatus,+ onSuccess: (data, variables) => {+ // Update cache ONLY with the isAuthenticated status+ queryClient.setQueryData<OAuthSettings>(OAUTH_QUERY_KEY, (oldData) => {+ if (!oldData) return oldData;+ const connectionId = variables.oauth_keys_prefix + '_TOKENS';+ const connection = oldData[connectionId];+ if (connection) {+ // Only update if the authenticated status actually changed+ if (connection.isAuthenticated === data.success) {+ return oldData; // Return original reference+ }+ return {+ ...oldData,+ [connectionId]: {+ ...connection,+ isAuthenticated: data.success,+ },+ };+ }+ return oldData;+ });+ },+ onError: (error, variables) => {+ console.error(`HOOK: useCheckAuthStatus - onError for ${variables.oauth_keys_prefix}`, error);+ // Update cache ONLY with the isAuthenticated status (false)+ queryClient.setQueryData<OAuthSettings>(OAUTH_QUERY_KEY, (oldData) => {+ if (!oldData) return oldData;+ const connectionId = variables.oauth_keys_prefix + '_TOKENS';+ const connection = oldData[connectionId];+ if (connection) {+ // Only update if the authenticated status is not already false+ if (connection.isAuthenticated === false) {+ return oldData; // Return original reference+ }+ return {+ ...oldData,+ [connectionId]: {+ ...connection,+ isAuthenticated: false, // Assume false on error+ },+ };+ }+ return oldData;+ });+ },+ });+}++/**+ * Hook to sign out an OAuth connection.+ * @returns Mutation object for signing out.+ */+export function useSignOutOAuth() {+ const queryClient = useQueryClient();++ return useMutation<any, Error, SignOutOAuthPayload>({+ mutationFn: signOutOAuth,+ onSuccess: (data, variables) => {+ if (data.invalidate) {+ // Invalidate the whole list to refetch status+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ // Or, more optimistically, update the specific item in the cache+ queryClient.setQueryData<OAuthSettings>(OAUTH_QUERY_KEY, (oldData) => {+ if (!oldData) return oldData;+ const connection = oldData[variables.connectionId];+ if (connection) {+ // Create a new object for the updated connection+ const updatedConnection = {+ ...connection,+ primary: undefined,+ secondary: undefined,+ expires_in: undefined,+ isAuthenticated: false, // Explicitly set to false+ };+ // Return the updated state+ return {+ ...oldData,+ [variables.connectionId]: updatedConnection,+ };+ }+ return oldData;+ });+ }+ },+ onError: (error) => {+ console.error('Failed to sign out:', error);+ // Optionally show a toast message to the user+ // toast({ title: 'Error', description: `Sign out failed: ${error.message}`, variant: 'destructive' });+ },+ });+}++const authenticateClientCredentials = async (payload: OAuthInfo): Promise<{ success: boolean; message: string }> => {+ return authenticateClientCredentialsShared(payload);+};++export function useAuthenticateClientCredentials() {+ const queryClient = useQueryClient();+ return useMutation<{ success: boolean; message: string }, Error, OAuthInfo>({+ mutationFn: authenticateClientCredentials,+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: OAUTH_QUERY_KEY });+ },+ onError: (error) => {+ console.error('Failed to authenticate client credentials:', error);+ },+ });+}+diff --git a/packages/app/src/react/features/vault/pages/VaultPage.tsx b/packages/app/src/react/features/vault/pages/VaultPage.tsxindex 0328cd5f..83197e04 100644--- a/packages/app/src/react/features/vault/pages/VaultPage.tsx+++ b/packages/app/src/react/features/vault/pages/VaultPage.tsx@@ -10,6 +10,7 @@ import { EnterpriseModels } from '../components/enterprise-models';import { RecommendedModels } from '../components/recommended-models';import { UserModels } from '../components/user-models';import { useVault } from '../hooks/use-vault';+import { OAuthConnections } from '../components/oauth-connections';export default function VaultPage() {const [isExporting, setIsExporting] = React.useState(false);@@ -78,6 +79,7 @@ export default function VaultPage() {<UserModels pageAccess={pageAccess} /><EnterpriseModels pageAccess={pageAccess} />+ <OAuthConnections /><ErrorBoundarySuspenseloadingFallback={<div>Loading...</div>}diff --git a/packages/app/src/react/features/vault/types/oauth-connection.ts b/packages/app/src/react/features/vault/types/oauth-connection.tsnew file mode 100644index 00000000..6a346a29--- /dev/null+++ b/packages/app/src/react/features/vault/types/oauth-connection.ts@@ -0,0 +1,140 @@+// src/webappv2/pages/vault/types/oauth-connection.ts+/**+ * Represents the detailed configuration for an OAuth connection.+ */+export interface OAuthInfo {+ oauth_keys_prefix: string; // e.g., OAUTH_ABC123XYZ+ service: string; // e.g., 'google', 'linkedin', 'oauth2', 'oauth', 'oauth2_client_credentials'+ name: string; // User-defined friendly name for the connection+ platform: string; // *** ADDED: The platform name (e.g., 'Google Mail', 'HubSpot') ***+ scope?: string;+ authorizationURL?: string;+ tokenURL?: string;+ clientID?: string;+ clientSecret?: string;+ oauth2CallbackURL?: string;+ requestTokenURL?: string; // OAuth 1.0a+ accessTokenURL?: string; // OAuth 1.0a+ userAuthorizationURL?: string; // OAuth 1.0a+ consumerKey?: string; // OAuth 1.0a+ consumerSecret?: string; // OAuth 1.0a+ oauth1CallbackURL?: string; // OAuth 1.0a+ // Allow any other string properties that might be added+ [key: string]: string | undefined;+}++/**+ * Represents a stored OAuth connection entry, including tokens if authenticated.+ */+export interface OAuthConnection {+ id: string; // The OAUTH_{UUID}_TOKENS key+ name: string; // User-defined friendly name+ primary?: string; // Access token or OAuth1 token+ secondary?: string; // Refresh token or OAuth1 token secret+ type: 'oauth' | 'oauth2' | 'oauth2_client_credentials'; // Type of OAuth flow used+ tokenURL?: string; // URL to refresh/get token+ clientID?: string; // Client ID (OAuth2)+ clientSecret?: string; // Client Secret (OAuth2) - Note: Sensitive, might be stored securely+ consumerKey?: string; // Consumer Key (OAuth1)+ consumerSecret?: string; // Consumer Secret (OAuth1) - Note: Sensitive+ expires_in?: string; // Timestamp (as string) when the token expires+ team?: string; // Team ID associated with the connection+ oauth_info: OAuthInfo; // Detailed configuration used for authentication+ isAuthenticated?: boolean; // Backend determines this, RQ fetches it+}++/**+ * Type for the data structure fetched from team settings under the 'oauth' key.+ * It's a record where keys are OAUTH_{UUID}_TOKENS and values are the connection details.+ */+export type OAuthSettings = Record<string, OAuthConnection>;++/**+ * Props for the CreateOAuthConnectionModal component.+ */+export interface CreateOAuthConnectionModalProps {+ isOpen: boolean;+ onClose: () => void;+ onSubmit: (data: OAuthConnectionFormData) => Promise<any>;+ editConnection?: OAuthConnection; // Provided when editing an existing connection+ isProcessing: boolean;+}++/**+ * Props for the DeleteOAuthConnectionModal component.+ */+export interface DeleteOAuthConnectionModalProps {+ isOpen: boolean;+ onClose: () => void;+ connection?: OAuthConnection;+ onConfirm: (connection: OAuthConnection) => Promise<void>;+ isProcessing: boolean;+}++/**+ * Represents the form data collected in the Create/Edit modal.+ * Mirrors fields needed for OAuthInfo plus the friendly name.+ */+export interface OAuthConnectionFormData {+ name: string;+ platform: string; // *** ADDED: Platform field for the form ***+ oauthService: string; // Maps to oauth_info.service, e.g., 'Google', 'Custom OAuth2.0'+ scope?: string;+ authorizationURL?: string;+ tokenURL?: string;+ clientID?: string;+ clientSecret?: string;+ // oauth2CallbackURL is derived+ requestTokenURL?: string;+ accessTokenURL?: string;+ userAuthorizationURL?: string;+ consumerKey?: string;+ consumerSecret?: string;+ // oauth1CallbackURL is derived++ // Include potential unknown fields captured from the form+ [key: string]: any;+}++/**+ * Payload for creating a new OAuth connection.+ */+export interface CreateOAuthConnectionPayload extends OAuthConnectionFormData {+ id?: string; // ID is generated if not provided (for creation)+}++/**+ * Payload for updating an existing OAuth connection.+ */+export interface UpdateOAuthConnectionPayload {+ connectionId: string; // OAUTH_{UUID}_TOKENS+ updatedFields: Partial<OAuthConnectionFormData>;+}++/**+ * Payload for deleting an OAuth connection.+ */+export interface DeleteOAuthConnectionPayload {+ connectionId: string; // OAUTH_{UUID}_TOKENS+}++/**+ * Payload for initiating OAuth authentication.+ */+export interface AuthenticateOAuthPayload extends OAuthInfo {+ // OAuthInfo contains all necessary fields like clientID, URLs, scope, etc.+}++/**+ * Payload for checking OAuth authentication status.+ */+export interface CheckAuthStatusPayload extends OAuthInfo {+ // OAuthInfo contains necessary fields for the checkAuth backend call+}++/**+ * Payload for signing out an OAuth connection.+ */+export interface SignOutOAuthPayload {+ connectionId: string; // OAUTH_{UUID}_TOKENS+}\ No newline at end of filediff --git a/packages/app/src/react/vite.config.ts b/packages/app/src/react/vite.config.tsindex 81dd3aa7..3edfbc59 100644--- a/packages/app/src/react/vite.config.ts+++ b/packages/app/src/react/vite.config.ts@@ -7,7 +7,7 @@ dotenv.config({ path: '../../.env' });// https://vite.dev/config/const EXPRESS_SERVER_PORT = parseInt(process.env.PORT || '4000');-const proxyRoutes = ['/api', '/app', '/js', '/css', '/metroui', '/img', '/assets'];+const proxyRoutes = ['/api', '/app', '/js', '/css', '/metroui', '/img', '/assets', '/oauth'];const redirectRoutes = ['/builder', '/logs', '/logto'];// Helper function to check if request should be proxieddiff --git a/packages/app/src/shared/helpers/oauth-api.helper.ts b/packages/app/src/shared/helpers/oauth-api.helper.tsnew file mode 100644index 00000000..102c8dc3--- /dev/null+++ b/packages/app/src/shared/helpers/oauth-api.helper.ts@@ -0,0 +1,366 @@+import {+ deriveCallbackUrl,+ handleApiResponse,+ isOAuth1Service,+ isOAuth2Service,+ mapInternalToServiceName+} from '@src/shared/utils/oauth.utils';++/**+ * Extract OAuth info from connection data supporting both old and new structures+ */+export function getConnectionOauthInfo(connection: any, connectionId?: string): any {+ if (!connection) return null;++ // New structure: connection has auth_settings at the root+ if (connection.auth_settings) {+ // First check if oauth_info is nested within auth_settings (before backend flattening)+ if (connection.auth_settings.oauth_info) {+ return connection.auth_settings.oauth_info;+ }++ // If oauth_info was flattened by backend, reconstruct it from auth_settings+ // Check if auth_settings has OAuth fields directly (after backend normalization)+ if (connection.auth_settings.service || connection.auth_settings.oauth_keys_prefix) {+ // 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'+ ];++ oauthFields.forEach(field => {+ if (connection.auth_settings[field] !== undefined) {+ reconstructed[field] = connection.auth_settings[field];+ }+ });++ // Ensure oauth_keys_prefix is set+ if (!reconstructed.oauth_keys_prefix && connectionId) {+ reconstructed.oauth_keys_prefix = connectionId.replace('_TOKENS', '');+ }++ return Object.keys(reconstructed).length > 0 ? reconstructed : null;+ }+ }++ // Old structure might have oauth_info at top level+ if (connection.oauth_info) {+ return connection.oauth_info;+ }++ // 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'+ ];++ fields.forEach(field => {+ if (connection[field] !== undefined) {+ oauthInfo[field] = connection[field];+ }+ });++ // Ensure oauth_keys_prefix is set+ if (!oauthInfo.oauth_keys_prefix && connectionId) {+ oauthInfo.oauth_keys_prefix = connectionId.replace('_TOKENS', '');+ }++ return Object.keys(oauthInfo).length > 0 ? oauthInfo : null;+}++/**+ * Extract service from connection supporting both structures+ */+export function extractServiceFromConnection(connection: any): string {+ if (!connection) return '';++ const oauthInfo = getConnectionOauthInfo(connection);+ 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;+}++/**+ * Check if an OAuth connection is authenticated+ */+export async function checkOAuthAuthentication(+ oauthInfo: any+): Promise<{ success: boolean }> {+ try {+ const response = await fetch('/oauth/checkAuth', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(oauthInfo),+ });++ if (!response.ok) {+ console.error(`Auth check failed:`, response.status);+ return { success: false };+ }++ const result = await response.json();+ return { success: result.success === true };+ } catch (error) {+ console.error(`Error checking auth:`, error);+ return { success: false };+ }+}++/**+ * Initiate OAuth authentication flow - returns auth URL or opens popup+ */+export async function initiateOAuthFlow(+ oauthInfo: any,+ openPopup: boolean = true+): Promise<{ authUrl?: string }> {+ // Enhance payload with callback URLs if needed+ const service = oauthInfo.service;+ const isOAuth1 = isOAuth1Service(service);+ const isOAuth2 = isOAuth2Service(service);++ let enhancedPayload = { ...oauthInfo };+ if (isOAuth1 && !enhancedPayload.oauth1CallbackURL) {+ enhancedPayload.oauth1CallbackURL = deriveCallbackUrl(service, 'oauth');+ } else if (isOAuth2 && !enhancedPayload.oauth2CallbackURL) {+ enhancedPayload.oauth2CallbackURL = deriveCallbackUrl(service, 'oauth2');+ }++ const response = await fetch('/oauth/init', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(enhancedPayload),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to initiate OAuth (Status: ${response.status})`);+ }++ const data = await response.json();++ if (data.authUrl && openPopup) {+ // Open OAuth popup+ const width = 600;+ const height = 700;+ const left = window.screen.width / 2 - width / 2;+ const top = window.screen.height / 2 - height / 2;++ window.open(+ data.authUrl,+ 'oauth_popup',+ `width=${width},height=${height},top=${top},left=${left},toolbar=no,menubar=no,scrollbars=yes,resizable=yes`+ );+ }++ return { authUrl: data.authUrl };+}++/**+ * Sign out from OAuth connection+ */+export async function signOutOAuthConnection(+ connectionId: string,+ invalidateAuthentication: boolean = true+): Promise<{ invalidate: boolean }> {+ const response = await fetch('/oauth/signOut', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ oauth_keys_prefix: connectionId.replace('_TOKENS', ''),+ invalidateAuthentication,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to sign out (Status: ${response.status})`);+ }++ const result = await response.json();+ if (!result.invalidate) {+ throw new Error('Sign out was not successful');+ }++ return result;+}++/**+ * Save OAuth connection to backend+ */+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' },+ body: JSON.stringify({+ entryId: connectionId,+ data: authSettings,+ }),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(+ errorData.error || `Failed to save OAuth connection (Status: ${response.status})`+ );+ }+}++/**+ * Delete OAuth connection from backend+ */+export async function deleteOAuthConnection(connectionId: string): Promise<void> {+ const response = await fetch(`/api/page/vault/oauth-connections/${connectionId}`, {+ method: 'DELETE',+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(+ errorData.error || `Failed to delete OAuth connection (Status: ${response.status})`+ );+ }+}++/**+ * Fetch OAuth connections from backend+ */+export async function fetchOAuthConnections(): Promise<Record<string, any>> {+ const response = await fetch('/api/page/vault/oauth-connections');+ const rawData = await handleApiResponse(response);++ // Normalize the data: parse any stringified values+ const normalizedData: Record<string, any> = {};++ if (rawData && typeof rawData === 'object') {+ Object.keys(rawData).forEach((id) => {+ const value = rawData[id];+ if (typeof value === 'string') {+ try {+ normalizedData[id] = JSON.parse(value);+ } catch (e) {+ console.warn(`Could not parse stringified connection for id=${id}:`, e);+ normalizedData[id] = value;+ }+ } else {+ normalizedData[id] = value;+ }+ });+ }++ return normalizedData;+}++/**+ * Authenticate OAuth2 Client Credentials+ */+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' },+ body: JSON.stringify(oauthInfo),+ });++ if (!response.ok) {+ const errorData = await response.json().catch(() => ({}));+ throw new Error(errorData.error || `Failed to authenticate (Status: ${response.status})`);+ }++ return await response.json();+}diff --git a/packages/app/src/shared/state_stores/builder/slices/oauth.slice.ts b/packages/app/src/shared/state_stores/builder/slices/oauth.slice.tsnew file mode 100644index 00000000..75271e2a--- /dev/null+++ b/packages/app/src/shared/state_stores/builder/slices/oauth.slice.ts@@ -0,0 +1,65 @@+import { StateCreator } from 'zustand';+import { Slice } from '../..';+import { BuilderStore } from '../store';++export interface OAuthSlice extends Slice {+ oauthConnections: Record<string, any> | null;+ oauthConnectionsPromise: Promise<any> | null;+ oauthConnectionsLoading: boolean;+ oauthConnectionsError: Error | null;+ getOAuthConnections: (forceRefresh?: boolean) => Promise<any>;+ invalidateOAuthConnectionsCache: () => void;+}++export const oauthSlice: StateCreator<BuilderStore, [], [], OAuthSlice> = (set, get, store) => ({+ oauthConnections: null,+ oauthConnectionsPromise: null,+ oauthConnectionsLoading: false,+ oauthConnectionsError: null,++ init: async () => { },++ getOAuthConnections: async (forceRefresh = false) => {+ if (forceRefresh) {+ set({ oauthConnections: null, oauthConnectionsPromise: null });+ }+ const { oauthConnections, oauthConnectionsPromise } = get();+ if (oauthConnections !== null) return oauthConnections;+ if (oauthConnectionsPromise !== null) return oauthConnectionsPromise;+ set({ oauthConnectionsLoading: true, oauthConnectionsError: null });+ const promise = fetch('/api/page/vault/oauth-connections', {+ method: 'GET',+ headers: { 'Content-Type': 'application/json' },+ credentials: 'include',+ })+ .then(async (response) => {+ if (!response.ok) {+ throw new Error(`Failed to fetch OAuth connections: ${response.status}`);+ }+ const data = await response.json();+ // Normalize: parse string values+ Object.keys(data || {}).forEach((id) => {+ const value = data[id];+ if (typeof value === 'string') {+ try {+ data[id] = JSON.parse(value);+ } catch (e) {+ // ignore+ }+ }+ });+ set({ oauthConnections: data, oauthConnectionsLoading: false, oauthConnectionsPromise: null });+ return data;+ })+ .catch((error) => {+ set({ oauthConnectionsError: error, oauthConnectionsLoading: false, oauthConnectionsPromise: null });+ throw error;+ });+ set({ oauthConnectionsPromise: promise });+ return promise;+ },++ invalidateOAuthConnectionsCache: () => {+ set({ oauthConnections: null, oauthConnectionsPromise: null });+ },+});diff --git a/packages/app/src/shared/state_stores/builder/store.ts b/packages/app/src/shared/state_stores/builder/store.tsindex b7133450..d0e7d4f8 100644--- a/packages/app/src/shared/state_stores/builder/store.ts+++ b/packages/app/src/shared/state_stores/builder/store.ts@@ -1,17 +1,18 @@// builderStore.ts-import { create, StoreApi } from 'zustand';-import { ServerStatusSlice, serverStatusSlice } from './slices/server_status.slice';+import { devtools } from 'zustand/middleware';import { createAppStore } from '..';import { BaseSlice, baseSlice } from './slices/base.slice';-import { devtools } from 'zustand/middleware';+import { OAuthSlice, oauthSlice } from './slices/oauth.slice';+import { ServerStatusSlice, serverStatusSlice } from './slices/server_status.slice';export type BuilderStore = ServerStatusSlice &- BaseSlice & {+ BaseSlice &+ OAuthSlice & {init: () => Promise<void>;};export const builderStore = createAppStore<BuilderStore>({name: 'builder',- slices: [serverStatusSlice, baseSlice],+ slices: [serverStatusSlice, baseSlice, oauthSlice],middlewares: [devtools],});diff --git a/packages/app/src/shared/utils/oauth.utils.ts b/packages/app/src/shared/utils/oauth.utils.tsnew file mode 100644index 00000000..b834e044--- /dev/null+++ b/packages/app/src/shared/utils/oauth.utils.ts@@ -0,0 +1,243 @@+// Shared OAuth helpers used across Builder UI and React Vault++export interface OAuthInfoLike {+ authorizationURL?: string;+ requestTokenURL?: string;+ userAuthorizationURL?: string;+ accessTokenURL?: string;+ 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',+};++// 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();+}++// 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;+}++// Gets the backend origin for OAuth callbacks+export function getBackendOrigin(): string {+ try {+ const { protocol, hostname } = window.location;+ const isLocal = hostname === 'localhost' || hostname === '127.0.0.1';+ if (isLocal) {+ return `${protocol}//localhost:4000`;+ }+ return window.location.origin;+ } catch {+ return window.location.origin;+ }+}++// Derives the callback URL based on service and OAuth type+export function deriveCallbackUrl(+ service: string,+ type: 'oauth' | 'oauth2'+): string | undefined {+ if (service === 'none') return undefined;++ const baseUrl = getBackendOrigin();+ const callbackPath = `/oauth/${service}/callback`;++ try {+ return new URL(callbackPath, baseUrl).toString();+ } catch (e) {+ console.error('Error constructing callback URL:', e);+ return undefined;+ }+}++// 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';+}++// 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);+}++// 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);+}++// 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';+}++// Attempts to extract a provider/service name from a URL's hostname+export function extractPlatformFromUrl(url?: string): string {+ if (!url) return 'unknown';+ try {+ const hostname = new URL(url).hostname.toLowerCase();++ // Quick checks for common providers+ if (hostname.includes('google')) return 'Google';+ if (hostname.includes('linkedin')) return 'LinkedIn';+ if (hostname.includes('twitter') || hostname.includes('x.com')) return 'Twitter/X';+ if (hostname.includes('facebook')) return 'Facebook';+ if (hostname.includes('github')) return 'GitHub';+ if (hostname.includes('microsoft') || hostname.includes('azure')) return 'Microsoft';+ if (hostname.includes('slack')) return 'Slack';+ if (hostname.includes('salesforce')) return 'Salesforce';+ if (hostname.includes('hubspot')) return 'HubSpot';++ // Generic extraction: capture first significant label+ const generic = hostname.match(+ /(?:^|\.)?([a-z0-9-]+)\.(?:com|net|org|io|co|app|ai|dev|cloud|us|tv)(?:$|\.)/i,+ );+ if (generic && generic[1]) {+ const label = generic[1].toLowerCase();+ if (!['www', 'api', 'auth', 'oauth', 'accounts', 'login', 'app'].includes(label)) {+ return label.charAt(0).toUpperCase() + label.slice(1);+ }+ }++ // Fallback: consider the left-most label if meaningful+ const parts = hostname.split('.');+ if (parts.length > 1) {+ const first = parts[0];+ if (!['www', 'api', 'auth', 'oauth', 'accounts', 'login', 'app'].includes(first)) {+ return first.charAt(0).toUpperCase() + first.slice(1);+ }+ }+ return 'unknown';+ } catch {+ return 'invalid_url';+ }+}++// Derives a provider/service name by checking typical OAuth URLs+export function deriveServiceFromOauthInfo(oauthInfo?: Partial<OAuthInfoLike>): string {+ if (!oauthInfo) return '';+ const urls = [+ oauthInfo.authorizationURL,+ oauthInfo.requestTokenURL,+ oauthInfo.userAuthorizationURL,+ oauthInfo.accessTokenURL,+ oauthInfo.tokenURL,+ ];+ for (const u of urls) {+ const platform = extractPlatformFromUrl(u);+ if (platform && platform !== 'unknown' && platform !== 'invalid_url') return platform;+ }+ return '';+}++// Map OAuth type to display string+export function mapOAuthTypeDisplay(type: string): string {+ switch (type) {+ case 'oauth':+ return 'OAuth1';+ case 'oauth2':+ return 'OAuth2';+ case 'oauth2_client_credentials':+ return 'Client Creds';+ default:+ return 'Unknown';+ }+}++// Generate a unique ID for OAuth connections+export function generateOAuthId(): string {+ return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();+}++// Handle API response with proper error handling+export async function handleApiResponse(response: Response): Promise<any> {+ if (!response.ok) {+ let errorData;+ try {+ errorData = await response.json();+ } catch (e) {+ // Ignore if body isn't JSON+ }+ const errorMessage = errorData?.message || `HTTP error! status: ${response.status}`;+ throw new Error(errorMessage);+ }++ // Handle empty responses (e.g., 204 No Content)+ if (response.status === 204) {+ return undefined;+ }++ return response.json();+}++// Map HTTP status codes to user-friendly messages+export function mapStatusCodeToMessage(statusCode: number): string {+ switch (statusCode) {+ case 400:+ return 'Bad Request. Please verify your request and try again.';+ case 401:+ return 'Unauthorized. Please ensure you are logged in and have the necessary permissions.';+ case 403:+ return 'Forbidden. Access is denied.';+ case 404:+ return 'Not Found. The requested resource was not found.';+ case 500:+ return 'Internal Server Error. Something went wrong on our end.';+ default:+ return 'An unexpected error occurred. Please try again.';+ }+}++diff --git a/packages/app/static/img/overview-tutorial-thumbnail.png b/packages/app/static/img/overview-tutorial-thumbnail.pngindex fd8ba182..6f4721be 100644Binary files a/packages/app/static/img/overview-tutorial-thumbnail.png and b/packages/app/static/img/overview-tutorial-thumbnail.png differ