Skip to content

AI Agents & MCPs & AI Workflow Automation • (~400 MCP servers for AI agents) • AI Automation / AI Agent with MCPs • AI Workflows & AI Agents • MCPs for AI Agents

15.7 KB
Raw Blame
import path from 'path'
import { isNil } from '@activepieces/core-utils'
import {
    AuthValidationServerContext,
    DropdownProperty,
    DynamicProperties,
    ExecutePropsResult,
    getAuthPropertyForValue,
    isPieceServerContextError,
    MultiSelectDropdownProperty,
    PieceAuthProperty,
    PieceMetadata,
    PiecePropertyMap,
    PieceServerContextError,
    pieceTranslation,
    PropertyType,
    ServerContext,
    StaticPropsValue } from '@activepieces/pieces-framework'
import { AppConnectionType, AppConnectionValue, EngineGenericError, ExecuteExtractPieceMetadata, ExecutePropsOptions, ExecuteRefreshTokenAuthOperation, ExecuteRefreshTokenAuthResponse, ExecuteResolveConnectionIdentifierOperation, ExecuteResolveConnectionIdentifierResponse, ExecuteValidateAuthOperation, ExecuteValidateAuthResponse } from '@activepieces/shared'
import { EngineConstants } from '../handler/context/engine-constants'

const DEFAULT_REFRESH_EXPIRES_IN_SECONDS = 3300
import { testExecutionContext } from '../handler/context/test-execution-context'
import { createFlowsContext } from '../piece-context/flows'
import { utils } from '../utils'
import { createPropsResolver } from '../variables/props-resolver'
import { dynamicPropKeys } from './dynamic-prop-keys'
import { pieceLoader } from './piece-loader'

export const pieceHelper = {
    async executeProps( operation: ExecutePropsParams): Promise<ExecutePropsResult<PropertyType.DROPDOWN | PropertyType.MULTI_SELECT_DROPDOWN | PropertyType.DYNAMIC>> {
        const constants = EngineConstants.fromExecutePropertyInput(operation)
        const executionState = await testExecutionContext.stateFromFlowVersion({
            apiUrl: operation.internalApiUrl,
            flowVersion: operation.flowVersion,
            projectId: operation.projectId,
            engineToken: operation.engineToken,
            sampleData: operation.sampleData,
            engineConstants: constants,
        })
        const { property, piece } = await pieceLoader.getPropOrThrow({ pieceName: operation.pieceName, pieceVersion: operation.pieceVersion, actionOrTriggerName: operation.actionOrTriggerName, propertyName: operation.propertyName, devPieces: EngineConstants.DEV_PIECES })
    
        if (property.type !== PropertyType.DROPDOWN && property.type !== PropertyType.MULTI_SELECT_DROPDOWN && property.type !== PropertyType.DYNAMIC) {
            throw new EngineGenericError('PropertyTypeNotExecutableError', `Property type is not executable: ${property.type} for ${property.displayName}`)
        }
        const { data: executePropsResult, error: executePropsError } = await utils.tryCatchAndThrowOnEngineError((async (): Promise<ExecutePropsResult<PropertyType.DROPDOWN | PropertyType.MULTI_SELECT_DROPDOWN | PropertyType.DYNAMIC>> => {
            const { resolvedInput } = await createPropsResolver({
                apiUrl: constants.internalApiUrl,
                projectId: constants.projectId,
                engineToken: constants.engineToken,
                contextVersion: piece.getContextInfo?.().version,
                stepNames: constants.stepNames,
                pieceName: operation.pieceName,
            }).resolve<
            StaticPropsValue<PiecePropertyMap>
            >({
                unresolvedInput: operation.input,
                executionState,
            })
            const ctx = {
                searchValue: operation.searchValue,
                server: {
                    ...buildServerContext({ internalApiUrl: constants.internalApiUrl, publicApiUrl: operation.publicApiUrl }),
                    token: constants.engineToken,
                },
                project: {
                    id: constants.projectId,
                    externalId: constants.externalProjectId,
                },
                flows: createFlowsContext(constants),
                step: {
                    name: operation.actionOrTriggerName,
                },
                connections: utils.createConnectionManager({
                    projectId: constants.projectId,
                    engineToken: constants.engineToken,
                    apiUrl: constants.internalApiUrl,
                    target: 'properties',
                    contextVersion: piece.getContextInfo?.().version,
                    pieceName: operation.pieceName,
                }),
            }
          
            switch (property.type) {
                case PropertyType.DYNAMIC: {
                    const dynamicProperty = property as DynamicProperties<boolean>
                    const props = await dynamicProperty.props(resolvedInput, ctx)
                    return {
                        type: PropertyType.DYNAMIC,
                        options: dynamicPropKeys.escapePropsKeys(props),
                    }
                }
                case PropertyType.MULTI_SELECT_DROPDOWN: {
                    const multiSelectProperty = property as MultiSelectDropdownProperty<
                    unknown,
                    boolean
                    >
                    const options = await multiSelectProperty.options(resolvedInput, ctx)
                    return {
                        type: PropertyType.MULTI_SELECT_DROPDOWN,
                        options,
                    }
                }
                case PropertyType.DROPDOWN: {
                    const dropdownProperty = property as DropdownProperty<unknown, boolean>
                    const options = await dropdownProperty.options(resolvedInput, ctx)
                    return {
                        type: PropertyType.DROPDOWN,
                        options,
                    }
                }
                default: {
                    throw new EngineGenericError('PropertyTypeNotExecutableError', `Property type is not executable: ${property}`)
                }
            }
        }))
        
        if (executePropsError) {
            console.error(executePropsError)
            return {
                type: property.type,
                options: {
                    disabled: true,
                    options: [],
                    placeholder: 'Throws an error, reconnect or refresh the page',
                },
            }
        }

        return executePropsResult
    },

    async executeValidateAuth(
        { params, devPieces }: { params: ExecuteValidateAuthOperation, devPieces: string[] },
    ): Promise<ExecuteValidateAuthResponse> {
        const { piece: piecePackage } = params

        const piece = await pieceLoader.loadPieceOrThrow({ pieceName: piecePackage.pieceName, pieceVersion: piecePackage.pieceVersion, devPieces })
        const server = buildAuthValidationServerContext(params)
        try {
            return await validateAuth({
                authValue: params.auth,
                pieceAuth: piece.auth,
                server,
            })
        }
        catch (error) {
            if (isPieceServerContextError(error)) {
                throw new EngineGenericError('OidcTokenRequestFailedError', error.message)
            }
            throw error
        }
    },

    async executeResolveConnectionIdentifier(
        { params, devPieces }: { params: ExecuteResolveConnectionIdentifierOperation, devPieces: string[] },
    ): Promise<ExecuteResolveConnectionIdentifierResponse> {
        const { piece: piecePackage } = params

        const piece = await pieceLoader.loadPieceOrThrow({ pieceName: piecePackage.pieceName, pieceVersion: piecePackage.pieceVersion, devPieces })
        const server = buildServerContext(params)
        return resolveConnectionIdentifier({
            authValue: params.auth,
            connectionType: params.connectionType,
            pieceAuth: piece.auth,
            server,
        })
    },

    async executeRefreshTokenAuth(
        { params, devPieces }: { params: ExecuteRefreshTokenAuthOperation, devPieces: string[] },
    ): Promise<ExecuteRefreshTokenAuthResponse> {
        const { piece: piecePackage } = params

        const piece = await pieceLoader.loadPieceOrThrow({ pieceName: piecePackage.pieceName, pieceVersion: piecePackage.pieceVersion, devPieces })

        if (params.auth.type !== AppConnectionType.CUSTOM_AUTH) {
            return { skipped: true }
        }

        const pieceAuth = getAuthPropertyForValue({ authValueType: params.auth.type, pieceAuth: piece.auth })

        if (isNil(pieceAuth) || pieceAuth.type !== PropertyType.CUSTOM_AUTH || isNil(pieceAuth.refresh)) {
            return { skipped: true }
        }

        const server = buildServerContext(params)
        const result = await pieceAuth.refresh.generate({
            auth: params.auth.props,
            server,
        })

        const expiresIn = result.expires_in ?? pieceAuth.refresh.defaultExpiresIn ?? DEFAULT_REFRESH_EXPIRES_IN_SECONDS

        return {
            skipped: false,
            access_token: result.access_token,
            expires_in: expiresIn,
        }
    },

    async extractPieceMetadata({ devPieces, params }: { devPieces: string[], params: ExecuteExtractPieceMetadata }): Promise<PieceMetadata> {
        const { pieceName, pieceVersion } = params
        const piece = await pieceLoader.loadPieceOrThrow({ pieceName, pieceVersion, devPieces })
        const pieceAlias = pieceLoader.getPackageAlias({ pieceName, pieceVersion, devPieces })
        const pieceIndexPath = await pieceLoader.getPiecePath({ packageName: pieceAlias, devPieces })
        const pieceDistRoot = path.dirname(path.dirname(pieceIndexPath))
        const i18n = await pieceTranslation.initializeI18n(pieceDistRoot)
        const fullMetadata = piece.metadata()
        return {
            ...fullMetadata,
            name: pieceName,
            version: pieceVersion,
            authors: piece.authors,
            i18n,
        }
    },
}

type ExecutePropsParams = Omit<ExecutePropsOptions, 'piece'> & { pieceName: string, pieceVersion: string }


function mismatchAuthTypeErrorMessage(pieceAuthType: PropertyType, connectionType: AppConnectionType): ExecuteValidateAuthResponse {
    return {
        valid: false,
        error: `Connection value type does not match piece auth type: ${pieceAuthType} !== ${connectionType}`,
    }
}

const validateAuth = async ({
    server,
    authValue,
    pieceAuth,
}: ValidateAuthParams): Promise<ExecuteValidateAuthResponse> => {
    if (isNil(pieceAuth)) {
        return {
            valid: true,
        }
    }
    const usedPieceAuth = getAuthPropertyForValue({
        authValueType: authValue.type,
        pieceAuth,
    })

    if (isNil(usedPieceAuth)) {
        return {
            valid: false,
            error: 'No piece auth found for auth value',
        }
    }
    if (isNil(usedPieceAuth.validate)) {
        return {
            valid: true,
        }
    }
  

    switch (usedPieceAuth.type) {
        case PropertyType.OAUTH2:{
            if (authValue.type !== AppConnectionType.OAUTH2 && authValue.type !== AppConnectionType.CLOUD_OAUTH2 && authValue.type !== AppConnectionType.PLATFORM_OAUTH2) {
                return mismatchAuthTypeErrorMessage(usedPieceAuth.type, authValue.type)
            }
            return usedPieceAuth.validate({
                auth: authValue,
                server,
            })
        }
        case PropertyType.BASIC_AUTH:{
            if (authValue.type !== AppConnectionType.BASIC_AUTH) {
                return mismatchAuthTypeErrorMessage(usedPieceAuth.type, authValue.type)
            }
            return usedPieceAuth.validate({
                auth: authValue,
                server,
            })
        }
        case PropertyType.SECRET_TEXT:{
            if (authValue.type !== AppConnectionType.SECRET_TEXT) {
                return mismatchAuthTypeErrorMessage(usedPieceAuth.type, authValue.type)
            }
            return usedPieceAuth.validate({
                auth: authValue.secret_text,
                server,
            })
        }
        case PropertyType.CUSTOM_AUTH:{
            if (authValue.type !== AppConnectionType.CUSTOM_AUTH) {
                return mismatchAuthTypeErrorMessage(usedPieceAuth.type, authValue.type)
            }
            return usedPieceAuth.validate({
                auth: authValue.props,
                server,
            })
        }
        case PropertyType.OIDC:{
            if (authValue.type !== AppConnectionType.OIDC) {
                return mismatchAuthTypeErrorMessage(usedPieceAuth.type, authValue.type)
            }
            return usedPieceAuth.validate({
                auth: authValue.props,
                server,
            })
        }
        default: {
            throw new EngineGenericError('InvalidAuthTypeError', 'Invalid auth type')
        }
    }
}

const resolveConnectionIdentifier = async ({
    server,
    authValue,
    connectionType,
    pieceAuth,
}: ResolveConnectionIdentifierParams): Promise<ExecuteResolveConnectionIdentifierResponse> => {
    if (isNil(pieceAuth)) {
        return { identifier: undefined }
    }
    const usedPieceAuth = getAuthPropertyForValue({
        authValueType: connectionType,
        pieceAuth,
    })
    if (isNil(usedPieceAuth)) {
        return { identifier: undefined }
    }
    switch (usedPieceAuth.type) {
        case PropertyType.OAUTH2: {
            if (!('access_token' in authValue)) {
                return { identifier: undefined }
            }
            return { identifier: await usedPieceAuth.getConnectionIdentifier?.({ auth: authValue, server }) }
        }
        case PropertyType.BASIC_AUTH: {
            if (!('username' in authValue)) {
                return { identifier: undefined }
            }
            return { identifier: await usedPieceAuth.getConnectionIdentifier?.({ auth: authValue, server }) }
        }
        case PropertyType.SECRET_TEXT: {
            if (!('secret_text' in authValue)) {
                return { identifier: undefined }
            }
            return { identifier: await usedPieceAuth.getConnectionIdentifier?.({ auth: authValue.secret_text, server }) }
        }
        case PropertyType.CUSTOM_AUTH:
        case PropertyType.OIDC: {
            if (!('props' in authValue)) {
                return { identifier: undefined }
            }
            return { identifier: await usedPieceAuth.getConnectionIdentifier?.({ auth: authValue.props, server }) }
        }
        default: {
            return { identifier: undefined }
        }
    }
}

type ValidateAuthParams = {
    server: AuthValidationServerContext
    authValue: AppConnectionValue
    pieceAuth: PieceAuthProperty | PieceAuthProperty[] | undefined
}

type ResolveConnectionIdentifierParams = Omit<ValidateAuthParams, 'server'> & {
    server: Omit<ServerContext, 'token'>
    connectionType: AppConnectionType
}

function buildServerContext({ internalApiUrl, publicApiUrl }: { internalApiUrl: string, publicApiUrl: string }): Omit<ServerContext, 'token'> {
    return {
        apiUrl: internalApiUrl.endsWith('/') ? internalApiUrl : internalApiUrl + '/',
        publicUrl: publicApiUrl,
    }
}

function buildAuthValidationServerContext({ internalApiUrl, publicApiUrl, engineToken }: { internalApiUrl: string, publicApiUrl: string, engineToken: string }): AuthValidationServerContext {
    const server = buildServerContext({ internalApiUrl, publicApiUrl })
    return {
        ...server,
        mintOidcToken: async ({ audience }) => {
            const response = await fetch(`${server.apiUrl}v1/worker/oidc-token`, {
                method: 'POST',
                headers: {
                    Authorization: `Bearer ${engineToken}`,
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ audience }),
            })
            if (!response.ok) {
                throw new PieceServerContextError(`Failed to get OIDC token: ${response.statusText}`)
            }
            const { token } = await response.json() as { token: string }
            return token
        },
    }
}