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

37.0 KB
Raw Blame
import { ActivepiecesError, apId, Cursor, ErrorCode, FlowId, isNil, Metadata, PlatformId, ProjectId, SeekPage, spreadIfDefined, tryCatch, tryCatchSync, unique, UserId } from '@activepieces/core-utils'
import { PieceMetadata } from '@activepieces/pieces-framework'
import { ApEdition, ApEnvironment, AppConnection, AppConnectionId, AppConnectionOwners, AppConnectionScope, AppConnectionStatus, AppConnectionType, AppConnectionValue, AppConnectionWithoutSensitiveData, ConnectionState, EngineResponse, EngineResponseStatus, ExecuteResolveConnectionIdentifierResponse, ExecuteValidateAuthResponse, MAX_PLATFORM_APP_CONNECTION_OWNERS, OAuth2GrantType, PlatformAppConnectionOwner, PlatformAppConnectionOwnersResponse, PlatformAppConnectionProjectInfo, PlatformAppConnectionsListItem, PlatformRole, UpsertAppConnectionRequestBody, WorkerJobType } from '@activepieces/shared'
import { FastifyBaseLogger } from 'fastify'
import semver from 'semver'
import { ArrayContains, Equal, FindOperator, FindOptionsWhere, ILike, In } from 'typeorm'
import { repoFactory } from '../../core/db/repo-factory'
import { projectMemberService } from '../../ee/projects/project-members/project-member.service'
import { containsSecretManagerReference, secretManagersService } from '../../ee/secret-managers/secret-managers.service'
import { flowService } from '../../flows/flow/flow.service'
import { encryptUtils } from '../../helper/encryption'
import { jwtUtils } from '../../helper/jwt-utils'
import { buildPaginator } from '../../helper/pagination/build-paginator'
import { paginationHelper } from '../../helper/pagination/pagination-utils'
import { system } from '../../helper/system/system'
import { AppSystemProp } from '../../helper/system/system-props'
import {
    getPiecePackageWithoutArchive,
    pieceMetadataService,
} from '../../pieces/metadata/piece-metadata-service'
import { projectRepo } from '../../project/project-service'
import { mapToUserWithMetaInformation, userService } from '../../user/user-service'
import { userInteractionWatcher } from '../../workers/user-interaction-watcher'
import {
    AppConnectionEntity,
    AppConnectionSchema,
} from '../app-connection.entity'
import { appConnectionHandler } from './app-connection.handler'
import { mergeConnectionMetadata } from './connection-metadata'
import { oauth2Handler } from './oauth2'
import { oauth2Util } from './oauth2/oauth2-util'
export const appConnectionsRepo = repoFactory(AppConnectionEntity)

export const appConnectionService = (log: FastifyBaseLogger) => ({
    async upsert(params: UpsertParams): Promise<AppConnectionWithoutSensitiveData> {
        const { projectIds, externalId, value, displayName, pieceName, ownerId, platformId, scope, type, status, metadata, preSelectForNewProjects } = params
        const pieceVersion = params.pieceVersion ?? ( await pieceMetadataService(log).getOrThrow({
            name: pieceName,
            platformId,
        })).version
        validatePieceVersion(pieceVersion)
        await assertProjectIds(projectIds, platformId)

        if (status === AppConnectionStatus.MISSING) {
            const existingForPlaceholder = await appConnectionsRepo().findOneBy({
                externalId,
                scope,
                platformId,
                ...(projectIds ? { projectIds: ArrayContains(projectIds) } : {}),
            })
            if (!isNil(existingForPlaceholder) && existingForPlaceholder.status !== AppConnectionStatus.MISSING) {
                log.info({ connection: { id: existingForPlaceholder.id }, piece: { name: pieceName }, platform: { id: platformId }, existingStatus: existingForPlaceholder.status }, 'Placeholder upsert skipped — non-missing connection already exists')
                return this.removeSensitiveData(existingForPlaceholder)
            }
        }

        const validatedConnectionValue = await validateConnectionValue({
            value: await secretManagersService(log).resolveObject({ value, platformId, projectIds }),
            pieceName,
            pieceVersion,
            projectId: projectIds[0],
            platformId,
        }, log)

        const encryptedConnectionValue = await encryptUtils.encryptObject({
            ...validatedConnectionValue,
            ...value,
        })

        const existingConnection = await appConnectionsRepo().findOneBy({
            externalId,
            scope,
            platformId,
            ...(projectIds ? { projectIds: ArrayContains(projectIds) } : {}),
        })

        const accountIdentifier = await resolveConnectionAccountIdentifier({
            connectionType: type,
            auth: validatedConnectionValue,
            pieceName,
            projectId: projectIds[0],
            platformId,
            log,
        })
        const connectionMetadata = mergeConnectionMetadata({
            requestMetadata: metadata,
            existingMetadata: existingConnection?.metadata,
            accountIdentifier,
        })

        const newId = existingConnection?.id ?? apId()
        const connection = {
            displayName,
            ...spreadIfDefined('ownerId', ownerId),
            status: status ?? AppConnectionStatus.ACTIVE,
            value: encryptedConnectionValue,
            externalId,
            pieceName,
            type,
            id: newId,
            scope,
            projectIds,
            platformId,
            ...spreadIfDefined('metadata', connectionMetadata),
            ...spreadIfDefined('preSelectForNewProjects', preSelectForNewProjects),
            pieceVersion,
        }

        await appConnectionsRepo().upsert(connection, ['id'])

        const updatedConnection = await appConnectionsRepo().findOneByOrFail({
            id: newId,
            platformId,
            ...(projectIds ? { projectIds: ArrayContains(projectIds) } : {}),
            scope,
        })
        log.info({ connection: { id: newId }, piece: { name: pieceName }, platform: { id: platformId }, isNew: isNil(existingConnection) }, 'App connection upserted')
        return this.removeSensitiveData(updatedConnection)
    },
    async update(params: UpdateParams): Promise<AppConnectionWithoutSensitiveData> {
        const { projectIds, id, request, scope, platformId } = params

        if (!isNil(request.projectIds)) {
            await assertProjectIds(request.projectIds, platformId)
        }

        const filter: FindOptionsWhere<AppConnectionSchema> = {
            id,
            scope,
            platformId,
            ...(projectIds ? { projectIds: ArrayContains(projectIds) } : {}),
        }

        const storedMetadata = isNil(request.metadata)
            ? undefined
            : (await appConnectionsRepo().findOneByOrFail(filter)).metadata
        const storedAccountIdentifier = storedMetadata?.['accountIdentifier']

        await appConnectionsRepo().update(filter, {
            displayName: request.displayName,
            ...spreadIfDefined('projectIds', request.projectIds),
            ...(isNil(request.metadata) ? {} : spreadIfDefined('metadata', mergeConnectionMetadata({
                requestMetadata: request.metadata,
                existingMetadata: storedMetadata,
                accountIdentifier: typeof storedAccountIdentifier === 'string' ? storedAccountIdentifier : undefined,
            }))),
            ...spreadIfDefined('preSelectForNewProjects', request.preSelectForNewProjects),
        })

        const updatedConnection = await appConnectionsRepo().findOneByOrFail(filter)
        return this.removeSensitiveData(updatedConnection)
    },
    async getOne({
        projectId,
        platformId,
        externalId,
    }: GetOneByName): Promise<AppConnection | null> {
        const encryptedAppConnection = await appConnectionsRepo().findOne({
            where: {
                projectIds: ArrayContains([projectId]),
                externalId,
                platformId,
            },
        })

        if (isNil(encryptedAppConnection)) {
            return null
        }
        const connection = await this.decryptAndRefreshConnection(encryptedAppConnection, projectId, log)

        if (isNil(connection)) {
            return null
        }

        const owner = isNil(connection.ownerId) ? null : await userService(log).getMetaInformation({
            id: connection.ownerId,
        })
        return {
            ...connection,
            owner,
        }
    },

    async getOneWithoutValue({ projectId, platformId, externalId }: GetOneByName): Promise<AppConnectionWithoutSensitiveData | null> {
        const connection = await appConnectionsRepo().findOneBy({
            projectIds: ArrayContains([projectId]),
            externalId,
            platformId,
        })
        return isNil(connection) ? null : this.removeSensitiveData(connection)
    },

    async getOneOrThrowWithoutValue(params: GetOneParams): Promise<AppConnectionWithoutSensitiveData> {
        const connectionById = await appConnectionsRepo().findOneBy({
            id: params.id,
            platformId: params.platformId,
            ...(params.projectId ? { projectIds: ArrayContains([params.projectId]) } : {}),
        })
        if (isNil(connectionById)) {
            throw new ActivepiecesError({
                code: ErrorCode.ENTITY_NOT_FOUND,
                params: {
                    entityType: 'AppConnection',
                    entityId: params.id,
                },
            })
        }
        return this.removeSensitiveData(connectionById)
    },

    async getOnePublicOrThrow(params: GetOneParams): Promise<AppConnectionWithoutSensitiveData> {
        const connection = await this.getOneOrThrowWithoutValue(params)
        const flowIdsByExternalId = await fetchFlowIdsForConnections(log, [connection])
        return {
            ...connection,
            flowIds: flowIdsByExternalId.get(connection.externalId) ?? [],
        }
    },

    async revalidate({ id, projectId, platformId }: RevalidateParams): Promise<AppConnectionWithoutSensitiveData> {
        const metadata = await this.getOneOrThrowWithoutValue({ id, projectId, platformId })
        const connection = await appConnectionHandler(log).revalidateConnection({
            id,
            platformId,
            projectId,
            externalId: metadata.externalId,
            validate: ({ pieceName, value }) => engineValidateAuth({ pieceName, projectId, platformId, auth: value }, log),
            log,
        })
        if (isNil(connection)) {
            throw new ActivepiecesError({
                code: ErrorCode.ENTITY_NOT_FOUND,
                params: { entityType: 'AppConnection', entityId: id },
            })
        }
        return this.removeSensitiveData(connection)
    },

    async listConnectedPieces({ projectId, platformId, limit }: { projectId: ProjectId, platformId: PlatformId, limit: number }): Promise<{ pieceName: string, externalId: string }[]> {
        return appConnectionsRepo().createQueryBuilder('connection')
            .select('connection.pieceName', 'pieceName')
            .addSelect('connection.externalId', 'externalId')
            .distinctOn(['connection.pieceName'])
            .where('connection.platformId = :platformId', { platformId })
            .andWhere(':projectId = ANY(connection.projectIds)', { projectId })
            .andWhere('connection.status = :status', { status: AppConnectionStatus.ACTIVE })
            .orderBy('connection.pieceName', 'ASC')
            .addOrderBy('connection.created', 'ASC')
            .limit(limit)
            .getRawMany()
    },

    async getManyConnectionStates(params: GetManyParams): Promise<ConnectionState[]> {
        const connections = await appConnectionsRepo().find({
            where: {
                projectIds: ArrayContains([params.projectId]),
            },
        })
        return connections.map((connection) => ({
            externalId: connection.externalId,
            pieceName: connection.pieceName,
            displayName: connection.displayName,
        }))
    },

    async replace(params: ReplaceParams): Promise<void> {
        const { sourceAppConnectionId, targetAppConnectionId, projectId, platformId, userId, applyToPublishedVersions, flowIds } = params
        if (sourceAppConnectionId === targetAppConnectionId) {
            throw new ActivepiecesError({
                code: ErrorCode.VALIDATION,
                params: {
                    message: 'Cannot replace a connection with itself',
                },
            })
        }
        const sourceAppConnection = await this.getOneOrThrowWithoutValue({
            id: sourceAppConnectionId,
            projectId,
            platformId,
        })

        const targetAppConnection = await this.getOneOrThrowWithoutValue({
            id: targetAppConnectionId,
            projectId,
            platformId,
        })

        if (sourceAppConnection.pieceName !== targetAppConnection.pieceName) {
            throw new ActivepiecesError({
                code: ErrorCode.VALIDATION,
                params: {
                    message: 'Connections must be from the same app',
                },
            })
        }

        const flows = await flowService(log).list({
            projectIds: [projectId],
            cursorRequest: null,
            folderId: undefined,
            name: undefined,
            status: undefined,
            flowIds,
        })
        if (flows.data.length !== unique(flowIds).length) {
            throw new ActivepiecesError({
                code: ErrorCode.VALIDATION,
                params: {
                    message: `Flows not found in this project: ${unique(flowIds).filter((flowId) => !flows.data.some((flow) => flow.id === flowId)).join(', ')}`,
                },
            })
        }
        await appConnectionHandler(log).replaceConnectionInFlows({
            flows: flows.data,
            appConnection: sourceAppConnection,
            newAppConnection: targetAppConnection,
            userId,
            platformId,
            applyToPublishedVersions,
        })
        log.info({ oldConnectionId: sourceAppConnectionId, newConnectionId: targetAppConnectionId, affectedFlows: flows.data.length, applyToPublishedVersions }, 'App connection replaced')
    },

    async delete(params: DeleteParams): Promise<void> {
        await appConnectionsRepo().delete({
            id: params.id,
            platformId: params.platformId,
            scope: params.scope,
            ...(params.projectId ? { projectIds: ArrayContains([params.projectId]) } : {}),
        })
        log.info({ connection: { id: params.id }, platform: { id: params.platformId } }, 'App connection deleted')
    },

    async list({
        projectId,
        projectIds,
        ownerIds,
        pieceName,
        cursorRequest,
        displayName,
        status,
        limit,
        scope,
        platformId,
        externalIds,
    }: ListParams): Promise<SeekPage<AppConnection>> {
        const decodedCursor = paginationHelper.decodeCursor(cursorRequest)
        const paginator = buildPaginator({
            entity: AppConnectionEntity,
            query: {
                limit,
                order: 'ASC',
                afterCursor: decodedCursor.nextCursor,
                beforeCursor: decodedCursor.previousCursor,
            },
        })

        const querySelector: Record<string, string | FindOperator<string>> = {
            ...(projectId ? { projectIds: ArrayContains([projectId]) } : {}),
            ...spreadIfDefined('scope', scope),
            platformId,
        }
        if (!isNil(pieceName)) {
            querySelector.pieceName = Equal(pieceName)
        }
        if (!isNil(displayName)) {
            querySelector.displayName = ILike(`%${displayName}%`)
        }
        if (!isNil(status)) {
            querySelector.status = In(status)
        }
        if (!isNil(externalIds)) {
            querySelector.externalId = In(externalIds)
        }
        if (!isNil(ownerIds) && ownerIds.length > 0) {
            querySelector.ownerId = In(ownerIds)
        }
        const queryBuilder = appConnectionsRepo()
            .createQueryBuilder('app_connection')
            .leftJoinAndSelect('app_connection.owner', 'owner')
            .leftJoinAndSelect('owner.identity', 'owner_identity')
            .where(querySelector)
        if (!isNil(projectIds) && projectIds.length > 0) {
            queryBuilder.andWhere('app_connection."projectIds" && :projectIds::varchar[]', { projectIds })
        }
        const { data, cursor } = await paginator.paginate(queryBuilder)

        const flowIdsByExternalId = await fetchFlowIdsForConnections(log, data)

        const promises = data.map(async (encryptedConnection) => {
            const apConnection: AppConnection = await appConnectionHandler(log).decryptConnection(encryptedConnection)
            const owner = mapToUserWithMetaInformation(encryptedConnection.owner)
            const flowIds = flowIdsByExternalId.get(apConnection.externalId) ?? []

            return {
                ...apConnection,
                owner,
                flowIds,
            }
        })
        const refreshConnections = await Promise.all(promises)

        return paginationHelper.createPage<AppConnection>(
            refreshConnections,
            cursor,
        )
    },
    removeSensitiveData: (
        appConnection: AppConnection | AppConnectionSchema,
    ): AppConnectionWithoutSensitiveData => {
        const { value, ...appConnectionWithoutSensitiveData } = appConnection
        return {
            ...appConnectionWithoutSensitiveData,
            usingSecretManager: containsSecretManagerReference(value),
        }
    },

    async decryptAndRefreshConnection(
        encryptedAppConnection: AppConnectionSchema,
        projectId: ProjectId,
        log: FastifyBaseLogger,
    ): Promise<AppConnection | null> {
        const appConnection = await appConnectionHandler(log).decryptConnection(encryptedAppConnection)
        if (!await appConnectionHandler(log).needRefresh(appConnection, log)) {
            return oauth2Util(log).removeRefreshTokenAndClientSecret(appConnection)
        }

        const refreshedConnection = await appConnectionHandler(log).lockAndRefreshConnection({ platformId: appConnection.platformId, projectId, externalId: appConnection.externalId, log })
        if (isNil(refreshedConnection)) {
            return null
        }
        return oauth2Util(log).removeRefreshTokenAndClientSecret(refreshedConnection)
    },
    async deleteAllProjectConnections(projectId: string) {
        await appConnectionsRepo().delete({
            scope: AppConnectionScope.PROJECT,
            projectIds: ArrayContains([projectId]),
        })
    },

    async getOwners({ projectId, platformId }: { projectId: ProjectId, platformId: PlatformId }): Promise<AppConnectionOwners[]> {
        const platformAdmins = (await userService(log).getByPlatformRole(platformId, PlatformRole.ADMIN)).map(user => ({
            firstName: user.identity.firstName,
            lastName: user.identity.lastName,
            email: user.identity.email,
        }))
        const edition = system.getOrThrow(AppSystemProp.EDITION)
        if (edition === ApEdition.COMMUNITY) {
            return platformAdmins
        }
        const projectMembers = await projectMemberService(log).list({
            platformId,
            projectId,
            cursorRequest: null,
            limit: 1000,
            projectRoleId: undefined,
        })
        const projectMembersDetails = projectMembers.data.map(pm => ({
            firstName: pm.user.firstName,
            lastName: pm.user.lastName,
            email: pm.user.email,
        }))
        return [...platformAdmins, ...projectMembersDetails]
    },

    async listForPlatform(params: ListForPlatformParams): Promise<SeekPage<PlatformAppConnectionsListItem>> {
        const service = appConnectionService(log)
        const page = await service.list({
            pieceName: params.pieceName,
            displayName: params.displayName,
            status: params.status,
            scope: params.scope,
            platformId: params.platformId,
            projectId: null,
            projectIds: params.projectIds,
            ownerIds: params.ownerIds,
            cursorRequest: params.cursorRequest,
            limit: params.limit,
            externalIds: undefined,
        })

        const projectIdsToLookUp = unique(page.data.flatMap((connection) => connection.projectIds))
        const projectsById = await fetchProjectsForPlatform(projectIdsToLookUp, params.platformId)

        const data: PlatformAppConnectionsListItem[] = page.data.map((connection) => {
            const sanitized = service.removeSensitiveData(connection)
            const projects: PlatformAppConnectionProjectInfo[] = connection.projectIds
                .map((id) => projectsById.get(id))
                .filter((project): project is PlatformAppConnectionProjectInfo => project !== undefined)
            return { ...sanitized, projects }
        })

        return { ...page, data }
    },

    async listOwnersForPlatform({ platformId }: { platformId: PlatformId }): Promise<PlatformAppConnectionOwnersResponse> {
        const rows = await appConnectionsRepo()
            .createQueryBuilder('app_connection')
            .innerJoin('app_connection.owner', 'owner')
            .innerJoin('owner.identity', 'identity')
            .where('app_connection.platformId = :platformId', { platformId })
            .select('owner.id', 'id')
            .addSelect('identity.firstName', 'firstName')
            .addSelect('identity.lastName', 'lastName')
            .addSelect('identity.email', 'email')
            .distinct(true)
            .orderBy('identity.email', 'ASC')
            .limit(MAX_PLATFORM_APP_CONNECTION_OWNERS + 1)
            .getRawMany<PlatformAppConnectionOwner>()

        const truncated = rows.length > MAX_PLATFORM_APP_CONNECTION_OWNERS
        const data = truncated ? rows.slice(0, MAX_PLATFORM_APP_CONNECTION_OWNERS) : rows
        return { data, truncated }
    },

})

const fetchProjectsForPlatform = async (projectIds: string[], platformId: string): Promise<Map<string, PlatformAppConnectionProjectInfo>> => {
    if (projectIds.length === 0) {
        return new Map()
    }
    const projects = await projectRepo().find({
        where: { id: In(projectIds), platformId },
        select: ['id', 'displayName', 'type'],
    })
    return new Map(projects.map((project) => [project.id, { id: project.id, displayName: project.displayName, type: project.type }]))
}

async function assertProjectIds(projectIds: ProjectId[], platformId: string): Promise<void> {
    const filteredProjects = await projectRepo().countBy({
        id: In(projectIds),
        platformId,
    })
    if (filteredProjects !== projectIds.length) {
        throw new ActivepiecesError({
            code: ErrorCode.ENTITY_NOT_FOUND,
            params: {
                entityType: 'Project',
            },
        })
    }
}
// The generic path decodes the OIDC id_token / email claim from the token
// response — this covers every provider that returns one (Google, Microsoft, …).
// Anything provider-specific (Slack's workspace/user) lives in the piece's own
// getConnectionIdentifier hook, resolved via the engine. Best-effort — never
// throws, returns undefined on any miss.
const resolveConnectionAccountIdentifier = async ({
    connectionType,
    auth,
    pieceName,
    projectId,
    platformId,
    log,
}: {
    connectionType: AppConnectionType
    auth: AppConnectionValue
    pieceName: string
    projectId: ProjectId | undefined
    platformId: string
    log: FastifyBaseLogger
}): Promise<string | undefined> => {
    if (connectionType === AppConnectionType.NO_AUTH) {
        return undefined
    }
    if (OAUTH_CONNECTION_TYPES.includes(connectionType)) {
        const emailFromToken = emailFromTokenResponse('data' in auth ? auth.data : undefined)
        if (!isNil(emailFromToken)) {
            return emailFromToken
        }
    }
    return engineResolveConnectionIdentifier({ pieceName, projectId, platformId, auth, connectionType }, log)
}

const OAUTH_CONNECTION_TYPES = [
    AppConnectionType.OAUTH2,
    AppConnectionType.CLOUD_OAUTH2,
    AppConnectionType.PLATFORM_OAUTH2,
]

// OIDC providers expose the sign-in email under different claims: Google uses
// `email`; Microsoft/Azure AD usually put it in `preferred_username` (the UPN)
// or `upn`. Fall back to those, but only when they actually look like an email.
const pickEmailClaim = (claims: Record<string, unknown> | undefined): string | undefined => {
    if (isNil(claims)) {
        return undefined
    }
    const directEmail = claims['email'] ?? claims['mail']
    if (typeof directEmail === 'string' && directEmail.length > 0) {
        return directEmail
    }
    return ['preferred_username', 'upn', 'unique_name']
        .map((key) => claims[key])
        .find((value): value is string => typeof value === 'string' && value.includes('@'))
}

const emailFromTokenResponse = (data: Record<string, unknown> | undefined): string | undefined => {
    const emailFromData = pickEmailClaim(data)
    if (!isNil(emailFromData)) {
        return emailFromData
    }
    const idToken = data?.['id_token']
    if (typeof idToken !== 'string') {
        return undefined
    }
    const { data: decoded } = tryCatchSync(() => jwtUtils.decode<Record<string, unknown>>({ jwt: idToken }))
    return pickEmailClaim(decoded?.payload)
}

const validateConnectionValue = async (
    params: ValidateConnectionValueParams,
    log: FastifyBaseLogger,
): Promise<AppConnectionValue> => {
    const { value, pieceName, pieceVersion, projectId, platformId } = params

    switch (value.type) {
        case AppConnectionType.PLATFORM_OAUTH2: {
            const tokenUrl = await oauth2Util(log).getOAuth2TokenUrl({
                pieceName,
                pieceVersion,
                platformId,
                props: value.props,
            })
            return oauth2Handler[value.type](log).claim({
                projectId,
                platformId,
                pieceName,
                request: {
                    grantType: OAuth2GrantType.AUTHORIZATION_CODE,
                    code: value.code,
                    tokenUrl,
                    clientId: value.client_id,
                    props: value.props,
                    authorizationMethod: value.authorization_method,
                    codeVerifier: value.code_challenge,
                    redirectUrl: value.redirect_url,
                    resource: value.resource,
                },
            })
        }
        case AppConnectionType.CLOUD_OAUTH2: {
            const tokenUrl = await oauth2Util(log).getOAuth2TokenUrl({
                pieceName,
                pieceVersion,
                platformId,
                props: value.props,
            })
            return oauth2Handler[value.type](log).claim({
                projectId,
                platformId,
                pieceName,
                request: {
                    tokenUrl,
                    grantType: OAuth2GrantType.AUTHORIZATION_CODE,
                    code: value.code,
                    props: value.props,
                    clientId: value.client_id,
                    authorizationMethod: value.authorization_method,
                    codeVerifier: value.code_challenge,
                    resource: value.resource,
                },
            })
        }
        case AppConnectionType.OAUTH2: {
            const tokenUrl = await oauth2Util(log).getOAuth2TokenUrl({
                pieceName,
                pieceVersion,
                platformId,
                props: value.props,
            })
            
            const auth = await oauth2Handler[value.type](log).claim({
                projectId,
                platformId,
                pieceName,
                request: {
                    tokenUrl,
                    code: value.code,
                    clientId: value.client_id,
                    props: value.props,
                    grantType: value.grant_type!,
                    redirectUrl: value.redirect_url,
                    clientSecret: value.client_secret,
                    authorizationMethod: value.authorization_method,
                    codeVerifier: value.code_challenge,
                    scope: value.scope,
                    resource: value.resource,
                },
            })
            await engineValidateAuth({
                pieceName,
                projectId,
                platformId,
                auth,
            }, log)
            return auth
        }
        case AppConnectionType.NO_AUTH:
            break
        case AppConnectionType.CUSTOM_AUTH:
        case AppConnectionType.OIDC:
        case AppConnectionType.BASIC_AUTH:
        case AppConnectionType.SECRET_TEXT:
            await engineValidateAuth({
                platformId,
                pieceName,
                projectId,
                auth: value,
            }, log)
    }

    return value
}

const engineValidateAuth = async (
    params: EngineValidateAuthParams,
    log: FastifyBaseLogger,
): Promise<void> => {
    const environment = system.getOrThrow(AppSystemProp.ENVIRONMENT)
    if (environment === ApEnvironment.TESTING) {
        return
    }
    const { pieceName, auth, projectId, platformId } = params

    const pieceMetadata = await pieceMetadataService(log).getOrThrow({
        name: pieceName,
        version: undefined,
        platformId,
    })

    const engineResponse = await userInteractionWatcher.submitAndWaitForResponse<EngineResponse<ExecuteValidateAuthResponse>>({
        piece: await getPiecePackageWithoutArchive(log, platformId, {
            pieceName,
            pieceVersion: pieceMetadata.version,
        }),
        projectId,
        platformId,
        connectionValue: auth,
        jobType: WorkerJobType.EXECUTE_VALIDATION,
    }, log)

    if (engineResponse.status !== EngineResponseStatus.OK) {
        log.error(
            { engineResponse },
            'Engine validate auth failed',
        )
        throw new ActivepiecesError({
            code: ErrorCode.ENGINE_OPERATION_FAILURE,
            params: {
                message: 'Failed to run engine validate auth',
                context: engineResponse,
            },
        })
    }

    const validateAuthResult = engineResponse.response

    if (!validateAuthResult.valid) {
        throw new ActivepiecesError({
            code: ErrorCode.INVALID_APP_CONNECTION,
            params: {
                error: validateAuthResult.error,
            },
        })
    }
}

// The hook is a function, so it cannot survive metadata serialization — without
// the flag Piece.metadata() derives from it, every OAuth connect would pay a
// sandbox round-trip to ask a piece that has nothing to answer with.
const declaresConnectionIdentifier = (auth: PieceMetadata['auth']): boolean => {
    if (isNil(auth)) {
        return false
    }
    return (Array.isArray(auth) ? auth : [auth]).some((single) => single.hasConnectionIdentifier === true)
}

// Unlike engineValidateAuth this is best-effort: resolving a display label must
// never fail — or delay — the connection upsert, so any error/failure collapses
// to undefined and the engine round-trip is capped by RESOLVE_IDENTIFIER_TIMEOUT_MS
// (the watcher's own safety timeout is 5 minutes, far too long to block a Save on).
const RESOLVE_IDENTIFIER_TIMEOUT_MS = 15000

const engineResolveConnectionIdentifier = async (
    params: EngineResolveConnectionIdentifierParams,
    log: FastifyBaseLogger,
): Promise<string | undefined> => {
    const environment = system.getOrThrow(AppSystemProp.ENVIRONMENT)
    if (environment === ApEnvironment.TESTING) {
        return undefined
    }
    const { pieceName, auth, projectId, platformId, connectionType } = params
    const { data: identifier } = await tryCatch(async () => {
        const pieceMetadata = await pieceMetadataService(log).getOrThrow({
            name: pieceName,
            version: undefined,
            platformId,
        })
        if (!declaresConnectionIdentifier(pieceMetadata.auth)) {
            log.debug({ piece: { name: pieceName, version: pieceMetadata.version } }, 'Piece auth declares no getConnectionIdentifier, skipping engine round-trip')
            return undefined
        }
        const enginePromise = userInteractionWatcher.submitAndWaitForResponse<EngineResponse<ExecuteResolveConnectionIdentifierResponse>>({
            piece: await getPiecePackageWithoutArchive(log, platformId, {
                pieceName,
                pieceVersion: pieceMetadata.version,
            }),
            projectId,
            platformId,
            connectionValue: auth,
            connectionType,
            jobType: WorkerJobType.EXECUTE_RESOLVE_CONNECTION_IDENTIFIER,
        }, log)
        const timeoutPromise = new Promise<undefined>((resolve) => {
            setTimeout(() => resolve(undefined), RESOLVE_IDENTIFIER_TIMEOUT_MS).unref()
        })
        const engineResponse = await Promise.race([enginePromise, timeoutPromise])
        return !isNil(engineResponse) && engineResponse.status === EngineResponseStatus.OK
            ? engineResponse.response.identifier
            : undefined
    })
    return identifier ?? undefined
}

async function fetchFlowIdsForConnections(
    log: FastifyBaseLogger,
    connections: Pick<AppConnectionSchema, 'externalId' | 'projectIds'>[],
): Promise<Map<string, string[]>> {
    const allExternalIds = new Set<string>()
    const allProjectIds = new Set<string>()
    
    connections.forEach((connection) => {
        allExternalIds.add(connection.externalId)
        connection.projectIds.forEach((projectId) => {
            allProjectIds.add(projectId)
        })
    })

    if (allExternalIds.size === 0 || allProjectIds.size === 0) {
        return new Map<string, string[]>()
    }

    const flowsPage = await flowService(log).list({
        projectIds: Array.from(allProjectIds),
        cursorRequest: null,
        connectionExternalIds: Array.from(allExternalIds),
    })

    const flowIdsByExternalId = new Map<string, string[]>()
    flowsPage.data.forEach((flow) => {
        if (flow.version?.connectionIds) {
            flow.version.connectionIds.forEach((connectionExternalId) => {
                if (!flowIdsByExternalId.has(connectionExternalId)) {
                    flowIdsByExternalId.set(connectionExternalId, [])
                }
                flowIdsByExternalId.get(connectionExternalId)!.push(flow.id)
            })
        }
    })

    return flowIdsByExternalId
}

function validatePieceVersion(pieceVersion: string): void {
    if (!semver.valid(pieceVersion)) {
        throw new ActivepiecesError({
            code: ErrorCode.VALIDATION,
            params: {
                message: 'Invalid piece version',
            },
        })
    }
}
type UpsertParams = {
    projectIds: ProjectId[]
    ownerId: string | null
    platformId: string
    scope: AppConnectionScope
    externalId: string
    value: Extract<UpsertAppConnectionRequestBody, { value: unknown }>['value']
    displayName: string
    type: AppConnectionType
    status?: AppConnectionStatus
    pieceName: string
    metadata?: Metadata
    pieceVersion?: string
    preSelectForNewProjects?: boolean
}


type GetOneByName = {
    projectId: ProjectId
    platformId: string
    externalId: string
}

type GetOneParams = {
    projectId: ProjectId | null
    platformId: string
    id: string
}

type GetManyParams = {
    projectId: ProjectId
}

type RevalidateParams = {
    id: AppConnectionId
    projectId: ProjectId
    platformId: PlatformId
}

type DeleteParams = {
    projectId: ProjectId | null
    scope: AppConnectionScope
    id: AppConnectionId
    platformId: string
}

type ValidateConnectionValueParams = {
    value: Extract<UpsertAppConnectionRequestBody, { value: unknown }>['value']
    pieceName: string
    pieceVersion: string
    projectId: ProjectId | undefined
    platformId: string
}

type ListParams = {
    projectId: ProjectId | null
    projectIds?: ProjectId[]
    ownerIds?: string[]
    platformId: string
    pieceName: string | undefined
    cursorRequest: Cursor | null
    scope: AppConnectionScope | undefined
    displayName: string | undefined
    status: AppConnectionStatus[] | undefined
    limit: number
    externalIds: string[] | undefined
}

type ListForPlatformParams = {
    platformId: string
    pieceName: string | undefined
    displayName: string | undefined
    status: AppConnectionStatus[] | undefined
    scope: AppConnectionScope | undefined
    projectIds: ProjectId[] | undefined
    ownerIds: string[] | undefined
    cursorRequest: Cursor | null
    limit: number
}

type UpdateParams = {
    projectIds: ProjectId[] | null
    platformId: string
    id: AppConnectionId
    scope: AppConnectionScope
    request: {
        displayName: string
        projectIds: ProjectId[] | null
        metadata?: Metadata
        preSelectForNewProjects?: boolean
    }
}

type EngineValidateAuthParams = {
    pieceName: string
    projectId: ProjectId | undefined
    platformId: string
    auth: AppConnectionValue
}

type EngineResolveConnectionIdentifierParams = EngineValidateAuthParams & {
    connectionType: AppConnectionType
}

type ReplaceParams = {
    sourceAppConnectionId: AppConnectionId
    targetAppConnectionId: AppConnectionId
    projectId: ProjectId
    platformId: string
    userId: UserId
    applyToPublishedVersions: boolean
    flowIds: FlowId[]
}