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

12.3 KB
Raw Blame
import { ActivepiecesError, assertNotNullOrUndefined, ErrorCode, isNil } from '@activepieces/core-utils'
import { ApEdition, ApEnvironment, AuthenticationResponse, EndpointScope, pickTelemetryPii, Platform, PlatformRole, PlatformWithoutSensitiveData, PrincipalType, Project, ProjectType, SsoDomainVerificationStatus, TelemetryEventName, User, UserIdentity, UserIdentityProvider, UserStatus } from '@activepieces/shared'
import { FastifyBaseLogger, FastifyRequest } from 'fastify'
import { system } from '../helper/system/system'
import { AppSystemProp } from '../helper/system/system-props'
import { telemetry } from '../helper/telemetry.utils'
import { platformService } from '../platform/platform.service'
import { projectService } from '../project/project-service'
import { userService } from '../user/user-service'
import { userInvitationsService } from '../user-invitations/user-invitation.service'
import { accessTokenManager } from './lib/access-token-manager'
import { signupNames } from './lib/signup-names'
import { userIdentityService } from './user-identity/user-identity-service'

export const authenticationUtils = (log: FastifyBaseLogger) => ({
    async assertUserIsInvitedToPlatformOrProject({
        email,
        platformId,
    }: AssertUserIsInvitedToPlatformOrProjectParams): Promise<void> {
        const isInvited = await userInvitationsService(log).hasAnyAcceptedInvitations({
            platformId,
            email,

        })
        if (!isInvited) {
            throw new ActivepiecesError({
                code: ErrorCode.INVITATION_ONLY_SIGN_UP,
                params: {
                    message: 'User is not invited to the platform',
                },
            })
        }
    },

    async getProjectAndToken(params: GetProjectAndTokenParams): Promise<AuthenticationResponse> {
        const user = await userService(log).getOneOrFail({ id: params.userId })
        const projects = await projectService(log).getAllForUser({
            platformId: params.platformId,
            userId: params.userId,
            isPrivileged: userService(log).isUserPrivileged(user),
        })
        const project = isNil(params.projectId)
            ? findPersonalProject(projects, params.userId) ?? projects?.[0]
            : projects.find((project) => project.id === params.projectId)
        const identity = await userIdentityService(log).getOneOrFail({ id: user.identityId })
        if (!identity.verified) {
            throw new ActivepiecesError({
                code: ErrorCode.EMAIL_IS_NOT_VERIFIED,
                params: {
                    email: identity.email,
                },
            })
        }
        if (user.status === UserStatus.INACTIVE) {
            throw new ActivepiecesError({
                code: ErrorCode.USER_IS_INACTIVE,
                params: {
                    email: identity.email,
                },
            })
        }
        const token = await accessTokenManager(log).generateToken({
            id: user.id,
            type: PrincipalType.USER,
            platform: {
                id: params.platformId,
            },
            tokenVersion: identity.tokenVersion,
        })
        return {
            ...user,
            firstName: identity.firstName,
            lastName: identity.lastName,
            email: identity.email,
            trackEvents: identity.trackEvents,
            newsLetter: identity.newsLetter,
            verified: identity.verified,
            token,
            projectId: project?.id ?? null,
        }
    },

    async getOnboardingResponse({ identityId }: GetOnboardingResponseParams): Promise<AuthenticationResponse> {
        const identity = await userIdentityService(log).getOneOrFail({ id: identityId })
        if (!identity.verified) {
            throw new ActivepiecesError({
                code: ErrorCode.EMAIL_IS_NOT_VERIFIED,
                params: {
                    email: identity.email,
                },
            })
        }

        const token = await accessTokenManager(log).generateToken({
            id: identity.id,
            type: PrincipalType.ONBOARDING,
            tokenVersion: identity.tokenVersion,
        })
        return {
            id: identity.id,
            platformId: null,
            platformRole: PlatformRole.ADMIN,
            status: UserStatus.ACTIVE,
            externalId: null,
            firstName: identity.firstName,
            lastName: identity.lastName,
            email: identity.email,
            trackEvents: identity.trackEvents,
            newsLetter: identity.newsLetter,
            verified: identity.verified,
            token,
            projectId: null,
        }
    },

    async provisionOrOnboard({ identityId }: ProvisionOrOnboardParams): Promise<AuthenticationResult> {
        const identity = await userIdentityService(log).getOneOrFail({ id: identityId })
        if (!identity.verified || signupNames.isPlaceholderName(identity)) {
            return { response: await this.getOnboardingResponse({ identityId }), signedUp: false }
        }
        const { response, provisioned } = await platformService(log).createPlatformWithProject({
            identityId,
            name: signupNames.platformNameFromSignup({ firstName: identity.firstName, email: identity.email }),
            invalidatePreviousTokens: false,
            isFirstPlatform: true,
            callerTokenVersion: undefined,
        })
        return { response, signedUp: provisioned }
    },

    async assertDomainIsAllowed({
        email,
        platformId,
    }: AssertDomainIsAllowedParams): Promise<void> {
        const edition = system.getEdition()
        if (edition === ApEdition.COMMUNITY) {
            return
        }
        const platform = await platformService(log).getOneWithPlanOrThrow(platformId)
        if (!platform.plan.ssoEnabled) {
            return
        }
        const emailDomain = email.split('@')[1]
        const isAllowedDomaiin =
            !platform.enforceAllowedAuthDomains ||
            platform.allowedAuthDomains.some((domain) => domain.toLowerCase() === emailDomain?.toLowerCase())

        if (!isAllowedDomaiin) {
            throw new ActivepiecesError({
                code: ErrorCode.DOMAIN_NOT_ALLOWED,
                params: {
                    domain: emailDomain,
                },
            })
        }
    },

    async assertEmailMatchesSsoDomain({
        email,
        platformId,
    }: AssertEmailMatchesSsoDomainParams): Promise<void> {
        const edition = system.getEdition()
        if (edition !== ApEdition.CLOUD) {
            return
        }
        const platform = await platformService(log).getOneWithPlanOrThrow(platformId)
        if (!platform.plan.ssoEnabled) {
            return
        }
        if (isNil(platform.ssoDomain) || platform.ssoDomainVerification?.status !== SsoDomainVerificationStatus.VERIFIED) {
            return
        }
        const emailDomain = email.split('@')[1]?.toLowerCase() ?? ''
        if (emailDomain !== platform.ssoDomain) {
            throw new ActivepiecesError({
                code: ErrorCode.DOMAIN_NOT_ALLOWED,
                params: {
                    domain: emailDomain,
                },
            })
        }
    },

    async assertEmailAuthIsEnabled({
        platformId,
        provider,
    }: AssertEmailAuthIsEnabledParams): Promise<void> {
        const edition = system.getEdition()
        if (edition === ApEdition.COMMUNITY) {
            return
        }
        const platform = await platformService(log).getOneWithPlanOrThrow(platformId)
        if (!platform.plan.ssoEnabled) {
            return
        }
        if (provider !== UserIdentityProvider.EMAIL) {
            return
        }
        if (!platform.emailAuthEnabled) {
            throw new ActivepiecesError({
                code: ErrorCode.EMAIL_AUTH_DISABLED,
                params: {},
            })
        }
    },

    async sendTelemetry({
        user,
        identity,
        projectId,
    }: SendTelemetryParams): Promise<void> {
        try {
            if (!isNil(user.platformId)) {
                await telemetry(log).identify({ identity, platformId: user.platformId, user })
            }
            await telemetry(log).trackProject({
                projectId,
                event: {
                    name: TelemetryEventName.SIGNED_UP,
                    payload: {
                        userId: user.id,
                        projectId,
                        ...pickTelemetryPii({
                            edition: system.getEdition(),
                            email: identity.email,
                            firstName: identity.firstName,
                            lastName: identity.lastName,
                        }),
                    },
                },
            })
        }
        catch (e) {
            log.warn({ error: e }, '[authenticationUtils#sendTelemetry] Failed to send telemetry')
        }
    },

    async saveNewsLetterSubscriber(identity: UserIdentity): Promise<void> {
        const environment = system.get(AppSystemProp.ENVIRONMENT)
        if (environment !== ApEnvironment.PRODUCTION) {
            return
        }
        try {
            const response = await fetch(
                'https://us-central1-activepieces-b3803.cloudfunctions.net/addContact',
                {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify({ email: identity.email }),
                },
            )
            await response.json()
        }
        catch (error) {
            log.warn({ error }, '[authenticationUtils#saveNewsLetterSubscriber] Failed to save newsletter subscriber')
        }
    },
    async extractUserIdFromRequest(request: FastifyRequest): Promise<string> {
        if (request.principal.type === PrincipalType.USER) {
            return request.principal.id
        }
        // TODO currently it's same as api service, but it's better to get it from api key service, in case we introduced more admin users
        const projectId = request.principal.type === PrincipalType.ENGINE ? request.principal.projectId : request.projectId
        assertNotNullOrUndefined(projectId, 'projectId')
        const project = await projectService(log).getOneOrThrow(projectId)
        return project.ownerId
    },
    getSignInMethods({ platform }: GetSignInMethodsParams): SignInMethods {
        const edition = system.getEdition()
        if (edition === ApEdition.COMMUNITY) {
            return { email: true, google: false, sso: false }
        }
        return {
            email: platform.emailAuthEnabled,
            google: isGoogleConfigured() && platform.googleAuthEnabled,
            sso: !isNil(platform.federatedAuthProviders?.saml) && (edition !== ApEdition.CLOUD || platform.ssoDomainVerification?.status === SsoDomainVerificationStatus.VERIFIED),
        }
    },
})

function findPersonalProject(projects: Project[], userId: string): Project | undefined {
    return projects.find((project) => project.ownerId === userId && project.type === ProjectType.PERSONAL)
}

function isGoogleConfigured(): boolean {
    return !isNil(system.get(AppSystemProp.GOOGLE_CLIENT_ID)) && !isNil(system.get(AppSystemProp.GOOGLE_CLIENT_SECRET))
}

type SendTelemetryParams = {
    identity: UserIdentity
    user: User
    projectId: string
}

type AssertDomainIsAllowedParams = {
    email: string
    platformId: string
}

type AssertEmailAuthIsEnabledParams = {
    platformId: string
    provider: UserIdentityProvider
}

type AssertEmailMatchesSsoDomainParams = {
    email: string
    platformId: string
}

type AssertUserIsInvitedToPlatformOrProjectParams = {
    email: string
    platformId: string
}

type ProvisionOrOnboardParams = {
    identityId: string
}

export type AuthenticationResult = {
    response: AuthenticationResponse
    signedUp: boolean
}

export type SignInMethods = {
    email: boolean
    google: boolean
    sso: boolean
}

type GetSignInMethodsParams = {
    platform: Pick<Platform | PlatformWithoutSensitiveData, 'emailAuthEnabled' | 'googleAuthEnabled' | 'federatedAuthProviders' | 'ssoDomainVerification'>
}

type GetOnboardingResponseParams = {
    identityId: string
}

type GetProjectAndTokenParams = {
    userId: string
    platformId: string
    projectId: string | null
    scope?: EndpointScope
}