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(oauth): resolve vault keys on-needed

Ahmed Essam0d9d855f1eab
diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.ts
index c5c2b3e9..2a72ba6d 100644
--- a/packages/app/src/backend/routes/api/page/vault.ts
+++ b/packages/app/src/backend/routes/api/page/vault.ts
@@ -347,7 +347,8 @@ async function deleteVaultKeys(entry: any, team: string, req: any) {
console.log('WE SHOULD DELETE', vaultKeys);
await Promise.all(
vaultKeys.map(async (key) => {
- return await vault.delete(key, team, req);
+ const result = await vault.delete(key, team, req);
+ console.log('DELETED KEY. Result: ', key, result);
}),
);
}
@@ -371,6 +372,7 @@ async function storeSensitiveKeysInVault(entry: { [key: string]: any }, entryId:
data: keyData,
keyId: keyName,
});
+ console.log('STORED KEY. Result: ', result);
if (!result?.success) {
console.error(`Failed to store sensitive key ${field} in vault:`, result?.error);
throw new Error(`Failed to store sensitive key ${field} in vault: ${result?.error}`);
@@ -480,7 +482,7 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
};
}
- await deleteVaultKeys(existingEntry, req?._team?.id, req);
+ // await deleteVaultKeys(existingEntry, req?._team?.id, req);
// 5. Merge and normalize the settings using helper (now both are guaranteed to be objects)
let preparedNewSettings = mergeAuthSettings(existingEntry, parsedNewSettings);
preparedNewSettings = await storeSensitiveKeysInVault(preparedNewSettings, entryId, req);
diff --git a/packages/app/src/backend/services/SmythVault.class.ts b/packages/app/src/backend/services/SmythVault.class.ts
index 6997887d..4afd6b5f 100644
--- a/packages/app/src/backend/services/SmythVault.class.ts
+++ b/packages/app/src/backend/services/SmythVault.class.ts
@@ -578,7 +578,8 @@ class SmythVault {
): Promise<Record<string, any>> {
const cacheKey = generateKey(this.settingsKey + team, 'vault');
const idToken = getUserToken(req);
- let cacheResult = await cache.get(cacheKey, 60 * 60); // extend ttl by 1 hour every time we get the keys
+ // let cacheResult = await cache.get(cacheKey, 60 * 60); // extend ttl by 1 hour every time we get the keys
+ let cacheResult = undefined;
let settings = cacheResult?.data || {}; // removed cache for now
// let settings = {};
diff --git a/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx b/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
index 99c71e57..5ac4f5d4 100644
--- a/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
+++ b/packages/app/src/react/features/vault/components/create-oauth-connection-modal.tsx
@@ -1,34 +1,26 @@
// src/webappv2/pages/vault/create-oauth-connection-modal.tsx
import {
- Dialog,
- DialogContent,
- DialogFooter,
- DialogHeader,
- DialogTitle,
+ Dialog,
+ DialogContent,
+ DialogFooter,
+ DialogHeader,
+ DialogTitle,
} from '@src/react/shared/components/ui/dialog';
-import { Input } from '@src/react/shared/components/ui/input';
-import { Label } from '@src/react/shared/components/ui/label';
import { Button as CustomButton } from '@src/react/shared/components/ui/newDesign/button'; // Your custom button
-import { TextArea } from '@src/react/shared/components/ui/newDesign/textarea';
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from '@src/react/shared/components/ui/select';
import { OAuthServicesRegistry } from '@src/shared/helpers/oauth/oauth-services.helper';
import {
- OAUTH_SERVICES,
- deriveCallbackUrl,
- mapInternalToServiceName,
- mapServiceNameToInternal,
+ deriveCallbackUrl,
+ mapInternalToServiceName,
+ mapServiceNameToInternal,
} from '@src/shared/helpers/oauth/oauth.utils';
import React, { useEffect, useMemo, useState } from 'react';
import type {
- CreateOAuthConnectionModalProps,
- OAuthConnectionFormData,
+ CreateOAuthConnectionModalProps,
+ OAuthConnectionFormData,
} from '../types/oauth-connection';
+import { hasVaultKeys, resolveVaultKeys } from '../utils/vault-key-resolver';
+import { OAuthFormFields } from './oauth-form-fields';
+import { OAuthFormSkeleton } from './oauth-form-skeleton';
export function CreateOAuthConnectionModal({
isOpen,
@@ -39,36 +31,81 @@ export function CreateOAuthConnectionModal({
}: CreateOAuthConnectionModalProps) {
const [formData, setFormData] = useState<Partial<OAuthConnectionFormData>>({});
const [selectedService, setSelectedService] = useState<string>('None');
+ const [isResolvingVaultKeys, setIsResolvingVaultKeys] = useState<boolean>(false);
// Determine if it's an edit operation
const isEditMode = !!editConnection;
// Initialize form data when opening in edit mode or when editConnection changes
useEffect(() => {
- if (isOpen && isEditMode && editConnection?.oauth_info) {
- // Map OAuthConnection back to form data structure
- const serviceName = mapInternalToServiceName(editConnection.oauth_info.service);
- setFormData({
- name: editConnection.name,
- platform: editConnection.oauth_info.platform,
- oauthService: serviceName,
- scope: editConnection.oauth_info.scope,
- authorizationURL: editConnection.oauth_info.authorizationURL,
- tokenURL: editConnection.oauth_info.tokenURL,
- clientID: editConnection.oauth_info.clientID,
- clientSecret: editConnection.oauth_info.clientSecret,
- requestTokenURL: editConnection.oauth_info.requestTokenURL,
- accessTokenURL: editConnection.oauth_info.accessTokenURL,
- userAuthorizationURL: editConnection.oauth_info.userAuthorizationURL,
- consumerKey: editConnection.oauth_info.consumerKey,
- consumerSecret: editConnection.oauth_info.consumerSecret,
- });
- setSelectedService(serviceName);
- } else if (isOpen && !isEditMode) {
- // Reset form for creating new connection
- setFormData({ name: '', platform: '', oauthService: 'None' });
- setSelectedService('None');
- }
+ /**
+ * Loads and resolves the connection data for editing
+ * If vault keys are present, resolves them before populating the form
+ */
+ const loadConnectionData = async () => {
+ if (isOpen && isEditMode && editConnection?.oauth_info) {
+ setIsResolvingVaultKeys(true);
+
+ try {
+ const oauthInfo = editConnection.oauth_info;
+
+ // Check if the connection has any vault keys that need to be resolved
+ let resolvedOAuthInfo = oauthInfo;
+ if (hasVaultKeys(oauthInfo)) {
+ // Resolve vault keys to get actual values
+ resolvedOAuthInfo = await resolveVaultKeys(oauthInfo);
+ }
+
+ // Map OAuthConnection back to form data structure with resolved values
+ const serviceName = mapInternalToServiceName(resolvedOAuthInfo.service);
+ setFormData({
+ name: editConnection.name,
+ platform: resolvedOAuthInfo.platform,
+ oauthService: serviceName,
+ scope: resolvedOAuthInfo.scope,
+ authorizationURL: resolvedOAuthInfo.authorizationURL,
+ tokenURL: resolvedOAuthInfo.tokenURL,
+ clientID: resolvedOAuthInfo.clientID,
+ clientSecret: resolvedOAuthInfo.clientSecret,
+ requestTokenURL: resolvedOAuthInfo.requestTokenURL,
+ accessTokenURL: resolvedOAuthInfo.accessTokenURL,
+ userAuthorizationURL: resolvedOAuthInfo.userAuthorizationURL,
+ consumerKey: resolvedOAuthInfo.consumerKey,
+ consumerSecret: resolvedOAuthInfo.consumerSecret,
+ });
+ setSelectedService(serviceName);
+ } catch (error) {
+ console.error('Error loading connection data:', error);
+ // Fall back to showing the placeholders if resolution fails
+ const serviceName = mapInternalToServiceName(editConnection.oauth_info.service);
+ setFormData({
+ name: editConnection.name,
+ platform: editConnection.oauth_info.platform,
+ oauthService: serviceName,
+ scope: editConnection.oauth_info.scope,
+ authorizationURL: editConnection.oauth_info.authorizationURL,
+ tokenURL: editConnection.oauth_info.tokenURL,
+ clientID: editConnection.oauth_info.clientID,
+ clientSecret: editConnection.oauth_info.clientSecret,
+ requestTokenURL: editConnection.oauth_info.requestTokenURL,
+ accessTokenURL: editConnection.oauth_info.accessTokenURL,
+ userAuthorizationURL: editConnection.oauth_info.userAuthorizationURL,
+ consumerKey: editConnection.oauth_info.consumerKey,
+ consumerSecret: editConnection.oauth_info.consumerSecret,
+ });
+ setSelectedService(serviceName);
+ } finally {
+ setIsResolvingVaultKeys(false);
+ }
+ } else if (isOpen && !isEditMode) {
+ // Reset form for creating new connection
+ setFormData({ name: '', platform: '', oauthService: 'None' });
+ setSelectedService('None');
+ setIsResolvingVaultKeys(false);
+ }
+ };
+
+ loadConnectionData();
}, [isOpen, isEditMode, editConnection]);
// Handle input changes
@@ -188,254 +225,27 @@ export function CreateOAuthConnectionModal({
<DialogTitle>{isEditMode ? 'Edit OAuth Connection' : 'Add OAuth Connection'}</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit}>
- <div className="grid gap-4 py-4">
- {/* Name Field */}
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="name">
- Name <span className="text-red-500">*</span>
- </Label>
- <div className="col-span-3">
- <Input
- id="name"
- name="name"
- value={formData.name || ''}
- onChange={handleChange}
- placeholder="e.g., My Google Connection"
- required
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
-
- {/* Platform Field */}
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="platform">
- Platform <span className="text-red-500">*</span>
- </Label>
- <div className="col-span-3">
- <Input
- id="platform"
- name="platform"
- value={formData.platform || ''}
- onChange={handleChange}
- placeholder="e.g., Google Mail, HubSpot CRM"
- required
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
-
- {/* OAuth Service Selector */}
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="oauthService">
- Auth Service <span className="text-red-500">*</span>
- </Label>
- <div className="col-span-3">
- <Select
- name="oauthService"
- value={selectedService}
- onValueChange={handleSelectChange}
- required
- disabled={isProcessing}
- >
- <SelectTrigger className="h-9 w-full">
- <SelectValue placeholder="Select a service" />
- </SelectTrigger>
- <SelectContent>
- {OAUTH_SERVICES.map((service) => (
- <SelectItem key={service} value={service}>
- {service}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
+ {/* Show skeleton loader while resolving vault keys */}
+ {isResolvingVaultKeys ? (
+ <OAuthFormSkeleton serviceType={editConnection?.type} />
+ ) : (
+ <div className="grid gap-4 py-4">
+ <OAuthFormFields
+ formData={formData}
+ selectedService={selectedService}
+ isProcessing={isProcessing}
+ isResolvingVaultKeys={isResolvingVaultKeys}
+ showOAuth2Fields={showOAuth2Fields}
+ showOAuth1Fields={showOAuth1Fields}
+ showClientCredentialsFields={showClientCredentialsFields}
+ showScopeField={showScopeField}
+ oauth2CallbackURL={oauth2CallbackURL}
+ oauth1CallbackURL={oauth1CallbackURL}
+ handleChange={handleChange}
+ handleSelectChange={handleSelectChange}
+ />
</div>
-
- {/* Conditional Fields based on selectedService */}
- {selectedService !== 'None' && (
- <>
- {/* OAuth 2.0 Fields */}
- {(showOAuth2Fields || showClientCredentialsFields) && (
- <>
- {showOAuth2Fields && ( // Auth URL only for standard OAuth2
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="authorizationURL">Auth URL</Label>
- <div className="col-span-3">
- <Input
- id="authorizationURL"
- name="authorizationURL"
- value={formData.authorizationURL || ''}
- onChange={handleChange}
- placeholder="Authorization Endpoint URL"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- )}
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="tokenURL">Token URL</Label>
- <div className="col-span-3">
- <Input
- id="tokenURL"
- name="tokenURL"
- value={formData.tokenURL || ''}
- onChange={handleChange}
- placeholder="Token Endpoint URL"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="clientID">Client ID</Label>
- <div className="col-span-3">
- <Input
- id="clientID"
- name="clientID"
- value={formData.clientID || ''}
- onChange={handleChange}
- placeholder="OAuth Client ID"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="clientSecret">Client Secret</Label>
- <div className="col-span-3">
- <Input
- id="clientSecret"
- name="clientSecret"
- type="password"
- value={formData.clientSecret || ''}
- onChange={handleChange}
- placeholder="OAuth Client Secret"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- {showOAuth2Fields &&
- oauth2CallbackURL && ( // Callback URL Display (OAuth2)
- <div className="grid grid-cols-4 items-center gap-4">
- <Label>Callback URL</Label>
- <div className="col-span-3 text-sm text-gray-500 break-all">
- {oauth2CallbackURL}
- </div>
- </div>
- )}
- </>
- )}
-
- {/* OAuth 1.0a Fields */}
- {showOAuth1Fields && (
- <>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="requestTokenURL">Request Token URL</Label>
- <div className="col-span-3">
- <Input
- id="requestTokenURL"
- name="requestTokenURL"
- value={formData.requestTokenURL || ''}
- onChange={handleChange}
- placeholder="Request Token URL"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="accessTokenURL">Access Token URL</Label>
- <div className="col-span-3">
- <Input
- id="accessTokenURL"
- name="accessTokenURL"
- value={formData.accessTokenURL || ''}
- onChange={handleChange}
- placeholder="Access Token URL"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="userAuthorizationURL">User Auth URL</Label>
- <div className="col-span-3">
- <Input
- id="userAuthorizationURL"
- name="userAuthorizationURL"
- value={formData.userAuthorizationURL || ''}
- onChange={handleChange}
- placeholder="User Authorization URL"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="consumerKey">Consumer Key</Label>
- <div className="col-span-3">
- <Input
- id="consumerKey"
- name="consumerKey"
- value={formData.consumerKey || ''}
- onChange={handleChange}
- placeholder="OAuth Consumer Key"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="consumerSecret">Consumer Secret</Label>
- <div className="col-span-3">
- <Input
- id="consumerSecret"
- name="consumerSecret"
- type="password"
- value={formData.consumerSecret || ''}
- onChange={handleChange}
- placeholder="OAuth Consumer Secret"
- disabled={isProcessing}
- fullWidth
- />
- </div>
- </div>
- {oauth1CallbackURL && ( // Callback URL Display (OAuth1)
- <div className="grid grid-cols-4 items-center gap-4">
- <Label>Callback URL</Label>
- <div className="col-span-3 text-sm text-gray-500 break-all">
- {oauth1CallbackURL}
- </div>
- </div>
- )}
- </>
- )}
-
- {/* Scope Field (Common for most OAuth2 flows) */}
- {showScopeField && (
- <div className="grid grid-cols-4 items-center gap-4">
- <Label htmlFor="scope">Scopes</Label>
- <div className="col-span-3">
- <TextArea
- id="scope"
- name="scope"
- value={formData.scope || ''}
- onChange={handleChange}
- placeholder="Enter scopes separated by space"
- disabled={isProcessing}
- fullWidth={true}
- />
- </div>
- </div>
- )}
- </>
- )}
- </div>
+ )}
<DialogFooter>
{/* <DialogClose asChild>
<CustomButton
@@ -449,9 +259,13 @@ export function CreateOAuthConnectionModal({
<CustomButton
variant="primary"
type="submit"
- loading={isProcessing}
+ loading={isProcessing || isResolvingVaultKeys}
disabled={
- isProcessing || selectedService === 'None' || !formData.name || !formData.platform
+ isProcessing ||
+ isResolvingVaultKeys ||
+ selectedService === 'None' ||
+ !formData.name ||
+ !formData.platform
}
label={isEditMode ? 'Save Changes' : 'Add Connection'}
/>
diff --git a/packages/app/src/react/features/vault/components/oauth-form-fields.tsx b/packages/app/src/react/features/vault/components/oauth-form-fields.tsx
new file mode 100644
index 00000000..1eae3123
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/oauth-form-fields.tsx
@@ -0,0 +1,356 @@
+/**
+ * OAuth Form Fields Component
+ *
+ * Renders the appropriate OAuth form fields based on the selected service type.
+ * Separated into its own component for better modularity and maintainability.
+ */
+
+import { Input } from '@src/react/shared/components/ui/input';
+import { Label } from '@src/react/shared/components/ui/label';
+import { TextArea } from '@src/react/shared/components/ui/newDesign/textarea';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@src/react/shared/components/ui/select';
+import { OAUTH_SERVICES } from '@src/shared/helpers/oauth/oauth.utils';
+import React from 'react';
+import type { OAuthConnectionFormData } from '../types/oauth-connection';
+
+/**
+ * Props for the OAuthFormFields component
+ */
+interface OAuthFormFieldsProps {
+ /**
+ * The current form data
+ */
+ formData: Partial<OAuthConnectionFormData>;
+
+ /**
+ * The currently selected OAuth service
+ */
+ selectedService: string;
+
+ /**
+ * Whether the form is currently being processed
+ */
+ isProcessing: boolean;
+
+ /**
+ * Whether vault keys are currently being resolved
+ */
+ isResolvingVaultKeys: boolean;
+
+ /**
+ * Whether to show OAuth 2.0 specific fields
+ */
+ showOAuth2Fields: boolean;
+
+ /**
+ * Whether to show OAuth 1.0a specific fields
+ */
+ showOAuth1Fields: boolean;
+
+ /**
+ * Whether to show Client Credentials specific fields
+ */
+ showClientCredentialsFields: boolean;
+
+ /**
+ * Whether to show the scope field
+ */
+ showScopeField: boolean;
+
+ /**
+ * The OAuth 2.0 callback URL (for display only)
+ */
+ oauth2CallbackURL?: string;
+
+ /**
+ * The OAuth 1.0a callback URL (for display only)
+ */
+ oauth1CallbackURL?: string;
+
+ /**
+ * Handler for input field changes
+ */
+ handleChange: (e: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement | HTMLSelectElement>) => void;
+
+ /**
+ * Handler for select field changes
+ */
+ handleSelectChange: (value: string) => void;
+}
+
+/**
+ * Renders OAuth form fields based on the selected service type
+ */
+export function OAuthFormFields({
+ formData,
+ selectedService,
+ isProcessing,
+ isResolvingVaultKeys,
+ showOAuth2Fields,
+ showOAuth1Fields,
+ showClientCredentialsFields,
+ showScopeField,
+ oauth2CallbackURL,
+ oauth1CallbackURL,
+ handleChange,
+ handleSelectChange,
+}: OAuthFormFieldsProps) {
+ const isDisabled = isProcessing || isResolvingVaultKeys;
+
+ return (
+ <>
+ {/* Name Field */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="name">
+ Name <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <Input
+ id="name"
+ name="name"
+ value={formData.name || ''}
+ onChange={handleChange}
+ placeholder="e.g., My Google Connection"
+ required
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+
+ {/* Platform Field */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="platform">
+ Platform <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <Input
+ id="platform"
+ name="platform"
+ value={formData.platform || ''}
+ onChange={handleChange}
+ placeholder="e.g., Google Mail, HubSpot CRM"
+ required
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+
+ {/* OAuth Service Selector */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="oauthService">
+ Auth Service <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <Select
+ name="oauthService"
+ value={selectedService}
+ onValueChange={handleSelectChange}
+ required
+ disabled={isDisabled}
+ >
+ <SelectTrigger className="h-9 w-full">
+ <SelectValue placeholder="Select a service" />
+ </SelectTrigger>
+ <SelectContent>
+ {OAUTH_SERVICES.map((service) => (
+ <SelectItem key={service} value={service}>
+ {service}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ </div>
+
+ {/* Conditional Fields based on selectedService */}
+ {selectedService !== 'None' && (
+ <>
+ {/* OAuth 2.0 Fields */}
+ {(showOAuth2Fields || showClientCredentialsFields) && (
+ <>
+ {showOAuth2Fields && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="authorizationURL">Auth URL</Label>
+ <div className="col-span-3">
+ <Input
+ id="authorizationURL"
+ name="authorizationURL"
+ value={formData.authorizationURL || ''}
+ onChange={handleChange}
+ placeholder="Authorization Endpoint URL"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ )}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="tokenURL">Token URL</Label>
+ <div className="col-span-3">
+ <Input
+ id="tokenURL"
+ name="tokenURL"
+ value={formData.tokenURL || ''}
+ onChange={handleChange}
+ placeholder="Token Endpoint URL"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="clientID">Client ID</Label>
+ <div className="col-span-3">
+ <Input
+ id="clientID"
+ name="clientID"
+ value={formData.clientID || ''}
+ onChange={handleChange}
+ placeholder="OAuth Client ID"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="clientSecret">Client Secret</Label>
+ <div className="col-span-3">
+ <Input
+ id="clientSecret"
+ name="clientSecret"
+ type="password"
+ value={formData.clientSecret || ''}
+ onChange={handleChange}
+ placeholder="OAuth Client Secret"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ {showOAuth2Fields && oauth2CallbackURL && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label>Callback URL</Label>
+ <div className="col-span-3 text-sm text-gray-500 break-all">
+ {oauth2CallbackURL}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ {/* OAuth 1.0a Fields */}
+ {showOAuth1Fields && (
+ <>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="requestTokenURL">Request Token URL</Label>
+ <div className="col-span-3">
+ <Input
+ id="requestTokenURL"
+ name="requestTokenURL"
+ value={formData.requestTokenURL || ''}
+ onChange={handleChange}
+ placeholder="Request Token URL"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="accessTokenURL">Access Token URL</Label>
+ <div className="col-span-3">
+ <Input
+ id="accessTokenURL"
+ name="accessTokenURL"
+ value={formData.accessTokenURL || ''}
+ onChange={handleChange}
+ placeholder="Access Token URL"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="userAuthorizationURL">User Auth URL</Label>
+ <div className="col-span-3">
+ <Input
+ id="userAuthorizationURL"
+ name="userAuthorizationURL"
+ value={formData.userAuthorizationURL || ''}
+ onChange={handleChange}
+ placeholder="User Authorization URL"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="consumerKey">Consumer Key</Label>
+ <div className="col-span-3">
+ <Input
+ id="consumerKey"
+ name="consumerKey"
+ value={formData.consumerKey || ''}
+ onChange={handleChange}
+ placeholder="OAuth Consumer Key"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="consumerSecret">Consumer Secret</Label>
+ <div className="col-span-3">
+ <Input
+ id="consumerSecret"
+ name="consumerSecret"
+ type="password"
+ value={formData.consumerSecret || ''}
+ onChange={handleChange}
+ placeholder="OAuth Consumer Secret"
+ disabled={isDisabled}
+ fullWidth
+ />
+ </div>
+ </div>
+ {oauth1CallbackURL && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label>Callback URL</Label>
+ <div className="col-span-3 text-sm text-gray-500 break-all">
+ {oauth1CallbackURL}
+ </div>
+ </div>
+ )}
+ </>
+ )}
+
+ {/* Scope Field (Common for most OAuth2 flows) */}
+ {showScopeField && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="scope">Scopes</Label>
+ <div className="col-span-3">
+ <TextArea
+ id="scope"
+ name="scope"
+ value={formData.scope || ''}
+ onChange={handleChange}
+ placeholder="Enter scopes separated by space"
+ disabled={isDisabled}
+ fullWidth={true}
+ />
+ </div>
+ </div>
+ )}
+ </>
+ )}
+ </>
+ );
+}
+
diff --git a/packages/app/src/react/features/vault/components/oauth-form-skeleton.tsx b/packages/app/src/react/features/vault/components/oauth-form-skeleton.tsx
new file mode 100644
index 00000000..645af771
--- /dev/null
+++ b/packages/app/src/react/features/vault/components/oauth-form-skeleton.tsx
@@ -0,0 +1,155 @@
+/**
+ * OAuth Form Skeleton Component
+ *
+ * Displays a loading skeleton for the OAuth connection form while resolving vault keys.
+ */
+
+import { Label } from '@src/react/shared/components/ui/label';
+
+/**
+ * Skeleton loader component for individual form fields
+ */
+function FieldSkeleton() {
+ return (
+ <div className="h-9 w-full bg-gray-200 animate-pulse rounded-md"></div>
+ );
+}
+
+/**
+ * Props for the OAuthFormSkeleton component
+ */
+interface OAuthFormSkeletonProps {
+ /**
+ * The OAuth service type to determine which fields to show
+ */
+ serviceType?: 'oauth' | 'oauth2' | 'oauth2_client_credentials' | 'none';
+}
+
+/**
+ * Displays a skeleton loader for the OAuth connection form
+ * Shows loading placeholders for all form fields
+ */
+export function OAuthFormSkeleton({ serviceType = 'none' }: OAuthFormSkeletonProps) {
+ const showOAuth2Fields = serviceType === 'oauth2';
+ const showOAuth1Fields = serviceType === 'oauth';
+ const showClientCredentialsFields = serviceType === 'oauth2_client_credentials';
+ const showScopeField = serviceType === 'oauth2';
+
+ return (
+ <div className="grid gap-4 py-4">
+ {/* Name Field */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="name">
+ Name <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+
+ {/* Platform Field */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="platform">
+ Platform <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+
+ {/* OAuth Service Selector */}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="oauthService">
+ Auth Service <span className="text-red-500">*</span>
+ </Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+
+ {/* OAuth 2.0 Fields */}
+ {(showOAuth2Fields || showClientCredentialsFields) && (
+ <>
+ {showOAuth2Fields && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="authorizationURL">Auth URL</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ )}
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="tokenURL">Token URL</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="clientID">Client ID</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="clientSecret">Client Secret</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* OAuth 1.0a Fields */}
+ {showOAuth1Fields && (
+ <>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="requestTokenURL">Request Token URL</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="accessTokenURL">Access Token URL</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="userAuthorizationURL">User Auth URL</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="consumerKey">Consumer Key</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="consumerSecret">Consumer Secret</Label>
+ <div className="col-span-3">
+ <FieldSkeleton />
+ </div>
+ </div>
+ </>
+ )}
+
+ {/* Scope Field */}
+ {showScopeField && (
+ <div className="grid grid-cols-4 items-center gap-4">
+ <Label htmlFor="scope">Scopes</Label>
+ <div className="col-span-3">
+ <div className="h-20 w-full bg-gray-200 animate-pulse rounded-md"></div>
+ </div>
+ </div>
+ )}
+
+ {/* Loading message */}
+ <div className="text-center text-sm text-gray-500 py-2">
+ Loading connection details...
+ </div>
+ </div>
+ );
+}
+
diff --git a/packages/app/src/react/features/vault/hooks/use-vault.tsx b/packages/app/src/react/features/vault/hooks/use-vault.tsx
index 313f3268..aac3da13 100644
--- a/packages/app/src/react/features/vault/hooks/use-vault.tsx
+++ b/packages/app/src/react/features/vault/hooks/use-vault.tsx
@@ -18,6 +18,15 @@ import { queryClient } from '@src/react/shared/query-client';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { useCallback, useEffect, useState } from 'react';
+const fetchOptions = {
+ refetchOnWindowFocus: false,
+ refetchOnMount: false,
+ refetchOnReconnect: false,
+ refetchInterval: false,
+ refetchIntervalInBackground: false,
+} as const;
+
+
export function useVault() {
const [enterpriseModels, setEnterpriseModels] = useState<EnterpriseModel[]>([]);
const [apiKeys, setApiKeys] = useState<ApiKey[]>([]);
@@ -71,10 +80,12 @@ export function useVault() {
}
};
+
const useUserModels = (options = {}) => {
return useQuery<UserModel[], Error>({
queryKey: ['get_vault_user_models'],
queryFn: () => userModelService.fetchUserModels(),
+ ...fetchOptions,
...options,
});
};
@@ -124,6 +135,7 @@ export function useVault() {
return useQuery<ApiKeysResponse, Error>({
queryKey: ['get_vault_api_keys'],
queryFn: () => apiKeyService.fetchAPIKeys(),
+ ...fetchOptions,
...options,
});
};
@@ -292,6 +304,7 @@ export function useUserCustomModels() {
return useQuery({
queryKey: USER_CUSTOM_MODEL_QUERY_KEYS.USER_CUSTOM_MODELS,
queryFn: () => userCustomModelService.getUserCustomModels(),
+ ...fetchOptions,
});
}
diff --git a/packages/app/src/react/features/vault/utils/vault-key-resolver.ts b/packages/app/src/react/features/vault/utils/vault-key-resolver.ts
new file mode 100644
index 00000000..d39c89d6
--- /dev/null
+++ b/packages/app/src/react/features/vault/utils/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);
+}