Skip to content

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

Refactor/oauth2 storage (#489)

Ahmed Essamf2d925af214e
diff --git a/packages/app/src/backend/routes/api/credentials/credentials.service.ts b/packages/app/src/backend/routes/api/credentials/credentials.service.ts
new file mode 100644
index 00000000..10ffee98
--- /dev/null
+++ b/packages/app/src/backend/routes/api/credentials/credentials.service.ts
@@ -0,0 +1,323 @@
+/**
+ * Credentials Service
+ *
+ * Business logic layer for credentials management.
+ * Handles CRUD operations for team credentials (OAuth, vector databases, etc.)
+ *
+ * @module
+ */
+
+import axios from 'axios';
+import type { Request } from 'express';
+import type {
+ CreateCredentialInput,
+ CredentialConnection,
+ DeleteCredentialInput,
+ DeleteCredentialResult,
+ UpdateCredentialInput,
+} from '../../../../shared/types/credentials.types';
+import config from '../../../config';
+import { authHeaders } from '../../../utils/api.utils';
+import { CredentialDependenciesChecker } from './dependencies';
+import {
+ deleteVaultKeysFromCredentials,
+ resolveVaultKeys as resolveVaultKeysHelper,
+ sanitizeCredentials,
+ storeSensitiveFieldsInVault,
+} from './vault-helpers';
+
+const smythAPIBaseUrl = `${config.env.SMYTH_API_BASE_URL}/v1`;
+
+// --- Internal Types ---
+
+interface CredentialData {
+ name: string;
+ provider: string;
+ credentials: Record<string, any>;
+ group: string;
+ createdAt?: string;
+ updatedAt?: string;
+ authType: string;
+}
+
+// --- Service Class ---
+
+export class CredentialsService {
+ /**
+ * Fetch all credentials for a specific group
+ */
+ static async getCredentialsByGroup(
+ group: string,
+ req: Request,
+ options: { resolveVaultKeys?: boolean } = {},
+ ): Promise<CredentialConnection[]> {
+ const { resolveVaultKeys = false } = options;
+
+ const response = await axios.get(`${smythAPIBaseUrl}/teams/settings`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ const settingsArray = response.data?.data || response.data?.settings || [];
+
+ // Normalize to array format
+ let settingsList: Array<{ settingKey: string; settingValue: string }> = [];
+ if (Array.isArray(settingsArray)) {
+ settingsList = settingsArray;
+ } else if (typeof settingsArray === 'object') {
+ settingsList = Object.entries(settingsArray).map(([key, value]: [string, any]) => ({
+ settingKey: key,
+ settingValue: typeof value === 'object' ? JSON.stringify(value) : value,
+ }));
+ }
+
+ // Parse and process credentials
+ const credentials = await Promise.all(
+ settingsList.map(async (setting): Promise<CredentialConnection | null> => {
+ try {
+ const parsedValue =
+ typeof setting.settingValue === 'string'
+ ? JSON.parse(setting.settingValue)
+ : setting.settingValue;
+
+ // Resolve or sanitize credentials based on options
+ let processedCredentials = parsedValue.credentials || {};
+ if (resolveVaultKeys) {
+ processedCredentials = await resolveVaultKeysHelper(processedCredentials, req);
+ } else {
+ processedCredentials = sanitizeCredentials(processedCredentials);
+ }
+
+ return {
+ id: setting.settingKey,
+ ...parsedValue,
+ credentials: processedCredentials,
+ };
+ } catch (error) {
+ console.error(`Error parsing credential ${setting.settingKey}:`, error);
+ return null;
+ }
+ }),
+ );
+
+ return credentials.filter((c): c is CredentialConnection => c !== null);
+ }
+
+ /**
+ * Fetch a single credential by ID
+ */
+ static async getCredentialById(
+ id: string,
+ group: string,
+ req: Request,
+ options: { resolveVaultKeys?: boolean } = {},
+ ): Promise<CredentialConnection> {
+ const { resolveVaultKeys: shouldResolveVaultKeys = false } = options;
+
+ const response = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ const settingValue = response.data?.setting?.settingValue;
+ if (!settingValue) {
+ throw new Error('Credential not found');
+ }
+
+ const credential = typeof settingValue === 'string' ? JSON.parse(settingValue) : settingValue;
+
+ // Resolve vault keys if requested (for editing)
+ let credentials = credential.credentials || {};
+ if (shouldResolveVaultKeys) {
+ credentials = await resolveVaultKeysHelper(credentials, req);
+ } else {
+ credentials = sanitizeCredentials(credentials);
+ }
+
+ return {
+ id,
+ ...credential,
+ credentials,
+ };
+ }
+
+ /**
+ * Create a new credential
+ */
+ static async createCredential(
+ input: CreateCredentialInput,
+ req: Request,
+ ): Promise<CredentialConnection> {
+ const { group, name, provider, credentials, authType } = input;
+
+ // Generate unique ID
+ const credentialId = `${group}@cred_${Math.random().toString(36).substring(2, 9)}`;
+
+ // Store sensitive fields in vault
+ const transformedCredentials = await storeSensitiveFieldsInVault(
+ credentials,
+ credentialId,
+ req,
+ );
+
+ // Prepare credential data
+ const credentialData: CredentialData = {
+ name,
+ provider,
+ credentials: transformedCredentials,
+ group,
+ createdAt: new Date().toISOString(),
+ updatedAt: new Date().toISOString(),
+ authType,
+ };
+
+ // Save to team settings
+ await axios.put(
+ `${smythAPIBaseUrl}/teams/settings`,
+ {
+ settingKey: credentialId,
+ settingValue: JSON.stringify(credentialData),
+ group,
+ },
+ await authHeaders(req),
+ );
+
+ // Return sanitized version
+ const sanitizedCredentials = sanitizeCredentials(transformedCredentials);
+
+ return {
+ id: credentialId,
+ name,
+ provider,
+ credentials: sanitizedCredentials,
+ group,
+ createdAt: credentialData.createdAt,
+ updatedAt: credentialData.updatedAt,
+ };
+ }
+
+ /**
+ * Update an existing credential
+ */
+ static async updateCredential(
+ credentialId: string,
+ group: string,
+ updatedFields: UpdateCredentialInput,
+ req: Request,
+ ): Promise<CredentialConnection> {
+ // Fetch existing credential to preserve createdAt
+ let createdAt: string;
+ let existingData: any;
+ try {
+ const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${credentialId}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+ existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
+ createdAt = existingData.createdAt || new Date().toISOString();
+ } catch (error) {
+ createdAt = new Date().toISOString();
+ }
+
+ // Store sensitive fields in vault
+ const transformedCredentials = updatedFields.credentials
+ ? await storeSensitiveFieldsInVault(updatedFields.credentials, credentialId, req)
+ : undefined;
+
+ // Prepare updated credential data
+
+ const credentialData: CredentialData = {
+ ...existingData,
+ // name: existingData.name,
+ ...(updatedFields.name ? { name: updatedFields.name } : {}),
+ ...(transformedCredentials ? { credentials: transformedCredentials } : {}),
+ createdAt,
+ updatedAt: new Date().toISOString(),
+ ...(updatedFields.customProperties
+ ? { customProperties: updatedFields.customProperties }
+ : {}),
+ ...(updatedFields.authType ? { authType: updatedFields.authType } : {}),
+ };
+
+ // Update team settings
+ await axios.put(
+ `${smythAPIBaseUrl}/teams/settings`,
+ {
+ settingKey: credentialId,
+ settingValue: JSON.stringify(credentialData),
+ group,
+ },
+ await authHeaders(req),
+ );
+
+ // Return sanitized version
+ const sanitizedCredentials = sanitizeCredentials(
+ transformedCredentials || existingData.credentials,
+ );
+
+ return {
+ id: credentialId,
+ name: existingData.name,
+ provider: existingData.provider,
+ credentials: sanitizedCredentials,
+ group: existingData.group,
+ createdAt: credentialData.createdAt,
+ updatedAt: credentialData.updatedAt,
+ // customProperties: existingData.customProperties || {},
+ };
+ }
+
+ /**
+ * Delete a credential
+ */
+ static async deleteCredential(
+ input: DeleteCredentialInput,
+ req: Request,
+ ): Promise<DeleteCredentialResult> {
+ const { id, group, consentedWarnings = false } = input;
+
+ // Fetch existing credential to clean up vault keys
+ const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ const existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
+ if (!existingData.credentials) {
+ throw new Error('Credential not found');
+ }
+
+ // Check dependencies
+ const dependenciesChecker = new CredentialDependenciesChecker(req, id, group);
+ const dependenciesResult = await dependenciesChecker.checkDependencies();
+
+ if (dependenciesResult.errors.length > 0) {
+ throw new Error(dependenciesResult.errors.join('\n'));
+ }
+
+ if (!consentedWarnings && dependenciesResult.warnings.length > 0) {
+ return {
+ success: false,
+ warnings: dependenciesResult.warnings,
+ };
+ }
+
+ // Delete associated vault keys
+ await deleteVaultKeysFromCredentials(existingData.credentials, req?._team?.id, req).catch(
+ (error) => {
+ console.warn('[Credentials] Could not delete vault keys:', error);
+ },
+ );
+
+ // Delete the credential from team settings
+ await axios.delete(`${smythAPIBaseUrl}/teams/settings/${id}`, {
+ params: { group },
+ ...(await authHeaders(req)),
+ });
+
+ return {
+ success: true,
+ message: 'Credential deleted successfully',
+ };
+ }
+}
diff --git a/packages/app/src/backend/routes/api/credentials/router.ts b/packages/app/src/backend/routes/api/credentials/router.ts
index e887183b..7a50259c 100644
--- a/packages/app/src/backend/routes/api/credentials/router.ts
+++ b/packages/app/src/backend/routes/api/credentials/router.ts
@@ -1,38 +1,23 @@
/**
* Credentials Router
*
- * Handles CRUD operations for team credentials (vector databases, etc.)
- * Credentials are stored in team settings with groups for organization
- *
- * Structure:
- * - group: Category (e.g., 'vector_database')
- * - settingKey: Unique credential ID
- * - settingValue: JSON string containing { provider, credentials, name }
+ * Handles CRUD operations for team credentials (vector databases, OAuth, etc.)
+ * Routes delegate business logic to CredentialsService
*/
-import axios from 'axios';
import express, { Request, Response } from 'express';
-import config from '../../../config';
import { includeTeamDetails } from '../../../middlewares/auth.mw';
-import { authHeaders } from '../../../utils/api.utils';
-import { CredentialDependenciesChecker } from './dependencies';
-import {
- deleteVaultKeysFromCredentials,
- resolveVaultKeys,
- sanitizeCredentials,
- storeSensitiveFieldsInVault,
-} from './vault-helpers';
+import { CredentialsService } from './credentials.service';
export const credentialsRouter = express.Router();
-const smythAPIBaseUrl = `${config.env.SMYTH_API_BASE_URL}/v1`;
-
/**
* Get all credentials for a specific group
- * GET /api/credentials?group=vector_database
+ * GET /api/credentials?group=vector_db_creds&resolveVaultKeys=true
*/
credentialsRouter.get('/', includeTeamDetails, async (req: Request, res: Response) => {
const group = req.query.group as string;
+ const resolveVaultKeys = req.query.resolveVaultKeys === 'true';
if (!group) {
return res.status(400).json({
@@ -42,73 +27,31 @@ credentialsRouter.get('/', includeTeamDetails, async (req: Request, res: Respons
}
try {
- const response = await axios.get(`${smythAPIBaseUrl}/teams/settings`, {
- params: { group },
- ...(await authHeaders(req)),
+ const credentials = await CredentialsService.getCredentialsByGroup(group, req, {
+ resolveVaultKeys,
});
- // Parse the settings response - middleware returns array of settings
- const settingsArray = response.data?.data || response.data?.settings || [];
-
- // If it's an object instead of array, convert to array
- let settingsList: Array<{ settingKey: string; settingValue: string }> = [];
- if (Array.isArray(settingsArray)) {
- settingsList = settingsArray;
- } else if (typeof settingsArray === 'object') {
- // If it's an object, convert to array format
- settingsList = Object.entries(settingsArray).map(([key, value]: [string, any]) => ({
- settingKey: key,
- settingValue: typeof value === 'object' ? JSON.stringify(value) : value,
- }));
- }
-
- const credentials = settingsList
- .map((setting: { settingKey: string; settingValue: string }) => {
- try {
- const parsedValue =
- typeof setting.settingValue === 'string'
- ? JSON.parse(setting.settingValue)
- : setting.settingValue;
-
- // Sanitize credentials to hide vault key references
- const sanitizedCredentials = parsedValue.credentials
- ? sanitizeCredentials(parsedValue.credentials)
- : {};
-
- return {
- id: setting.settingKey,
- ...parsedValue,
- credentials: sanitizedCredentials,
- };
- } catch (error) {
- console.error(`Error parsing credential ${setting.settingKey}:`, error);
- return null;
- }
- })
- .filter(Boolean);
-
res.json({
success: true,
data: credentials,
});
} catch (error: any) {
console.error('Error fetching credentials:', error?.message);
- console.error('Full error:', error?.response?.data);
res.status(error?.response?.status || 500).json({
success: false,
- error: error?.response?.data?.message || 'Failed to fetch credentials',
+ error: error?.response?.data?.message || error?.message || 'Failed to fetch credentials',
});
}
});
/**
* Get a specific credential by ID
- * GET /api/credentials/:id?group=vector_database&resolveVaultKeys=true
+ * GET /api/credentials/:id?group=vector_db_creds&resolveVaultKeys=true
*/
credentialsRouter.get('/:id', includeTeamDetails, async (req: Request, res: Response) => {
const { id } = req.params;
const group = req.query.group as string;
- const shouldResolveVaultKeys = req.query.resolveVaultKeys === 'true';
+ const resolveVaultKeys = req.query.resolveVaultKeys === 'true';
if (!group) {
return res.status(400).json({
@@ -118,39 +61,16 @@ credentialsRouter.get('/:id', includeTeamDetails, async (req: Request, res: Resp
}
try {
- const response = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
- params: { group },
- ...(await authHeaders(req)),
+ const credential = await CredentialsService.getCredentialById(id, group, req, {
+ resolveVaultKeys,
});
- const settingValue = response.data?.setting?.settingValue;
- if (!settingValue) {
- return res.status(404).json({
- success: false,
- error: 'Credential not found',
- });
- }
-
- const credential = typeof settingValue === 'string' ? JSON.parse(settingValue) : settingValue;
-
- // Resolve vault keys if requested (for editing)
- let credentials = credential.credentials || {};
- if (shouldResolveVaultKeys) {
- credentials = await resolveVaultKeys(credentials, req);
- } else {
- credentials = sanitizeCredentials(credentials);
- }
-
res.json({
success: true,
- data: {
- id,
- ...credential,
- credentials,
- },
+ data: credential,
});
} catch (error: any) {
- if (error?.response?.status === 404) {
+ if (error?.response?.status === 404 || error?.message === 'Credential not found') {
return res.status(404).json({
success: false,
error: 'Credential not found',
@@ -160,7 +80,7 @@ credentialsRouter.get('/:id', includeTeamDetails, async (req: Request, res: Resp
console.error('Error fetching credential:', error?.message);
res.status(error?.response?.status || 500).json({
success: false,
- error: error?.response?.data?.message || 'Failed to fetch credential',
+ error: error?.response?.data?.message || error?.message || 'Failed to fetch credential',
});
}
});
@@ -171,7 +91,7 @@ credentialsRouter.get('/:id', includeTeamDetails, async (req: Request, res: Resp
* Body: { group, name, provider, credentials: { fieldName: { value, sensitive }, ... } }
*/
credentialsRouter.post('/', includeTeamDetails, async (req: Request, res: Response) => {
- const { group, name, provider, credentials } = req.body;
+ const { group, name, provider, credentials, authType } = req.body;
// Validation
if (!group || !name || !provider || !credentials) {
@@ -182,58 +102,21 @@ credentialsRouter.post('/', includeTeamDetails, async (req: Request, res: Respon
}
try {
- // Generate unique ID for the credential
- const credentialId = `${group}@cred_${Math.random().toString(36).substring(2, 9)}`;
-
- // Store sensitive fields in vault and get transformed credentials
- const transformedCredentials = await storeSensitiveFieldsInVault(
- credentials,
- credentialId,
+ const result = await CredentialsService.createCredential(
+ { group, name, provider, credentials, authType },
req,
);
- // Prepare credential data
- const credentialData = {
- name,
- provider,
- credentials: transformedCredentials,
- group,
- createdAt: new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- };
-
- // Save to team settings
- await axios.put(
- `${smythAPIBaseUrl}/teams/settings`,
- {
- settingKey: credentialId,
- settingValue: JSON.stringify(credentialData),
- group,
- },
- await authHeaders(req),
- );
-
- // Return sanitized credentials (with [REDACTED] for sensitive fields)
- const sanitizedCredentials = sanitizeCredentials(transformedCredentials);
-
res.status(201).json({
success: true,
- data: {
- id: credentialId,
- name,
- provider,
- credentials: sanitizedCredentials,
- group,
- createdAt: credentialData.createdAt,
- updatedAt: credentialData.updatedAt,
- },
+ data: result,
message: 'Credential created successfully',
});
} catch (error: any) {
console.error('Error creating credential:', error?.message);
res.status(error?.response?.status || 500).json({
success: false,
- error: error?.response?.data?.message || 'Failed to create credential',
+ error: error?.response?.data?.message || error?.message || 'Failed to create credential',
});
}
});
@@ -245,7 +128,7 @@ credentialsRouter.post('/', includeTeamDetails, async (req: Request, res: Respon
*/
credentialsRouter.put('/:id', includeTeamDetails, async (req: Request, res: Response) => {
const { id } = req.params;
- const { group, name, provider, credentials } = req.body;
+ const { group, name, provider, credentials, authType } = req.body;
// Validation
if (!group || !name || !provider || !credentials) {
@@ -256,77 +139,35 @@ credentialsRouter.put('/:id', includeTeamDetails, async (req: Request, res: Resp
}
try {
- // Fetch existing credential to preserve createdAt
- let createdAt: string | undefined;
- try {
- const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
- params: { group },
- ...(await authHeaders(req)),
- });
- const existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
- createdAt = existingData.createdAt;
- } catch (error) {
- // If not found, we'll create it as a new credential
- createdAt = new Date().toISOString();
- }
-
- // Store sensitive fields in vault and get transformed credentials
- const transformedCredentials = await storeSensitiveFieldsInVault(credentials, id, req);
-
- // Prepare updated credential data
- const credentialData = {
- name,
- provider,
- credentials: transformedCredentials,
+ const result = await CredentialsService.updateCredential(
+ id,
group,
- createdAt: createdAt || new Date().toISOString(),
- updatedAt: new Date().toISOString(),
- };
-
- // Update team settings
- await axios.put(
- `${smythAPIBaseUrl}/teams/settings`,
- {
- settingKey: id,
- settingValue: JSON.stringify(credentialData),
- group,
- },
- await authHeaders(req),
+ { name, provider, credentials, authType },
+ req,
);
- // Return sanitized credentials (with [REDACTED] for sensitive fields)
- const sanitizedCredentials = sanitizeCredentials(transformedCredentials);
-
res.json({
success: true,
- data: {
- id,
- name,
- provider,
- credentials: sanitizedCredentials,
- group,
- createdAt: credentialData.createdAt,
- updatedAt: credentialData.updatedAt,
- },
+ data: result,
message: 'Credential updated successfully',
});
} catch (error: any) {
console.error('Error updating credential:', error?.message);
res.status(error?.response?.status || 500).json({
success: false,
- error: error?.response?.data?.message || 'Failed to update credential',
+ error: error?.response?.data?.message || error?.message || 'Failed to update credential',
});
}
});
/**
* Delete a credential
- * DELETE /api/credentials/:id?group=vector_database
+ * DELETE /api/credentials/:id?group=vector_db_creds&consentedWarnings=true
*/
credentialsRouter.delete('/:id', includeTeamDetails, async (req: Request, res: Response) => {
const { id } = req.params;
const group = req.query.group as string;
- const consentedWarnings = req.query.consentedWarnings as string;
+ const consentedWarnings = req.query.consentedWarnings === 'true';
if (!group) {
return res.status(400).json({
@@ -336,58 +177,25 @@ credentialsRouter.delete('/:id', includeTeamDetails, async (req: Request, res: R
}
try {
- // Fetch existing credential to clean up vault keys
- const existing = await axios.get(`${smythAPIBaseUrl}/teams/settings/${id}`, {
- params: { group },
- ...(await authHeaders(req)),
- });
+ const result = await CredentialsService.deleteCredential({ id, group, consentedWarnings }, req);
- const existingData = JSON.parse(existing.data?.setting?.settingValue || '{}');
- if (!existingData.credentials) {
- return res.status(400).json({
- success: false,
- error: 'Credential not found',
- });
- }
-
- // check if there are dependencies on this credential
- const dependenciesChecker = new CredentialDependenciesChecker(req, id, group);
- const dependenciesResult = await dependenciesChecker.checkDependencies();
-
- if (dependenciesResult.errors.length > 0) {
- return res.status(400).json({
- success: false,
- error: dependenciesResult.errors.join('\n'),
- });
- } else if (consentedWarnings != 'true' && dependenciesResult.warnings.length > 0) {
+ // Handle warnings (requires user confirmation)
+ if (!result.success && result.warnings) {
return res.status(200).json({
success: false,
- warnings: dependenciesResult.warnings,
+ warnings: result.warnings,
});
}
- // Delete associated vault keys
- await deleteVaultKeysFromCredentials(existingData.credentials, req?._team?.id, req).catch(
- (error) => {
- console.warn('[Credentials] Could not delete vault keys:', error);
- },
- );
-
- // Delete the credential from team settings
- await axios.delete(`${smythAPIBaseUrl}/teams/settings/${id}`, {
- params: { group },
- ...(await authHeaders(req)),
- });
-
res.json({
success: true,
- message: 'Credential deleted successfully',
+ message: result.message,
});
} catch (error: any) {
console.error('Error deleting credential:', error?.message);
res.status(error?.response?.status || 500).json({
success: false,
- error: error?.response?.data?.message || 'Failed to delete credential',
+ error: error?.message || error?.response?.data?.message || 'Failed to delete credential',
});
}
});
diff --git a/packages/app/src/backend/routes/oauth/router.ts b/packages/app/src/backend/routes/oauth/router.ts
index 8abfc072..4848f9bd 100644
--- a/packages/app/src/backend/routes/oauth/router.ts
+++ b/packages/app/src/backend/routes/oauth/router.ts
@@ -1,5 +1,6 @@
import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import { mapStatusCodeToMessage } from '@src/shared/helpers/oauth/oauth.utils';
+import { CredentialConnection } from '@src/shared/types/credentials.types';
import axios from 'axios';
import crypto from 'crypto';
import express from 'express';
@@ -7,7 +8,7 @@ import rateLimit from 'express-rate-limit';
import passport from 'passport';
import { includeTeamDetails } from '../../middlewares/auth.mw';
import { oauthStrategyInitialization } from '../../middlewares/oauthStrategy.mw';
-import { getTeamSettingsObj, saveTeamSettingsObj } from '../../services/team-data.service';
+import { CredentialsService } from '../api/credentials/credentials.service';
import { replaceTemplateVariablesOptimized } from './helper/oauthHelper';
const router = express.Router();
@@ -98,21 +99,24 @@ function normalizeAuthSettings(mergedSettings: any): any {
return mergedSettings;
}
-router.post('/checkAuth', includeTeamDetails, async (req, res) => {
+router.post('/check-auth', includeTeamDetails, async (req, res) => {
try {
- const existing = await getTeamSettingsObj(req, 'oauth');
- if (existing) {
- const result = await compareOAuthDetails(existing, req);
- // Use res.send() or res.json() to send the result back to the client.
- res.json({ success: result });
+ const credRecord = await CredentialsService.getCredentialById(
+ req.body.oauth_conn_id || req.body.oauth_keys_prefix,
+ 'oauth_connections_creds',
+ req,
+ { resolveVaultKeys: true },
+ );
+
+ if (credRecord.customProperties?.tokens?.primary) {
+ return res.json({ success: true });
} else {
- // If there are no existing settings, respond accordingly.
- res.status(404).send('No existing OAuth settings found.');
+ return res.json({ success: false });
}
} catch (error) {
- console.error('Error during comparing oauth values:', error?.message);
+ console.error('Error during checking OAuth authentication:', error?.message);
// Send a 500 Internal Server Error response with an error message.
- res.status(500).send('Failed to compare oauth values.');
+ res.status(500).send('Failed to check OAuth authentication.');
}
});
@@ -178,7 +182,6 @@ router.post(
}
};
-
try {
if (authorizationURL) validateURL(authorizationURL, 'authorizationURL');
if (tokenURL) validateURL(tokenURL, 'tokenURL');
@@ -194,7 +197,6 @@ router.post(
if (OAuthServicesRegistry.isOAuth2Service(service) || service === 'oauth2') {
// OAuth2 flow - Store sensitive data in session, return clean URL
-
// Validate required OAuth2 fields
if (!clientID || !clientSecret) {
return res
@@ -255,11 +257,9 @@ router.post(
console.error('Error in /init route:', error);
res.status(500).json({ error: 'Failed to initialize authentication' });
}
-
},
);
-
router.get('/:provider', async (req, res, next) => {
try {
const scopes = req?.session?.scopes?.split(' ') || [];
@@ -385,7 +385,7 @@ router.get('/:provider/callback', async (req, res, next) => {
req.session?.oauth_info?.authorizationURL?.includes('twitter.com');
// Handle Twitter OAuth2
- if (isTwitterAuth) {
+ if (isTwitterAuth && req.session.strategyType === 'oauth2') {
// Verify state parameter
if (!state || state !== req.session.oauth_state) {
console.error('State parameter mismatch or missing');
@@ -508,7 +508,7 @@ function calculateExpirationTimestamp(expiresInSeconds: number) {
async function handleTokenStorage(session, oauthUser, req) {
try {
const { oauth_info, team, strategyType, templateKeys } = session;
- const entryId = `${oauth_info?.oauth_keys_prefix}_TOKENS`;
+ const entryId = oauth_info?.oauth_keys_prefix;
const accessToken = req.user.accessToken;
// Check if it's Twitter OAuth 1.0a
@@ -566,6 +566,59 @@ async function handleTokenStorage(session, oauthUser, req) {
}
}
+type OAuthInfo = {
+ [key: string]: any; // you can refine this if you know the schema
+};
+
+type AuthSettings = {
+ name?: string;
+ platform?: string;
+ oauth_info?: OAuthInfo;
+ [key: string]: any; // other arbitrary setting fields
+};
+
+type AuthData = {
+ primary?: string;
+ secondary?: string;
+ expires_in?: number;
+};
+
+export type ExistingEntryData = {
+ // NEW structure
+ auth_data?: AuthData;
+ auth_settings?: AuthSettings;
+};
+
+function transformOAuthCredEntry(
+ credentialEntry: CredentialConnection & { tokens: any },
+): ExistingEntryData {
+ // if old flow, return the old structure
+ if (credentialEntry.credentials?.primary) {
+ const { primary, secondary, expires_in, ...credentials } = credentialEntry.credentials;
+ return {
+ auth_data: {
+ primary,
+ secondary,
+ expires_in,
+ },
+ auth_settings: credentials,
+ };
+ }
+
+ // if new flow, return the new structure
+ return {
+ auth_data: {
+ primary: credentialEntry.tokens?.primary,
+ secondary: credentialEntry.tokens?.secondary,
+ expires_in: credentialEntry.tokens?.expires_in,
+ },
+ auth_settings: {
+ platform: credentialEntry.name,
+ ...credentialEntry.credentials,
+ },
+ };
+}
+
async function handleOAuthOperation(
settingKey: string,
entryId: string,
@@ -573,8 +626,15 @@ async function handleOAuthOperation(
req: express.Request,
) {
try {
- const existingSettings = await getTeamSettingsObj(req, settingKey);
- const existingEntryData = existingSettings?.[entryId] || {};
+ // const existingSettings = await getTeamSettingsObj(req, settingKey);
+ // const existingEntryData = existingSettings?.[entryId] || {};
+ // const credentialEntry = await CredentialsService.getCredentialById(
+ // entryId,
+ // 'oauth_connections_creds',
+ // req,
+ // { resolveVaultKeys: true },
+ // );
+ // const existingEntryData = transformOAuthCredEntry(credentialEntry as any);
// 1. Separate new token data from new settings data
const { primary, secondary, expires_in, ...newSettingsFromAuthFlowRaw } = newDataFromAuthFlow;
@@ -584,49 +644,68 @@ async function handleOAuthOperation(
// 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;
- }
+ // 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 as any;
+ // 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
+ // };
- // 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,
- };
- }
+ // 5. Save the final data object
+ // await saveTeamSettingsObj({ req, settingKey, entryId, data: finalDataToSave });
- // 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
- };
+ await CredentialsService.updateCredential(
+ entryId,
+ 'oauth_connections_creds',
+ {
+ // ...credentialEntry,
+ // credentials: finalDataToSave.auth_settings,
- // 5. Save the final data object
- await saveTeamSettingsObj({ req, settingKey, entryId, data: finalDataToSave });
+ customProperties: {
+ tokens: newAuthData,
+ },
+ },
+ req,
+ );
} catch (error) {
console.error(`[handleOAuthOperation] Error handling OAuth operation for ${entryId}:`, error);
throw error; // Re-throw the error for higher-level handling
@@ -713,25 +792,22 @@ async function compareOAuthDetails(existing: Record<string, any>, req: express.R
router.post('/signOut', includeTeamDetails, async (req, res) => {
try {
- // 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 entryId = req.body.oauth_keys_prefix;
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 data if it's a string
- let existingData = settings[entryId];
+ let existingData: ExistingEntryData;
try {
- existingData = typeof existingData === 'string' ? JSON.parse(existingData) : existingData;
+ existingData = await CredentialsService.getCredentialById(
+ entryId,
+ 'oauth_connections_creds',
+ req,
+ { resolveVaultKeys: true },
+ ).then(transformOAuthCredEntry);
} catch (error) {
- console.error('Error parsing existing settings:', error?.message);
- return res.status(500).json({ error: 'Invalid settings format' });
+ console.error('Error getting OAuth settings:', error?.message);
+ return res
+ .status(500)
+ .json({ error: 'No existing OAuth settings found for the provided prefix' });
}
if (invalidateAuthentication !== true) {
@@ -741,60 +817,35 @@ router.post('/signOut', includeTeamDetails, async (req, res) => {
}
// 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.' });
+ let newAuthData: AuthData;
+
+ // New structure: Clear tokens within auth_data
+ newAuthData = {
+ ...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 (newAuthData.expires_in === undefined) {
+ delete newAuthData.expires_in;
}
- // Save the updated settings
- const saveResult = await saveTeamSettingsObj({
- req,
- settingKey: 'oauth',
- entryId,
- data: updatedData, // Save the structure with cleared tokens
- });
-
- if (!saveResult.success) {
- 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.' });
+ try {
+ const saveResult = await CredentialsService.updateCredential(
+ entryId,
+ 'oauth_connections_creds',
+ {
+ customProperties: {
+ tokens: newAuthData,
+ },
+ },
+ req,
+ );
+ } catch (error) {
+ console.error('Failed to save team settings during sign out:', error?.message);
+ return res.status(500).json({ error: error.message || 'Failed to process Sign out.' });
}
return res.json({ invalidate: true, message: 'Signed out successfully.' });
diff --git a/packages/app/src/builder-ui/components/APICall.class.ts b/packages/app/src/builder-ui/components/APICall.class.ts
index fb2c88d3..3c4bc211 100644
--- a/packages/app/src/builder-ui/components/APICall.class.ts
+++ b/packages/app/src/builder-ui/components/APICall.class.ts
@@ -1,10 +1,9 @@
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,
+ signOutOAuthConnection,
} from '@src/shared/helpers/oauth/oauth-api.helper';
import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import {
@@ -14,16 +13,11 @@ import {
mapInternalToServiceName,
mapServiceNameToInternal,
} from '@src/shared/helpers/oauth/oauth.utils';
-import { hasVaultKeys, resolveVaultKeys } from '@src/shared/helpers/oauth/vault-key-resolver';
import { builderStore } from '../../shared/state_stores/builder/store';
import { COMP_NAMES } from '../config';
-import {
- generateOAuthModalHTML,
- generateOAuthModalLoadingSkeleton,
-} from '../helpers/oauth/oauth-modal.helper';
import { createBadge } from '../ui/badges'; // *** ADDED: Import createBadge ***
import { destroyCodeEditor, toggleMode } from '../ui/dom';
-import { closeTwDialog, twEditValuesWithCallback } from '../ui/tw-dialogs';
+import { renderOAuthCredentialsModal } from '../ui/react-injects';
import { delay, getVaultData, handleKvFieldEditBtn, handleKvFieldEditBtnForParams } from '../utils';
import { attachTooltipV2 } from '../utils/tooltip-wrapper-v2';
import { Workspace } from '../workspace/Workspace.class';
@@ -53,10 +47,6 @@ export class APICall extends Component {
return extractServiceFromConnection(connection);
}
- private getConnectionOauthInfo(connection: any, connectionId?: string): any {
- return getConnectionOauthInfo(connection, connectionId);
- }
-
// private deriveServiceFromOauthInfo(oauthInfo: any): string {
// return deriveServiceFromOauthInfo(oauthInfo);
// }
@@ -65,8 +55,8 @@ export class APICall extends Component {
try {
// console.log('[APICall.prepare] Getting OAuth connections from workspace cache...');
- // Get OAuth connections from workspace cache
- const oauthConnectionsData = await builderStore.getState().getOAuthConnections();
+ // Get OAuth connections from workspace cache with resolved vault keys
+ const oauthConnectionsData = await builderStore.getState().getOAuthConnections(false, true);
// console.log('[APICall.prepare] OAuth connections retrieved from cache:', oauthConnectionsData);
this.oauthConnections = oauthConnectionsData || {};
@@ -581,10 +571,7 @@ export class APICall extends Component {
const selectedConnection = this.oauthConnections[selectedConnectionId];
// console.log('[OAuth Auth] Selected connection:', selectedConnection);
- const synthesizedOauthInfo = this.getConnectionOauthInfo(
- selectedConnection,
- selectedConnectionId,
- );
+ const synthesizedOauthInfo = getConnectionOauthInfo(selectedConnection, selectedConnectionId);
// console.log('[OAuth Auth] Synthesized oauth_info:', synthesizedOauthInfo);
if (!selectedConnection || !synthesizedOauthInfo) {
@@ -1004,24 +991,11 @@ export class APICall extends Component {
return false;
}
- 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];
- }
- }
+ let connectionId: string | null = selectedValue;
+ let selectedConnection: any = getConnectionOauthInfo(
+ this.oauthConnections[selectedValue],
+ selectedValue,
+ );
// If no valid connection was found by ID or name
if (!connectionId || !selectedConnection) {
@@ -1031,11 +1005,8 @@ export class APICall extends Component {
return false;
}
- // 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;
+ let oauth_keys_prefix = selectedConnection?.oauth_keys_prefix;
if (
!oauth_keys_prefix &&
connectionId &&
@@ -1052,13 +1023,13 @@ export class APICall extends Component {
// Call backend checkAuth to get actual authentication status
const authCheckPayload = {
- oauth_keys_prefix: oauth_keys_prefix,
+ oauth_conn_id: connectionId,
};
// console.log(`[checkAuth] Sending auth check request for ${connectionId}`);
try {
- const response = await fetch(`${this.workspace.server}/oauth/checkAuth`, {
+ const response = await fetch(`${this.workspace.server}/oauth/check-auth`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(authCheckPayload),
@@ -1626,7 +1597,7 @@ export class APICall extends Component {
// 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);
+ const selectedOauthInfo = getConnectionOauthInfo(selectedConn, selectedValue);
if (selectedOauthInfo?.service) {
// Store a user-friendly value for legacy consumers
this.data.oauthService = mapInternalToServiceName(selectedOauthInfo.service);
@@ -1649,282 +1620,90 @@ export class APICall extends Component {
private async handleOAuthConnectionAction(currentValue: string) {
const isNone = !currentValue || currentValue === 'None';
- // Fetch existing OAuth connections ONLY when editing to avoid modal delay on "Add New"
+ // Fetch existing OAuth connections for edit mode
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);
+ this.oauthConnections = await builderStore.getState().getOAuthConnections(false, true);
} 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
-
- let 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
- let currentService = currentSettings
- ? mapInternalToServiceName(currentOauthInfo.service)
- : 'None';
- let currentPlatform = currentOauthInfo.platform || '';
-
- // Check if we need to resolve vault keys
- const needsVaultResolution = !isNone && hasVaultKeys(currentOauthInfo);
-
- // Extract values needed for later use in onDOMReady
- let consumerKeyValue = currentOauthInfo.consumerKey || '';
- let consumerSecretValue = currentOauthInfo.consumerSecret || '';
-
- // Generate initial form HTML - use loading skeleton if vault keys need resolution
- let initialFormHTML = needsVaultResolution
- ? generateOAuthModalLoadingSkeleton()
- : generateOAuthModalHTML(currentName, currentPlatform, currentService, currentOauthInfo);
-
- // Show dialog using twEditValuesWithCallback, passing HTML content
- await twEditValuesWithCallback(
- {
- title: isNone ? 'Add OAuth Connection' : 'Edit OAuth Connection',
- content: initialFormHTML,
- onDOMReady: async (dialog) => {
- // If we need to resolve vault keys, do it now
- if (needsVaultResolution) {
- console.log('[OAuth Vault Resolution] Starting vault key resolution...');
- try {
- // Resolve vault keys
- console.log('[OAuth Vault Resolution] Resolving vault keys...');
- currentOauthInfo = await resolveVaultKeys(currentOauthInfo);
- console.log('[OAuth Vault Resolution] Vault keys resolved successfully');
- currentPlatform = currentOauthInfo.platform || '';
- consumerKeyValue = currentOauthInfo.consumerKey || '';
- consumerSecretValue = currentOauthInfo.consumerSecret || '';
-
- // Generate the actual form HTML with resolved values
- const resolvedFormHTML = generateOAuthModalHTML(
- currentName,
- currentPlatform,
- currentService,
- currentOauthInfo,
- );
-
- // Find the content container and update it
- // Try multiple selectors to find the right container
- let contentContainer =
- dialog.querySelector('.tw-dialog-content') ||
- dialog.querySelector('.grid.gap-4.py-4')?.parentElement ||
- dialog.querySelector('[role="document"]') ||
- dialog;
-
- console.log(
- '[OAuth Vault Resolution] Found content container:',
- contentContainer?.className,
- );
-
- if (contentContainer) {
- contentContainer.innerHTML = resolvedFormHTML;
- console.log('[OAuth Vault Resolution] Updated content with resolved values');
- } else {
- console.error('[OAuth Vault Resolution] Could not find content container');
- }
+ }
- // Re-run the setup logic after content is loaded
- this.setupOAuthModalHandlers(
- dialog,
- currentOauthInfo,
- consumerKeyValue,
- consumerSecretValue,
- );
- } catch (error) {
- console.error('Error resolving vault keys:', error);
- errorToast('Failed to load connection details. Please try again.', 'Error', 'alert');
-
- // Show form anyway with placeholders
- const fallbackHTML = generateOAuthModalHTML(
- currentName,
- currentPlatform,
- currentService,
- currentOauthInfo,
- );
-
- let contentContainer =
- dialog.querySelector('.tw-dialog-content') ||
- dialog.querySelector('.grid.gap-4.py-4')?.parentElement ||
- dialog.querySelector('[role="document"]') ||
- dialog;
-
- if (contentContainer) {
- contentContainer.innerHTML = fallbackHTML;
- }
+ // Prepare edit connection data if editing
+ let editConnection: any = undefined;
+
+ if (!isNone && this.oauthConnections[currentValue]) {
+ const currentConnectionRaw = this.oauthConnections[currentValue];
+ const oauthInfo = getConnectionOauthInfo(currentConnectionRaw, currentValue);
+
+ if (oauthInfo) {
+ // Transform to CredentialConnection format expected by modal
+ editConnection = {
+ id: currentValue,
+ name: oauthInfo.name || 'OAuth Connection',
+ provider: oauthInfo.service || 'custom_oauth2',
+ group: 'oauth_connections_creds',
+ credentials: {
+ platform: oauthInfo.platform || '',
+ ...(oauthInfo.clientID && { clientID: oauthInfo.clientID }),
+ ...(oauthInfo.clientSecret && { clientSecret: oauthInfo.clientSecret }),
+ ...(oauthInfo.authorizationURL && { authorizationURL: oauthInfo.authorizationURL }),
+ ...(oauthInfo.tokenURL && { tokenURL: oauthInfo.tokenURL }),
+ ...(oauthInfo.scope && { scope: oauthInfo.scope }),
+ ...(oauthInfo.consumerKey && { consumerKey: oauthInfo.consumerKey }),
+ ...(oauthInfo.consumerSecret && { consumerSecret: oauthInfo.consumerSecret }),
+ ...(oauthInfo.requestTokenURL && { requestTokenURL: oauthInfo.requestTokenURL }),
+ ...(oauthInfo.accessTokenURL && { accessTokenURL: oauthInfo.accessTokenURL }),
+ ...(oauthInfo.userAuthorizationURL && {
+ userAuthorizationURL: oauthInfo.userAuthorizationURL,
+ }),
+ },
+ };
+ }
+ }
- this.setupOAuthModalHandlers(
- dialog,
- currentOauthInfo,
- consumerKeyValue,
- consumerSecretValue,
- );
- }
- } else {
- // No vault keys, setup handlers immediately
- this.setupOAuthModalHandlers(
- dialog,
- currentOauthInfo,
- consumerKeyValue,
- consumerSecretValue,
- );
+ // Open React modal
+ try {
+ const result = await renderOAuthCredentialsModal({
+ editConnection,
+ onSuccess: async (data) => {
+ const connectionId = data.id || `OAUTH_${generateOAuthId()}_TOKENS`;
+
+ const isEdit = !isNone;
+ successToast(
+ isEdit ? 'Connection created successfully' : 'Connection updated successfully',
+ );
+
+ if (isEdit) {
+ // /signOut to let user authenticate again using the new credentials
+ await signOutOAuthConnection(currentValue, true);
}
+
+ // 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();
+ await this.updateAuthenticationButtonState();
},
- 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 || '';
- // Scope is supported for both OAuth2 and Client Credentials
- newOauthInfo.scope = formData.scope || '';
- // Audience is typically used for Client Credentials (e.g., Auth0)
- if (type === 'oauth2_client_credentials') {
- newOauthInfo.audience = formData.audience || '';
- }
- if (type === 'oauth2') {
- // Only for full OAuth2
- newOauthInfo.authorizationURL = formData.authorizationURL || '';
- }
- } 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
- );
+ });
+ } catch (error) {
+ // Modal was closed without saving
+ if (error?.message !== 'Modal closed') {
+ console.error('Error with OAuth modal:', error);
+ errorToast(`Error: ${error?.message}`, 'Error', 'alert');
+ }
+ }
}
// Build OAuth select options from connections with unified name detection and legacy fallback
@@ -2015,8 +1794,8 @@ export class APICall extends Component {
*/
private async updateOAuthConnectionOptions() {
try {
- // Force refresh to get latest connections
- this.oauthConnections = await builderStore.getState().getOAuthConnections();
+ // Force refresh to get latest connections with resolved vault keys
+ this.oauthConnections = await builderStore.getState().getOAuthConnections(true, true);
const componentSpecificId = `OAUTH_${this.uid}_TOKENS`;
diff --git a/packages/app/src/builder-ui/ui/react-injects.tsx b/packages/app/src/builder-ui/ui/react-injects.tsx
index f181e28c..158fe849 100644
--- a/packages/app/src/builder-ui/ui/react-injects.tsx
+++ b/packages/app/src/builder-ui/ui/react-injects.tsx
@@ -20,6 +20,10 @@ import {
} from '@src/react/features/builder/contexts/deployment-sidebar.context';
import ComponentInputEditor from '@src/react/features/builder/modals/ComponentInputEditor';
import { MobileHandler } from '@src/react/features/builder/modals/mobile-warning-modal';
+import {
+ CreateCredentialsModal,
+ type CredentialConnection,
+} from '@src/react/features/credentials/components/create-credentials.modal';
import ConfirmModal from '@src/react/shared/components/ui/modals/ConfirmModal';
import { Spinner } from '@src/react/shared/components/ui/spinner';
import { TooltipProvider } from '@src/react/shared/components/ui/tooltip';
@@ -351,3 +355,69 @@ export function renderMobileHandler({ rootID }: { rootID: string }) {
const root = createRoot(container);
root.render(<MobileHandler platformName="AI Agent Builder" showDismissOption={true} />);
}
+
+/**
+ * Renders OAuth Credentials Modal for APICall component
+ * @param config Configuration for the OAuth credential modal
+ * @returns Promise that resolves with the saved credential or rejects on cancel
+ */
+export async function renderOAuthCredentialsModal({
+ editConnection,
+ onSuccess,
+ onClose,
+}: {
+ editConnection?: CredentialConnection;
+ onSuccess?: (data: {
+ id?: string;
+ name: string;
+ provider: string;
+ credentials: Record<string, string>;
+ isEdit: boolean;
+ }) => void;
+ onClose?: () => void;
+}): Promise<any> {
+ const { root, id } = createOneTimeRoot('oauth-credentials-modal');
+
+ return new Promise((resolve, reject) => {
+ const cleanup = () => {
+ root.unmount();
+ const modalRoot = document.getElementById(id);
+ if (modalRoot) {
+ modalRoot.remove();
+ }
+ };
+
+ const handleSuccess = (data: {
+ id?: string;
+ name: string;
+ provider: string;
+ credentials: Record<string, string>;
+ isEdit: boolean;
+ }) => {
+ if (onSuccess) onSuccess(data);
+ cleanup();
+ resolve(data);
+ };
+
+ const handleClose = () => {
+ if (onClose) onClose();
+ cleanup();
+ reject(new Error('Modal closed'));
+ };
+
+ root.render(
+ <QueryClientProvider client={queryClient}>
+ <TooltipProvider delayDuration={300} skipDelayDuration={100}>
+ <CreateCredentialsModal
+ isOpen={true}
+ onClose={handleClose}
+ onSuccess={handleSuccess}
+ group="oauth_connections_creds"
+ editConnection={editConnection}
+ />
+ </TooltipProvider>
+ </QueryClientProvider>,
+ );
+ });
+}
+
diff --git a/packages/app/src/react/features/credentials/clients/credentials.client.ts b/packages/app/src/react/features/credentials/clients/credentials.client.ts
index f66ec7d8..1e67d40e 100644
--- a/packages/app/src/react/features/credentials/clients/credentials.client.ts
+++ b/packages/app/src/react/features/credentials/clients/credentials.client.ts
@@ -23,9 +23,16 @@ export const credentialsClient = {
/**
* Fetch all credentials for a specific group
*/
- fetchCredentials: async (group: string): Promise<CredentialConnection[]> => {
+ fetchCredentials: async (
+ group: string,
+ options: { resolveVaultKeys?: boolean } = { resolveVaultKeys: false },
+ ): Promise<CredentialConnection[]> => {
try {
- const response = await fetch(`/api/app/credentials?group=${encodeURIComponent(group)}`, {
+ const url = `/api/app/credentials?group=${encodeURIComponent(group)}${
+ options.resolveVaultKeys ? '&resolveVaultKeys=true' : ''
+ }`;
+
+ const response = await fetch(url, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
@@ -48,10 +55,14 @@ export const credentialsClient = {
/**
* Fetch a single credential by ID
*/
- fetchCredentialById: async (id: string, group: string): Promise<CredentialConnection> => {
+ fetchCredentialById: async (
+ id: string,
+ group: string,
+ options: { resolveVaultKeys: boolean } = { resolveVaultKeys: false },
+ ): Promise<CredentialConnection> => {
try {
const response = await fetch(
- `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}`,
+ `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}${options.resolveVaultKeys ? '&resolveVaultKeys=true' : ''}`,
{
method: 'GET',
headers: {
@@ -178,7 +189,7 @@ export const credentialsClient = {
): Promise<{ success: boolean; warnings?: string[] }> => {
try {
const url = `/api/app/credentials/${encodeURIComponent(id)}?group=${encodeURIComponent(group)}${consentedWarnings ? '&consentedWarnings=true' : ''}`;
-
+
const response = await fetch(url, {
method: 'DELETE',
headers: {
diff --git a/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx b/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx
index 09004d3f..ab3e4b50 100644
--- a/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx
+++ b/packages/app/src/react/features/credentials/components/create-credentials.modal.tsx
@@ -17,6 +17,7 @@ import {
} from '@src/react/shared/components/ui/dialog';
import { Input } from '@src/react/shared/components/ui/input';
import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { TextArea } from '@src/react/shared/components/ui/newDesign/textarea';
import {
Select,
SelectContent,
@@ -27,7 +28,9 @@ import {
import React, { useEffect, useMemo, useState } from 'react';
import { credentialsClient } from '../clients/credentials.client';
import credentialsSchema from '../credentials-schema.json';
+import { parseCredsShemaPlaceholders } from '../utils';
import { CredentialFormSkeleton } from './credential-form-skeleton';
+import { PasswordInput } from './password-input';
/**
* Field schema definition from credentials-schema.json
@@ -35,9 +38,10 @@ import { CredentialFormSkeleton } from './credential-form-skeleton';
interface CredentialField {
key: string;
label: string;
- type: 'string' | 'password' | 'number' | 'email' | 'url';
+ type: 'string' | 'password' | 'number' | 'email' | 'url' | 'textarea';
required: boolean;
placeholder?: string;
+ default?: string;
}
/**
@@ -53,6 +57,11 @@ interface ProviderSchema {
fields: CredentialField[];
docs_url?: string;
test_endpoint?: string;
+
+ metadata?: {
+ requires_callback?: boolean;
+ callback_path?: string;
+ };
}
/**
@@ -67,6 +76,7 @@ export interface CredentialConnection {
isActive?: boolean;
isReadOnly?: boolean;
isManaged?: boolean;
+ customProperties?: Record<string, any>;
}
/**
@@ -219,12 +229,13 @@ export function CreateCredentialsModal({
*/
const handleProviderSelect = (providerId: string) => {
setSelectedProviderId(providerId);
- // Initialize credentials object with empty values
+ // Initialize credentials object with default values or empty strings
const provider = availableProviders.find((p) => p.id === providerId);
if (provider) {
const initialCredentials: Record<string, string> = {};
provider.fields.forEach((field) => {
- initialCredentials[field.key] = '';
+ // Use default value if available in create mode, otherwise empty string
+ initialCredentials[field.key] = field.default || '';
});
setCredentials(initialCredentials);
}
@@ -342,6 +353,7 @@ export function CreateCredentialsModal({
name: connectionName,
provider: selectedProviderId,
credentials: credentialsWithMetadata,
+ authType: selectedProvider.auth_type,
};
let result;
@@ -537,21 +549,63 @@ export function CreateCredentialsModal({
{/* Dynamic Fields */}
{selectedProvider.fields.map((field) => (
<div key={field.key}>
- <Input
- label={field.label}
- required={field.required}
- fullWidth
- type={getInputType(field.type)}
- placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
- value={credentials[field.key] || ''}
- onChange={(e) => handleCredentialChange(field.key, e.target.value)}
- onBlur={() => handleBlur(field.key)}
- error={touched[field.key] && !!errors[field.key]}
- errorMessage={errors[field.key]}
- disabled={isProcessing || isResolvingVaultKeys}
- />
+ {field.type === 'textarea' ? (
+ <TextArea
+ label={field.label}
+ required={field.required}
+ fullWidth
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ value={credentials[field.key] || ''}
+ onChange={(e) => handleCredentialChange(field.key, e.target.value)}
+ onBlur={() => handleBlur(field.key)}
+ error={touched[field.key] && !!errors[field.key]}
+ errorMessage={errors[field.key]}
+ disabled={isProcessing || isResolvingVaultKeys}
+ rows={3}
+ autoGrow={true}
+ maxHeight={200}
+ />
+ ) : field.type === 'password' ? (
+ <PasswordInput
+ label={field.label}
+ required={field.required}
+ fullWidth
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ value={credentials[field.key] || ''}
+ onChange={(e) => handleCredentialChange(field.key, e.target.value)}
+ onBlur={() => handleBlur(field.key)}
+ error={touched[field.key] && !!errors[field.key]}
+ errorMessage={errors[field.key]}
+ disabled={isProcessing || isResolvingVaultKeys}
+ />
+ ) : (
+ <Input
+ label={field.label}
+ required={field.required}
+ fullWidth
+ type={getInputType(field.type)}
+ placeholder={field.placeholder || `Enter ${field.label.toLowerCase()}`}
+ value={credentials[field.key] || ''}
+ onChange={(e) => handleCredentialChange(field.key, e.target.value)}
+ onBlur={() => handleBlur(field.key)}
+ error={touched[field.key] && !!errors[field.key]}
+ errorMessage={errors[field.key]}
+ disabled={isProcessing || isResolvingVaultKeys}
+ />
+ )}
</div>
))}
+
+ {selectedProvider.metadata?.callback_path && (
+ <div>
+ <p className="mt-2 text-sm">
+ <span className="font-medium">Callback Path: </span>
+ <span className="text-gray-500">
+ {parseCredsShemaPlaceholders(selectedProvider.metadata.callback_path)}
+ </span>
+ </p>
+ </div>
+ )}
</div>
)}
</div>
diff --git a/packages/app/src/react/features/credentials/components/password-input.tsx b/packages/app/src/react/features/credentials/components/password-input.tsx
new file mode 100644
index 00000000..304d1d3a
--- /dev/null
+++ b/packages/app/src/react/features/credentials/components/password-input.tsx
@@ -0,0 +1,97 @@
+/**
+ * PasswordInput Component
+ *
+ * A password input field with visibility toggle functionality
+ * - Shows password as visible text by default
+ * - Beautiful eye/eye-off toggle button on the right
+ * - Matches the design system styling
+ *
+ * @component
+ */
+
+import { Eye, EyeOff } from 'lucide-react';
+import React, { useState } from 'react';
+
+export interface PasswordInputProps {
+ label: string;
+ required?: boolean;
+ fullWidth?: boolean;
+ placeholder?: string;
+ value: string;
+ onChange: (e: React.ChangeEvent<HTMLInputElement>) => void;
+ onBlur: () => void;
+ error?: boolean;
+ errorMessage?: string;
+ disabled?: boolean;
+}
+
+export const PasswordInput: React.FC<PasswordInputProps> = ({
+ label,
+ required,
+ fullWidth,
+ placeholder,
+ value,
+ onChange,
+ onBlur,
+ error,
+ errorMessage,
+ disabled,
+}) => {
+ const [isVisible, setIsVisible] = useState(true);
+
+ return (
+ <div className={`${fullWidth ? 'w-full' : ''}`}>
+ {label && (
+ <div className="text-gray-700 mb-1 text-sm font-normal flex items-center">
+ {label} {required && <span className="text-red-500 mr-1">*</span>}
+ </div>
+ )}
+ <div className={`relative ${fullWidth ? 'w-full' : 'w-fit'}`}>
+ <input
+ type={isVisible ? 'text' : 'password'}
+ className={`h-[42px] w-full bg-white border text-gray-900 rounded block outline-none focus:outline-none focus:ring-0 focus:ring-offset-0 focus:ring-shadow-none text-sm font-light placeholder:text-sm placeholder:font-normal pr-10 pl-[10px] ${
+ error
+ ? '!border-[#C50F1F] focus:border-[#C50F1F]'
+ : 'border-gray-300 border-b-gray-500 focus:border-b-2 focus:border-b-blue-500 focus-visible:border-b-2 focus-visible:border-b-blue-500'
+ } ${disabled ? 'bg-gray-50 cursor-not-allowed' : ''}`}
+ placeholder={placeholder}
+ value={value}
+ onChange={onChange}
+ onBlur={onBlur}
+ disabled={disabled}
+ />
+ <button
+ type="button"
+ onClick={() => setIsVisible(!isVisible)}
+ className="absolute inset-y-0 right-0 flex items-center pr-3 text-gray-500 hover:text-gray-700 focus:outline-none transition-colors duration-150"
+ tabIndex={-1}
+ disabled={disabled}
+ aria-label={isVisible ? 'Hide password' : 'Show password'}
+ >
+ {isVisible ? (
+ <EyeOff className="w-5 h-5" />
+ ) : (
+ <Eye className="w-5 h-5" />
+ )}
+ </button>
+ </div>
+ {error && errorMessage && (
+ <div className="flex items-start mt-[2px]">
+ <svg
+ className="w-[10px] h-[10px] mt-[3px] mr-1 text-red-500"
+ fill="currentColor"
+ viewBox="0 0 20 20"
+ >
+ <path
+ fillRule="evenodd"
+ d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7 4a1 1 0 11-2 0 1 1 0 012 0zm-1-9a1 1 0 00-1 1v4a1 1 0 102 0V6a1 1 0 00-1-1z"
+ clipRule="evenodd"
+ />
+ </svg>
+ <p className="text-[12px] text-red-500 font-normal">{errorMessage}</p>
+ </div>
+ )}
+ </div>
+ );
+};
+
diff --git a/packages/app/src/react/features/credentials/credentials-schema.json b/packages/app/src/react/features/credentials/credentials-schema.json
index b27ccbc1..0429d90a 100644
--- a/packages/app/src/react/features/credentials/credentials-schema.json
+++ b/packages/app/src/react/features/credentials/credentials-schema.json
@@ -50,5 +50,313 @@
],
"docs_url": "https://milvus.io/",
"test_endpoint": "https://milvus.io/"
+ },
+ {
+ "id": "google",
+ "name": "Google",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth2",
+ "description": "Connect to Google services using OAuth 2.0",
+ "logo_url": "https://www.google.com/favicon.ico",
+ "docs_url": "https://developers.google.com/identity/protocols/oauth2",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/google/callback",
+ "requires_callback": true
+ },
+ "fields": [
+
+ {
+ "key": "authorizationURL",
+ "label": "Authorization URL",
+ "type": "string",
+ "required": true,
+ "default": "https://accounts.google.com/o/oauth2/v2/auth"
+ },
+ {
+ "key": "tokenURL",
+ "label": "Token URL",
+ "type": "url",
+ "required": true,
+ "default": "https://oauth2.googleapis.com/token"
+ },
+ {
+ "key": "clientID",
+ "label": "Client ID",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Google Client ID"
+ },
+ {
+ "key": "clientSecret",
+ "label": "Client Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Google Client Secret"
+ },
+ {
+ "key": "scope",
+ "label": "Scopes",
+ "type": "textarea",
+ "required": true,
+ "default": "https://www.googleapis.com/auth/gmail.readonly",
+ "placeholder": "Space-separated list of scopes"
+ }
+ ]
+ },
+ {
+ "id": "linkedin",
+ "name": "LinkedIn",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth2",
+ "description": "Connect to LinkedIn using OAuth 2.0",
+ "logo_url": "https://www.linkedin.com/favicon.ico",
+ "docs_url": "https://docs.microsoft.com/en-us/linkedin/shared/authentication/authentication",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/linkedin/callback",
+ "requires_callback": true
+ },
+ "fields": [
+
+
+ {
+ "key": "authorizationURL",
+ "label": "Authorization URL",
+ "type": "url",
+ "required": true,
+ "default": "https://www.linkedin.com/oauth/v2/authorization"
+ },
+ {
+ "key": "tokenURL",
+ "label": "Token URL",
+ "type": "url",
+ "required": true,
+ "default": "https://www.linkedin.com/oauth/v2/accessToken"
+ },
+ {
+ "key": "clientID",
+ "label": "Client ID",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your LinkedIn Client ID"
+ },
+ {
+ "key": "clientSecret",
+ "label": "Client Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your LinkedIn Client Secret"
+ },
+ {
+ "key": "scope",
+ "label": "Scopes",
+ "type": "textarea",
+ "required": true,
+ "default": "r_liteprofile r_emailaddress",
+ "placeholder": "Space-separated list of scopes"
+ }
+ ]
+ },
+ {
+ "id": "twitter",
+ "name": "Twitter",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth",
+ "description": "Connect to Twitter using OAuth 1.0a",
+ "logo_url": "https://twitter.com/favicon.ico",
+ "docs_url": "https://developer.twitter.com/en/docs/authentication/oauth-1-0a",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/twitter/callback",
+ "requires_callback": true
+ },
+ "fields": [
+
+ {
+ "key": "requestTokenURL",
+ "label": "Request Token URL",
+ "type": "url",
+ "required": true,
+ "default": "https://api.twitter.com/oauth/request_token"
+ },
+ {
+ "key": "accessTokenURL",
+ "label": "Access Token URL",
+ "type": "url",
+ "required": true,
+ "default": "https://api.twitter.com/oauth/access_token"
+ },
+ {
+ "key": "userAuthorizationURL",
+ "label": "User Authorization URL",
+ "type": "url",
+ "required": true,
+ "default": "https://api.twitter.com/oauth/authorize"
+ },
+ {
+ "key": "consumerKey",
+ "label": "Consumer Key",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Twitter Consumer Key"
+ },
+ {
+ "key": "consumerSecret",
+ "label": "Consumer Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Twitter Consumer Secret"
+ }
+ ]
+ },
+ {
+ "id": "custom_oauth2",
+ "name": "Custom OAuth2.0",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth2",
+ "description": "Connect to any service using custom OAuth 2.0 configuration",
+ "logo_url": null,
+ "docs_url": "https://oauth.net/2/",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/oauth2/callback",
+ "requires_callback": true
+ },
+ "fields": [
+
+ {
+ "key": "authorizationURL",
+ "label": "Authorization URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/authorize"
+ },
+ {
+ "key": "tokenURL",
+ "label": "Token URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/token"
+ },
+ {
+ "key": "clientID",
+ "label": "Client ID",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Client ID"
+ },
+ {
+ "key": "clientSecret",
+ "label": "Client Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Client Secret"
+ },
+ {
+ "key": "scope",
+ "label": "Scopes",
+ "type": "textarea",
+ "required": true,
+ "placeholder": "Space-separated list of scopes"
+ }
+ ]
+ },
+ {
+ "id": "custom_oauth1",
+ "name": "Custom OAuth1.0",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth",
+ "description": "Connect to any service using custom OAuth 1.0a configuration",
+ "logo_url": null,
+ "docs_url": "https://oauth.net/core/1.0a/",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/oauth1/callback",
+ "requires_callback": true
+ },
+ "fields": [
+ {
+ "key": "requestTokenURL",
+ "label": "Request Token URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/request_token"
+ },
+ {
+ "key": "accessTokenURL",
+ "label": "Access Token URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/access_token"
+ },
+ {
+ "key": "userAuthorizationURL",
+ "label": "User Authorization URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/authorize"
+ },
+ {
+ "key": "consumerKey",
+ "label": "Consumer Key",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Consumer Key"
+ },
+ {
+ "key": "consumerSecret",
+ "label": "Consumer Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Consumer Secret"
+ }
+ ]
+ },
+ {
+ "id": "oauth2_client_credentials",
+ "name": "OAuth2 Client Credentials",
+ "group": "oauth_connections_creds",
+ "auth_type": "oauth2_client_credentials",
+ "description": "Connect using OAuth 2.0 Client Credentials flow (server-to-server)",
+ "logo_url": null,
+ "docs_url": "https://oauth.net/2/grant-types/client-credentials/",
+ "metadata": {
+ "callback_path": "{{BASE_URL}}/oauth/oauth2/callback",
+ "requires_callback": false
+ },
+ "fields": [
+
+ {
+ "key": "tokenURL",
+ "label": "Token URL",
+ "type": "url",
+ "required": true,
+ "placeholder": "https://provider.com/oauth/token"
+ },
+ {
+ "key": "clientID",
+ "label": "Client ID",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Client ID"
+ },
+ {
+ "key": "clientSecret",
+ "label": "Client Secret",
+ "type": "password",
+ "required": true,
+ "placeholder": "Enter your Client Secret"
+ },
+ {
+ "key": "scope",
+ "label": "Scopes",
+ "type": "textarea",
+ "required": false,
+ "placeholder": "Space-separated list of scopes (optional)"
+ },
+ {
+ "key": "audience",
+ "label": "Audience",
+ "type": "string",
+ "required": false,
+ "placeholder": "Audience URL"
+ }
+ ]
}
- ]
\ No newline at end of file
+ ]
diff --git a/packages/app/src/react/features/credentials/hooks/use-credentials.ts b/packages/app/src/react/features/credentials/hooks/use-credentials.ts
index 58324f2d..761d44ea 100644
--- a/packages/app/src/react/features/credentials/hooks/use-credentials.ts
+++ b/packages/app/src/react/features/credentials/hooks/use-credentials.ts
@@ -6,7 +6,7 @@
* @module use-credentials
*/
-import { useEffect, useMemo, useState } from 'react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
import { credentialsClient } from '../clients/credentials.client';
import type { CredentialConnection } from '../components/create-credentials.modal';
@@ -56,7 +56,7 @@ export function useCredentials(group: string) {
try {
const data = await credentialsClient.fetchCredentials(group);
- const internalCreds = INTERNAL_CREDENTIALS[group];
+ const internalCreds = INTERNAL_CREDENTIALS[group] || [];
setCredentials([...internalCreds, ...data]);
} catch (err: any) {
console.error('Error fetching credentials:', err);
@@ -75,7 +75,7 @@ export function useCredentials(group: string) {
// Sort alphabetically by name
const sortedCredentials = useMemo(() => {
return [...credentials].sort((a, b) =>
- a.name.localeCompare(b.name, undefined, { sensitivity: 'base' }),
+ (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' }),
);
}, [credentials]);
@@ -103,11 +103,36 @@ export function useCredentials(group: string) {
* const { credential, isLoading, error } = useCredentialById('cred-1', 'vector_database');
* ```
*/
-export function useCredentialById(id: string, group: string) {
+export function useCredentialById(
+ id: string,
+ group: string,
+ options: { lazy?: boolean; resolveVaultKeys?: boolean } = {
+ lazy: false,
+ resolveVaultKeys: false,
+ },
+) {
const [credential, setCredential] = useState<CredentialConnection | undefined>(undefined);
- const [isLoading, setIsLoading] = useState<boolean>(true);
+ const [isLoading, setIsLoading] = useState<boolean>(options.lazy ? false : true);
const [error, setError] = useState<string | undefined>(undefined);
+ const fetchCredential = useCallback(async () => {
+ setIsLoading(true);
+ setError(undefined);
+
+ try {
+ const data = await credentialsClient.fetchCredentialById(id, group, {
+ resolveVaultKeys: options.resolveVaultKeys ?? false,
+ });
+ setCredential(data);
+ } catch (err: any) {
+ console.error('Error fetching credential:', err);
+ setError(err.message || 'Failed to fetch credential');
+ setCredential(undefined);
+ } finally {
+ setIsLoading(false);
+ }
+ }, [id, group]);
+
useEffect(() => {
if (!id || !group) {
setCredential(undefined);
@@ -115,29 +140,27 @@ export function useCredentialById(id: string, group: string) {
return;
}
- const fetchCredential = async () => {
- setIsLoading(true);
- setError(undefined);
-
- try {
- const data = await credentialsClient.fetchCredentialById(id, group);
- setCredential(data);
- } catch (err: any) {
- console.error('Error fetching credential:', err);
- setError(err.message || 'Failed to fetch credential');
- setCredential(undefined);
- } finally {
- setIsLoading(false);
- }
- };
-
- fetchCredential();
- }, [id, group]);
+ if (!options.lazy) {
+ fetchCredential();
+ }
+ }, [id, group, options.lazy, fetchCredential]);
+
+ // const fireFetch = useCallback(() => {
+ // fetchCredential();
+ // }, [fetchCredential]);
+
+ const getData = useCallback(async () => {
+ if (options.lazy && !credential && !error && !isLoading) {
+ await fetchCredential();
+ }
+ return credential;
+ }, [options.lazy, fetchCredential, credential, error, isLoading]);
return {
- credential,
+ // credential,
isLoading,
error,
+ getData,
};
}
diff --git a/packages/app/src/react/features/credentials/utils.ts b/packages/app/src/react/features/credentials/utils.ts
new file mode 100644
index 00000000..b3a1d731
--- /dev/null
+++ b/packages/app/src/react/features/credentials/utils.ts
@@ -0,0 +1,13 @@
+const availableVars = {
+ BASE_URL: window.location.origin,
+};
+export function parseCredsShemaPlaceholders(path: string) {
+ if (!path) return '';
+
+ return path.replace(/{{\s*(.*?)\s*}}/g, (match, key) => {
+ const varName = key.trim();
+ const value = availableVars[varName as keyof typeof availableVars];
+
+ return value !== undefined ? String(value) : match;
+ });
+}
diff --git a/packages/app/src/react/features/vault/components/oauth-connection-row.tsx b/packages/app/src/react/features/vault/components/oauth-connection-row.tsx
new file mode 100644
index 00000000..9cbabe1d
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/oauth-connection-row.tsx
@@ -0,0 +1,287 @@
+/**
+ * OAuthConnectionRow Component
+ *
+ * Handles a single OAuth connection row with its own authentication state and actions.
+ *
+ * @component
+ */
+
+import { Button } from '@src/react/shared/components/ui/button';
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@src/react/shared/components/ui/tooltip';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { Circle, Pencil, Trash2 } from 'lucide-react';
+import { useCallback, useEffect, useRef, useState } from 'react';
+import type { CredentialConnection } from '../../credentials/components/create-credentials.modal';
+import credentialsSchema from '../../credentials/credentials-schema.json';
+import { useCredentialById } from '../../credentials/hooks/use-credentials';
+import {
+ useAuthenticateClientCredentials,
+ useCheckAuthStatus,
+ useInitiateOAuth,
+ useSignOutOAuth,
+} from '../components/use-oauth-creds';
+import { OAuthInfo } from '../types/oauth-connection';
+
+
+
+
+// --- Helper Functions ---
+
+/**
+ * Build OAuth info object from credential connection
+ */
+
+const PROVIDER_TO_SERVICE_MAP: Record<string, string> = {
+ google: 'google',
+ linkedin: 'linkedin',
+ twitter: 'twitter',
+ custom_oauth2: 'oauth2',
+ custom_oauth1: 'oauth1',
+ oauth2_client_credentials: 'oauth2_client_credentials',
+};
+function buildOAuthInfoFromCred(connection: CredentialConnection): OAuthInfo | null {
+ if (!connection ||!connection.credentials || !connection.id) return null;
+
+ const service = PROVIDER_TO_SERVICE_MAP[connection.provider] || connection.provider;
+
+ const oauthInfo: OAuthInfo = {
+ oauth_keys_prefix: connection.id,
+ service,
+ name: connection.name,
+ platform: connection.credentials.platform || '',
+ ...connection.credentials,
+ };
+
+ oauthInfo.tokens = connection.customProperties?.tokens;
+
+ return oauthInfo;
+}
+
+
+
+
+
+
+/**
+ * Get provider display info from schema
+ */
+function getProviderInfo(providerId: string) {
+ const provider = (credentialsSchema as Array<{ id: string; name: string; logo_url?: string }>)
+ .find((p) => p.id === providerId);
+
+ return {
+ name: provider?.name || providerId,
+ logoUrl: provider?.logo_url,
+ };
+}
+
+// --- Component Props ---
+interface OAuthConnectionRowProps {
+ connection: CredentialConnection;
+ onEdit: (connection: CredentialConnection) => void;
+ onDelete: (connection: CredentialConnection) => void;
+ onAuthStatusChange?: (isAuthenticated: boolean) => void;
+}
+
+/**
+ * OAuthConnectionRow Component
+ */
+export function OAuthConnectionRow({ connection, onEdit, onDelete, onAuthStatusChange }: OAuthConnectionRowProps) {
+ const [isProcessing, setIsProcessing] = useState(false);
+ const hasCheckedAuth = useRef(false);
+ const [isAuthenticated, setIsAuthenticated] = useState(false);
+
+ const providerInfo = getProviderInfo(connection.provider);
+
+ // --- OAuth Mutations ---
+ const checkAuthMutation = useCheckAuthStatus();
+ const initiateAuthMutation = useInitiateOAuth();
+ const signOutMutation = useSignOutOAuth();
+ const authenticateClientCredsMutation = useAuthenticateClientCredentials();
+
+
+const {getData} = useCredentialById(connection.id, 'oauth_connections_creds', { lazy: true, resolveVaultKeys: true });
+
+const getOAuthFullInfo = useCallback(async () => {
+ const oauthFullCredRecord = await getData();
+ return buildOAuthInfoFromCred(oauthFullCredRecord);
+}, [getData]);
+
+ // Check authentication status on mount (only once)
+ useEffect(() => {
+ async function fetch() {
+ const oauthInfo = await getOAuthFullInfo();
+ if (hasCheckedAuth.current || !oauthInfo) return;
+
+ // Skip client credentials and already authenticated
+ if (oauthInfo.service === 'oauth2_client_credentials') return;
+ if (typeof connection.isActive === 'boolean') return;
+
+ hasCheckedAuth.current = true;
+ checkAuthMutation.mutate(oauthInfo);
+ }
+
+
+ fetch();
+ }, [connection, checkAuthMutation, getOAuthFullInfo]);
+
+ useEffect(() => {
+ async function isActiveFetch() {
+ const oauthInfo = await getOAuthFullInfo();
+ // const isActive = isConnectionActive(oauthInfo);
+ if (typeof oauthInfo.isActive === 'boolean') return oauthInfo.isActive;
+
+ // const isClientCreds = oauthInfo?.service.includes('oauth');
+ const _isActive = Boolean((oauthInfo?.tokens as any)?.primary);
+ setIsAuthenticated(_isActive);
+ }
+
+ isActiveFetch();
+
+ }, [connection, getOAuthFullInfo]);
+
+ // --- Event Handlers ---
+ const handleAuthenticateClick = async () => {
+ if (!connection.id) {
+ errorToast('OAuth configuration not found for this connection.');
+ return;
+ }
+
+ setIsProcessing(true);
+ try {
+ const oauthInfo = await getOAuthFullInfo();
+ if (oauthInfo.service === 'oauth2_client_credentials') {
+ await authenticateClientCredsMutation.mutateAsync(oauthInfo);
+ successToast('Authenticated! Client Credentials authentication was successful.');
+ setIsAuthenticated(true);
+ onAuthStatusChange && onAuthStatusChange(true);
+ } else {
+ await initiateAuthMutation.mutateAsync(oauthInfo);
+ }
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Unknown error';
+ errorToast(`Could not start authentication: ${errorMessage}`);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ const handleSignOutClick = async () => {
+ setIsProcessing(true);
+ try {
+ await signOutMutation.mutateAsync({ connectionId: connection.id });
+ successToast('Successfully signed out.');
+ hasCheckedAuth.current = false; // Allow re-checking
+ setIsAuthenticated(false);
+ onAuthStatusChange && onAuthStatusChange(false);
+ } catch (err) {
+ const errorMessage = err instanceof Error ? err.message : 'Unknown error';
+ errorToast(`Failed to sign out: ${errorMessage}`);
+ } finally {
+ setIsProcessing(false);
+ }
+ };
+
+ // const isCheckingStatus = checkAuthMutation.isLoading &&
+ // oauthInfo &&
+ // checkAuthMutation.variables?.oauth_keys_prefix === oauthInfo.oauth_keys_prefix;
+
+ const isDisabled = isProcessing ||
+ signOutMutation.isLoading ||
+ initiateAuthMutation.isLoading ||
+ authenticateClientCredsMutation.isLoading;
+
+ // --- Render ---
+ return (
+ <tr className="border-t">
+ {/* Connection Name */}
+ <td className="pr-4 py-3 truncate" title={connection.name}>
+ <div className="flex items-center gap-2">
+ <span className="font-medium">{connection.name}</span>
+ {connection.isManaged && (
+ <span
+ className="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-semibold bg-gradient-to-r from-blue-100 to-purple-100 text-blue-700 border border-blue-200 shadow-sm"
+ title="This is an internal connection automatically managed by SmythOS"
+ >
+ <svg className="w-3 h-3 mr-1 text-blue-400" fill="currentColor" viewBox="0 0 20 20">
+ <path d="M10 2a8 8 0 100 16 8 8 0 000-16zm.93 12.412a.75.75 0 11-1.86 0l-1.406-5.624A.75.75 0 017.38 7h5.24a.75.75 0 01.716.788l-1.406 5.624zm-.93-7.162a1 1 0 110-2 1 1 0 010 2z" />
+ </svg>
+ Managed
+ </span>
+ )}
+ </div>
+ </td>
+
+ {/* Provider */}
+ <td className="px-4 py-3" title={providerInfo.name}>
+ <div className="flex items-center gap-2">
+ {providerInfo.logoUrl && (
+ <img src={providerInfo.logoUrl} alt={providerInfo.name} className="w-5 h-5 object-contain" />
+ )}
+ <span className="truncate">{providerInfo.name}</span>
+ </div>
+ </td>
+
+ {/* Status */}
+ <td className="px-4 py-3">
+ <div className="flex" title={isAuthenticated ? 'Active' : 'Inactive'}>
+ {/* {isCheckingStatus ? (
+ <div className="animate-spin rounded-full h-3 w-3 border-t-2 border-b-2 border-gray-400" title="Checking..." />
+ ) : (
+ )} */}
+ <Circle className={`h-3 w-3 ${isAuthenticated ? 'fill-green-500 text-green-500' : 'fill-gray-400 text-gray-400'}`} />
+ </div>
+ </td>
+
+ {/* Actions */}
+ {!connection.isReadOnly && (
+ <td className="pl-4 py-3">
+ <div className="flex items-center justify-end gap-1">
+ {/* Authentication Button */}
+ {connection.id && (
+ isAuthenticated ? (
+ <CustomButton
+ variant="secondary"
+ handleClick={handleSignOutClick}
+ disabled={isDisabled}
+ label="Sign Out"
+ className="h-8 px-3 text-xs whitespace-nowrap"
+ />
+ ) : (
+ <CustomButton
+ variant="secondary"
+ handleClick={handleAuthenticateClick}
+ disabled={isDisabled}
+ label="Authenticate"
+ className="h-8 px-3 text-xs whitespace-nowrap"
+ />
+ )
+ )}
+
+ {/* Edit Button */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="sm" onClick={() => onEdit(connection)} disabled={isDisabled}>
+ <Pencil className="h-4 w-4" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent><p>Edit</p></TooltipContent>
+ </Tooltip>
+
+ {/* Delete Button */}
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Button variant="ghost" size="sm" onClick={() => onDelete(connection)} disabled={isDisabled}>
+ <Trash2 className="h-4 w-4 hover:text-red-500" />
+ </Button>
+ </TooltipTrigger>
+ <TooltipContent><p>Delete</p></TooltipContent>
+ </Tooltip>
+ </div>
+ </td>
+ )}
+ </tr>
+ );
+}
+
diff --git a/packages/app/src/react/features/vault/components/oauth-connections-creds.tsx b/packages/app/src/react/features/vault/components/oauth-connections-creds.tsx
new file mode 100644
index 00000000..4bbafc2a
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/oauth-connections-creds.tsx
@@ -0,0 +1,209 @@
+/**
+ * OAuthConnectionsCredentials Component
+ *
+ * Main container for displaying and managing OAuth credential connections.
+ *
+ * @component
+ */
+
+import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button';
+import { Tooltip, TooltipContent, TooltipTrigger } from '@src/react/shared/components/ui/tooltip';
+import { errorToast, successToast } from '@src/shared/components/toast';
+import { signOutOAuthConnection } from '@src/shared/helpers/oauth/oauth-api.helper';
+import { getBackendOrigin } from '@src/shared/helpers/oauth/oauth.utils';
+import { Info, PlusCircle } from 'lucide-react';
+import { useCallback, useEffect, useMemo, useState } from 'react';
+import {
+ CreateCredentialsModal,
+ type CredentialConnection,
+} from '../../credentials/components/create-credentials.modal';
+import { CredentialsListSkeleton } from '../../credentials/components/credentials-list-skeleton';
+import { DeleteCredentialsModal } from '../../credentials/components/delete-credentials.modal';
+import { useCredentials } from '../../credentials/hooks/use-credentials';
+import { OAuthConnectionRow } from './oauth-connection-row';
+
+/**
+ * OAuthConnectionsCredentials Component
+ */
+export function OAuthConnectionsCredentials() {
+ // --- State ---
+ const [isCreateModalOpen, setIsCreateModalOpen] = useState(false);
+ const [editingConnection, setEditingConnection] = useState<CredentialConnection | undefined>();
+ const [deletingConnection, setDeletingConnection] = useState<CredentialConnection | undefined>();
+
+ const {
+ credentials: allCredentials,
+ isLoading,
+ refetch,
+ } = useCredentials('oauth_connections_creds');
+
+ const credentials = useMemo(() => {
+ if (!allCredentials) return [];
+
+ return allCredentials.filter((c) => !c.customProperties?._isHidden);
+ }, [allCredentials]);
+
+ // --- Authentication Message Handler ---
+ const handleAuthTabMessage = useCallback(
+ (event: MessageEvent) => {
+ const allowedOrigins = new Set([window.location.origin, getBackendOrigin()]);
+
+ if (!allowedOrigins.has(event.origin)) return;
+
+ const { type, data } = event.data || {};
+ console.log('[handleAuthTabMessage] Message received:', event.data);
+
+ if (type === 'oauth' || type === 'oauth2') {
+ successToast('Authentication successful!');
+ refetch();
+ } else if (type === 'error') {
+ errorToast(`Authentication Error: ${data?.message || 'An unknown error occurred'}`);
+ }
+ },
+ [refetch],
+ );
+
+ // --- Effects ---
+ useEffect(() => {
+ window.addEventListener('message', handleAuthTabMessage);
+ return () => window.removeEventListener('message', handleAuthTabMessage);
+ }, [handleAuthTabMessage]);
+
+ // --- Event Handlers ---
+ const handleSuccess = async (data: {
+ id?: string;
+ name: string;
+ provider: string;
+ credentials: Record<string, string>;
+ isEdit: boolean;
+ }) => {
+ successToast(
+ data.isEdit ? 'Connection updated successfully.' : 'Connection created successfully.',
+ );
+
+ if (data.isEdit) {
+ // /signOut to let user authenticate again using the new credentials
+ await signOutOAuthConnection(data.id, true);
+ }
+ setEditingConnection(undefined);
+ refetch();
+ };
+
+ const handleEditClick = (connection: CredentialConnection) => {
+ setEditingConnection(connection);
+ setIsCreateModalOpen(true);
+ };
+
+ const handleDeleteClick = (connection: CredentialConnection) => {
+ setDeletingConnection(connection);
+ };
+
+ const handleDeleteSuccess = () => {
+ setDeletingConnection(undefined);
+ refetch();
+ };
+
+ const handleModalClose = () => {
+ setIsCreateModalOpen(false);
+ setEditingConnection(undefined);
+ };
+
+ // const handleAuthSuccess = () => {
+ // refetch();
+ // };
+
+ // --- Render ---
+ return (
+ <div
+ id="oauth-connections-credentials"
+ className="rounded-lg bg-card text-card-foreground border border-solid border-gray-200 shadow-sm"
+ >
+ <div className="p-6">
+ {/* Header */}
+ <div className="flex items-center justify-between mb-4 pr-2 flex-wrap">
+ <h2 className="flex items-center gap-2 text-lg font-semibold">
+ OAuth Connections
+ <Tooltip>
+ <TooltipTrigger asChild>
+ <Info className="w-4 h-4 cursor-help" />
+ </TooltipTrigger>
+ <TooltipContent className="w-72 text-center">
+ <p>Manage connections to OAuth services for storing and retrieving credentials</p>
+ </TooltipContent>
+ </Tooltip>
+ </h2>
+ </div>
+
+ {/* Table */}
+ <div className="overflow-x-auto">
+ {isLoading ? (
+ <CredentialsListSkeleton rows={3} />
+ ) : credentials.length === 0 ? (
+ <div className="py-8 text-center">
+ <p className="text-muted-foreground mb-2">No OAuth connections found</p>
+ <p className="text-sm text-gray-500">Get started by adding your first connection</p>
+ </div>
+ ) : (
+ <table className="w-full min-w-[500px] text-sm text-left table-fixed">
+ <thead className="text-xs text-muted-foreground">
+ <tr>
+ <th className="pr-4 py-2 w-1/4">Connection Name</th>
+ <th className="px-4 py-2 w-1/4">Provider</th>
+ <th className="px-4 py-2 w-1/6">Status</th>
+ <th className="px-4 py-2 w-1/3 text-right">Actions</th>
+ </tr>
+ </thead>
+ <tbody>
+ {credentials.map((connection) => (
+ <OAuthConnectionRow
+ key={connection.id}
+ connection={connection}
+ onEdit={handleEditClick}
+ onDelete={handleDeleteClick}
+ // onAuthSuccess={handleAuthSuccess}
+ />
+ ))}
+ </tbody>
+ </table>
+ )}
+ </div>
+
+ {/* Add Button */}
+ <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>
+
+ {/* Create/Edit Modal */}
+ <CreateCredentialsModal
+ isOpen={isCreateModalOpen}
+ onClose={handleModalClose}
+ onSuccess={handleSuccess}
+ group="oauth_connections_creds"
+ editConnection={editingConnection}
+ />
+
+ {/* Delete Confirmation Modal */}
+ {deletingConnection && (
+ <DeleteCredentialsModal
+ isOpen={!!deletingConnection}
+ credentialId={deletingConnection.id}
+ credentialName={deletingConnection.name}
+ group="oauth_connections_creds"
+ onClose={() => setDeletingConnection(undefined)}
+ onSuccess={handleDeleteSuccess}
+ />
+ )}
+ </div>
+ );
+}
diff --git a/packages/app/src/react/features/vault/components/use-oauth-creds.ts b/packages/app/src/react/features/vault/components/use-oauth-creds.ts
new file mode 100644
index 00000000..2c053e65
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/use-oauth-creds.ts
@@ -0,0 +1,294 @@
+/*
+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,
+ };
+*/
+import {
+ authenticateClientCredentials as authenticateClientCredentialsShared,
+ checkOAuthAuthentication as checkOAuthAuthenticationShared,
+ initiateOAuthFlow as initiateOAuthFlowShared,
+ signOutOAuthConnection as signOutOAuthConnectionShared,
+} from '@src/shared/helpers/oauth/oauth-api.helper';
+import { useMutation, useQueryClient } from '@tanstack/react-query';
+import type {
+ AuthenticateOAuthPayload,
+ CheckAuthStatusPayload,
+ OAuthConnection,
+ OAuthInfo,
+ SignOutOAuthPayload,
+} from '../types/oauth-connection';
+
+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;
+}
+
+/**
+ * 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);
+};
+
+/**
+ * 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) {
+ // 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.tsx
index 238da092..96ddd7e0 100644
--- a/packages/app/src/react/features/vault/pages/VaultPage.tsx
+++ b/packages/app/src/react/features/vault/pages/VaultPage.tsx
@@ -9,6 +9,7 @@ import React, { useEffect, useMemo } from 'react';
import { CiExport } from 'react-icons/ci';
import { ApiKeys } from '../components/api-keys';
import { OAuthConnections } from '../components/oauth-connections';
+import { OAuthConnectionsCredentials } from '../components/oauth-connections-creds';
import UserCustomModels from '../components/user-custom-models';
import { UserModels } from '../components/user-models';
import { VectorDatabases } from '../components/vector-databases';
@@ -101,6 +102,7 @@ export default function VaultPage() {
<UserCustomModels pageAccess={pageAccess} />
<PluginComponents targetId={PluginTarget.VaultPageEnterpriseModels} />
<OAuthConnections />
+ <OAuthConnectionsCredentials />
<VectorDatabases />
diff --git a/packages/app/src/react/features/vault/types/oauth-connection.ts b/packages/app/src/react/features/vault/types/oauth-connection.ts
index 27aaf97f..3431e622 100644
--- a/packages/app/src/react/features/vault/types/oauth-connection.ts
+++ b/packages/app/src/react/features/vault/types/oauth-connection.ts
@@ -21,7 +21,7 @@ export interface OAuthInfo {
consumerSecret?: string; // OAuth 1.0a
oauth1CallbackURL?: string; // OAuth 1.0a
// Allow any other string properties that might be added
- [key: string]: string | undefined;
+ [key: string]: string | undefined | Record<string, string>;
}
/**
@@ -139,4 +139,4 @@ export interface CheckAuthStatusPayload extends OAuthInfo {
*/
export interface SignOutOAuthPayload {
connectionId: string; // OAUTH_{UUID}_TOKENS
-}
\ No newline at end of file
+}
diff --git a/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts b/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
index b89a7c8f..f00b2c9e 100644
--- a/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
+++ b/packages/app/src/shared/helpers/oauth/oauth-api.helper.ts
@@ -1,3 +1,4 @@
+import { CredentialConnection } from '@src/react/features/credentials/components/create-credentials.modal';
import {
deriveCallbackUrl,
handleApiResponse,
@@ -48,7 +49,9 @@ export function getConnectionOauthInfo(connection: any, connectionId?: string):
// Ensure oauth_keys_prefix is set
if (!reconstructed.oauth_keys_prefix && connectionId) {
- reconstructed.oauth_keys_prefix = connectionId.replace('_TOKENS', '');
+ // reconstructed.oauth_keys_prefix = connectionId.replace('_TOKENS', '');
+ reconstructed.oauth_keys_prefix = connectionId
+
}
return Object.keys(reconstructed).length > 0 ? reconstructed : null;
@@ -205,7 +208,7 @@ export function extractServiceFromConnection(connection: any): string {
*/
export async function checkOAuthAuthentication(oauthInfo: any): Promise<{ success: boolean }> {
try {
- const response = await fetch('/oauth/checkAuth', {
+ const response = await fetch('/oauth/check-auth', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(oauthInfo),
@@ -284,7 +287,8 @@ export async function signOutOAuthConnection(
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
- oauth_keys_prefix: connectionId.replace('_TOKENS', ''),
+ // oauth_keys_prefix: connectionId.replace('_TOKENS', ''),
+ oauth_keys_prefix: connectionId,
invalidateAuthentication,
}),
});
@@ -305,14 +309,85 @@ export async function signOutOAuthConnection(
/**
* Save OAuth connection to backend
*/
+/**
+ * Save OAuth connection using new credentials API
+ * Converts from legacy format to new credentials format
+ */
export async function saveOAuthConnection(connectionId: string, authSettings: any): Promise<void> {
- const response = await fetch('/api/page/vault/oauth-connections', {
- method: 'PUT',
+ const { name, type, oauth_info } = authSettings;
+
+ if (!oauth_info) {
+ throw new Error('oauth_info is required in authSettings');
+ }
+
+ // Build credentials object from oauth_info
+ const credentials: Record<string, { value: string; sensitive: boolean }> = {};
+
+ // Add platform and name
+ if (oauth_info.platform) {
+ credentials.platform = { value: oauth_info.platform, sensitive: false };
+ }
+
+ // Map OAuth2 fields
+ if (oauth_info.authorizationURL) {
+ credentials.authorizationURL = { value: oauth_info.authorizationURL, sensitive: false };
+ }
+ if (oauth_info.tokenURL) {
+ credentials.tokenURL = { value: oauth_info.tokenURL, sensitive: false };
+ }
+ if (oauth_info.clientID) {
+ credentials.clientID = { value: oauth_info.clientID, sensitive: true };
+ }
+ if (oauth_info.clientSecret) {
+ credentials.clientSecret = { value: oauth_info.clientSecret, sensitive: true };
+ }
+ if (oauth_info.scope) {
+ credentials.scope = { value: oauth_info.scope, sensitive: false };
+ }
+
+ // Map OAuth1 fields
+ if (oauth_info.requestTokenURL) {
+ credentials.requestTokenURL = { value: oauth_info.requestTokenURL, sensitive: false };
+ }
+ if (oauth_info.accessTokenURL) {
+ credentials.accessTokenURL = { value: oauth_info.accessTokenURL, sensitive: false };
+ }
+ if (oauth_info.userAuthorizationURL) {
+ credentials.userAuthorizationURL = { value: oauth_info.userAuthorizationURL, sensitive: false };
+ }
+ if (oauth_info.consumerKey) {
+ credentials.consumerKey = { value: oauth_info.consumerKey, sensitive: true };
+ }
+ if (oauth_info.consumerSecret) {
+ credentials.consumerSecret = { value: oauth_info.consumerSecret, sensitive: true };
+ }
+
+ // Determine if we're creating or updating based on whether the credential exists
+ const checkResponse = await fetch(
+ `/api/app/credentials/${encodeURIComponent(connectionId)}?group=oauth_connections_creds`,
+ {
+ method: 'GET',
+ headers: { 'Content-Type': 'application/json' },
+ },
+ );
+
+ const isUpdate = checkResponse.ok;
+ const method = isUpdate ? 'PUT' : 'POST';
+ const url = isUpdate
+ ? `/api/app/credentials/${encodeURIComponent(connectionId)}`
+ : '/api/app/credentials';
+
+ const body: any = {
+ group: 'oauth_connections_creds',
+ name: name || oauth_info.name || 'OAuth Connection',
+ provider: oauth_info.service || type || 'custom_oauth2',
+ credentials,
+ };
+
+ const response = await fetch(url, {
+ method,
headers: { 'Content-Type': 'application/json' },
- body: JSON.stringify({
- entryId: connectionId,
- data: authSettings,
- }),
+ body: JSON.stringify(body),
});
if (!response.ok) {
@@ -324,12 +399,16 @@ export async function saveOAuthConnection(connectionId: string, authSettings: an
}
/**
- * Delete OAuth connection from backend
+ * Delete OAuth connection using new credentials API
*/
export async function deleteOAuthConnection(connectionId: string): Promise<void> {
- const response = await fetch(`/api/page/vault/oauth-connections/${connectionId}`, {
- method: 'DELETE',
- });
+ const response = await fetch(
+ `/api/app/credentials/${encodeURIComponent(connectionId)}?group=oauth_connections_creds`,
+ {
+ method: 'DELETE',
+ headers: { 'Content-Type': 'application/json' },
+ },
+ );
if (!response.ok) {
const errorData = await response.json().catch(() => ({}));
@@ -387,3 +466,63 @@ export async function authenticateClientCredentials(
return await response.json();
}
+
+type OAuthInfo = {
+ [key: string]: any; // you can refine this if you know the schema
+};
+
+type AuthSettings = {
+ name?: string;
+ platform?: string;
+ oauth_info?: OAuthInfo;
+ [key: string]: any; // other arbitrary setting fields
+};
+
+type AuthData = {
+ primary?: string;
+ secondary?: string;
+ expires_in?: number;
+};
+
+export type ExistingEntryData = {
+ // NEW structure
+ auth_data?: AuthData;
+ auth_settings?: AuthSettings;
+};
+
+export function transformOAuthCredEntry(
+ credentialEntry: CredentialConnection & { tokens: any },
+): ExistingEntryData {
+ // if old flow, return the old structure
+ if (credentialEntry.credentials?.primary) {
+ const { primary, secondary, expires_in, ...credentials } = credentialEntry.credentials;
+ return {
+ auth_data: {
+ primary,
+ secondary,
+ expires_in: expires_in ? parseInt(expires_in) : undefined,
+ },
+ auth_settings: {
+ ...credentials,
+ name: credentialEntry.name,
+ service: credentialEntry.provider,
+ platform: credentialEntry.name,
+ },
+ };
+ }
+
+ // if new flow, return the new structure
+ return {
+ auth_data: {
+ primary: credentialEntry.tokens?.primary,
+ secondary: credentialEntry.tokens?.secondary,
+ expires_in: credentialEntry.tokens?.expires_in,
+ },
+ auth_settings: {
+ name: credentialEntry.name,
+ service: credentialEntry.provider,
+ platform: credentialEntry.name,
+ ...credentialEntry.credentials,
+ },
+ };
+}
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.ts
index 75271e2a..5e366b42 100644
--- a/packages/app/src/shared/state_stores/builder/slices/oauth.slice.ts
+++ b/packages/app/src/shared/state_stores/builder/slices/oauth.slice.ts
@@ -1,3 +1,4 @@
+import { transformOAuthCredEntry } from '@src/shared/helpers/oauth/oauth-api.helper';
import { StateCreator } from 'zustand';
import { Slice } from '../..';
import { BuilderStore } from '../store';
@@ -7,7 +8,7 @@ export interface OAuthSlice extends Slice {
oauthConnectionsPromise: Promise<any> | null;
oauthConnectionsLoading: boolean;
oauthConnectionsError: Error | null;
- getOAuthConnections: (forceRefresh?: boolean) => Promise<any>;
+ getOAuthConnections: (forceRefresh?: boolean, resolveVaultKeys?: boolean) => Promise<any>;
invalidateOAuthConnectionsCache: () => void;
}
@@ -17,9 +18,9 @@ export const oauthSlice: StateCreator<BuilderStore, [], [], OAuthSlice> = (set,
oauthConnectionsLoading: false,
oauthConnectionsError: null,
- init: async () => { },
+ init: async () => {},
- getOAuthConnections: async (forceRefresh = false) => {
+ getOAuthConnections: async (forceRefresh = false, resolveVaultKeys = true) => {
if (forceRefresh) {
set({ oauthConnections: null, oauthConnectionsPromise: null });
}
@@ -27,7 +28,11 @@ export const oauthSlice: StateCreator<BuilderStore, [], [], OAuthSlice> = (set,
if (oauthConnections !== null) return oauthConnections;
if (oauthConnectionsPromise !== null) return oauthConnectionsPromise;
set({ oauthConnectionsLoading: true, oauthConnectionsError: null });
- const promise = fetch('/api/page/vault/oauth-connections', {
+
+ // Build URL with optional vault key resolution
+ const url = `/api/app/credentials?group=oauth_connections_creds${resolveVaultKeys ? '&resolveVaultKeys=true' : ''}`;
+
+ const promise = fetch(url, {
method: 'GET',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
@@ -36,23 +41,29 @@ export const oauthSlice: StateCreator<BuilderStore, [], [], OAuthSlice> = (set,
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
- }
- }
+ const result = await response.json();
+ const credentials = result.data || [];
+
+ // Transform to legacy format and index by ID
+ const connectionsMap: Record<string, any> = {};
+ credentials.forEach((credential: any) => {
+ connectionsMap[credential.id] = transformOAuthCredEntry(credential);
});
- set({ oauthConnections: data, oauthConnectionsLoading: false, oauthConnectionsPromise: null });
- return data;
+
+ set({
+ oauthConnections: connectionsMap,
+ oauthConnectionsLoading: false,
+ oauthConnectionsPromise: null,
+ });
+ return connectionsMap;
})
.catch((error) => {
- set({ oauthConnectionsError: error, oauthConnectionsLoading: false, oauthConnectionsPromise: null });
+ console.error('[OAuth Slice] Error fetching connections:', error);
+ set({
+ oauthConnectionsError: error,
+ oauthConnectionsLoading: false,
+ oauthConnectionsPromise: null,
+ });
throw error;
});
set({ oauthConnectionsPromise: promise });
diff --git a/packages/app/src/shared/types/credentials.types.ts b/packages/app/src/shared/types/credentials.types.ts
new file mode 100644
index 00000000..49fff56e
--- /dev/null
+++ b/packages/app/src/shared/types/credentials.types.ts
@@ -0,0 +1,133 @@
+/**
+ * Shared Types for Credentials
+ *
+ * Common type definitions used across frontend and backend for credentials management.
+ *
+ * @module
+ */
+
+/**
+ * Credential Connection
+ * Represents a stored credential (OAuth, vector DB, etc.)
+ */
+export interface CredentialConnection {
+ /** Unique identifier for the credential */
+ id: string;
+
+ /** Display name for the credential */
+ name: string;
+
+ /** Provider ID (e.g., 'google', 'pinecone') */
+ provider: string;
+
+ /** Credential fields (sanitized in GET requests) */
+ credentials: Record<string, any>;
+
+ /** Group category (e.g., 'oauth_connections_creds', 'vector_db_creds') */
+ group: string;
+
+ /** ISO timestamp when credential was created */
+ createdAt: string;
+
+ /** ISO timestamp when credential was last updated */
+ updatedAt: string;
+
+ /** Whether the credential is read-only */
+ isReadOnly?: boolean;
+
+ /** Whether this is an internal managed credential */
+ isManaged?: boolean;
+
+ /** Whether the credential is currently authenticated/active */
+ isActive?: boolean;
+
+ customProperties?: Record<string, any>;
+}
+
+/**
+ * Input for creating a new credential
+ */
+export interface CreateCredentialInput {
+ /** Group category */
+ group: string;
+
+ /** Display name */
+ name: string;
+
+ /** Provider ID */
+ provider: string;
+
+ /** Credential fields with value and sensitivity flag */
+ credentials: Record<string, { value: string; sensitive: boolean }>;
+
+ /** Authentication type */
+ authType: string;
+}
+
+/**
+ * Input for updating an existing credential
+ */
+export interface UpdateCredentialInput {
+ /** Display name */
+ name?: string;
+
+ /** Provider ID */
+ provider?: string;
+
+ /** Credential fields with value and sensitivity flag */
+ credentials?: Record<string, { value: string; sensitive: boolean }>;
+
+ /** Extra data to be stored in the credential */
+ customProperties?: Record<string, any>;
+
+ /** Authentication type */
+ authType?: string;
+}
+
+/**
+ * Input for deleting a credential
+ */
+export interface DeleteCredentialInput {
+ /** Credential ID */
+ id: string;
+
+ /** Group category */
+ group: string;
+
+ /** Whether user has consented to warnings */
+ consentedWarnings?: boolean;
+}
+
+/**
+ * Result of credential deletion
+ */
+export interface DeleteCredentialResult {
+ /** Whether deletion was successful */
+ success: boolean;
+
+ /** Success/error message */
+ message?: string;
+
+ /** Warnings that require user confirmation */
+ warnings?: string[];
+}
+
+/**
+ * API Response wrapper for credentials
+ */
+export interface CredentialsApiResponse<T = any> {
+ /** Whether the request was successful */
+ success: boolean;
+
+ /** Response data */
+ data?: T;
+
+ /** Error message if unsuccessful */
+ error?: string;
+
+ /** Optional message */
+ message?: string;
+
+ /** Warnings that require user attention */
+ warnings?: string[];
+}