SmythOS Studio: Open-Source Visual AI Agent Builder and deployable runtime stack from SmythOS. Start with an intuitive drag-and-drop workspace, extend with custom code, and deploy your agents anywhere — local, cloud, or edge — with full governance and control.
JavaScript a2aagentic-aiai-agentsdevtoolsmcp-clientn8n-alternativeno-codeopen-sourceorchestrationsmythosvisual-builder
optimize the api key implementation
Forhad Hosain779e86a9f313
diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.tsindex 4cd4fe13..cd06901c 100644--- a/packages/app/src/backend/routes/api/page/vault.ts+++ b/packages/app/src/backend/routes/api/page/vault.ts@@ -838,49 +838,6 @@ router.get('/user-custom-llm/:id', includeTeamDetails, async (req, res) => {}});-/**- * Get a specific user custom LLM model by ID with decrypted credentials- * GET /user-custom-llm/:id/with-credentials- */-router.get('/user-custom-llm/:id/with-credentials', includeTeamDetails, async (req, res) => {- try {- const entryId = req.params.id;- const modelInfo = await userCustomLLMHelper.getUserCustomLLMWithCredentials(req, entryId);-- if (!modelInfo) {- return res.status(404).json({ success: false, error: 'User custom LLM model not found.' });- }-- res.status(200).json({ success: true, data: modelInfo });- } catch (error) {- console.error('Error getting user custom LLM model with credentials:', error?.message);- res.status(500).json({ success: false, error: 'Error getting user custom LLM model.' });- }-});--/**- * Get a user custom LLM model with credentials by name- * GET /user-custom-llm/with-credentials/:name- */-router.get('/user-custom-llm/with-credentials/:name', includeTeamDetails, async (req, res) => {- try {- const modelName = req.params.name;- const modelInfo = await userCustomLLMHelper.getUserCustomLLMByName(req, modelName);-- if (!modelInfo || Object.keys(modelInfo).length === 0) {- return res.status(404).json({ success: false, error: 'User custom LLM model not found.' });- }-- // Return the full model configuration including credentials (baseURL, etc.)- res.status(200).json({ success: true, data: modelInfo });- } catch (error) {- console.error('Error getting user custom LLM model with credentials:', error?.message);- res- .status(500)- .json({ success: false, error: 'Error getting user custom LLM model with credentials.' });- }-});-/*** Delete a user custom LLM model* DELETE /user-custom-llm/:iddiff --git a/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.tsindex c3a7d3ac..868ceae9 100644--- a/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts+++ b/packages/app/src/backend/routes/router.helpers/userCustomLLM.helper.ts@@ -109,6 +109,10 @@ async function saveUserCustomLLM(req: Request, params: UserCustomLLMInputParams)};const teamId = params.teamId || req?._team?.id;++ // userEmail is required for vault key management when storing API keys.+ // The vault service uses it to track ownership, maintain audit trails,+ // and manage access control for sensitive credentials.const userEmail = params.userEmail || req?._user?.email;if (!teamId || !userEmail) {@@ -362,75 +366,6 @@ async function getAllUserCustomLLMs(req: Request): Promise<Record<string, UserCu}}-/**- * Gets a user custom LLM configuration with credentials (API key from vault)- * @param req - Express request object- * @param entryId - The ID of the entry to retrieve- * @returns Promise with the model info including decrypted API key- */-async function getUserCustomLLMWithCredentials(- req: Request,- entryId: string,-): Promise<UserCustomLLMInfo | null> {- try {- const teamId = req?._team?.id;- const accessToken = req?.user?.accessToken;- const idToken = req?.session?.idToken;-- if (!teamId) {- throw new Error('Team ID is required');- }-- // Get the model info first- const modelInfo = await getUserCustomLLMByEntryId(req, entryId);-- if (!modelInfo) {- return null;- }-- // If the model has credentials with a vault key template variable, retrieve the actual key- if (modelInfo.credentials?.isUserKey && modelInfo.credentials?.apiKey) {- const apiKeyTemplateVariable = modelInfo.credentials.apiKey;-- // Extract the key name from the template variable {{KEY(...)}}- const match = apiKeyTemplateVariable.match(/\{\{KEY\((.+?)\)\}\}/);-- if (match && match[1]) {- const apiKeyName = match[1];-- // Retrieve the key from vault- try {- const keyEntry = await vault.get(- {- team: teamId,- keyName: apiKeyName,- },- req,- );-- // Return the model info with the decrypted API key- return {- ...modelInfo,- credentials: {- apiKey: keyEntry?.key || '',- isUserKey: true,- },- };- } catch (vaultError) {- console.warn('Error retrieving API key from vault:', vaultError?.message);- // Return model info without the key if vault retrieval fails- return modelInfo;- }- }- }-- return modelInfo;- } catch (error) {- console.error('Error getting user custom LLM with credentials:', error?.message);- throw error;- }-}-/*** Deletes a user custom LLM configuration* @param req - Express request object@@ -479,7 +414,6 @@ export const userCustomLLMHelper = {saveUserCustomLLM,getUserCustomLLMByName,getUserCustomLLMByEntryId,- getUserCustomLLMWithCredentials,getAllUserCustomLLMs,deleteUserCustomLLM,};diff --git a/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsxindex 72699027..d1f3d338 100644--- a/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx+++ b/packages/app/src/react/features/vault/components/create-user-custom-model-modal.tsx@@ -181,7 +181,8 @@ export function CreateUserCustomModelModal({// Extract API key info from template variable if presentconst apiKeyTemplateVariable = editModel.credentials?.apiKey || '';const extractedKeyName = extractKeyNameFromTemplate(apiKeyTemplateVariable);- const hasVaultKey = editModel.credentials?.isUserKey === true && extractedKeyName !== '';+ // If we successfully extracted a key name, it means there's a vault key+ const hasVaultKey = extractedKeyName !== '';// Update formData with latest editModel values// Only update apiKey field if it's currently empty (not revealed) or if modal is just opening@@ -369,22 +370,19 @@ export function CreateUserCustomModelModal({/*** Handles revealing the API key from vault- * Fetches the decrypted API key and populates the form field+ * Fetches the decrypted API key using the key name we already have* If key cannot be retrieved, sets empty value allowing user to enter a new key*/const handleRevealApiKey = async () => {- if (!editModel?.id) return;+ if (!formData.apiKeyName) return;setIsLoadingApiKey(true);try {- const modelWithCredentials = await userCustomModelService.getUserCustomModelWithCredentials(- editModel.id,- );+ // Use the vault key name we already extracted from credentials when modal opened+ // No need to fetch the model again - we already have the key name+ const apiKey = await userCustomModelService.getVaultKeyByName(formData.apiKeyName);- // Validate that we received an actual API key, not a template variable- const apiKey = modelWithCredentials.credentials?.apiKey || '';-- // Check if we got the actual key or if it's still a template variable+ // Check if we got an actual key (not a template variable or empty string)// If it's a template or empty, set empty string so user can enter a new keyconst actualKey = apiKey && !apiKey.startsWith('{{KEY(') ? apiKey : '';diff --git a/packages/app/src/react/features/vault/vault-business-logic.ts b/packages/app/src/react/features/vault/vault-business-logic.tsindex d8325b01..a267e308 100644--- a/packages/app/src/react/features/vault/vault-business-logic.ts+++ b/packages/app/src/react/features/vault/vault-business-logic.ts@@ -826,11 +826,12 @@ export const userCustomModelService = {},/**- * Gets a user custom LLM model with decrypted credentials+ * Gets a vault key value by its name+ * Uses the vault key name directly without needing to fetch model info first*/- getUserCustomModelWithCredentials: async (modelId: string): Promise<UserCustomModel> => {+ getVaultKeyByName: async (keyName: string): Promise<string> => {try {- const response = await fetch(`/api/page/vault/user-custom-llm/${modelId}/with-credentials`, {+ const response = await fetch(`/api/page/vault/keys/name/${encodeURIComponent(keyName)}`, {method: 'GET',headers: {'Content-Type': 'application/json',@@ -838,41 +839,18 @@ export const userCustomModelService = {});if (!response.ok) {- throw new Error('Failed to get user custom model with credentials');+ throw new Error('Failed to get vault key');}const result = await response.json();if (!result.success) {- throw new Error(result.error || 'Failed to get user custom model with credentials');+ throw new Error(result.error || 'Failed to get vault key');}- const modelData = result.data;-- // Transform the data to match UserCustomModel format- const transformedModel: UserCustomModel = {- id: modelData.id,- name: modelData.name,- modelId: modelData.modelId,- // Remove '.forbidden' from baseURL if present- baseURL: modelData.baseURL?.replace(/\.forbidden/gi, '') || modelData.baseURL,- provider: modelData.provider,- contextWindow:- modelData.contextWindow !== undefined ? modelData.contextWindow : modelData.tokens,- maxOutputTokens:- modelData.maxOutputTokens !== undefined- ? modelData.maxOutputTokens- : modelData.completionTokens,- fallbackLLM: modelData.fallbackLLM || '',- features: modelData.features || ['text'],- credentials: modelData.credentials,- };-- return transformedModel;+ return result.data?.data?.key || '';} catch (error) {- console.error('Error getting user custom model with credentials:', error);- throw new Error(- error.error || error.message || 'Failed to get user custom model with credentials',- );+ console.error('Error getting vault key:', error);+ throw new Error(error.error || error.message || 'Failed to get vault key');}},