const path = require('node:path'); function normalizeOutgoingAttachments(value) { if (value === undefined) return []; if (!Array.isArray(value)) throw new Error('The attachment list is invalid.'); return value.map(file => { if (!file || typeof file !== 'object' || typeof file.contentBase64 !== 'string') { throw new Error('An attachment could not be read.'); } const filename = path.basename(String(file.filename || 'attachment').replace(/\\/g, '/')) .replace(/[\r\n\0]/g, '') .slice(0, 255) || 'attachment'; const contentType = String(file.contentType || 'application/octet-stream').trim().toLowerCase(); if (!/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/.test(contentType)) { throw new Error(`The content type for ${filename} is invalid.`); } const encoded = file.contentBase64; if (encoded.length % 4 !== 0 || !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(encoded)) { throw new Error(`The contents of ${filename} are invalid.`); } const content = Buffer.from(encoded, 'base64'); return { filename, contentType, contentBase64: encoded, size: content.length, content }; }); } function serializeOutgoingAttachments(attachments) { return attachments.map(({ content, ...file }) => file); } module.exports = { normalizeOutgoingAttachments, serializeOutgoingAttachments };