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

3.8 KB
Raw Blame
import * as crypto from 'crypto'
import { randomBytes } from 'node:crypto'
import { promisify } from 'util'

import { assertNotNullOrUndefined, isNil } from '@activepieces/core-utils'
import { Mutex } from 'async-mutex'
import { z } from 'zod'
import { RedisType } from '../database/redis/types'
import { redisConnections } from '../database/redis-connections'
import { localFileStore } from './local-store'
import { system } from './system/system'
import { AppSystemProp } from './system/system-props'

const algorithm = 'aes-256-cbc'
const ivLength = 16
const mutexLock = new Mutex()

export const EncryptedObject = z.object({
    iv: z.string(),
    data: z.string(),
})
export type EncryptedObject = z.infer<typeof EncryptedObject>
const redisType = redisConnections.getRedisType()


export const encryptUtils = {
    decryptString: async (encryptedObject: EncryptedObject): Promise<string> => {
        const secret = await encryptUtils.getEncryptionKey()
        const iv = Buffer.from(encryptedObject.iv, 'hex')
        const key = Buffer.from(secret!, 'binary')
        const decipher = crypto.createDecipheriv(algorithm, key, iv)
        let decrypted = decipher.update(encryptedObject.data, 'hex', 'utf8')
        decrypted += decipher.final('utf8')
        return decrypted
    },
    decryptObject: async <T>(encryptedObject: EncryptedObject): Promise<T> => {
        const secret = await encryptUtils.getEncryptionKey()
        const iv = Buffer.from(encryptedObject.iv, 'hex')
        const key = Buffer.from(secret!, 'binary')
        const decipher = crypto.createDecipheriv(algorithm, key, iv)
        let decrypted = decipher.update(encryptedObject.data, 'hex', 'utf8')
        decrypted += decipher.final('utf8')
        return JSON.parse(decrypted)
    },
    encryptObject: async (object: unknown): Promise<EncryptedObject> => {
        const objectString = JSON.stringify(object)
        return encryptUtils.encryptString(objectString)
    },
    encryptString: async (inputString: string): Promise<EncryptedObject> => {
        const secret = await encryptUtils.getEncryptionKey()
        const iv = crypto.randomBytes(ivLength)
        assertNotNullOrUndefined(secret, 'secret')
        const key = Buffer.from(secret, 'binary')
        const cipher = crypto.createCipheriv(algorithm, key, iv)
        let encrypted = cipher.update(inputString, 'utf8', 'hex')
        encrypted += cipher.final('hex')
        return {
            iv: iv.toString('hex'),
            data: encrypted,
        }
    },
    hmacString: async (inputString: string): Promise<string> => {
        const secret = await encryptUtils.getEncryptionKey()
        assertNotNullOrUndefined(secret, 'secret')
        return crypto.createHmac('sha256', Buffer.from(secret, 'binary')).update(inputString).digest('hex')
    },
    digestsMatch: (stored: string, candidate: string): boolean => {
        const left = Buffer.from(stored, 'utf8')
        const right = Buffer.from(candidate, 'utf8')
        return left.length === right.length && crypto.timingSafeEqual(left, right)
    },
    getEncryptionKey: async (): Promise<string | null> => {
        const secret = system.get(AppSystemProp.ENCRYPTION_KEY) ?? null
        if (!isNil(secret)) {
            return secret
        }
        if (redisType === RedisType.MEMORY) {
            return generateAndStoreSecret()
        }
        return null
    },
}


function generateAndStoreSecret(): Promise<string> {
    return mutexLock.runExclusive(async () => {
        const storedSecret = await localFileStore.load(AppSystemProp.ENCRYPTION_KEY)
        if (!isNil(storedSecret)) {
            return storedSecret
        }
        const secretLengthInBytes = 16
        const secretBuffer = await promisify(randomBytes)(secretLengthInBytes)
        const secret = secretBuffer.toString('hex')
        await localFileStore.save(AppSystemProp.ENCRYPTION_KEY, secret)
        return secret
    })
}