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

5.4 KB
Raw Blame
import { ActivepiecesError, ErrorCode, tryCatch } from '@activepieces/core-utils'
import { safeHttp } from '@activepieces/server-utils'
import { SAMLAttributeMapping, SAMLAuthnProviderConfig } from '@activepieces/shared'
import * as validator from '@authenio/samlify-node-xmllint'
import * as saml from 'samlify'
import { resolveSamlAttributes, SamlAttributes } from './saml-attributes'

export const createSamlClient = async ({ platformId, samlProvider, acsUrl }: CreateSamlClientArgs): Promise<SamlClient> => {
    const cached = instanceCache.get(platformId)
    if (cached) {
        return cached
    }
    saml.setSchemaValidator(validator)
    const metadataXml = await resolveIdpMetadata(samlProvider.idpMetadata)
    const idp = createIdp(metadataXml)
    const sp = createSp({ privateKey: samlProvider.idpCertificate, acsUrl })
    const client = samlClient({ idp, sp, attributeMapping: samlProvider.attributeMapping })
    instanceCache.set(platformId, client)
    return client
}

export const invalidateSamlClientCache = (platformId: string): void => {
    instanceCache.delete(platformId)
}

const samlClient = ({ idp, sp, attributeMapping }: SamlClientArgs) => ({
    getLoginUrl(): string {
        return sp.createLoginRequest(idp, LOGIN_REQUEST_BINDING).context
    },
    async parseAndValidateLoginResponse(idpLoginResponse: IdpLoginResponse): Promise<SamlAttributes> {
        const { data: loginResult, error: parseError } = await tryCatch(
            () => sp.parseLoginResponse(idp, LOGIN_RESPONSE_BINDING, {
                body: toStringRecord(idpLoginResponse.body),
                query: toStringRecord(idpLoginResponse.query),
            }),
        )
        if (parseError !== null) {
            throw new ActivepiecesError({
                code: ErrorCode.INVALID_SAML_RESPONSE,
                params: {
                    message: `Failed to parse SAML response: ${toErrorMessage(parseError)}`,
                },
            })
        }
        return resolveSamlAttributes({
            rawAttributes: loginResult.extract?.attributes,
            mapping: attributeMapping,
        })
    },
})

const createIdp = (metadata: string): saml.IdentityProviderInstance => {
    return saml.IdentityProvider({
        metadata,
        isAssertionEncrypted: false,
        messageSigningOrder: 'encrypt-then-sign',
        wantLogoutRequestSigned: true,
    })
}

const resolveIdpMetadata = async (idpMetadata: string): Promise<string> => {
    const trimmed = idpMetadata.trim()
    if (!/^https?:\/\//i.test(trimmed)) {
        return idpMetadata
    }
    const { data: response, error } = await tryCatch(() => safeHttp.axios.get<string>(trimmed, {
        responseType: 'text',
        timeout: 10_000,
        maxContentLength: 5 * 1024 * 1024,
        maxBodyLength: 5 * 1024 * 1024,
        transformResponse: (data) => data,
    }))
    if (error !== null) {
        throw new ActivepiecesError({
            code: ErrorCode.INVALID_SAML_RESPONSE,
            params: {
                message: `Failed to fetch IdP metadata from URL: ${toErrorMessage(error)}`,
            },
        })
    }
    const contentType = String(response.headers['content-type'] ?? '').toLowerCase()
    if (contentType !== '' && !contentType.includes('xml') && !contentType.includes('text/plain')) {
        throw new ActivepiecesError({
            code: ErrorCode.INVALID_SAML_RESPONSE,
            params: {
                message: `Failed to fetch IdP metadata from URL: Unexpected content-type "${contentType}" — expected XML.`,
            },
        })
    }
    return typeof response.data === 'string' ? response.data : String(response.data)
}

const createSp = ({ privateKey, acsUrl }: CreateSpArgs): saml.ServiceProviderInstance => {
    return saml.ServiceProvider({
        entityID: 'Activepieces',
        authnRequestsSigned: false,
        wantMessageSigned: true,
        wantLogoutResponseSigned: true,
        wantLogoutRequestSigned: true,
        privateKey,
        isAssertionEncrypted: true,
        assertionConsumerService: [{
            Binding: saml.Constants.namespace.binding.post,
            Location: acsUrl,
        }],
        signatureConfig: {},
    })
}

const toErrorMessage = (error: unknown): string => {
    return error instanceof Error ? error.message : String(error)
}

const firstString = (value: unknown): string | undefined => {
    if (typeof value === 'string') {
        return value
    }
    if (Array.isArray(value)) {
        return value.find((item): item is string => typeof item === 'string')
    }
    return undefined
}

const toStringRecord = (input: Record<string, unknown>): Record<string, string | undefined> => {
    return Object.fromEntries(
        Object.entries(input).map(([key, value]) => [key, firstString(value)]),
    )
}

const LOGIN_REQUEST_BINDING = 'redirect'
const LOGIN_RESPONSE_BINDING = 'post'

const instanceCache = new Map<string, SamlClient>()

type SamlClient = ReturnType<typeof samlClient>

type SamlClientArgs = {
    idp: saml.IdentityProviderInstance
    sp: saml.ServiceProviderInstance
    attributeMapping: SAMLAttributeMapping | undefined
}

type CreateSpArgs = {
    privateKey: string
    acsUrl: string
}

type CreateSamlClientArgs = {
    platformId: string
    samlProvider: SAMLAuthnProviderConfig
    acsUrl: string
}

export type IdpLoginResponse = {
    body: Record<string, unknown>
    query: Record<string, unknown>
}

export type { SamlAttributes } from './saml-attributes'