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
add cors for chatbot and form preview embodiment
Forhad Hosaina106cdf8e9d7
diff --git a/.gitignore b/.gitignoreindex a3fae087..69e0acab 100644--- a/.gitignore+++ b/.gitignore@@ -146,7 +146,3 @@ dist__MACOSXanalysis/*--# Ignore all files and subfolders in the data directory, but keep the data folder tracked by including a .gitkeep file-data/*-!data/.gitkeep\ No newline at end of filediff --git a/data/.gitkeep b/data/.gitkeepdeleted file mode 100644index e69de29b..00000000diff --git a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts b/packages/runtime/src/core/connectors/SmythOSSAccount.class.tsindex f9c07e7f..d4b9629d 100644--- a/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts+++ b/packages/runtime/src/core/connectors/SmythOSSAccount.class.ts@@ -7,7 +7,6 @@ import {ConnectorService,IAccessCandidate,KeyValueObject,- Logger,OAuthConfig,TAccessLevel,TAccessRole,@@ -16,7 +15,6 @@ import {import { getM2MToken } from '@core/helpers/logto.helper';import { SmythConfigs } from '@core/types/general.types';-const console = Logger('SmythOSSAccount');export class SmythOSSAccount extends AccountConnector {public name = 'SmythOSSAccount';private oAuthAppId: string;diff --git a/packages/runtime/src/index.ts b/packages/runtime/src/index.tsindex ed5574ad..487aad5a 100644--- a/packages/runtime/src/index.ts+++ b/packages/runtime/src/index.ts@@ -15,10 +15,11 @@ import { Logger, SmythRuntime, version } from '@smythos/sre';import config from '@core/config';import { modelsConfig } from '@core/config/models.config';import { startServers } from '@core/management-router';+import { requestContext } from '@core/services/request-context';+import cors from '@core/middlewares/cors.mw';import { errorHandler, notFoundHandler } from '@core/middlewares/error.mw';import RateLimiter from '@core/middlewares/rateLimiter.mw';-import { requestContext } from '@core/services/request-context';import { registerConnectors } from '@core/connectors/connectorRegistry';@@ -122,6 +123,7 @@ function getCurrentFormattedDate() {app.disable('x-powered-by');app.set('trust proxy', 1);+// Generic CORSapp.use(cors);app.options('*', cors);diff --git a/packages/runtime/src/modules/embodiment/constants.ts b/packages/runtime/src/modules/embodiment/constants.tsindex 2c75d22d..d433511d 100644--- a/packages/runtime/src/modules/embodiment/constants.ts+++ b/packages/runtime/src/modules/embodiment/constants.ts@@ -1,4 +1,5 @@export enum EMBODIMENT_TYPES {ChatBot = 'chatBot',ChatGPT = 'chatGPT',+ FormPreview = 'form',}diff --git a/packages/runtime/src/modules/embodiment/middlewares/cors.mw.ts b/packages/runtime/src/modules/embodiment/middlewares/cors.mw.tsnew file mode 100644index 00000000..3cbd727d--- /dev/null+++ b/packages/runtime/src/modules/embodiment/middlewares/cors.mw.ts@@ -0,0 +1,86 @@+import cors from 'cors';++import { Agent, Logger } from '@smythos/sre';++import config from '@core/config';+import { EMBODIMENT_TYPES } from '@embodiment/constants';++const console = Logger('[Embodiment] Middleware: CORS');++// Custom CORS middleware+// FIXME : make default CORS configurable from .env file+const corsOptionsDelegate = async (req, callback) => {+ const embodimentType = req.originalUrl.includes('form-preview') ? EMBODIMENT_TYPES.FormPreview : EMBODIMENT_TYPES.ChatBot;++ // default origins are the origins that are allowed to make requests to the server+ const defaultOrigins = [config.env.UI_SERVER];+ let agentAllowedDomains = []; // agent allowed domains are the origins that user has specified in the embodiment configuration+ const allAllowedOrigins = [...defaultOrigins];++ // *** ADD MORE HOSTS TO ALLOW AS NEEDED ***+ const knownHosts = ['localhost'];++ let corsOptions;++ if (req._agent) {+ const agent: Agent = req._agent;++ // wait for agent embodiments to be ready+ await agent.agentSettings?.embodiments?.ready();++ agentAllowedDomains = agent.agentSettings?.embodiments?.get(embodimentType, 'allowedDomains');++ if (!agentAllowedDomains || !Array.isArray(agentAllowedDomains)) agentAllowedDomains = [];+ agentAllowedDomains = agentAllowedDomains.map(domain => {+ if (domain?.startsWith('http')) {+ try {+ return new URL(domain)?.origin;+ } catch (error) {+ return domain;+ }+ }++ return `https://${domain}`;+ });+ if (agentAllowedDomains && agentAllowedDomains.length > 0) {+ allAllowedOrigins.push(...agentAllowedDomains);+ }+ }+ const origin = req.get('Origin');+ const host = req.get('Host');++ // check if the origin is the same as the host+ const isSameOrigin = origin === `http://${host}` || origin === `https://${host}`;++ const currentHost = new URL(config.env.BASE_URL || '').host;++ // bypass allowed hosts for CORS because they send debug requests+ const isKnownHost = host == currentHost || knownHosts.includes(host);++ const isAllowedOrigin = allAllowedOrigins.includes(origin);++ const allowAllOrigins = agentAllowedDomains?.length === 0; // if user has not specified any allowed domains, allow all origins++ if (isKnownHost || isSameOrigin || isAllowedOrigin || allowAllOrigins) {+ // Enable CORS for the same origin and the allowed domains+ corsOptions = {+ origin: true,+ credentials: true, // Allow credentials (cookies, etc.)+ methods: ['GET', 'POST', 'PUT', 'DELETE'], // Allowed methods+ allowedHeaders: ['Content-Type', 'Authorization', 'X-Conversation-Id', 'X-Auth-Token', 'X-Parent-Cookie'],+ };+ } else {+ // Disable CORS for other requests+ corsOptions = { origin: false };+ if (req.method == 'OPTIONS') {+ console.log('CORS check ', { path: req.path, host, origin }, '==> Denied ');+ console.log('Allowed Domains for this request ', allAllowedOrigins);+ }+ }++ callback(null, corsOptions);+};++const middleware = cors(corsOptionsDelegate);++export default middleware;diff --git a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.tsindex ad49f719..7647c62d 100644--- a/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts+++ b/packages/runtime/src/modules/embodiment/modules/chatbot/routes/router.ts@@ -6,6 +6,8 @@ import { Agent, Logger } from '@smythos/sre';import config from '@core/config';import { readAgentOAuthConfig } from '@core/helpers/agent.helper';import { uploadHandler } from '@core/middlewares/uploadHandler.mw';++import cors from '@embodiment/middlewares/cors.mw';import { uploadFile } from '@embodiment/modules/chat/routes/router';import { EMBODIMENT_TYPES } from '@embodiment/constants';@@ -32,7 +34,7 @@ const router = express.Router();let localAgentAuthorizations = {};-const middleweares = [agentLoader, ChatbotLoader];+const middleweares = [cors, agentLoader, ChatbotLoader];router.use(middleweares);router.get('/', async (req, res) => {diff --git a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.tsindex a15d9d47..347df12d 100644--- a/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts+++ b/packages/runtime/src/modules/embodiment/modules/formPreview/routes/router.ts@@ -1,12 +1,14 @@import config from '@core/config';+import { callSkill } from '@embodiment/helpers/formPreview.helper';import agentLoader from '@embodiment/middlewares/agentLoader.mw';+import cors from '@embodiment/middlewares/cors.mw';import { Agent } from '@smythos/sre';import express from 'express';const router = express.Router();-const middlewares = [agentLoader];+const middlewares = [cors, agentLoader];router.use(middlewares);router.get('/', async (req, res) => {