diff --git a/CHANGELOG.md b/CHANGELOG.md index 014cdbf..e92ba15 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,9 @@ +## [Unreleased] + +### Fixed + +* **Recipient names with commas, quotes or angle brackets arrive unchanged.** `"Doe, Jane" ` in to, cc or bcc used to be split at the comma and partly lower-cased, so the recipient saw the name "doe, Jane" (SMTP, Gmail, Outlook, Yahoo and Mailgun). Addresses are now read with the same RFC 5322 parser the transports use; only the address is lower-cased, never the name. Bare address lists are normalised exactly as before. + ## [4.6.1](https://github.com/Schero94/Magic-Mail/compare/v4.6.0...v4.6.1) (2026-11-18) diff --git a/server/src/services/email-router.js b/server/src/services/email-router.js index 3af6600..d074c4d 100644 --- a/server/src/services/email-router.js +++ b/server/src/services/email-router.js @@ -362,6 +362,59 @@ function parseAddressList(value) { return out; } +/** RFC 5322 atext plus spaces and Unicode letters: a display name that needs no quotes. */ +const PLAIN_DISPLAY_NAME = /^[\p{L}\p{M}\p{N} !#$%&'*+\-/=?^_`{|}~]+$/u; + +/** + * Formats one parsed mailbox with a lower-cased address. The display name is + * kept byte for byte; it is quoted (with `"` and `\` escaped) only when it + * contains characters that would otherwise change how it parses, such as a + * comma or angle brackets. + * + * @param {{name?: string, address: string}} entry + * @returns {string} + */ +function formatNormalizedMailbox(entry) { + const address = entry.address.trim().toLowerCase(); + const name = entry.name || ''; + if (!name) return address; + const phrase = PLAIN_DISPLAY_NAME.test(name) ? name : `"${name.replace(/["\\]/g, '\\$&')}"`; + return `${phrase} <${address}>`; +} + +/** + * Normalises one recipient string: parsed with the RFC 5322 parser the + * transports use, so commas, quotes and angle brackets inside quoted display + * names are kept. Only the address part is lower-cased (RFC 5321: the domain + * is case-insensitive; Magic Mail has always lower-cased the whole address). + * Values the parser cannot read as plain mailboxes (groups, empty addresses) + * are returned trimmed and otherwise unchanged; validation handles them later. + * + * @param {*} value + * @returns {*} the normalised string, or the value unchanged when it is not a string + */ +function normalizeRecipientString(value) { + if (typeof value !== 'string') return value; + const entries = getAddressParser()(value); + if (entries.length === 0 || entries.some((e) => Array.isArray(e.group) || !e.address)) { + return value.trim(); + } + return entries.map(formatNormalizedMailbox).join(', '); +} + +/** + * Normalises a to/cc/bcc value (string, array of strings, or `{ name, address }` + * objects, which are passed through) without touching display names. + * + * @param {*} value + * @returns {*} + */ +function normalizeRecipients(value) { + if (!value) return value; + if (Array.isArray(value)) return value.map(normalizeRecipientString); + return normalizeRecipientString(value); +} + /** * Returns the bare, lower-cased addresses of a recipient value. * @param {*} value @@ -1006,25 +1059,10 @@ module.exports = ({ strapi }) => ({ throw validationError('Recipient email address (to) is required'); } - // Normalize addresses (RFC 5321: the domain part is case-insensitive). - const normalizeAddr = (addr) => { - if (typeof addr !== 'string') return addr; - if (addr.includes('<') && addr.includes('>')) { - return addr.replace(/<([^>]+)>/, (_, email) => `<${email.trim().toLowerCase()}>`); - } - return addr.trim().toLowerCase(); - }; - const normalizeAddrs = (value) => { - if (!value) return value; - if (Array.isArray(value)) return value.map(normalizeAddr); - if (typeof value === 'string' && value.includes(',')) { - return value.split(',').map(normalizeAddr).join(', '); - } - return normalizeAddr(value); - }; - data.to = normalizeAddrs(data.to); - if (data.cc) data.cc = normalizeAddrs(data.cc); - if (data.bcc) data.bcc = normalizeAddrs(data.bcc); + // Lower-case the address parts; display names stay exactly as given. + data.to = normalizeRecipients(data.to); + if (data.cc) data.cc = normalizeRecipients(data.cc); + if (data.bcc) data.bcc = normalizeRecipients(data.bcc); if (data.skipLinkTracking) { strapi.log.debug('[magic-mail] [SKIP-TRACK] Link tracking disabled for this email'); diff --git a/tests/address-display-names.test.js b/tests/address-display-names.test.js new file mode 100644 index 0000000..1d82068 --- /dev/null +++ b/tests/address-display-names.test.js @@ -0,0 +1,174 @@ +'use strict'; + +// Regression tests: display names in to/cc/bcc reach every provider +// unchanged. send() used to split address strings on every comma (also +// inside quoted display names) and lower-case the pieces, so +// `"Ops, Live" ` arrived as `"ops, Live" `. Found by the live +// SendGrid run (SG-9). Only the address part may be lower-cased. +// Synthetic data only; fetch is faked and the SMTP/OAuth transports are +// replaced by recorders at the provider boundary. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { + accountFor, + createHarness, + fakeFetch, + withEncryptionKey, +} = require('./helpers/provider-send-harness'); + +/** Input address strings and the mailboxes every provider must receive. */ +const CASES = [ + { + label: 'comma in a quoted name', + cc: '"Ops, Live" ', + expected: [{ name: 'Ops, Live', address: 'cc@example.test' }], + }, + { + label: 'escaped quotes and a comma in a quoted name', + cc: '"Doe, Jane \\"JD\\"" ', + expected: [{ name: 'Doe, Jane "JD"', address: 'jd@example.test' }], + }, + { + label: 'unicode names, quoted with a comma and unquoted', + cc: '"Müller, Zoë" , Zoë Müller ', + expected: [ + { name: 'Müller, Zoë', address: 'zoe@example.test' }, + { name: 'Zoë Müller', address: 'zoe2@example.test' }, + ], + }, + { + label: 'angle brackets inside a quoted name', + cc: '"Ops " ', + expected: [{ name: 'Ops ', address: 'ops@example.test' }], + }, + { + label: 'mixed list: quoted comma name, plain name, bare address', + cc: '"Ops, Live" , Bob Builder , C@example.test', + expected: [ + { name: 'Ops, Live', address: 'a@example.test' }, + { name: 'Bob Builder', address: 'b@example.test' }, + { name: '', address: 'c@example.test' }, + ], + }, + { + label: 'array items with quoted comma names', + cc: ['"Ops, Live" ', '"Ünal, Ada" '], + expected: [ + { name: 'Ops, Live', address: 'a@example.test' }, + { name: 'Ünal, Ada', address: 'ada@example.test' }, + ], + }, +]; + +const TO = 'Primary Person '; +const TO_EXPECTED = [{ name: 'Primary Person', address: 'to@example.test' }]; + +/** + * Parses what a provider received into mailboxes. + * + * @param {*} value + * @returns {{name: string, address: string}[]} + */ +function mailboxes(value) { + const parse = require('nodemailer/lib/addressparser'); + const items = Array.isArray(value) ? value : [value]; + return items.flatMap((item) => + typeof item === 'string' + ? parse(item).map((e) => ({ name: e.name || '', address: (e.address || '').toLowerCase() })) + : [{ name: item.name || '', address: String(item.address).toLowerCase() }] + ); +} + +for (const { label, cc, expected } of CASES) { + test(`SendGrid receives the right addresses: ${label}`, async () => { + // SendGrid sends bare addresses in this release (names are not passed + // on), so only the addresses are compared. + const restoreKey = withEncryptionKey(); + const fetchFake = fakeFetch(); + try { + const { router } = createHarness([accountFor('sendgrid')]); + await router.send({ to: TO, cc, subject: 'Names', text: 'x' }); + const p = fetchFake.calls.at(-1).json.personalizations[0]; + assert.deepEqual( + p.to.map((entry) => entry.email), + TO_EXPECTED.map((m) => m.address) + ); + assert.deepEqual( + p.cc.map((entry) => entry.email), + expected.map((m) => m.address) + ); + } finally { + fetchFake.restore(); + restoreKey(); + } + }); + + test(`Mailgun keeps display names: ${label}`, async () => { + const restoreKey = withEncryptionKey(); + const fetchFake = fakeFetch(); + try { + const { router } = createHarness([accountFor('mailgun')]); + await router.send({ to: TO, cc, subject: 'Names', text: 'x' }); + const form = fetchFake.calls.at(-1).form; + const field = (key) => form.filter(([k]) => k === key).map(([, v]) => v); + assert.deepEqual(mailboxes(field('to')), TO_EXPECTED); + assert.deepEqual(mailboxes(field('cc')), expected); + } finally { + fetchFake.restore(); + restoreKey(); + } + }); + + for (const [provider, method] of [ + ['smtp', 'sendViaSMTP'], + ['gmail-oauth', 'sendViaGmailOAuth'], + ['microsoft-oauth', 'sendViaMicrosoftOAuth'], + ['yahoo-oauth', 'sendViaYahooOAuth'], + ]) { + test(`${provider} receives the display names unchanged: ${label}`, async () => { + const restoreKey = withEncryptionKey(); + try { + const account = { ...accountFor('sendgrid'), provider, documentId: `acc-${provider}` }; + const { router } = createHarness([account]); + let received; + router[method] = async (_account, emailData) => { + received = emailData; + return { messageId: 'm1' }; + }; + await router.send({ to: TO, cc, bcc: cc, subject: 'Names', text: 'x' }); + assert.deepEqual(mailboxes(received.to), TO_EXPECTED); + assert.deepEqual(mailboxes(received.cc), expected); + assert.deepEqual(mailboxes(received.bcc), expected); + } finally { + restoreKey(); + } + }); + } +} + +test('bare address lists are normalised exactly as before', async () => { + const restoreKey = withEncryptionKey(); + try { + const account = { ...accountFor('sendgrid'), provider: 'smtp', documentId: 'acc-smtp' }; + const { router } = createHarness([account]); + let received; + router.sendViaSMTP = async (_account, emailData) => { + received = emailData; + return { messageId: 'm1' }; + }; + await router.send({ + to: ['Ada@Example.test', 'bob@example.test'], + cc: 'Carol@Example.test,dave@example.test', + bcc: ' Eve@Example.test ', + subject: 'Bare', + text: 'x', + }); + assert.deepEqual(received.to, ['ada@example.test', 'bob@example.test']); + assert.equal(received.cc, 'carol@example.test, dave@example.test'); + assert.equal(received.bcc, 'eve@example.test'); + } finally { + restoreKey(); + } +}); diff --git a/tests/helpers/provider-send-harness.js b/tests/helpers/provider-send-harness.js new file mode 100644 index 0000000..c4b2aaa --- /dev/null +++ b/tests/helpers/provider-send-harness.js @@ -0,0 +1,192 @@ +'use strict'; + +/** + * Test harness for the SendGrid and Mailgun send paths: a minimal fake + * Strapi with the real email-router service, in-memory accounts, a + * deterministic delivery log and tracking, and a recording fake `fetch`. + * Synthetic data only; nothing leaves the process. + */ + +const ROUTER_PATH = '../../server/src/services/email-router'; +const quietLog = { debug() {}, info() {}, warn() {}, error() {} }; + +/** + * Sets a throw-away encryption key for account configs. + * + * @returns {() => void} restores the previous value + */ +function withEncryptionKey() { + const previous = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = 's'.repeat(32); + return () => { + if (previous === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previous; + }; +} + +/** + * Builds a SendGrid or Mailgun account with an encrypted config. + * + * @param {'sendgrid'|'mailgun'} provider + * @param {object} [config] - Extra plain config (region, domain, ...) + * @returns {object} + */ +function accountFor(provider, config = {}) { + const { encryptCredentials } = require('../../server/src/utils/encryption'); + const plain = + provider === 'sendgrid' + ? { apiKey: 'SG.fake', ...config } + : { apiKey: 'key-fake', domain: 'mg.example.test', ...config }; + return { + documentId: `acc${provider}`, + name: `test-${provider}`, + provider, + fromEmail: `noreply@${provider}.example.test`, + fromName: 'Test Sender', + isActive: true, + isPrimary: true, + priority: 5, + config: encryptCredentials(plain), + }; +} + +/** + * Fake Strapi with the real router. + * + * @param {object[]} accounts + * @param {{logDocumentId?: string|null, tracking?: 'all'|'opens'|'none'}} [options] + * `tracking`: what the fake analytics service really applies + * @returns {{router: object, logs: string[], accountManager: object}} + */ +function createHarness(accounts, { logDocumentId = 'logdoc123', tracking = 'all' } = {}) { + const logs = []; + const log = { + debug() {}, + info() {}, + warn: (message) => logs.push(String(message)), + error: (message) => logs.push(String(message)), + }; + const services = {}; + const strapi = { + log, + config: { get: (key, fallback) => fallback }, + plugin(name) { + if (name !== 'magic-mail') return null; + return { service: (serviceName) => services[serviceName] }; + }, + documents(uid) { + return { + findMany: async ({ filters = {} } = {}) => { + if (uid.endsWith('routing-rule')) return []; + const excluded = filters.documentId?.$notIn || []; + return accounts + .filter((a) => a.isActive !== false && !excluded.includes(a.documentId)) + .sort((a, b) => (b.priority || 0) - (a.priority || 0)); + }, + findOne: async ({ documentId }) => + accounts.find((a) => a.documentId === documentId) || null, + findFirst: async () => null, + update: async ({ data }) => data, + }; + }, + }; + services['plugin-settings'] = { getSettings: async () => ({}) }; + services.analytics = { + createEmailLog: async () => + logDocumentId === null ? null : { documentId: logDocumentId, emailId: 'emailtest1' }, + updateEmailLog: async () => {}, + generateRecipientHash: () => 'hash', + addTracking: async (html, emailId, hash, { openTracking, linkTracking, applied }) => { + if (tracking === 'none') return html; + let out = html; + if (linkTracking && tracking === 'all' && out.includes('https://shop.example.test/')) { + out = out.replace('https://shop.example.test/', 'https://track.example.test/c/1?u='); + if (applied) applied.clicks = true; + } + if (openTracking) { + out = `${out}`; + if (applied) applied.opens = true; + } + return out; + }, + }; + delete require.cache[require.resolve(ROUTER_PATH)]; + const router = require(ROUTER_PATH)({ strapi }); + router.updateAccountStats = async () => {}; + router.reserveQuota = async () => 'unlimited'; + router.releaseQuota = async () => {}; + router.markLog = async () => {}; + router.queueService = () => null; + services['email-router'] = router; + delete require.cache[require.resolve('../../server/src/services/account-manager')]; + services['account-manager'] = require('../../server/src/services/account-manager')({ strapi }); + return { router, logs, accountManager: services['account-manager'] }; +} + +/** + * Replaces global fetch with a recorder. + * + * @param {(call: object) => (object|Promise)} [respond] - fake Response factory + * @returns {{calls: object[], restore: () => void}} + */ +function fakeFetch(respond) { + const calls = []; + const original = global.fetch; + global.fetch = async (url, opts = {}) => { + const call = { url: String(url), method: opts.method, headers: { ...(opts.headers || {}) } }; + if (opts.body instanceof FormData) { + call.form = []; + call.files = []; + for (const [key, value] of opts.body.entries()) { + if (typeof value === 'string') call.form.push([key, value]); + else { + call.form.push([key, '']); + call.files.push({ field: key, filename: value.name, type: value.type, size: value.size }); + } + } + } else if (typeof opts.body === 'string') { + call.json = JSON.parse(opts.body); + call.bodyBytes = Buffer.byteLength(opts.body); + } + calls.push(call); + if (respond) return respond(call); + return call.url.includes('mailgun') + ? jsonResponse(200, { id: '<20261118.abc@mg.example.test>', message: 'Queued. Thank you.' }) + : jsonResponse(202, undefined, { 'x-message-id': 'sg-message-1' }); + }; + return { calls, restore: () => (global.fetch = original) }; +} + +/** + * Builds a real WHATWG Response. + * + * @param {number} status + * @param {unknown} [body] - JSON value, a string (sent as text) or undefined + * @param {Record} [headers] + * @returns {Response} + */ +function jsonResponse(status, body, headers = {}) { + if (body === undefined) return new Response(null, { status, headers }); + const text = typeof body === 'string' ? body : JSON.stringify(body); + return new Response(text, { + status, + headers: { + 'content-type': typeof body === 'string' ? 'text/plain' : 'application/json', + ...headers, + }, + }); +} + +/** 1x1 transparent PNG (synthetic inline image), base64. */ +const PIXEL_PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='; + +module.exports = { + PIXEL_PNG, + accountFor, + createHarness, + fakeFetch, + jsonResponse, + quietLog, + withEncryptionKey, +};