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

6.5 KB
Raw Blame
import { ApId, apId, SeekPage } from '@activepieces/core-utils'
import { wideEvent } from '@activepieces/server-utils'
import { AppConnectionScope, AppConnectionWithoutSensitiveData, ApplicationEventName, ListGlobalConnectionsRequestQuery, PrincipalType, SERVICE_KEY_SECURITY_OPENAPI, UpdateGlobalConnectionValueRequestBody, UpsertGlobalConnectionRequestBody } from '@activepieces/shared'
import { FastifyPluginAsyncZod } from 'fastify-type-provider-zod'
import { StatusCodes } from 'http-status-codes'
import { z } from 'zod'
import { appConnectionService } from '../../app-connection/app-connection-service/app-connection-service'
import { securityAccess } from '../../core/security/authorization/fastify-security'
import { applicationEvents } from '../../helper/application-events'
import { auditEvents } from '../../helper/audit-events'
import { securityHelper } from '../../helper/security-helper'
import { platformMustHaveFeatureEnabled } from '../authentication/ee-authorization'

export const globalConnectionModule: FastifyPluginAsyncZod = async (app) => {
    app.addHook('preHandler', platformMustHaveFeatureEnabled((platform) => platform.plan.globalConnectionsEnabled))
    await app.register(globalConnectionController, { prefix: '/v1/global-connections' })
}

const globalConnectionController: FastifyPluginAsyncZod = async (app) => {
    app.post('/', UpsertGlobalConnectionRequest, async (request, reply) => {
        const appConnection = await appConnectionService(request.log).upsert({
            platformId: request.principal.platform.id,
            type: request.body.type,
            projectIds: request.body.projectIds,
            externalId: request.body.externalId ?? apId(),
            value: request.body.value,
            displayName: request.body.displayName,
            pieceName: request.body.pieceName,
            ownerId: await securityHelper.getUserIdFromRequest(request),
            scope: AppConnectionScope.PLATFORM,
            pieceVersion: request.body.pieceVersion,
            preSelectForNewProjects: request.body.preSelectForNewProjects,
        })
        applicationEvents(request.log).sendUserEvent(request, {
            action: ApplicationEventName.CONNECTION_UPSERTED,
            data: {
                connection: appConnection,
            },
        })
        await reply
            .status(StatusCodes.CREATED)
            .send(appConnection)
    })

    app.post('/:id', UpdateGlobalConnectionRequest, async (request) => {
        return appConnectionService(request.log).update({
            id: request.params.id,
            platformId: request.principal.platform.id,
            scope: AppConnectionScope.PLATFORM,
            projectIds: null,
            request: {
                displayName: request.body.displayName,
                projectIds: request.body.projectIds ?? null,
                preSelectForNewProjects: request.body.preSelectForNewProjects,
            },
        })
    })

    app.get('/', ListGlobalConnectionsRequest, async (request): Promise<SeekPage<AppConnectionWithoutSensitiveData>> => {
        const { displayName, pieceName, status, cursor, limit } = request.query

        const appConnections = await appConnectionService(request.log).list({
            pieceName,
            displayName,
            status,
            platformId: request.principal.platform.id,
            projectId: null,
            scope: AppConnectionScope.PLATFORM,
            cursorRequest: cursor ?? null,
            limit: limit ?? DEFAULT_PAGE_SIZE,
            externalIds: undefined,
        })

        const appConnectionsWithoutSensitiveData = {
            ...appConnections,
            data: appConnections.data.map(appConnectionService(request.log).removeSensitiveData),
        }
        wideEvent.audit(auditEvents.globalConnectionListed({
            actor: auditEvents.actorFromPrincipal(request.principal),
            target: {
                type: 'platform',
                id: request.principal.platform.id,
                connectionCount: appConnectionsWithoutSensitiveData.data.length,
            },
        }))
        return appConnectionsWithoutSensitiveData
    },
    )

    app.delete('/:id', DeleteGlobalConnectionRequest, async (request, reply): Promise<void> => {
        const connection = await appConnectionService(request.log).getOneOrThrowWithoutValue({
            id: request.params.id,
            platformId: request.principal.platform.id,
            projectId: null,
        })
        await appConnectionService(request.log).delete({
            id: request.params.id,
            platformId: request.principal.platform.id,
            scope: AppConnectionScope.PLATFORM,
            projectId: null,
        })
        applicationEvents(request.log).sendUserEvent(request, {
            action: ApplicationEventName.CONNECTION_DELETED,
            data: {
                connection,
            },
        })
        await reply.status(StatusCodes.NO_CONTENT).send()
    })
}

const DEFAULT_PAGE_SIZE = 10

const UpsertGlobalConnectionRequest = {
    config: {
        security: securityAccess.platformAdminOnly([PrincipalType.USER, PrincipalType.SERVICE]),
    },
    schema: {
        tags: ['global-connections'],
        body: UpsertGlobalConnectionRequestBody,
        security: [SERVICE_KEY_SECURITY_OPENAPI],
        response: {
            [StatusCodes.CREATED]: AppConnectionWithoutSensitiveData,
        },
    },
}

const UpdateGlobalConnectionRequest = {
    config: {
        security: securityAccess.platformAdminOnly([PrincipalType.USER, PrincipalType.SERVICE]),
    },
    schema: {
        tags: ['global-connections'],
        body: UpdateGlobalConnectionValueRequestBody,
        params: z.object({
            id: ApId,
        }),
        security: [SERVICE_KEY_SECURITY_OPENAPI],
    },
}

const ListGlobalConnectionsRequest = {
    config: {
        security: securityAccess.platformAdminOnly([PrincipalType.USER, PrincipalType.SERVICE]),
    },
    schema: {
        tags: ['global-connections'],
        querystring: ListGlobalConnectionsRequestQuery,
        security: [SERVICE_KEY_SECURITY_OPENAPI],
        response: {
            [StatusCodes.OK]: SeekPage(AppConnectionWithoutSensitiveData),
        },
    },
}

const DeleteGlobalConnectionRequest = {
    config: {
        security: securityAccess.platformAdminOnly([PrincipalType.USER, PrincipalType.SERVICE]),
    },
    schema: {
        tags: ['global-connections'],
        params: z.object({
            id: ApId,
        }),
        security: [SERVICE_KEY_SECURITY_OPENAPI],
        response: {
            [StatusCodes.NO_CONTENT]: z.never(),
        },
    },
}