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): store secrets in vault

Ahmed Essam5545dd362427
diff --git a/packages/app/src/backend/routes/api/page/vault.ts b/packages/app/src/backend/routes/api/page/vault.ts
index bd0356fd..c5c2b3e9 100644
--- a/packages/app/src/backend/routes/api/page/vault.ts
+++ b/packages/app/src/backend/routes/api/page/vault.ts
@@ -1,3 +1,4 @@
+import { VAULT_SCOPE_OAUTH_CONNECTIONS } from '@src/shared/constants/general';
import express from 'express';
import config from '../../../config';
import {
@@ -19,7 +20,6 @@ import { isCustomLLMAllowed } from '../../../utils/customLLM';
import { customLLMHelper } from '../../router.helpers/customLLM.helper';
import { userCustomLLMHelper } from '../../router.helpers/userCustomLLM.helper';
import { getVaultKeys, setVaultKey } from '../../router.utils';
-
const router = express.Router();
const vault = new Vault();
@@ -317,6 +317,78 @@ function sanitizeOAuthConnections(connections: any): any {
return sanitized;
}
+function isVaultKey(key: string): string | null {
+ // pattern is {{KEY(keyName)}}
+ const pattern = /{{KEY\((.*?)\)}}/;
+ const match = key.match(pattern);
+ return match ? match[1] : null;
+}
+
+async function deleteVaultKeys(entry: any, team: string, req: any) {
+ const vaultKeys = [];
+
+ const entriesToCheck = [entry];
+ // crawl the entry using BFS so that we can go deep if objects are nested
+ while (entriesToCheck.length > 0) {
+ const currentEntry = entriesToCheck.shift();
+ // check if the current entry is
+ // string: then check if it is vault key
+ // object: add it to the entriesToCheck
+ if (typeof currentEntry === 'string') {
+ const keyNameNullable = isVaultKey(currentEntry);
+ if (keyNameNullable) {
+ vaultKeys.push(keyNameNullable);
+ }
+ } else if (typeof currentEntry === 'object') {
+ entriesToCheck.push(...Object.values(currentEntry));
+ }
+ }
+
+ console.log('WE SHOULD DELETE', vaultKeys);
+ await Promise.all(
+ vaultKeys.map(async (key) => {
+ return await vault.delete(key, team, req);
+ }),
+ );
+}
+
+async function storeSensitiveKeysInVault(entry: { [key: string]: any }, entryId: string, req: any) {
+ let clonedEntry = JSON.parse(JSON.stringify(entry));
+ const senstiveFields = ['clientID', 'clientSecret', 'consumerKey', 'consumerSecret'];
+
+ const storeKeyPromises = senstiveFields.map(async (field) => {
+ if (!clonedEntry[field]) return;
+ const keyName = `${entryId}_${field}`;
+ const keyData = {
+ team: req?._team?.id,
+ owner: req?._user?.email,
+ name: keyName,
+ key: clonedEntry[field],
+ scope: [VAULT_SCOPE_OAUTH_CONNECTIONS],
+ };
+ const result = await vault.set({
+ req,
+ data: keyData,
+ keyId: keyName,
+ });
+ 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}`);
+ }
+
+ clonedEntry[field] = `{{KEY(${keyName})}}`;
+ return result;
+ });
+
+ try {
+ await Promise.all(storeKeyPromises);
+ } catch (error) {
+ console.error('Failed to store sensitive keys in vault:', error);
+ throw new Error('Failed to store sensitive keys in vault');
+ }
+ return clonedEntry;
+}
+
router.get('/oauth-connections', includeTeamDetails, async (req, res) => {
try {
const settings = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);
@@ -328,30 +400,15 @@ router.get('/oauth-connections', includeTeamDetails, async (req, res) => {
}
// Parse any stringified entries before sanitization
- const parsedSettings = {};
- if (settings && typeof settings === 'object') {
- for (const [key, value] of Object.entries(settings)) {
- if (typeof value === 'string') {
- try {
- parsedSettings[key] = JSON.parse(value);
- } catch (e) {
- // If parsing fails, keep as is
- parsedSettings[key] = value;
- }
- } else {
- parsedSettings[key] = value;
- // Log warning if tokens are exposed (for security monitoring)
- if (value && typeof value === 'object') {
- const hasExposedTokens =
- (value.auth_data?.primary && value.auth_data.primary !== '[REDACTED]') ||
- (value.primary && value.primary !== '[REDACTED]');
- if (hasExposedTokens) {
- //console.warn(`[OAuth Security] Connection ${key} has unsanitized tokens - will be sanitized before sending to frontend`);
- }
- }
- }
+ const parsedSettings = Object.entries(settings || {}).reduce((acc, [key, value]) => {
+ acc[key] = value;
+ if (typeof value === 'string') {
+ try {
+ acc[key] = JSON.parse(value);
+ } catch {}
}
- }
+ return acc;
+ }, {});
// Sanitize the settings before sending to frontend
const sanitizedSettings = sanitizeOAuthConnections(parsedSettings);
@@ -423,8 +480,11 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
};
}
+ await deleteVaultKeys(existingEntry, req?._team?.id, req);
// 5. Merge and normalize the settings using helper (now both are guaranteed to be objects)
- const mergedAuthSettings = mergeAuthSettings(existingEntry, parsedNewSettings);
+ let preparedNewSettings = mergeAuthSettings(existingEntry, parsedNewSettings);
+ preparedNewSettings = await storeSensitiveKeysInVault(preparedNewSettings, entryId, req);
+
// 6. Parse preservedAuthData if it's somehow still a string (defensive coding)
preservedAuthData = safeJsonParse(
preservedAuthData,
@@ -436,7 +496,7 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
const existingOAuthInfo =
existingEntry.auth_settings?.oauth_info || existingEntry.oauth_info || {};
const newOAuthInfo =
- mergedAuthSettings.oauth_info || mergedAuthSettings.auth_settings?.oauth_info || {};
+ preparedNewSettings.oauth_info || preparedNewSettings.auth_settings?.oauth_info || {};
const authCriticalFields = [
'clientID',
'clientSecret',
@@ -465,7 +525,7 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
: oldValueFromRoot;
// Get values from both possible locations for new data
const newValueFromOAuthInfo = newOAuthInfo[field];
- const newValueFromSettings = mergedAuthSettings[field]; // New data might be at root of mergedAuthSettings
+ const newValueFromSettings = preparedNewSettings[field]; // New data might be at root of mergedAuthSettings
const newValue =
newValueFromOAuthInfo !== undefined ? newValueFromOAuthInfo : newValueFromSettings;
// Normalize values: treat undefined, null, empty string, and whitespace as equivalent
@@ -487,7 +547,7 @@ router.put('/oauth-connections', includeTeamDetails, async (req, res) => {
// Clear tokens if auth-critical fields changed, otherwise preserve them
const finalDataToSave = {
auth_data: hasAuthCriticalChanges ? {} : preservedAuthData,
- auth_settings: mergedAuthSettings,
+ auth_settings: preparedNewSettings,
};
// 9. Save the updated entry back using saveTeamSettingsObj
@@ -534,6 +594,25 @@ router.delete('/oauth-connections/:connectionId', includeTeamDetails, async (req
}
try {
+ const existingSettingsMap = await getTeamSettingsObj(req, OAUTH_SETTING_KEY);
+ if (existingSettingsMap === null) {
+ return res
+ .status(500)
+ .json({ success: false, error: 'Failed to retrieve existing OAuth settings.' });
+ }
+
+ let existingEntry = safeJsonParse(
+ existingSettingsMap[connectionId],
+ {},
+ `OAuth DELETE existingEntry ${connectionId}`,
+ );
+
+ if (!existingEntry) {
+ return res.status(404).json({ success: false, error: 'OAuth connection not found.' });
+ }
+
+ await deleteVaultKeys(existingEntry, req?._team?.id, req);
+
const result = await deleteTeamSettingsObj(req, OAUTH_SETTING_KEY, connectionId);
if (!result.success) {
diff --git a/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts b/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts
index 08c20039..8510022e 100644
--- a/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts
+++ b/packages/app/src/backend/routes/oauth/helper/oauthHelper.ts
@@ -1,4 +1,5 @@
-import { getTeamSettingsObj } from '../../../services/team-data.service';
+import { vault } from '@src/backend/services/SmythVault.class';
+import { getTeamSettingsObj } from '@src/backend/services/team-data.service';
export const isKeyTemplateVariable = (str: string): boolean => {
if (!str) return false;
@@ -34,11 +35,8 @@ export const replaceTemplateVariablesOptimized = async (req) => {
// Extract request body
const reqBody = req.body;
- // Fetch all team settings
- const allKeys = await getTeamSettingsObj(req, 'vault');
-
// Fetch template variables and their corresponding values
- const templateValues = fetchTemplateValues(reqBody, allKeys, keysToCheck, req._team?.id);
+ const templateValues = await fetchTemplateValues(req, keysToCheck);
// Map template variables to their fetched values
const valuesObj = mapTemplateValues(templateValues, reqBody);
@@ -50,14 +48,27 @@ export const replaceTemplateVariablesOptimized = async (req) => {
};
// Function to fetch template values asynchronously
-export const fetchTemplateValues = (reqBody, allKeys, keysToCheck, teamId) => {
+export const fetchTemplateValues = async (req, keysToCheck) => {
+ /*
+ This is supposed to search the keys in agent settings (legacy) and if not, search in the VAULT
+ */
+ const reqBody = req.body;
+ const teamId = req._team?.id;
+ // Fetch all team settings
+ const allKeys = await getTeamSettingsObj(req, 'vault');
const templateValues = [];
for (const key of keysToCheck) {
if (isKeyTemplateVariable(reqBody[key])) {
- const keyNames = getKeyIdsFromTemplateVars(reqBody[key]);
- const filteredKeys = filter(allKeys, { team: teamId, keyName: keyNames[0] });
- const value = Object.values(filteredKeys).length ? Object.values(filteredKeys)[0] : null;
+ const keyName = getKeyIdsFromTemplateVars(reqBody[key])[0];
+ const filteredKeys = filter(allKeys, { team: teamId, keyName });
+ // 1. search in agent settings
+ let value = Object.values(filteredKeys).length ? Object.values(filteredKeys)[0] : null;
+
+ // 2. search in vault
+ if (!value) {
+ value = (await vault.get({ team: teamId, keyName }, req)).key;
+ }
templateValues.push({ key, value });
}
}
@@ -72,7 +83,7 @@ export const mapTemplateValues = (templateValues, reqBody) => {
templateValues.forEach(({ key, value }) => {
if (value) {
valuesObj[key] = value;
- reqBody[key] = value['key']; // Assuming 'key' is the property to be assigned
+ reqBody[key] = typeof value === 'object' ? value['key'] : value;
}
});
diff --git a/packages/app/src/backend/routes/router.utils/vault.utils.ts b/packages/app/src/backend/routes/router.utils/vault.utils.ts
index 3530c174..a14befd7 100644
--- a/packages/app/src/backend/routes/router.utils/vault.utils.ts
+++ b/packages/app/src/backend/routes/router.utils/vault.utils.ts
@@ -1,6 +1,6 @@
import { Request } from 'express';
import Joi from 'joi';
-import { VAULT_SCOPE_AGENT_LLM } from '../../../shared/constants/general';
+import { MANAGED_VAULT_SCOPES } from '../../../shared/constants/general';
import { type VaultKeyObj } from '../../../shared/types';
import { vault } from '../../services/SmythVault.class';
@@ -17,7 +17,7 @@ const scope = [
'_hidden',
'ALL_NON_GLOBAL_KEYS',
'CUSTOM_LLM',
- VAULT_SCOPE_AGENT_LLM,
+ ...MANAGED_VAULT_SCOPES,
];
const fields = ['name', 'scope', 'key', 'owner', 'team', 'isInvalid'];
diff --git a/packages/app/src/react/features/builder/components/VariablesWidget.tsx b/packages/app/src/react/features/builder/components/VariablesWidget.tsx
index f1c2ddd2..a572b01a 100644
--- a/packages/app/src/react/features/builder/components/VariablesWidget.tsx
+++ b/packages/app/src/react/features/builder/components/VariablesWidget.tsx
@@ -10,6 +10,7 @@ import { Spinner } from '@src/react/shared/components/ui/spinner';
import { errKeys } from '@src/react/shared/constants';
import { useAuthCtx } from '@src/react/shared/contexts/auth.context';
import { errorToast, successToast } from '@src/shared/components/toast';
+import { MANAGED_VAULT_SCOPES } from '@src/shared/constants/general';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Tooltip } from 'flowbite-react';
import { Component, useEffect, useRef, useState } from 'react';
@@ -92,7 +93,7 @@ const VariablesWidget = ({ agentId, workspace }: { agentId: string; workspace: W
queryKey: ['vaultKeys'],
queryFn: async () => {
const response = await fetch(
- '/api/page/builder/keys?fields=name,scope&excludeScope=global,AgentLLM',
+ `/api/page/builder/keys?fields=name,scope&excludeScope=global,${MANAGED_VAULT_SCOPES.join(',')}`,
);
return response.json();
},
diff --git a/packages/app/src/react/features/vault/vault-business-logic.ts b/packages/app/src/react/features/vault/vault-business-logic.ts
index d49e889a..d9aee679 100644
--- a/packages/app/src/react/features/vault/vault-business-logic.ts
+++ b/packages/app/src/react/features/vault/vault-business-logic.ts
@@ -2,7 +2,7 @@ import {
CUSTOM_LLM_PROVIDERS,
CUSTOM_LLM_REGIONS,
} from '@src/shared/constants/custom-llm.constants';
-import { VAULT_SCOPE_AGENT_LLM } from '@src/shared/constants/general';
+import { MANAGED_VAULT_SCOPES } from '@src/shared/constants/general';
import { customModels } from '@src/shared/custom-models';
import type {
ApiKey,
@@ -432,7 +432,7 @@ export const apiKeyService = {
fetchAPIKeys: async (): Promise<{ keys?: ApiKey[]; error?: string }> => {
try {
const response = await fetch(
- '/api/page/vault/keys?excludeScope=global,' + VAULT_SCOPE_AGENT_LLM,
+ `/api/page/vault/keys?excludeScope=global,${MANAGED_VAULT_SCOPES.join(',')}`,
{
method: 'GET',
headers: {
@@ -682,7 +682,8 @@ export const userCustomModelService = {
provider: value.provider,
// Check for new field name first, then fall back to old field name
contextWindow: value.contextWindow !== undefined ? value.contextWindow : value.tokens,
- maxOutputTokens: value.maxOutputTokens !== undefined ? value.maxOutputTokens : value.completionTokens,
+ maxOutputTokens:
+ value.maxOutputTokens !== undefined ? value.maxOutputTokens : value.completionTokens,
fallbackLLM: value.fallbackLLM || '', // Provide default empty string for backward compatibility with cached data
features: value.features,
}));
diff --git a/packages/app/src/shared/constants/general.ts b/packages/app/src/shared/constants/general.ts
index fe395264..67431773 100644
--- a/packages/app/src/shared/constants/general.ts
+++ b/packages/app/src/shared/constants/general.ts
@@ -98,6 +98,8 @@ export const WEAVER_REQUIRE_CREDITS = 'Weaver requires credits';
export const AGENTS_WITH_NEXT_STEPS_SHOWN = 'agentsWithNextStepsShown';
export const VAULT_SCOPE_AGENT_LLM = 'AgentLLM';
+export const VAULT_SCOPE_OAUTH_CONNECTIONS = 'OAuthConnections';
+export const MANAGED_VAULT_SCOPES = [VAULT_SCOPE_AGENT_LLM, VAULT_SCOPE_OAUTH_CONNECTIONS];
type EmbodimentDescription = {
title: string;
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 26a3de21..2737528b 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -679,6 +679,9 @@ importers:
uuid:
specifier: ^9.0.1
version: 9.0.1
+ ws:
+ specifier: ^8.18.3
+ version: 8.18.3([email protected])
devDependencies:
'@rollup/plugin-commonjs':
specifier: ^28.0.1