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
Merge branch 'dev' into feat/triggers-oauth-refactor
Alaa-eddine K.e2cb685fb7c3
diff --cc packages/app/src/backend/middlewares/oauthStrategy.mw.tsindex 6dc25004,0a3bddae..682fad3f--- a/packages/app/src/backend/middlewares/oauthStrategy.mw.ts+++ b/packages/app/src/backend/middlewares/oauthStrategy.mw.ts@@@ -30,77 -29,26 +30,81 @@@ export const oauthStrategyInitializatio// Prepare the configurationlet config: any = { ...defaultConfig }; // Spread operator for shallow clone- // Override default config with body parameters- const updatedReqBody = await replaceTemplateVariablesOptimized(req).catch((error) => {- console.log('error', error?.message);- return { error };- });-- Object.entries(updatedReqBody).forEach(([key, value]) => {- if (key === 'oauth1CallbackURL' || key === 'oauth2CallbackURL') {- config['callbackURL'] = value;- } else if (key in config) {- config[key] = value;- }- });++++ // Use session-stored configuration instead of URL parameters+ if (isOAuth2 && req.session.oauth2Config) {+ const oauth2Config = req.session.oauth2Config;++ // Handle template variables in session-stored config+ const configToProcess = { ...oauth2Config };+ const mockReq = {+ body: configToProcess,+ _team: req._team,+ session: req.session,+ };++ const processedConfig = await replaceTemplateVariablesOptimized(mockReq).catch((error) => {+ console.log('Template processing error for OAuth2:', error);+ return configToProcess;+ });++ config.clientID = processedConfig.clientID;+ config.clientSecret = processedConfig.clientSecret; // Safe from session + templates resolved+ config.callbackURL = processedConfig.callbackURL;+ if (processedConfig.authorizationURL)+ config.authorizationURL = processedConfig.authorizationURL;+ if (processedConfig.tokenURL) config.tokenURL = processedConfig.tokenURL;+ } else if (isOAuth1 && req.session.oauth1Config) {+ const oauth1Config = req.session.oauth1Config;++ // Handle template variables in session-stored config+ const configToProcess = { ...oauth1Config };+ const mockReq = {+ body: configToProcess,+ _team: req._team,+ session: req.session,+ };++ //TODO : do we really need to handle template variables for oauth+ const processedConfig = await replaceTemplateVariablesOptimized(mockReq).catch((error) => {+ console.log('Template processing error for OAuth1:', error);+ return configToProcess;+ });++ config.consumerKey = processedConfig.consumerKey;+ config.consumerSecret = processedConfig.consumerSecret; // Safe from session + templates resolved+ config.callbackURL = processedConfig.callbackURL;+ if (processedConfig.requestTokenURL) config.requestTokenURL = processedConfig.requestTokenURL;+ if (processedConfig.accessTokenURL) config.accessTokenURL = processedConfig.accessTokenURL;+ if (processedConfig.userAuthorizationURL)+ config.userAuthorizationURL = processedConfig.userAuthorizationURL;+ } else {+ // Fallback to legacy URL parameter method (for backward compatibility)+ //TODO : do we really need to handle template variables for oauth+ const updatedReqBody = await replaceTemplateVariablesOptimized(req).catch((error) => {+ console.log('error', error);+ return { error };+ });++ Object.entries(updatedReqBody).forEach(([key, value]) => {+ if (key === 'oauth1CallbackURL' || key === 'oauth2CallbackURL') {+ config['callbackURL'] = value;+ } else if (key in config) {+ config[key] = value;+ }+ });+ }++// Derive callback URL when missingif (!config['callbackURL']) {try {const origin = req.headers?.origin || `${req.protocol}://${req.get('host')}`;const internalService = String(service).toLowerCase();- const isOAuth2 = ['google', 'linkedin', 'oauth2'].includes(internalService);+++ const isOAuth2 = OAuthServicesRegistry.isOAuth2Service(internalService);++const provider = isOAuth2? internalService === 'oauth2'? 'oauth2'diff --cc packages/app/src/backend/routes/oauth/router.tsindex 437ec173,6fa8c1dd..7839577a--- a/packages/app/src/backend/routes/oauth/router.ts+++ b/packages/app/src/backend/routes/oauth/router.ts@@@ -115,146 -98,86 +115,150 @@@ router.post('/checkAuth', includeTeamDe}});-router.post('/init', includeTeamDetails, oauthStrategyInitialization, async (req, res) => {- // Store the frontend origin from the referer or origin header- const referer = req.headers.referer || req.headers.referrer || req.headers.origin;- if (referer && typeof referer === 'string') {- try {- const frontendOrigin = new URL(referer).origin;- req.session.frontendOrigin = frontendOrigin;- } catch (error) {- console.error('[/oauth/init] Invalid referer/origin URL:', referer);+router.post(+ '/init',+ oauthInitLimit,+ includeTeamDetails,+ oauthStrategyInitialization,+ async (req, res) => {+ // Validate and store frontend origin+ const referer = req.headers.referer || req.headers.referrer || req.headers.origin;+ if (referer && typeof referer === 'string') {+ try {+ const frontendOrigin = new URL(referer).origin;++ // Validate against allowed origins (add your allowed origins to env)+ const allowedOrigins = process.env.ALLOWED_ORIGINS?.split(',') || [frontendOrigin];+ if (!allowedOrigins.includes(frontendOrigin)) {+ console.warn(`[/oauth/init] Unauthorized origin: ${frontendOrigin}`);+ return res.status(403).json({ error: 'Origin not allowed' });+ }++ req.session.frontendOrigin = frontendOrigin;+ } catch (error) {+ console.error('[/oauth/init] Invalid referer/origin URL:', referer);+ return res.status(400).json({ error: 'Invalid origin' });+ }}- }- try {- const {- service,- scope,- clientID,- clientSecret,- authorizationURL,- tokenURL,- oauth2CallbackURL,- // OAuth1 parameters- consumerKey,- consumerSecret,- requestTokenURL,- accessTokenURL,- userAuthorizationURL,- oauth1CallbackURL,- } = req.body;-- let authUrl = `/oauth/${service}`;-- if (['google', 'linkedin', 'oauth2'].includes(service)) {- // OAuth2 flow- const oauthParams: any = {- scopes: encodeURIComponent(scope),- clientID: encodeURIComponent(clientID),- clientSecret: encodeURIComponent(clientSecret),- callbackURL: encodeURIComponent(oauth2CallbackURL),- };+ try {+ const {+ service,+ scope,+ clientID,+ clientSecret,+ authorizationURL,+ tokenURL,+ oauth2CallbackURL,+ // OAuth1 parameters+ consumerKey,+ consumerSecret,+ requestTokenURL,+ accessTokenURL,+ userAuthorizationURL,+ oauth1CallbackURL,+ } = req.body;++ // Input validation+ if (!service || typeof service !== 'string') {+ return res.status(400).json({ error: 'Service is required and must be a string' });+ }- if (authorizationURL) oauthParams.authorizationURL = encodeURIComponent(authorizationURL);- if (tokenURL) oauthParams.tokenURL = encodeURIComponent(tokenURL);-- authUrl +=- '?' +- Object.entries(oauthParams)- .map(([key, value]) => `${key}=${value}`)- .join('&');- } else if (['oauth1', 'twitter'].includes(service)) {- // OAuth1 flow- const oauthParams: any = {- scopes: encodeURIComponent(scope || ''),- consumerKey: encodeURIComponent(consumerKey),- consumerSecret: encodeURIComponent(consumerSecret),- callbackURL: encodeURIComponent(oauth1CallbackURL),+ // Validate URLs if provided+ const validateURL = (url: string, fieldName: string) => {+ if (!url) return;+ try {+ const parsed = new URL(url);+ if (!['http:', 'https:'].includes(parsed.protocol)) {+ throw new Error(`${fieldName} must use HTTP or HTTPS`);+ }+ } catch (error) {+ throw new Error(`Invalid ${fieldName}: ${error.message}`);+ }};- if (requestTokenURL) oauthParams.requestTokenURL = encodeURIComponent(requestTokenURL);- if (accessTokenURL) oauthParams.accessTokenURL = encodeURIComponent(accessTokenURL);- if (userAuthorizationURL)- oauthParams.userAuthorizationURL = encodeURIComponent(userAuthorizationURL);+- authUrl +=- '?' +- Object.entries(oauthParams)- .map(([key, value]) => `${key}=${value}`)- .join('&');- } else {- // Unsupported service- return res.status(400).json({ error: 'Invalid or unsupported service.' });+ try {+ if (authorizationURL) validateURL(authorizationURL, 'authorizationURL');+ if (tokenURL) validateURL(tokenURL, 'tokenURL');+ if (requestTokenURL) validateURL(requestTokenURL, 'requestTokenURL');+ if (accessTokenURL) validateURL(accessTokenURL, 'accessTokenURL');+ if (userAuthorizationURL) validateURL(userAuthorizationURL, 'userAuthorizationURL');+ if (oauth2CallbackURL) validateURL(oauth2CallbackURL, 'oauth2CallbackURL');+ if (oauth1CallbackURL) validateURL(oauth1CallbackURL, 'oauth1CallbackURL');+ } catch (validationError) {+ return res.status(400).json({ error: validationError.message });+ }++ if (OAuthServicesRegistry.isOAuth2Service(service) || service === 'oauth2') {+ // OAuth2 flow - Store sensitive data in session, return clean URL++++ // Validate required OAuth2 fields+ if (!clientID || !clientSecret) {+ return res+ .status(400)+ .json({ error: 'clientID and clientSecret are required for OAuth2' });+ }++ // Store OAuth2 configuration in session (server-side only)+ req.session.oauth2Config = {+ service,+ clientID,+ //TODO: Do we need a stronger protection for this?+ clientSecret, // Safe in session+ authorizationURL,+ tokenURL,+ scope,+ callbackURL: oauth2CallbackURL,+ };++ // Return internal URL that will trigger Passport (no secrets exposed)+ // Let Passport handle state management internally+ const authUrl = `/oauth/${service}`;++ return res.json({ authUrl });+ } else if (OAuthServicesRegistry.isOAuth1Service(service) || service === 'oauth1') {+ // OAuth1 flow - Store sensitive data in session++ // Validate required OAuth1 fields+ if (!consumerKey || !consumerSecret) {+ return res+ .status(400)+ .json({ error: 'consumerKey and consumerSecret are required for OAuth1' });+ }++ // Store OAuth1 configuration in session (server-side only)+ req.session.oauth1Config = {+ service,+ consumerKey,+ //TODO: Do we need a stronger protection for this?+ consumerSecret, //Safe in session+ requestTokenURL,+ accessTokenURL,+ userAuthorizationURL,+ callbackURL: oauth1CallbackURL,+ scope,+ };++ // Return internal URL that will trigger Passport (no secrets exposed)+ // Let Passport handle state management internally+ const authUrl = `/oauth/${service}`;++ return res.json({ authUrl });+ } else {+ // Unsupported service+ return res.status(400).json({ error: 'Invalid or unsupported service.' });+ }+ } catch (error) {+ console.error('Error in /init route:', error);+ res.status(500).json({ error: 'Failed to initialize authentication' });}- // console.log({ authUrl })- res.json({ authUrl });- } catch (error) {- console.error('Error in /init route:', error?.message);- res.status(500).json({ error: 'Failed to initialize authentication' });- }-});+++ },+);++router.get('/:provider', async (req, res, next) => {try {const scopes = req?.session?.scopes?.split(' ') || [];