UNPKG

@websolutespa/payload-plugin-bowl

Version:

Bowl PayloadCms plugin of the BOM Repository

66 lines (65 loc) 2.45 kB
import { isDataField, withFieldHook } from '@websolutespa/payload-utils'; import crypto from 'crypto'; import { fieldHasSubFields } from 'payload/shared'; const findEncryptedFields = (collectionConfig, fields)=>{ let encryptedFields = []; for (const field of fields){ if (isDataField(field) && (field.custom?.encrypted || collectionConfig.custom?.encrypted)) { encryptedFields.push(field); } if (fieldHasSubFields(field)) { const subfields = findEncryptedFields(collectionConfig, field.fields); encryptedFields = encryptedFields.concat(subfields); } } return encryptedFields; }; const createKeyFromSecret = (secretKey)=>crypto.createHash('sha256').update(secretKey).digest('hex').slice(0, 32); export const encrypt = (text)=>{ const iv = crypto.randomBytes(16); const cipher = crypto.createCipheriv('aes-256-ctr', createKeyFromSecret(process.env.PAYLOAD_SECRET || ''), iv); const encrypted = Buffer.concat([ cipher.update(text), cipher.final() ]); const ivString = iv.toString('hex'); const encryptedString = encrypted.toString('hex'); const result = `${ivString}${encryptedString}`; return result; }; export const decrypt = (hash)=>{ const iv = hash.slice(0, 32); const content = hash.slice(32); if (iv.length !== 32 || content.length === 0) { return hash; } const decipher = crypto.createDecipheriv('aes-256-ctr', createKeyFromSecret(process.env.PAYLOAD_SECRET || ''), Buffer.from(iv, 'hex')); const decrypted = Buffer.concat([ decipher.update(Buffer.from(content, 'hex')), decipher.final() ]); const result = decrypted.toString(); return result; }; export const encryptField = ({ value })=>{ if (typeof value === 'string') { return encrypt(value); } return undefined; }; export const decryptField = ({ value })=>{ try { const decrypted = typeof value === 'string' ? decrypt(value) : value; return decrypted; } catch (error) { return undefined; } }; export const encryptData = (collectionConfig)=>{ const encryptedFields = findEncryptedFields(collectionConfig, collectionConfig.fields); for (const field of encryptedFields){ withFieldHook(field, 'beforeChange', encryptField); withFieldHook(field, 'afterRead', decryptField); } }; //# sourceMappingURL=encryption.js.map