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.

resolve vault keys in oauth edit form in builder

Ahmed Essamf9fd133b401d
diff --git a/packages/app/src/builder-ui/components/APICall.class.ts b/packages/app/src/builder-ui/components/APICall.class.ts
index c13c8da9..68f180a2 100644
--- a/packages/app/src/builder-ui/components/APICall.class.ts
+++ b/packages/app/src/builder-ui/components/APICall.class.ts
@@ -14,9 +14,13 @@ 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 } from '../helpers/oauth/oauth-modal.helper';
+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';
@@ -1600,7 +1604,7 @@ 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"
if (!isNone) {
try {
@@ -1628,174 +1632,120 @@ export class APICall extends Component {
? currentConnectionRaw.auth_settings
: currentConnectionRaw; // Assume old structure if new one isn't present
- const currentOauthInfo = this.getConnectionOauthInfo(currentSettings, currentValue) || {}; // Support both structures
+ 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
- const currentService = currentSettings
+ let currentService = currentSettings
? mapInternalToServiceName(currentOauthInfo.service)
: 'None';
- const currentPlatform = currentOauthInfo.platform || '';
+ 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
- const consumerKeyValue = currentOauthInfo.consumerKey || '';
- const consumerSecretValue = currentOauthInfo.consumerSecret || '';
-
- // Generate form HTML using helper function
- const formHTML = generateOAuthModalHTML(
- currentName,
- currentPlatform,
- currentService,
- currentOauthInfo,
- );
+ 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: formHTML,
- onDOMReady: (dialog) => {
- // Get all containers
- const oauth1Container = dialog.querySelector('#oauth1-fields');
- const oauth2Container = dialog.querySelector('#oauth2-fields');
- const callbackDisplayContainer = dialog.querySelector('#callback-url-display');
- const serviceSelect = dialog.querySelector('#oauthService') as HTMLSelectElement;
- const initialServiceValue = serviceSelect?.value || 'None';
-
- // Force-set OAuth1 fields (our working fix)
- const consumerKeyInput = dialog.querySelector('#consumerKey') as HTMLInputElement;
- const consumerSecretInput = dialog.querySelector('#consumerSecret') as HTMLInputElement;
- if (consumerKeyInput && consumerKeyValue) {
- consumerKeyInput.value = consumerKeyValue;
- }
- if (consumerSecretInput && consumerSecretValue) {
- consumerSecretInput.value = consumerSecretValue;
- }
-
- // Force-set OAuth2 fields the same way
- const clientIDInput = dialog.querySelector('#clientID') as HTMLInputElement;
- const clientSecretInput = dialog.querySelector('#clientSecret') as HTMLInputElement;
- const tokenURLInput = dialog.querySelector('#tokenURL') as HTMLInputElement;
- const authURLInput = dialog.querySelector('#authorizationURL') as HTMLInputElement;
- const scopeInput = dialog.querySelector('#scope') as HTMLTextAreaElement;
-
- if (clientIDInput && currentOauthInfo.clientID) {
- clientIDInput.value = currentOauthInfo.clientID;
- }
- if (clientSecretInput && currentOauthInfo.clientSecret) {
- clientSecretInput.value = currentOauthInfo.clientSecret;
- }
- if (tokenURLInput && currentOauthInfo.tokenURL) {
- tokenURLInput.value = currentOauthInfo.tokenURL;
- }
- if (authURLInput && currentOauthInfo.authorizationURL) {
- authURLInput.value = currentOauthInfo.authorizationURL;
- }
- if (scopeInput && currentOauthInfo.scope) {
- scopeInput.value = currentOauthInfo.scope;
- }
-
- // Comprehensive update field visibility function
- const updateFieldVisibility = (selectedValue: string) => {
- const isOAuth2 = ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedValue);
- const isOAuth1 = ['Twitter', 'Custom OAuth1.0'].includes(selectedValue);
- const isClientCreds = selectedValue === 'OAuth2 Client Credentials';
-
- // Show/hide main containers
- oauth1Container?.classList.toggle('hidden', !isOAuth1);
- oauth2Container?.classList.toggle('hidden', !(isOAuth2 || isClientCreds));
-
- // Toggle specific fields within OAuth2
- const scopeGroup = dialog.querySelector('[data-oauth-field="scope"]');
- const authURLGroup = dialog.querySelector('#authorizationURL')?.closest('.form-group');
-
- if (scopeGroup) {
- scopeGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);
- }
- if (authURLGroup) {
- authURLGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);
- }
-
- // Handle callback URL display
- callbackDisplayContainer?.classList.toggle(
- 'hidden',
- isClientCreds || (!isOAuth2 && !isOAuth1),
- );
- if (!callbackDisplayContainer?.classList.contains('hidden')) {
- const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');
- const service = selectedValue === 'None' ? '' : selectedValue;
- let callbackURL = '';
-
- try {
- const baseUrl = window.location.origin;
- const serviceInternal = APICall.prototype.mapServiceNameToInternal.call(
- this,
- service,
- );
- if (serviceInternal && serviceInternal !== 'none') {
- callbackURL = `${baseUrl}/oauth/${serviceInternal}/callback`;
- }
- } catch (e) {
- console.error('Error creating callback URL:', e);
+ 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');
}
- if (callbackUrlDiv) {
- callbackUrlDiv.textContent = callbackURL;
+ // 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;
}
- }
- };
-
- // Apply initial visibility
- updateFieldVisibility(initialServiceValue);
-
- // Re-add change handler
- if (serviceSelect) {
- serviceSelect.addEventListener('change', (e) => {
- const target = e.target as HTMLSelectElement;
- updateFieldVisibility(target.value);
-
- // Add this code to prefill values when service changes
- const selectedService = target.value;
- if (['Google', 'Twitter', 'LinkedIn'].includes(selectedService)) {
- // Get default configuration for selected service
- const baseUrl = window.location.origin;
- const service = this.mapServiceNameToInternal(selectedService);
- const callbackUrl = `${baseUrl}/oauth/${service}/callback`;
-
- // Set default values based on service
- if (selectedService === 'Google') {
- (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
- 'https://accounts.google.com/o/oauth2/v2/auth';
- (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
- 'https://oauth2.googleapis.com/token';
- (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
- 'https://www.googleapis.com/auth/gmail.readonly';
- } else if (selectedService === 'LinkedIn') {
- (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
- 'https://www.linkedin.com/oauth/v2/authorization';
- (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
- 'https://www.linkedin.com/oauth/v2/accessToken';
- (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
- 'r_liteprofile r_emailaddress';
- } else if (selectedService === 'Twitter') {
- (dialog.querySelector('#requestTokenURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/request_token';
- (dialog.querySelector('#accessTokenURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/access_token';
- (dialog.querySelector('#userAuthorizationURL') as HTMLInputElement).value =
- 'https://api.twitter.com/oauth/authorize';
- }
- // Update callback URL display
- const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');
- if (callbackUrlDiv) {
- callbackUrlDiv.textContent = callbackUrl;
- }
- }
- });
+ this.setupOAuthModalHandlers(
+ dialog,
+ currentOauthInfo,
+ consumerKeyValue,
+ consumerSecretValue,
+ );
+ }
+ } else {
+ // No vault keys, setup handlers immediately
+ this.setupOAuthModalHandlers(
+ dialog,
+ currentOauthInfo,
+ consumerKeyValue,
+ consumerSecretValue,
+ );
}
},
actions: [
@@ -2173,4 +2123,152 @@ export class APICall extends Component {
oauth_button.innerHTML = isAuthenticated ? 'Sign Out' : 'Authenticate';
oauth_button.disabled = false;
}
+
+ /**
+ * Sets up the OAuth modal handlers (field visibility, change events, etc.)
+ * Extracted from onDOMReady to allow reuse after vault key resolution
+ */
+ private setupOAuthModalHandlers(
+ dialog: HTMLElement,
+ currentOauthInfo: any,
+ consumerKeyValue: string,
+ consumerSecretValue: string,
+ ) {
+ // Get all containers
+ const oauth1Container = dialog.querySelector('#oauth1-fields');
+ const oauth2Container = dialog.querySelector('#oauth2-fields');
+ const callbackDisplayContainer = dialog.querySelector('#callback-url-display');
+ const serviceSelect = dialog.querySelector('#oauthService') as HTMLSelectElement;
+ const initialServiceValue = serviceSelect?.value || 'None';
+
+ // Force-set OAuth1 fields (our working fix)
+ const consumerKeyInput = dialog.querySelector('#consumerKey') as HTMLInputElement;
+ const consumerSecretInput = dialog.querySelector('#consumerSecret') as HTMLInputElement;
+ if (consumerKeyInput && consumerKeyValue) {
+ consumerKeyInput.value = consumerKeyValue;
+ }
+ if (consumerSecretInput && consumerSecretValue) {
+ consumerSecretInput.value = consumerSecretValue;
+ }
+
+ // Force-set OAuth2 fields the same way
+ const clientIDInput = dialog.querySelector('#clientID') as HTMLInputElement;
+ const clientSecretInput = dialog.querySelector('#clientSecret') as HTMLInputElement;
+ const tokenURLInput = dialog.querySelector('#tokenURL') as HTMLInputElement;
+ const authURLInput = dialog.querySelector('#authorizationURL') as HTMLInputElement;
+ const scopeInput = dialog.querySelector('#scope') as HTMLTextAreaElement;
+
+ if (clientIDInput && currentOauthInfo.clientID) {
+ clientIDInput.value = currentOauthInfo.clientID;
+ }
+ if (clientSecretInput && currentOauthInfo.clientSecret) {
+ clientSecretInput.value = currentOauthInfo.clientSecret;
+ }
+ if (tokenURLInput && currentOauthInfo.tokenURL) {
+ tokenURLInput.value = currentOauthInfo.tokenURL;
+ }
+ if (authURLInput && currentOauthInfo.authorizationURL) {
+ authURLInput.value = currentOauthInfo.authorizationURL;
+ }
+ if (scopeInput && currentOauthInfo.scope) {
+ scopeInput.value = currentOauthInfo.scope;
+ }
+
+ // Comprehensive update field visibility function
+ const updateFieldVisibility = (selectedValue: string) => {
+ const isOAuth2 = ['Google', 'LinkedIn', 'Custom OAuth2.0'].includes(selectedValue);
+ const isOAuth1 = ['Twitter', 'Custom OAuth1.0'].includes(selectedValue);
+ const isClientCreds = selectedValue === 'OAuth2 Client Credentials';
+
+ // Show/hide main containers
+ oauth1Container?.classList.toggle('hidden', !isOAuth1);
+ oauth2Container?.classList.toggle('hidden', !(isOAuth2 || isClientCreds));
+
+ // Toggle specific fields within OAuth2
+ const scopeGroup = dialog.querySelector('[data-oauth-field="scope"]');
+ const authURLGroup = dialog.querySelector('#authorizationURL')?.closest('.form-group');
+
+ if (scopeGroup) {
+ scopeGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);
+ }
+ if (authURLGroup) {
+ authURLGroup.classList.toggle('hidden', isClientCreds || !isOAuth2);
+ }
+
+ // Handle callback URL display
+ callbackDisplayContainer?.classList.toggle(
+ 'hidden',
+ isClientCreds || (!isOAuth2 && !isOAuth1),
+ );
+ if (!callbackDisplayContainer?.classList.contains('hidden')) {
+ const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');
+ const service = selectedValue === 'None' ? '' : selectedValue;
+ let callbackURL = '';
+
+ try {
+ const baseUrl = window.location.origin;
+ const serviceInternal = APICall.prototype.mapServiceNameToInternal.call(this, service);
+ if (serviceInternal && serviceInternal !== 'none') {
+ callbackURL = `${baseUrl}/oauth/${serviceInternal}/callback`;
+ }
+ } catch (e) {
+ console.error('Error creating callback URL:', e);
+ }
+
+ if (callbackUrlDiv) {
+ callbackUrlDiv.textContent = callbackURL;
+ }
+ }
+ };
+
+ // Apply initial visibility
+ updateFieldVisibility(initialServiceValue);
+
+ // Re-add change handler
+ if (serviceSelect) {
+ serviceSelect.addEventListener('change', (e) => {
+ const target = e.target as HTMLSelectElement;
+ updateFieldVisibility(target.value);
+
+ // Add this code to prefill values when service changes
+ const selectedService = target.value;
+ if (['Google', 'Twitter', 'LinkedIn'].includes(selectedService)) {
+ // Get default configuration for selected service
+ const baseUrl = window.location.origin;
+ const service = this.mapServiceNameToInternal(selectedService);
+ const callbackUrl = `${baseUrl}/oauth/${service}/callback`;
+
+ // Set default values based on service
+ if (selectedService === 'Google') {
+ (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
+ 'https://accounts.google.com/o/oauth2/v2/auth';
+ (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
+ 'https://oauth2.googleapis.com/token';
+ (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
+ 'https://www.googleapis.com/auth/gmail.readonly';
+ } else if (selectedService === 'LinkedIn') {
+ (dialog.querySelector('#authorizationURL') as HTMLInputElement).value =
+ 'https://www.linkedin.com/oauth/v2/authorization';
+ (dialog.querySelector('#tokenURL') as HTMLInputElement).value =
+ 'https://www.linkedin.com/oauth/v2/accessToken';
+ (dialog.querySelector('#scope') as HTMLTextAreaElement).value =
+ 'r_liteprofile r_emailaddress';
+ } else if (selectedService === 'Twitter') {
+ (dialog.querySelector('#requestTokenURL') as HTMLInputElement).value =
+ 'https://api.twitter.com/oauth/request_token';
+ (dialog.querySelector('#accessTokenURL') as HTMLInputElement).value =
+ 'https://api.twitter.com/oauth/access_token';
+ (dialog.querySelector('#userAuthorizationURL') as HTMLInputElement).value =
+ 'https://api.twitter.com/oauth/authorize';
+ }
+
+ // Update callback URL display
+ const callbackUrlDiv = callbackDisplayContainer?.querySelector('div.col-span-3');
+ if (callbackUrlDiv) {
+ callbackUrlDiv.textContent = callbackUrl;
+ }
+ }
+ });
+ }
+ }
}
diff --git a/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts b/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
index 51b82627..454af5ae 100644
--- a/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
+++ b/packages/app/src/builder-ui/helpers/oauth/oauth-modal.helper.ts
@@ -299,3 +299,76 @@ export function buildOAuthSettingsForSave(
export function generateOAuthConnectionId(): string {
return (Date.now() + Math.random()).toString(36).replace('.', '').toUpperCase();
}
+
+/**
+ * Generate loading skeleton HTML for OAuth modal while resolving vault keys
+ */
+export function generateOAuthModalLoadingSkeleton(): string {
+ return `
+ <div class="grid gap-4 py-4">
+ <!-- Name Field Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Name <span class="text-red-500">*</span></label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Platform Field Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Platform <span class="text-red-500">*</span></label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Service Selector Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Auth Service <span class="text-red-500">*</span></label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Auth URL Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Auth URL</label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Token URL Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Token URL</label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Client ID Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Client ID</label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Client Secret Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Client Secret</label>
+ <div class="col-span-3">
+ <div class="h-9 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+
+ <!-- Scope Skeleton -->
+ <div class="grid grid-cols-4 items-center gap-4 form-group">
+ <label class="text-sm font-medium">Scopes</label>
+ <div class="col-span-3">
+ <div class="h-20 w-full bg-gray-200 animate-pulse rounded"></div>
+ </div>
+ </div>
+ </div>
+ `;
+}
diff --git a/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts b/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts
index 735d8974..7b7f47e3 100644
--- a/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts
+++ b/packages/app/src/builder-ui/helpers/oauth/ui.helper.ts
@@ -1,9 +1,13 @@
-import { generateOAuthModalHTML } from '@src/builder-ui/helpers/oauth/oauth-modal.helper';
+import {
+ generateOAuthModalHTML,
+ generateOAuthModalLoadingSkeleton,
+} from '@src/builder-ui/helpers/oauth/oauth-modal.helper';
import { twEditValuesWithCallback } from '@src/builder-ui/ui/tw-dialogs';
import { errorToast, successToast } from '@src/shared/components/toast';
import { getConnectionOauthInfo } from '@src/shared/helpers/oauth/oauth-api.helper';
import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import { generateOAuthId, mapInternalToServiceName } from '@src/shared/helpers/oauth/oauth.utils';
+import { hasVaultKeys, resolveVaultKeys } from '@src/shared/helpers/oauth/vault-key-resolver';
import type { OAuthConnection } from './oauth.types';
export class UIHelper {
@@ -97,26 +101,74 @@ export class UIHelper {
const isNone = !currentValue || currentValue === 'None';
const currentConnection = !isNone ? connections[currentValue] : null;
const currentSettings = currentConnection?.auth_settings;
- const currentOauthInfo = getConnectionOauthInfo(currentSettings, currentValue) || {};
+ let currentOauthInfo = getConnectionOauthInfo(currentSettings, currentValue) || {};
const currentName = currentSettings?.name || '';
- const currentService = currentSettings
+ let currentService = currentSettings
? mapInternalToServiceName(currentOauthInfo.service)
: 'None';
- const currentPlatform = currentOauthInfo.platform || '';
+ let currentPlatform = currentOauthInfo.platform || '';
- const formHTML = generateOAuthModalHTML(
- currentName,
- currentPlatform,
- currentService,
- currentOauthInfo,
- );
+ // Check if we need to resolve vault keys
+ const needsVaultResolution = !isNone && hasVaultKeys(currentOauthInfo);
+
+ // If vault keys need resolution, show loading skeleton initially
+ let initialFormHTML = needsVaultResolution
+ ? generateOAuthModalLoadingSkeleton()
+ : generateOAuthModalHTML(currentName, currentPlatform, currentService, currentOauthInfo);
+
+ let dialogElement: HTMLElement | null = null;
await twEditValuesWithCallback(
{
title: isNone ? 'Add OAuth Connection' : 'Edit OAuth Connection',
- content: formHTML,
- onDOMReady: (dialog) => {
- this.setupModalHandlers(dialog, currentOauthInfo);
+ content: initialFormHTML,
+ onDOMReady: async (dialog) => {
+ dialogElement = dialog;
+
+ // If we need to resolve vault keys, do it now
+ if (needsVaultResolution) {
+ try {
+ // Resolve vault keys
+ currentOauthInfo = await resolveVaultKeys(currentOauthInfo);
+ currentPlatform = currentOauthInfo.platform || '';
+
+ // Generate the actual form HTML with resolved values
+ const resolvedFormHTML = generateOAuthModalHTML(
+ currentName,
+ currentPlatform,
+ currentService,
+ currentOauthInfo,
+ );
+
+ // Find the content container and update it
+ const contentContainer = dialog.querySelector('.tw-dialog-content-container');
+ if (contentContainer) {
+ contentContainer.innerHTML = resolvedFormHTML;
+ }
+
+ // Setup handlers after content is loaded
+ this.setupModalHandlers(dialog, currentOauthInfo);
+ } 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,
+ );
+ const contentContainer = dialog.querySelector('.tw-dialog-content-container');
+ if (contentContainer) {
+ contentContainer.innerHTML = fallbackHTML;
+ }
+ this.setupModalHandlers(dialog, currentOauthInfo);
+ }
+ } else {
+ // No vault keys, setup handlers immediately
+ this.setupModalHandlers(dialog, currentOauthInfo);
+ }
},
actions: [
{
diff --git a/packages/app/src/shared/helpers/oauth/vault-key-resolver.ts b/packages/app/src/shared/helpers/oauth/vault-key-resolver.ts
new file mode 100644
index 00000000..d39c89d6
--- /dev/null
+++ b/packages/app/src/shared/helpers/oauth/vault-key-resolver.ts
@@ -0,0 +1,135 @@
+/**
+ * Vault Key Resolver Utilities
+ *
+ * Provides utilities for detecting and resolving vault key placeholders in OAuth connections.
+ * Vault keys follow the pattern: {{KEY(keyName)}}
+ */
+
+/**
+ * Regular expression pattern to match vault key placeholders
+ * Matches: {{KEY(keyName)}}
+ */
+const VAULT_KEY_PATTERN = /{{KEY\((.*?)\)}}/;
+
+/**
+ * Checks if a string contains a vault key placeholder
+ * @param value - The value to check
+ * @returns True if the value contains a vault key placeholder
+ */
+export function isVaultKey(value: string | undefined): boolean {
+ if (!value || typeof value !== 'string') {
+ return false;
+ }
+ return VAULT_KEY_PATTERN.test(value);
+}
+
+/**
+ * Extracts the key name from a vault key placeholder
+ * @param value - The vault key placeholder string
+ * @returns The extracted key name, or null if no match
+ */
+export function extractVaultKeyName(value: string): string | null {
+ const match = value.match(VAULT_KEY_PATTERN);
+ return match ? match[1] : null;
+}
+
+/**
+ * Fetches a vault key value from the backend
+ * @param keyName - The name of the vault key to fetch
+ * @returns The vault key data
+ */
+export async function fetchVaultKey(keyName: string): Promise<string | undefined> {
+ try {
+ const response = await fetch(`/api/page/vault/keys/name/${encodeURIComponent(keyName)}`);
+
+ if (!response.ok) {
+ console.error(`Failed to fetch vault key ${keyName}:`, response.statusText);
+ return undefined;
+ }
+
+ const result = await response.json();
+
+ if (result.success && result.data?.data) {
+ // The backend returns the key value in result.data.data
+ return result.data.data.key;
+ }
+
+ return undefined;
+ } catch (error) {
+ console.error(`Error fetching vault key ${keyName}:`, error);
+ return undefined;
+ }
+}
+
+/**
+ * OAuth connection fields that may contain vault keys
+ */
+export const VAULT_PROTECTED_FIELDS = [
+ 'clientID',
+ 'clientSecret',
+ 'consumerKey',
+ 'consumerSecret',
+] as const;
+
+export type VaultProtectedField = (typeof VAULT_PROTECTED_FIELDS)[number];
+
+/**
+ * Checks if an OAuth connection has any vault keys
+ * @param oauthInfo - The OAuth connection info object
+ * @returns True if any field contains a vault key
+ */
+export function hasVaultKeys(oauthInfo: Record<string, any>): boolean {
+ return VAULT_PROTECTED_FIELDS.some((field) => {
+ const value = oauthInfo[field];
+ return isVaultKey(value);
+ });
+}
+
+/**
+ * Resolves all vault keys in an OAuth connection
+ * @param oauthInfo - The OAuth connection info object
+ * @returns A new object with resolved vault keys
+ */
+export async function resolveVaultKeys(
+ oauthInfo: Record<string, any>,
+): Promise<Record<string, any>> {
+ const resolved = { ...oauthInfo };
+
+ // Create an array of promises to resolve all vault keys in parallel
+ const resolutionPromises = VAULT_PROTECTED_FIELDS.map(async (field) => {
+ const value = oauthInfo[field];
+
+ if (isVaultKey(value)) {
+ const keyName = extractVaultKeyName(value);
+
+ if (keyName) {
+ try {
+ const resolvedValue = await fetchVaultKey(keyName);
+
+ if (resolvedValue !== undefined) {
+ resolved[field] = resolvedValue;
+ } else {
+ // Keep the placeholder if we couldn't resolve it
+ console.warn(`Could not resolve vault key for field ${field}: ${keyName}`);
+ }
+ } catch (error) {
+ console.error(`Error resolving vault key for field ${field}:`, error);
+ }
+ }
+ }
+ });
+
+ // Wait for all resolutions to complete
+ await Promise.all(resolutionPromises);
+
+ return resolved;
+}
+
+/**
+ * Type guard to check if a field is a vault-protected field
+ * @param field - The field name to check
+ * @returns True if the field is vault-protected
+ */
+export function isVaultProtectedField(field: string): field is VaultProtectedField {
+ return VAULT_PROTECTED_FIELDS.includes(field as VaultProtectedField);
+}