From cd3421f2c7076ae13a3166114f5835ef435c3093 Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Wed, 18 Nov 2026 07:10:12 +0100 Subject: [PATCH 01/10] test: record golden SendGrid, Mailgun and SMTP payloads of 4.5.1 Recorded from main c457477 before the provider send-path fixes, so the following commits can prove that normal sends keep their recipients, content, headers and attachments. Co-Authored-By: Claude Opus 5.5 --- .../fixtures/send-golden/mailgun-direct.json | 17 + .../fixtures/send-golden/mailgun-tracked.json | 44 +++ .../mailgun-untracked-marketing.json | 49 +++ .../fixtures/send-golden/sendgrid-direct.json | 41 ++ .../send-golden/sendgrid-tracked.json | 78 ++++ .../sendgrid-untracked-marketing.json | 83 ++++ tests/fixtures/send-golden/smtp-tracked.json | 70 ++++ .../send-golden/smtp-untracked-marketing.json | 75 ++++ tests/provider-send-golden.test.js | 371 ++++++++++++++++++ 9 files changed, 828 insertions(+) create mode 100644 tests/fixtures/send-golden/mailgun-direct.json create mode 100644 tests/fixtures/send-golden/mailgun-tracked.json create mode 100644 tests/fixtures/send-golden/mailgun-untracked-marketing.json create mode 100644 tests/fixtures/send-golden/sendgrid-direct.json create mode 100644 tests/fixtures/send-golden/sendgrid-tracked.json create mode 100644 tests/fixtures/send-golden/sendgrid-untracked-marketing.json create mode 100644 tests/fixtures/send-golden/smtp-tracked.json create mode 100644 tests/fixtures/send-golden/smtp-untracked-marketing.json create mode 100644 tests/provider-send-golden.test.js diff --git a/tests/fixtures/send-golden/mailgun-direct.json b/tests/fixtures/send-golden/mailgun-direct.json new file mode 100644 index 0000000..25f3903 --- /dev/null +++ b/tests/fixtures/send-golden/mailgun-direct.json @@ -0,0 +1,17 @@ +{ + "url": "https://api.eu.mailgun.net/v3/mg.example.test/messages", + "method": "POST", + "headers": { + "Authorization": "" + }, + "body": { + "formData": [ + ["from", "\"Golden Sender\" "], + ["to", "ada@example.test"], + ["subject", "Direct"], + ["text", "Direct body"], + ["h:X-Mailer", "MagicMail/1.0"], + ["h:X-Email-Type", "transactional"] + ] + } +} diff --git a/tests/fixtures/send-golden/mailgun-tracked.json b/tests/fixtures/send-golden/mailgun-tracked.json new file mode 100644 index 0000000..e5fd878 --- /dev/null +++ b/tests/fixtures/send-golden/mailgun-tracked.json @@ -0,0 +1,44 @@ +{ + "url": "https://api.eu.mailgun.net/v3/mg.example.test/messages", + "method": "POST", + "headers": { + "Authorization": "" + }, + "body": { + "formData": [ + ["from", "\"Golden Sender\" "], + ["to", "ada@example.test, bob@example.test"], + ["cc", "carol@example.test"], + ["bcc", "dave@example.test"], + ["subject", "Golden order 42"], + [ + "html", + "

Hello

Shop" + ], + ["text", "Hello\nShop https://shop.example.test/a?x=1"], + ["h:Reply-To", "support@example.test"], + ["h:X-Campaign", "golden"], + ["h:List-Id", ""], + ["h:X-Mailer", "MagicMail/1.0"], + ["h:X-Email-Type", "transactional"], + [ + "attachment", + { + "blob": "text/plain", + "size": 12, + "filename": "receipt.txt", + "base64": "cmVjZWlwdCBib2R5" + } + ], + [ + "inline", + { + "blob": "image/png", + "size": 68, + "filename": "logo", + "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" + } + ] + ] + } +} diff --git a/tests/fixtures/send-golden/mailgun-untracked-marketing.json b/tests/fixtures/send-golden/mailgun-untracked-marketing.json new file mode 100644 index 0000000..06ca2e9 --- /dev/null +++ b/tests/fixtures/send-golden/mailgun-untracked-marketing.json @@ -0,0 +1,49 @@ +{ + "url": "https://api.eu.mailgun.net/v3/mg.example.test/messages", + "method": "POST", + "headers": { + "Authorization": "" + }, + "body": { + "formData": [ + ["from", "\"Golden Sender\" "], + ["to", "ada@example.test, bob@example.test"], + ["cc", "carol@example.test"], + ["bcc", "dave@example.test"], + ["subject", "Golden order 42"], + [ + "html", + "

Hello

Shop" + ], + ["text", "Hello\nShop https://shop.example.test/a?x=1"], + ["h:Reply-To", "support@example.test"], + ["h:X-Campaign", "golden"], + ["h:List-Id", ""], + ["h:X-Mailer", "MagicMail/1.0"], + ["h:X-Email-Type", "marketing"], + ["h:X-Priority", "1 (Highest)"], + ["h:Importance", "high"], + ["h:List-Unsubscribe", ""], + ["h:List-Unsubscribe-Post", "List-Unsubscribe=One-Click"], + ["h:Precedence", "bulk"], + [ + "attachment", + { + "blob": "text/plain", + "size": 12, + "filename": "receipt.txt", + "base64": "cmVjZWlwdCBib2R5" + } + ], + [ + "inline", + { + "blob": "image/png", + "size": 68, + "filename": "logo", + "base64": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" + } + ] + ] + } +} diff --git a/tests/fixtures/send-golden/sendgrid-direct.json b/tests/fixtures/send-golden/sendgrid-direct.json new file mode 100644 index 0000000..ac7d993 --- /dev/null +++ b/tests/fixtures/send-golden/sendgrid-direct.json @@ -0,0 +1,41 @@ +{ + "url": "https://api.sendgrid.com/v3/mail/send", + "method": "POST", + "headers": { + "Authorization": "", + "Content-Type": "application/json" + }, + "body": { + "json": { + "personalizations": [ + { + "to": [ + { + "email": "ada@example.test" + } + ] + } + ], + "from": { + "email": "noreply@sendgrid.example.test", + "name": "Golden Sender" + }, + "subject": "Direct", + "content": [ + { + "type": "text/plain", + "value": "Direct body" + } + ], + "custom_args": { + "magicmail_version": "1.0", + "email_type": "transactional", + "priority": "normal" + }, + "headers": { + "X-Mailer": "MagicMail/1.0", + "X-Email-Type": "transactional" + } + } + } +} diff --git a/tests/fixtures/send-golden/sendgrid-tracked.json b/tests/fixtures/send-golden/sendgrid-tracked.json new file mode 100644 index 0000000..c1d2347 --- /dev/null +++ b/tests/fixtures/send-golden/sendgrid-tracked.json @@ -0,0 +1,78 @@ +{ + "url": "https://api.sendgrid.com/v3/mail/send", + "method": "POST", + "headers": { + "Authorization": "", + "Content-Type": "application/json" + }, + "body": { + "json": { + "personalizations": [ + { + "to": [ + { + "email": "ada@example.test" + }, + { + "email": "bob@example.test" + } + ], + "cc": [ + { + "email": "carol@example.test" + } + ], + "bcc": [ + { + "email": "dave@example.test" + } + ] + } + ], + "from": { + "email": "noreply@sendgrid.example.test", + "name": "Golden Sender" + }, + "subject": "Golden order 42", + "content": [ + { + "type": "text/plain", + "value": "Hello\nShop https://shop.example.test/a?x=1" + }, + { + "type": "text/html", + "value": "

Hello

Shop" + } + ], + "custom_args": { + "magicmail_version": "1.0", + "email_type": "transactional", + "priority": "normal" + }, + "headers": { + "X-Campaign": "golden", + "List-Id": "", + "X-Mailer": "MagicMail/1.0", + "X-Email-Type": "transactional" + }, + "reply_to": { + "email": "support@example.test" + }, + "attachments": [ + { + "content": "cmVjZWlwdCBib2R5", + "filename": "receipt.txt", + "type": "text/plain", + "disposition": "attachment" + }, + { + "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", + "filename": "logo", + "type": "image/png", + "disposition": "inline", + "content_id": "logo" + } + ] + } + } +} diff --git a/tests/fixtures/send-golden/sendgrid-untracked-marketing.json b/tests/fixtures/send-golden/sendgrid-untracked-marketing.json new file mode 100644 index 0000000..de14f71 --- /dev/null +++ b/tests/fixtures/send-golden/sendgrid-untracked-marketing.json @@ -0,0 +1,83 @@ +{ + "url": "https://api.sendgrid.com/v3/mail/send", + "method": "POST", + "headers": { + "Authorization": "", + "Content-Type": "application/json" + }, + "body": { + "json": { + "personalizations": [ + { + "to": [ + { + "email": "ada@example.test" + }, + { + "email": "bob@example.test" + } + ], + "cc": [ + { + "email": "carol@example.test" + } + ], + "bcc": [ + { + "email": "dave@example.test" + } + ] + } + ], + "from": { + "email": "noreply@sendgrid.example.test", + "name": "Golden Sender" + }, + "subject": "Golden order 42", + "content": [ + { + "type": "text/plain", + "value": "Hello\nShop https://shop.example.test/a?x=1" + }, + { + "type": "text/html", + "value": "

Hello

Shop" + } + ], + "custom_args": { + "magicmail_version": "1.0", + "email_type": "marketing", + "priority": "high" + }, + "headers": { + "X-Campaign": "golden", + "List-Id": "", + "X-Mailer": "MagicMail/1.0", + "X-Email-Type": "marketing", + "X-Priority": "1 (Highest)", + "Importance": "high", + "List-Unsubscribe": "", + "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", + "Precedence": "bulk" + }, + "reply_to": { + "email": "support@example.test" + }, + "attachments": [ + { + "content": "cmVjZWlwdCBib2R5", + "filename": "receipt.txt", + "type": "text/plain", + "disposition": "attachment" + }, + { + "content": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=", + "filename": "logo", + "type": "image/png", + "disposition": "inline", + "content_id": "logo" + } + ] + } + } +} diff --git a/tests/fixtures/send-golden/smtp-tracked.json b/tests/fixtures/send-golden/smtp-tracked.json new file mode 100644 index 0000000..91e02d0 --- /dev/null +++ b/tests/fixtures/send-golden/smtp-tracked.json @@ -0,0 +1,70 @@ +{ + "transport": { + "host": "smtp.example.test", + "port": 587, + "secure": false, + "auth": { + "user": "u", + "pass": "p" + }, + "requireTLS": true, + "tls": { + "rejectUnauthorized": true, + "minVersion": "TLSv1.2" + }, + "disableFileAccess": true, + "disableUrlAccess": true, + "transactionLog": true, + "logger": true + }, + "options": { + "from": { + "name": "Golden Sender", + "address": "noreply@smtp.example.test" + }, + "to": ["ada@example.test", "bob@example.test"], + "cc": "carol@example.test", + "bcc": ["dave@example.test"], + "replyTo": [ + { + "name": "", + "address": "support@example.test" + } + ], + "subject": "Golden order 42", + "text": "Hello\nShop https://shop.example.test/a?x=1", + "html": "

Hello

Shop", + "attachments": [ + { + "filename": "receipt.txt", + "content": { + "buffer": "cmVjZWlwdCBib2R5" + }, + "contentType": "text/plain", + "contentDisposition": "attachment" + }, + { + "content": { + "buffer": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" + }, + "contentType": "image/png", + "cid": "logo", + "contentDisposition": "inline" + } + ], + "disableFileAccess": true, + "disableUrlAccess": true, + "date": "", + "messageId": "<@smtp.example.test>", + "headers": { + "X-Campaign": "golden", + "List-Id": "", + "X-Mailer": "MagicMail/1.0", + "X-Email-Type": "transactional", + "X-Content-Type-Options": "nosniff", + "X-Entity-Ref-ID": "magicmail-" + }, + "encoding": "utf-8", + "textEncoding": "base64" + } +} diff --git a/tests/fixtures/send-golden/smtp-untracked-marketing.json b/tests/fixtures/send-golden/smtp-untracked-marketing.json new file mode 100644 index 0000000..9011825 --- /dev/null +++ b/tests/fixtures/send-golden/smtp-untracked-marketing.json @@ -0,0 +1,75 @@ +{ + "transport": { + "host": "smtp.example.test", + "port": 587, + "secure": false, + "auth": { + "user": "u", + "pass": "p" + }, + "requireTLS": true, + "tls": { + "rejectUnauthorized": true, + "minVersion": "TLSv1.2" + }, + "disableFileAccess": true, + "disableUrlAccess": true, + "transactionLog": true, + "logger": true + }, + "options": { + "from": { + "name": "Golden Sender", + "address": "noreply@smtp.example.test" + }, + "to": ["ada@example.test", "bob@example.test"], + "cc": "carol@example.test", + "bcc": ["dave@example.test"], + "replyTo": [ + { + "name": "", + "address": "support@example.test" + } + ], + "subject": "Golden order 42", + "text": "Hello\nShop https://shop.example.test/a?x=1", + "html": "

Hello

Shop", + "attachments": [ + { + "filename": "receipt.txt", + "content": { + "buffer": "cmVjZWlwdCBib2R5" + }, + "contentType": "text/plain", + "contentDisposition": "attachment" + }, + { + "content": { + "buffer": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=" + }, + "contentType": "image/png", + "cid": "logo", + "contentDisposition": "inline" + } + ], + "disableFileAccess": true, + "disableUrlAccess": true, + "date": "", + "messageId": "<@smtp.example.test>", + "headers": { + "X-Campaign": "golden", + "List-Id": "", + "X-Mailer": "MagicMail/1.0", + "X-Email-Type": "marketing", + "X-Priority": "1 (Highest)", + "Importance": "high", + "List-Unsubscribe": "", + "List-Unsubscribe-Post": "List-Unsubscribe=One-Click", + "Precedence": "bulk", + "X-Content-Type-Options": "nosniff", + "X-Entity-Ref-ID": "magicmail-" + }, + "encoding": "utf-8", + "textEncoding": "base64" + } +} diff --git a/tests/provider-send-golden.test.js b/tests/provider-send-golden.test.js new file mode 100644 index 0000000..528c703 --- /dev/null +++ b/tests/provider-send-golden.test.js @@ -0,0 +1,371 @@ +'use strict'; + +// Golden regression tests for normal (non-template) sends through SendGrid, +// Mailgun and SMTP. The fixtures in tests/fixtures/send-golden/ were recorded +// from Magic Mail 4.5.1 (main c457477) BEFORE the provider send-path fixes. +// +// Only the fields listed in ADDED_FIELDS may differ from the recording; they +// are the deliberate additions of the send-path fixes (correlation id, +// provider tracking switched off where Magic Mail tracks, Mailgun metadata). +// Everything else must stay byte-identical, so a normal send keeps its +// recipients, content, headers, attachments and order. +// +// To re-record deliberately (a reviewed, intended change only) run: +// GOLDEN_WRITE=1 node --test tests/provider-send-golden.test.js +// +// Synthetic data only; every provider call goes to a fake fetch or a fake +// nodemailer transport. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); + +const ROUTER_PATH = '../server/src/services/email-router'; +const FIXTURE_DIR = path.join(__dirname, 'fixtures', 'send-golden'); +const quietLog = { debug() {}, info() {}, warn() {}, error() {} }; + +/** 1x1 transparent PNG (synthetic inline image). */ +const PIXEL_PNG = + 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII='; + +/** + * Fields the send-path fixes add on purpose. They are removed from the + * current output before it is compared with the 4.5.1 recording. + */ +const ADDED_FIELDS = { + sendgridJson: ['custom_args.magicmail_id', 'tracking_settings'], + mailgunForm: [ + 'o:tracking-opens', + 'o:tracking-clicks', + 'o:tag', + 'v:magicmail_email_type', + 'v:magicmail_priority', + 'v:magicmail_id', + ], +}; + +/** + * Replaces values that legitimately change per run (random Message-ID local + * parts) with stable markers. Everything else is compared as is. + * + * @param {unknown} value + * @returns {unknown} + */ +function normalize(value) { + if (typeof value === 'string') + return value + .replace(/\b[a-f0-9]{24}\b/g, '') + .replace(/magicmail-\d{10,}/g, 'magicmail-'); + if (value instanceof Date) return ''; + if (Buffer.isBuffer(value)) return { buffer: value.toString('base64') }; + if (Array.isArray(value)) return value.map(normalize); + if (value && typeof value === 'object') { + return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, normalize(v)])); + } + return value; +} + +/** + * Removes the deliberately added fields from a captured request. + * + * @param {any} captured - Normalised capture + * @returns {any} A copy without ADDED_FIELDS + */ +function withoutAddedFields(captured) { + const copy = JSON.parse(JSON.stringify(captured)); + const json = copy?.body?.json; + if (json) { + for (const field of ADDED_FIELDS.sendgridJson) { + const [head, tail] = field.split('.'); + if (tail) { + if (json[head]) delete json[head][tail]; + } else delete json[head]; + } + } + if (copy?.body?.formData) { + copy.body.formData = copy.body.formData.filter( + ([name]) => !ADDED_FIELDS.mailgunForm.includes(name) + ); + } + return copy; +} + +/** + * Compares a capture with its fixture (or records it with GOLDEN_WRITE=1). + * + * @param {string} name - Fixture file name without extension + * @param {unknown} actual - Captured request + * @returns {any} The normalised capture (with the added fields) + */ +function assertGolden(name, actual) { + const file = path.join(FIXTURE_DIR, `${name}.json`); + const normalized = JSON.parse(JSON.stringify(normalize(actual))); + if (process.env.GOLDEN_WRITE === '1') { + fs.mkdirSync(FIXTURE_DIR, { recursive: true }); + fs.writeFileSync(file, `${JSON.stringify(normalized, null, 2)}\n`); + return normalized; + } + assert.ok(fs.existsSync(file), `Golden fixture ${name}.json is missing`); + const expected = JSON.parse(fs.readFileSync(file, 'utf8')); + assert.deepEqual( + withoutAddedFields(normalized), + expected, + `Provider payload for ${name} changed` + ); + return normalized; +} + +function withEncryptionKey() { + const previous = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = 'g'.repeat(32); + return () => { + if (previous === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previous; + }; +} + +function accountFor(provider) { + const { encryptCredentials } = require('../server/src/utils/encryption'); + const base = { + documentId: `acc-${provider}`, + name: `golden-${provider}`, + provider, + fromEmail: `noreply@${provider}.example.test`, + fromName: 'Golden Sender', + isActive: true, + isPrimary: true, + priority: 5, + }; + if (provider === 'sendgrid') { + return { ...base, config: encryptCredentials({ apiKey: 'SG.fake' }) }; + } + if (provider === 'mailgun') { + return { + ...base, + config: encryptCredentials({ apiKey: 'key-fake', domain: 'mg.example.test', region: 'eu' }), + }; + } + return { + ...base, + config: encryptCredentials({ host: 'smtp.example.test', port: 587, user: 'u', pass: 'p' }), + }; +} + +/** Fake strapi with deterministic tracking and in-memory accounts. */ +function createHarness(accounts) { + const services = {}; + const strapi = { + log: quietLog, + 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 () => ({ documentId: 'goldenlog1', emailId: 'emailgolden1' }), + updateEmailLog: async () => {}, + generateRecipientHash: () => 'hash', + injectTrackingPixel: (html, emailId) => + `${html}`, + rewriteLinksForTracking: async (html) => + html.replace('https://shop.example.test/a?x=1', 'https://track.example.test/c/1'), + }; + 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; + return { router }; +} + +/** Records fetch calls; returns provider-shaped success responses. */ +function captureFetch() { + const calls = []; + const original = global.fetch; + global.fetch = async (url, opts = {}) => { + let body = opts.body; + if (body instanceof FormData) { + const entries = []; + for (const [key, value] of body.entries()) { + entries.push([ + key, + typeof value === 'string' + ? value + : { + blob: value.type, + size: value.size, + filename: value.name, + base64: Buffer.from(await value.arrayBuffer()).toString('base64'), + }, + ]); + } + body = { formData: entries }; + } else if (typeof body === 'string') { + body = { json: JSON.parse(body) }; + } + const headers = { ...(opts.headers || {}) }; + if (headers.Authorization) headers.Authorization = ''; + calls.push({ url: String(url), method: opts.method, headers, body }); + return { + ok: true, + status: 202, + headers: { get: (name) => (name.toLowerCase() === 'x-message-id' ? 'golden-sg-id' : null) }, + json: async () => ({ id: '', message: 'Queued. Thank you.' }), + }; + }; + return { calls, restore: () => (global.fetch = original) }; +} + +function captureNodemailer() { + const nodemailer = require('nodemailer'); + const original = nodemailer.createTransport; + const calls = []; + nodemailer.createTransport = (config) => ({ + sendMail: async (options) => { + const { logger, ...transportConfig } = config; + calls.push({ transport: { ...transportConfig, logger: Boolean(logger) }, options }); + return { messageId: '', response: '250 OK' }; + }, + }); + return { calls, restore: () => (nodemailer.createTransport = original) }; +} + +/** A normal send with every common field (no duplicates, no display names). */ +const NORMAL_SEND = () => ({ + to: ['Ada@Example.test', 'bob@example.test'], + cc: 'carol@example.test', + bcc: ['dave@example.test'], + subject: 'Golden order 42', + html: '

Hello

Shop', + text: 'Hello\nShop https://shop.example.test/a?x=1', + replyTo: 'support@example.test', + headers: { 'X-Campaign': 'golden', 'List-Id': '' }, + attachments: [ + { filename: 'receipt.txt', content: 'receipt body', contentType: 'text/plain' }, + { cid: 'logo', content: PIXEL_PNG, encoding: 'base64', contentType: 'image/png' }, + ], +}); + +const UNTRACKED_MARKETING = () => ({ + ...NORMAL_SEND(), + enableTracking: false, + type: 'marketing', + priority: 'high', + unsubscribeUrl: 'https://example.test/unsub', +}); + +for (const provider of ['sendgrid', 'mailgun']) { + test(`golden: normal tracked send through ${provider}`, async () => { + const restoreKey = withEncryptionKey(); + const fetchCapture = captureFetch(); + try { + const { router } = createHarness([accountFor(provider)]); + const result = await router.send(NORMAL_SEND()); + assert.equal(result.success, true); + assert.equal(fetchCapture.calls.length, 1); + assertGolden(`${provider}-tracked`, fetchCapture.calls[0]); + } finally { + fetchCapture.restore(); + restoreKey(); + } + }); + + test(`golden: untracked marketing send through ${provider}`, async () => { + const restoreKey = withEncryptionKey(); + const fetchCapture = captureFetch(); + try { + const { router } = createHarness([accountFor(provider)]); + await router.send(UNTRACKED_MARKETING()); + assert.equal(fetchCapture.calls.length, 1); + assertGolden(`${provider}-untracked-marketing`, fetchCapture.calls[0]); + } finally { + fetchCapture.restore(); + restoreKey(); + } + }); +} + +test('golden: direct adapter call (no delivery log) through SendGrid is unchanged', async () => { + const restoreKey = withEncryptionKey(); + const fetchCapture = captureFetch(); + try { + const { router } = createHarness([]); + await router.sendViaSendGrid(accountFor('sendgrid'), { + to: 'ada@example.test', + subject: 'Direct', + text: 'Direct body', + }); + const captured = assertGolden('sendgrid-direct', fetchCapture.calls[0]); + // No log id and no Magic Mail tracking: nothing is added at all. + assert.equal(captured.body.json.custom_args.magicmail_id, undefined); + assert.equal(captured.body.json.tracking_settings, undefined); + } finally { + fetchCapture.restore(); + restoreKey(); + } +}); + +test('golden: direct adapter call (no delivery log) through Mailgun', async () => { + const restoreKey = withEncryptionKey(); + const fetchCapture = captureFetch(); + try { + const { router } = createHarness([]); + await router.sendViaMailgun(accountFor('mailgun'), { + to: 'ada@example.test', + subject: 'Direct', + text: 'Direct body', + }); + assertGolden('mailgun-direct', fetchCapture.calls[0]); + } finally { + fetchCapture.restore(); + restoreKey(); + } +}); + +for (const [name, input] of [ + ['smtp-tracked', NORMAL_SEND], + ['smtp-untracked-marketing', UNTRACKED_MARKETING], +]) { + test(`golden: ${name} through SMTP is byte-identical`, async () => { + const restoreKey = withEncryptionKey(); + const smtp = captureNodemailer(); + try { + const { router } = createHarness([accountFor('smtp')]); + const result = await router.send(input()); + assert.equal(result.success, true); + assert.equal(smtp.calls.length, 1); + // SMTP has no added fields: the comparison is exact. + const normalized = JSON.parse(JSON.stringify(normalize(smtp.calls[0]))); + if (process.env.GOLDEN_WRITE === '1') { + assertGolden(name, smtp.calls[0]); + return; + } + const expected = JSON.parse(fs.readFileSync(path.join(FIXTURE_DIR, `${name}.json`), 'utf8')); + assert.deepEqual(normalized, expected); + } finally { + smtp.restore(); + restoreKey(); + } + }); +} From bf4ac347779f80b42be1c289c6491faa7687cf7b Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Wed, 18 Nov 2026 07:33:52 +0100 Subject: [PATCH 02/10] test: vendor the pinned SendGrid and Mailgun OpenAPI specs and contract helper Byte-identical copies of feat/provider-templates (sha256 checked): tests/fixtures/openapi/{sendgrid-mail,mailgun}.json, tests/helpers/openapi-contract.js and tests/helpers/extract-openapi.js, plus the ajv ^8.20.0 devDependency and the test:live script with the same lines, so both branches rebase without conflicts. Co-Authored-By: Claude Opus 5.5 --- package-lock.json | 1 + package.json | 2 + tests/fixtures/openapi/mailgun.json | 1017 +++++++++++++++++++++ tests/fixtures/openapi/sendgrid-mail.json | 880 ++++++++++++++++++ tests/helpers/extract-openapi.js | 78 ++ tests/helpers/openapi-contract.js | 262 ++++++ 6 files changed, 2240 insertions(+) create mode 100644 tests/fixtures/openapi/mailgun.json create mode 100644 tests/fixtures/openapi/sendgrid-mail.json create mode 100644 tests/helpers/extract-openapi.js create mode 100644 tests/helpers/openapi-contract.js diff --git a/package-lock.json b/package-lock.json index 0c55c45..e0b8326 100644 --- a/package-lock.json +++ b/package-lock.json @@ -34,6 +34,7 @@ "@strapi/sdk-plugin": "^6.1.1", "@strapi/strapi": "^5.62.0", "@strapi/utils": "^5.62.0", + "ajv": "^8.20.0", "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "eslint": "^10.14.0", diff --git a/package.json b/package.json index 105e639..44ccfc9 100644 --- a/package.json +++ b/package.json @@ -57,6 +57,7 @@ "verify:runtime": "node scripts/verify-server-bundle.mjs", "test": "node --test tests/*.test.js", "test:multi-instance": "node --test tests/multi-instance.test.js tests/multi-instance-units.test.js tests/multi-instance-queue.test.js tests/bounce-monitor.test.js tests/analytics-stats-sqlite.test.js", + "test:live": "node --test --test-concurrency=1 tests/live/*.live.test.js", "lint": "eslint .", "lint:fix": "eslint . --fix", "format": "prettier --write .", @@ -91,6 +92,7 @@ "@strapi/sdk-plugin": "^6.1.1", "@strapi/strapi": "^5.62.0", "@strapi/utils": "^5.62.0", + "ajv": "^8.20.0", "better-sqlite3": "^13.0.3", "esbuild": "^0.28.2", "eslint": "^10.14.0", diff --git a/tests/fixtures/openapi/mailgun.json b/tests/fixtures/openapi/mailgun.json new file mode 100644 index 0000000..f4f113f --- /dev/null +++ b/tests/fixtures/openapi/mailgun.json @@ -0,0 +1,1017 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Mailgun API", + "description": "Mailgun API defined by OpenAPI Specification (OAS) 3.1.0", + "version": "3.0.0" + }, + "servers": [ + { + "url": "https://api.mailgun.net", + "description": "US Mailgun" + }, + { + "url": "https://api.eu.mailgun.net", + "description": "EU Mailgun" + } + ], + "paths": { + "/v3/{domain_name}/templates": { + "get": { + "tags": ["Domain Templates"], + "summary": "Get templates", + "description": "Returns a list of templates for the domain.", + "operationId": "GET-v3--domain-name--templates", + "parameters": [ + { + "name": "domain_name", + "in": "path", + "description": "Domain name to fetch the templates for.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "page", + "in": "query", + "description": "Name of the page to retrieve. Value can be `first`, `last`, `next`, or `previous`. Defaults to `first`.", + "schema": { + "type": "string", + "enum": ["first", "last", "next", "previous"], + "x-enumDescriptions": { + "first": "Get the first list's page", + "last": "Get the last list's page", + "next": "Get the next list's page", + "previous": "Get the previous list's page" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of templates to retrieve. Default and max limit is 100.", + "schema": { + "type": "integer" + } + }, + { + "name": "p", + "in": "query", + "description": "Pivot used to retrieve the next page of templates.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "A 200 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-temple-httpapi-getPageResponse" + }, + "examples": { + "Example": { + "value": { + "items": [ + { + "name": "template.0", + "description": "Description for template 0", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "id": "48d63154-8c8f-4104-ab14-687d01dbf296" + }, + { + "name": "template.1", + "description": "Description for template 1", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "id": "8d9c0f0d-7bf7-43a4-92a9-791a854d12a4" + } + ], + "paging": { + "previous": "https://api.mailgun.net/v3/{domain}/templates?page=previous&p=template.0&limit=10", + "first": "https://api.mailgun.net/v3/{domain}/templates?limit=10", + "next": "https://api.mailgun.net/v3/{domain}/templates?page=next&p=template.2&limit=10", + "last": "https://api.mailgun.net/v3/{domain}/templates?page=last&limit=10" + } + } + } + } + } + } + }, + "401": { + "description": "A 401 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "500": { + "description": "A 500 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/v3/{domain_name}/templates/{template_name}": { + "get": { + "tags": ["Domain Templates"], + "summary": "Get template", + "description": "Returns metadata information about the stored template specified in the url. If the active flag is provided, the content of the active version of the template is returned. If the version_name flag is provided, version information will be included as well. By default: the `version` field is not provided. To see available versions other than the active version, use the `/versions` API instead", + "operationId": "GET-v3--domain-name--templates--template-name-", + "parameters": [ + { + "name": "domain_name", + "in": "path", + "description": "Domain name the template is stored under.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "template_name", + "in": "path", + "description": "Template name to fetch.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "active", + "in": "query", + "description": "If this flag is set to yes the active version of the template is included in the response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "A 200 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-temple-httpapi-getTemplateOrVersionResponse" + }, + "examples": { + "Example": { + "value": { + "template": { + "name": "template_name", + "description": "This is the description of the template", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "createdBy": "user-supplied-value", + "id": "46565d87-68b6-4edb-8b3c-34554af4bb77", + "domain": "header.tld", + "version": { + "tag": "tag", + "template": "template content", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "comment": "Version comment", + "active": true, + "id": "3efd2b85-0f41-4a1d-9898-05d7e7459c4a", + "headers": { + "From": "from@header.tld", + "Reply-To": "reply-to@header.tld", + "Subject": "Subject Value" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "A 401 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "404": { + "description": "A 404 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "500": { + "description": "A 500 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/v4/templates": { + "get": { + "tags": ["Account Templates"], + "summary": "Get account-level templates", + "description": "Returns a list of account-level templates.", + "operationId": "GET-v4-templates", + "parameters": [ + { + "name": "page", + "in": "query", + "description": "Name of the page to retrieve. Value can be `first`, `last`, `next`, or `previous`. Defaults to `first`.", + "schema": { + "type": "string", + "enum": ["first", "last", "next", "previous"], + "x-enumDescriptions": { + "first": "Get the first list's page", + "last": "Get the last list's page", + "next": "Get the next list's page", + "previous": "Get the previous list's page" + } + } + }, + { + "name": "limit", + "in": "query", + "description": "Number of templates to retrieve. Default and max limit is 100.", + "schema": { + "type": "integer" + } + }, + { + "name": "p", + "in": "query", + "description": "Pivot used to retrieve the next page of templates.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "A 200 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-temple-httpapi-getPageResponse" + }, + "examples": { + "Example": { + "value": { + "items": [ + { + "name": "template.0", + "description": "Description for template 0", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "id": "48d63154-8c8f-4104-ab14-687d01dbf296" + }, + { + "name": "template.1", + "description": "Description for template 1", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "id": "8d9c0f0d-7bf7-43a4-92a9-791a854d12a4" + } + ], + "paging": { + "previous": "https://api.mailgun.net/v4/templates?page=previous&p=template.0&limit=10", + "first": "https://api.mailgun.net/v4/templates?limit=10", + "next": "https://api.mailgun.net/v4/templates?page=next&p=template.2&limit=10", + "last": "https://api.mailgun.net/v4/templates?page=last&limit=10" + } + } + } + } + } + } + }, + "401": { + "description": "A 401 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "500": { + "description": "A 500 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/v4/templates/{template_name}": { + "get": { + "tags": ["Account Templates"], + "summary": "Get an account-level template", + "description": "Returns metadata information about the stored account-level template. If the active flag is provided, the content of the active version of the template is returned.", + "operationId": "GET-v4-templates--template-name-", + "parameters": [ + { + "name": "template_name", + "in": "path", + "description": "Template name to fetch.", + "required": true, + "schema": { + "type": "string" + } + }, + { + "name": "active", + "in": "query", + "description": "If this flag is set to yes the active version of the template is included in the response.", + "schema": { + "type": "string" + } + } + ], + "responses": { + "200": { + "description": "A 200 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-temple-httpapi-getTemplateOrVersionResponse" + }, + "examples": { + "Example": { + "value": { + "template": { + "name": "template_name", + "description": "This is the description of the template", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "createdBy": "user-supplied-value", + "id": "46565d87-68b6-4edb-8b3c-34554af4bb77", + "domain": "header.tld", + "version": { + "tag": "tag", + "template": "template content", + "createdAt": "Sat, 12 Nov 1955 06:38:00 UTC", + "comment": "Version comment", + "active": true, + "id": "3efd2b85-0f41-4a1d-9898-05d7e7459c4a", + "headers": { + "From": "from@header.tld", + "Reply-To": "reply-to@header.tld", + "Subject": "Subject Value" + } + } + } + } + } + } + } + } + }, + "401": { + "description": "A 401 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "404": { + "description": "A 404 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + }, + "500": { + "description": "A 500 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-GenericResponse" + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + }, + "/v3/{domain_name}/messages": { + "post": { + "tags": ["Messages"], + "summary": "Send an email", + "description": "Pass the components of the messages such as To, From, Subject, HTML, text parts, attachments, etc. Mailgun will build a MIME representation of the message and send it. In order to send you must provide one of the following parameters: 'text', 'html', 'amp-html' or 'template'. Important: Send options (parameters starting with o:, h:, v:, or t:) are limited to 16KB total", + "operationId": "POST-v3--domain-name--messages", + "parameters": [ + { + "name": "domain_name", + "in": "path", + "description": "Domain name used to send the message", + "required": true, + "schema": { + "type": "string" + } + } + ], + "requestBody": { + "content": { + "multipart/form-data": { + "schema": { + "$ref": "#/components/schemas/POST-v3-domain_name-messages-multipart-form-data-RequestBody" + } + } + }, + "required": true + }, + "responses": { + "200": { + "description": "A 200 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-influx-httpapi-SendMessageResponse" + }, + "examples": { + "Example": { + "value": { + "id": "message-id", + "message": "Queued. Thank you." + } + } + } + } + } + }, + "400": { + "description": "A 400 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-influx-httpapi-GetMessageResponseNotFound" + }, + "examples": { + "Example": { + "value": { + "message": "A simple message describing the issue - A few examples:'to parameter is not a valid address. please check documentation.' 'Only one parameters 'html' or 'template' is allowed.' 'Need at least one of 'text', 'html', 'amp-html' or 'template' parameters specified.' 'from parameter is missing. ''Send options (parameters starting with o:, h:, or v:) are limited to 16KB total'" + } + } + } + } + } + }, + "401": { + "description": "A 401 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/string" + }, + "examples": { + "Example": { + "value": "Forbidden" + } + } + } + } + }, + "429": { + "description": "A 429 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-influx-httpapi-GetMessageResponseNotFound" + }, + "examples": { + "Example": { + "value": { + "message": "Domain example.com is not allowed to send: account-requests-per-sec limit exceeded, try again after 120 seconds" + } + } + } + } + } + }, + "500": { + "description": "A 500 response", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/github.com-mailgun-influx-httpapi-GetMessageResponseNotFound" + }, + "examples": { + "Example": { + "value": { + "message": "Internal Server Error" + } + } + } + } + } + } + }, + "security": [ + { + "basicAuth": [] + } + ] + } + } + }, + "components": { + "schemas": { + "github.com-mailgun-temple-httpapi-getPageResponse": { + "type": "object", + "properties": { + "items": { + "type": ["array", "null"], + "items": { + "$ref": "#/components/schemas/github.com-mailgun-temple-model-Template" + }, + "description": "List of items" + }, + "paging": { + "type": "object", + "allOf": [ + { + "$ref": "#/components/schemas/github.com-mailgun-scaffold-httpapi-paging-PagingResponse" + } + ], + "description": "Pagination details" + } + }, + "required": ["items", "paging"] + }, + "github.com-mailgun-scaffold-httpapi-GenericResponse": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "Response message" + } + }, + "required": ["message"] + }, + "github.com-mailgun-temple-httpapi-getTemplateOrVersionResponse": { + "type": "object", + "properties": { + "template": { + "anyOf": [ + { + "$ref": "#/components/schemas/github.com-mailgun-temple-model-Template" + }, + { + "type": "null" + } + ], + "description": "Template details" + } + }, + "required": ["template"] + }, + "POST-v3-domain_name-messages-multipart-form-data-RequestBody": { + "type": "object", + "properties": { + "from": { + "type": "string", + "description": "Email address of the `From` header. Can include a friendly name using the format `Friendly Name `. Note: not required if sending with a template that has a pre-set From header, but will override the template's From header if provided. Friendly names (display names) with special characters, such as commas, should be enclosed in double quotes." + }, + "to": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Email address of the recipient(s). Supports friendly name format. Example: `Bob `. If a friendly name contains a comma, we recommend submitting each recipient in a separate `to` field. Alternatively, use commas to separate multiple recipients. Duplicate addresses are automatically ignored. We recommend enclosing friendly names (display names) in double quotes when they contain special characters, such as commas. For example: `\"Bob, Account Manager\" `. This follows RFC 5322 formatting and helps avoid ambiguity when specifying multiple recipients. Simple names such as `Bob ` do not require quotes." + }, + "cc": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Same as `to` but for carbon copy recipients. Supports friendly name format. See `to` for guidance on quoting friendly names." + }, + "bcc": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Same as `to` but for blind carbon copy recipients. Supports friendly name format. See `to` for guidance on quoting friendly names." + }, + "subject": { + "type": "string", + "description": "Message subject. Note: not required if sending with a template that has a pre-set Subject header, but it will override it if provided." + }, + "text": { + "type": "string", + "description": "Body of the message (text version)" + }, + "html": { + "type": "string", + "description": "Body of the message (HTML version)" + }, + "amp-html": { + "type": "string", + "description": "AMP part of the message. Please follow Google guidelines to compose and send AMP emails" + }, + "attachment": { + "type": "array", + "items": { + "type": "string", + "format": "binary" + }, + "description": "File attachment. You can post multiple `attachment` values. **Important:** You must use `multipart/form-data` encoding for sending attachments" + }, + "inline": { + "type": "array", + "items": { + "type": "string", + "format": "binary" + }, + "format": "binary", + "description": "Attachment with `inline` disposition. Can be used to send inline images (see example). You can post multiple `inline` values" + }, + "template": { + "type": "string", + "description": "Name of a template stored via the Templates API to use to render the email body. See [Templates](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/send-templates) for more information" + }, + "t:version": { + "type": "string", + "description": "Render a specific version of the given template instead of the latest version. `template` option must also be provided." + }, + "t:text": { + "type": "string", + "enum": ["yes"], + "description": "Generates a plain text version of the template alongside the HTML version when sending templated emails. When set to 'yes', instructs Mailgun to create a text/plain MIME part based on the template content, ensuring compatibility with email clients that don't support HTML or have HTML rendering disabled. This improves email deliverability and accessibility by providing a fallback text version in multipart emails.", + "x-enumDescriptions": { + "yes": "Render template in the text part of the message" + } + }, + "t:variables": { + "type": "string", + "description": "A valid JSON-encoded dictionary used as the input for template variable expansion. See [Templates](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/send-templates) for more information" + }, + "o:tag": { + "type": "array", + "items": { + "type": "string" + }, + "description": "Tag string. See [Tagging](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/track-tagging) for more information" + }, + "o:dkim": { + "type": "string", + "enum": ["yes", "no", "true", "false"], + "description": "Enables or disables DKIM signatures on a per-message basis. Overrides the domain-level DKIM setting for this specific message.", + "x-enumDescriptions": { + "yes": "Enables DKIM signatures", + "no": "Disable DKIM signatures", + "true": "Enables DKIM signatures", + "false": "Disable DKIM signatures" + } + }, + "o:secondary-dkim": { + "type": "string", + "description": "Specify a second domain key to sign the email with. The value is formatted as `signing_domain/selector`, e.g. `example.com/s1`. This tells Mailgun to sign the message with the signing domain `example.com` using the selector `s1`. Note: the domain key specified must have been previously created and activated." + }, + "o:secondary-dkim-public": { + "type": "string", + "description": "Specify an alias of the domain key specified in `o:secondary-dkim`. Also formatted as `public_signing_domain/selector`. `o:secondary-dkim` option must also be provided. Mailgun will sign the message with the provided key of the secondary DKIM, but use the public secondary DKIM name and selector. Note: We will perform a DNS check prior to signing the message to ensure the public keys matches the secondary DKIM." + }, + "o:deliverytime": { + "type": "string", + "description": "Specifies the scheduled delivery time in [RFC-2822 format](https://documentation.mailgun.com/docs/mailgun/api-reference/api-overview#date-format). Depending on your plan, you can schedule messages up to 3 or 7 days in advance. If your domain has a custom message_ttl (time-to-live) setting, this value determines the maximum scheduling duration. Example: 'Fri, 14 Oct 2011 12:00:00 +0000'" + }, + "o:deliver-within": { + "type": "string", + "description": "Specifies the maximum time window for delivering the message. Accepts values in format `[0-9]+h[0-9]+m` (e.g., `1h30m`, `30m`, `24h`), with a minimum of `5m` and maximum of `24h`. For scheduled messages, the delivery window starts from the scheduled time. The standard retry schedule applies within this window, so shorter timeframes may result in fewer delivery attempts." + }, + "o:deliverytime-optimize-period": { + "type": "string", + "description": "Toggles Send Time Optimization (STO) on a per-message basis. String should be set to the number of hours in `[0-9]+h` format, with the minimum being `24h` and the maximum being `72h`. This value defines the time window in which Mailgun will run the optimization algorithm based on prior engagement data of a given recipient. See [Sending a Message with STO](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/send-sto) for details. *Please note that STO is only available on certain plans. See www.mailgun.com/pricing for more info*" + }, + "o:time-zone-localize": { + "type": "string", + "description": "Toggles Timezone Optimization (TZO) on a per message basis. String should be set to preferred delivery time in `HH:mm` or `hh:mmaa` format, where `HH:mm` is used for 24 hour format without AM/PM and hh:mmaa is used for 12 hour format with AM/PM. See [Sending a Message with TZO](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/send-tzo) for details. *Please note that TZO is only available on certain plans. See www.mailgun.com/pricing for more info*" + }, + "o:testmode": { + "type": "string", + "enum": ["yes"], + "description": "Enables sending in test mode. Messages are processed normally but not actually delivered to recipients. Useful for testing without sending real emails. See [Sending in Test Mode](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/test-mode)", + "x-enumDescriptions": { + "yes": "Send in test mode" + } + }, + "o:tracking": { + "type": "string", + "enum": ["yes", "no", "true", "false", "htmlonly"], + "description": "Toggles both click and open tracking on a per-message basis", + "x-enumDescriptions": { + "yes": "Enable tracking on a per-message basis", + "no": "Disable tracking on a per-message basis", + "true": "Enable tracking on a per-message basis", + "false": "Disable tracking on a per-message basis", + "htmlonly": "Use if you only want links rewritten in the HTML part of the message" + } + }, + "o:tracking-clicks": { + "type": "string", + "enum": ["yes", "no", "true", "false", "htmlonly"], + "description": "Toggles click tracking on a per-message basis, see [Tracking Clicks](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/tracking-clicks). This overrides the domain-level click tracking setting.", + "x-enumDescriptions": { + "yes": "Enable tracking on a per-message basis", + "no": "Disable tracking on a per-message basis", + "true": "Enable tracking on a per-message basis", + "false": "Disable tracking on a per-message basis", + "htmlonly": "Use if you only want links rewritten in the HTML part of the message" + } + }, + "o:tracking-opens": { + "type": "string", + "enum": ["yes", "no", "true", "false"], + "description": "Toggles opens tracking on a per-message basis, see [Tracking Opens](https://documentation.mailgun.com/docs/mailgun/user-manual/tracking-messages/tracking-opens). Has higher priority than domain-level setting.", + "x-enumDescriptions": { + "yes": "Enables opens tracking", + "no": "Disable opens tracking", + "true": "Enables opens tracking", + "false": "Disable opens tracking" + } + }, + "o:require-tls": { + "type": "string", + "enum": ["yes", "no", "true", "false"], + "description": "When set to 'yes', requires the message to be sent only over a TLS connection to the Email Service Provider. If TLS cannot be established, the message will not be delivered. When set to 'no' (default), Mailgun attempts TLS but falls back to plaintext SMTP if needed.", + "x-enumDescriptions": { + "yes": "Message only be sent over a TLS connection", + "no": "Message do not require to be sent over a TLS connection", + "true": "Message only be sent over a TLS connection", + "false": "Message do not require to be sent over a TLS connection" + } + }, + "o:skip-verification": { + "type": "string", + "enum": ["yes", "no", "true", "false"], + "description": "If `true`, the certificate and hostname of the resolved MX Host will not be verified when trying to establish a TLS connection. If `false`, Mailgun will verify the certificate and hostname. If either one can not be verified, a TLS connection will not be established. The default is `false`", + "x-enumDescriptions": { + "yes": "Verification skipped", + "no": "Verification active", + "true": "Verification skipped", + "false": "Verification active" + } + }, + "o:sending-ip": { + "type": "string", + "description": "Used to specify an IP Address to send an email that is owned by your account" + }, + "o:sending-ip-pool": { + "type": "string", + "description": "If an IP Pool ID is provided, the email will be delivered with an IP that belongs in that pool" + }, + "o:tracking-pixel-location-top": { + "type": "string", + "enum": ["yes", "no", "true", "false", "htmlonly"], + "description": "Places the tracking pixel at the top of emails instead of the bottom. Useful for long emails that may be truncated or have rendering issues, ensuring open tracking works accurately.", + "x-enumDescriptions": { + "yes": "Enables tracking", + "no": "Disable tracking", + "true": "Enables tracking", + "false": "Disable tracking", + "htmlonly": "Use if you only want links rewritten in the HTML part of the message" + } + }, + "o:archive-to": { + "type": "string", + "description": "Sends a copy of successfully delivered messages to the specified URL via HTTP POST. The request uses Content-Type: application/mime and contains the exact message the recipient's SMTP server received. NOTE: These are accounted for and billed as delivered messages" + }, + "o:suppress-headers": { + "type": "string", + "description": "Removes specified X-Mailgun headers from the delivered message. Provide header names separated by commas (e.g., 'X-Mailgun-Variables,X-Mailgun-Tag') or use 'all' to remove all X-Mailgun headers.Note: X-Mailgun-Sid header is currently used to process complains received via feedback loops." + }, + "o:inbox-placement-test-key": { + "type": "string", + "description": "Triggers an Inbox Placement test for this message using the provided value as an idempotency key. Retried or duplicate send requests that use the same key will not create additional tests. Requires Inbox Placement to be enabled for your account." + }, + "h:X-My-Header": { + "type": "string", + "description": "Adds custom headers to the email. Use 'h:' prefix followed by header name and value. Example: 'h:X-Custom-Header=my-value'" + }, + "v:my-var": { + "type": "string", + "description": "Attaches custom data to the message using the 'v:' prefix followed by a variable name. When sending with templates, provides values for template variable substitution (overridden by 't:variables' if both are provided). When not using templates, treated as metadata and included in events/webhooks. Variables are visible in the delivered email's X-Mailgun-Variables header. Example: 'v:user-id=123'. NOTE: Anything over 4KB will be truncated in the event/webhooks." + }, + "recipient-variables": { + "type": "string", + "description": "A JSON-encoded dictionary for batch sending with personalized variables per recipient. Each key is a recipient email address, each value is a dictionary of variables for that recipient. Variables can be referenced in the message using %recipient.variablename%. Example: '{\"alice@example.com\": {\"name\":\"Alice\", \"id\":1}, \"bob@example.com\": {\"name\":\"Bob\", \"id\":2}}'. Maximum 1,000 recipients per batch. See [Batch Sending](https://documentation.mailgun.com/docs/mailgun/user-manual/sending-messages/batch-sending) for more information" + } + }, + "required": ["from", "to", "subject"], + "additionalProperties": true + }, + "github.com-mailgun-influx-httpapi-SendMessageResponse": { + "type": "object", + "properties": { + "id": { + "type": "string", + "description": "The unique identifier of the message as defined by [RFC-2392](https://datatracker.ietf.org/doc/html/rfc2392)." + }, + "message": { + "type": "string", + "description": "A success message" + } + }, + "required": ["id", "message"] + }, + "github.com-mailgun-influx-httpapi-GetMessageResponseNotFound": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "A failure message" + } + }, + "required": ["message"] + }, + "string": { + "type": "string" + }, + "github.com-mailgun-temple-model-Template": { + "type": "object", + "properties": { + "name": { + "type": "string", + "description": "Name of the template" + }, + "description": { + "type": "string", + "description": "Description of the template" + }, + "createdAt": { + "type": "string", + "description": "Creation date in RFC822 format", + "readOnly": true + }, + "createdBy": { + "type": "string", + "description": "Indicate who created the template" + }, + "id": { + "type": "string", + "description": "Template ID", + "readOnly": true + }, + "domain": { + "type": "string", + "description": "Domain of the template" + }, + "version": { + "anyOf": [ + { + "$ref": "#/components/schemas/github.com-mailgun-temple-model-Version" + }, + { + "type": "null" + } + ], + "description": "Active version information", + "readOnly": true + }, + "versions": { + "type": ["array", "null"], + "items": { + "$ref": "#/components/schemas/github.com-mailgun-temple-model-Version" + }, + "description": "List of template's versions", + "readOnly": true + } + }, + "required": ["name"] + }, + "github.com-mailgun-scaffold-httpapi-paging-PagingResponse": { + "type": "object", + "properties": { + "previous": { + "type": "string", + "description": "Previous page URL" + }, + "first": { + "type": "string", + "description": "First page URL" + }, + "next": { + "type": "string", + "description": "Next page URL" + }, + "last": { + "type": "string", + "description": "Last page URL" + } + }, + "required": ["previous", "first", "next", "last"] + }, + "github.com-mailgun-temple-model-Version": { + "type": "object", + "properties": { + "tag": { + "type": "string", + "description": "Tag of the version. Must be unique to the template" + }, + "template": { + "type": "string", + "description": "Template content" + }, + "engine": { + "type": "string", + "description": "Rendering engine" + }, + "mjml": { + "type": "string", + "description": "Template source" + }, + "createdAt": { + "type": "string", + "description": "Creation date in RFC822 format", + "readOnly": true + }, + "comment": { + "type": "string", + "description": "Comment related to the version" + }, + "active": { + "type": "boolean", + "description": "If this flag is true" + }, + "id": { + "type": "string", + "description": "Template ID", + "readOnly": true + }, + "headers": { + "type": "object", + "additionalProperties": { + "type": "string" + }, + "description": "Key value JSON object of headers to be stored with the template. Where key is the header name and value is the header value. The header names `From`" + } + }, + "required": ["tag", "engine", "mjml", "createdAt", "comment", "active", "id"] + } + } + }, + "x-magic-mail-source": { + "url": "https://documentation.mailgun.com/_bundle/docs/mailgun/api-reference/send/mailgun.json?download", + "sha256": "3bf29afd36c06a9a7998ed492838ed3fd4a1f4578799af285998ad73de1f8151", + "retrieved": "2026-11-17", + "operations": [ + "GET /v3/{domain_name}/templates", + "GET /v3/{domain_name}/templates/{template_name}", + "GET /v4/templates", + "GET /v4/templates/{template_name}", + "POST /v3/{domain_name}/messages" + ] + } +} diff --git a/tests/fixtures/openapi/sendgrid-mail.json b/tests/fixtures/openapi/sendgrid-mail.json new file mode 100644 index 0000000..9908518 --- /dev/null +++ b/tests/fixtures/openapi/sendgrid-mail.json @@ -0,0 +1,880 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "Twilio SendGrid Mail API", + "summary": "The Twilio SendGrid v3 Mail API allows you to send email at scale over HTTP. You can also group mail sends into batches.", + "description": "The Twilio SendGrid v3 Mail API allows you to send email at scale over HTTP. The Mail Send endpoint supports many levels of functionality, allowing you to send templates, set categories and custom arguments that can be used to analyze your send, and configure which tracking settings to include such as opens and clicks. You can also group mail sends into batches, allowing you to schedule and cancel sends by their batch IDs.", + "termsOfService": "https://www.twilio.com/legal/tos", + "contact": { + "name": "Twilio SendGrid Support", + "url": "https://support.sendgrid.com/hc/en-us" + }, + "license": { + "name": "MIT", + "url": "https://code.hq.twilio.com/twilio/sendgrid-oas/blob/main/LICENSE" + }, + "version": "1.0.0", + "x-sendgrid": { + "libraryPackage": "mail" + } + }, + "servers": [ + { + "url": "https://api.sendgrid.com", + "description": "for global users and subusers" + }, + { + "url": "https://api.eu.sendgrid.com", + "description": "for EU regional subusers" + } + ], + "paths": { + "/v3/mail/send": { + "post": { + "tags": ["Mail Send"], + "summary": "Send Email with Twilio SendGrid.", + "description": "*The Mail Send operation allows you to send email over SendGrid's v3 Web API*\n\nFor an overview of this API, including its features and limitations, please see the [Mail Send API overview page](https://www.twilio.com/docs/sendgrid/api-reference/mail-send)\n\nThe overview page also includes links to SendGrid's Email API quickstarts and helper libraries to get you working with this endpoint even faster.\n", + "operationId": "SendMail", + "parameters": [ + { + "$ref": "#/components/parameters/MailBodyCompression" + } + ], + "requestBody": { + "$ref": "#/components/requestBodies/PostMailSend" + }, + "responses": { + "202": { + "description": "Accepted" + }, + "400": { + "$ref": "#/components/responses/PostMailSend400" + }, + "401": { + "$ref": "#/components/responses/PostMailSend401" + }, + "403": { + "$ref": "#/components/responses/PostMailSend403" + }, + "404": { + "$ref": "#/components/responses/PostMailSend404" + }, + "405": { + "$ref": "#/components/responses/PostMailSend405" + }, + "413": { + "$ref": "#/components/responses/PostMailSend413" + }, + "500": { + "$ref": "#/components/responses/PostMailSend500" + } + } + } + } + }, + "components": { + "parameters": { + "MailBodyCompression": { + "name": "Content-Encoding", + "in": "header", + "description": "Use this header when sending a gzip compressed mail body. Mail body compression is available to some high volume accounts. Submit a [request to support](https://support.sendgrid.com/hc/en-us) to have gzip enabled on your account.", + "required": false, + "schema": { + "type": "string", + "$ref": "#/components/schemas/ContentEncoding" + } + } + }, + "requestBodies": { + "PostMailSend": { + "content": { + "application/json": { + "schema": { + "type": "object", + "properties": { + "personalizations": { + "type": "array", + "description": "An array of messages and their metadata. Each object within the `personalizations` array can be thought of as a mail envelope—it defines who should receive an individual message and how that message should be handled. See [**Personalizations**](https://sendgrid.com/docs/for-developers/sending-email/personalizations/) for more information.", + "uniqueItems": false, + "maxItems": 1000, + "items": { + "type": "object", + "properties": { + "from": { + "$ref": "#/components/schemas/MailFrom" + }, + "to": { + "type": "array", + "description": "An array of recipients to whom the email will be sent. Each object in this array must contain a recipient's email address. Each object in the array may optionally contain a recipient's name.", + "items": { + "$ref": "#/components/schemas/MailTo" + } + }, + "cc": { + "type": "array", + "description": "An array of recipients to whom a copy of the email will be sent. Each object in this array must contain a recipient's email address. Each object in the array may optionally contain a recipient's name.", + "maxItems": 1000, + "items": { + "$ref": "#/components/schemas/MailTo" + } + }, + "bcc": { + "type": "array", + "description": "An array of recipients to whom a blind carbon copy of your email will be sent. Each object in this array must contain a recipient's email address. Each object in the array may optionally contain a recipient's name.", + "maxItems": 1000, + "items": { + "$ref": "#/components/schemas/MailTo" + } + }, + "subject": { + "type": "string", + "description": "The subject of your email. See line length limits specified in [RFC 2822](https://www.rfc-editor.org/rfc/rfc2822#section-2.1.1) for guidance on subject line character limits.", + "minLength": 1 + }, + "headers": { + "type": "object", + "description": "A collection of JSON property name and property value pairs allowing you to specify handling instructions for your email. You may not override the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`." + }, + "substitutions": { + "type": "object", + "description": "A collection property names that will be substituted by their corresponding property values in the `subject`, `reply-to` and `content` portions of your message. Name and value pairs follow the pattern `\"substitution_tag\":\"value to substitute\"`. The total collective size of your substitutions may not exceed 100,000 bytes per personalization object. Substitutions allow you to insert data without using SendGrid's Dynamic Templates. This property should not be used in combination with a Dynamic Template, which can be identified by a `template_id` starting with `d-`. See [**Substitution Tags**](https://docs.sendgrid.com/for-developers/sending-email/substitution-tags) for more information.", + "maxProperties": 10000, + "additionalProperties": { + "type": "string" + } + }, + "dynamic_template_data": { + "type": "object", + "description": "A collection property names that will be substituted by their corresponding property values in the `subject`, `reply-to` and `content` portions of a SendGrid Dynamic Template. Dynamic template data is available in a template using [Handlebars](https://docs.sendgrid.com/for-developers/sending-email/using-handlebars) syntax. This property should be used in combination with a Dynamic Template, which can be identified by a `template_id` starting with `d-`. See [**How to Send an Email with Dynamic Templates**](https://docs.sendgrid.com/ui/sending-email/how-to-send-an-email-with-dynamic-templates) for more information." + }, + "custom_args": { + "type": "object", + "description": "Values that are specific to this personalization that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is assigned to this property will be assumed to be the custom argument that you would like to be used. This field may not exceed 10,000 bytes.", + "maxProperties": 10000 + }, + "send_at": { + "type": "integer", + "description": "A [unix timestamp](https://en.wikipedia.org/wiki/Unix_time) allowing you to specify when your email should be sent. A send cannot be scheduled more than 72 hours in advance." + } + }, + "required": ["to"] + } + }, + "from": { + "$ref": "#/components/schemas/MailFrom" + }, + "reply_to": { + "$ref": "#/components/schemas/MailTo" + }, + "reply_to_list": { + "type": "array", + "description": "An array of recipients to whom replies will be sent. Each object in this array must contain a recipient's email address. Each object in the array may optionally contain a recipient's name. You can use either the `reply_to` property or `reply_to_list` property but not both.", + "uniqueItems": true, + "maxItems": 1000, + "items": { + "$ref": "#/components/schemas/MailTo" + } + }, + "subject": { + "type": "string", + "description": "The global or _message level_ subject of your email. Subject lines set in personalizations objects will override this global subject line. See line length limits specified in [RFC 2822](https://www.rfc-editor.org/rfc/rfc2822#section-2.1.1) for guidance on subject line character limits.", + "minLength": 1 + }, + "content": { + "type": "array", + "description": "An array of objects, each containing a message body's content and [MIME type](https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types). You must specify at least one MIME type and may include multiple. To include more than one MIME type, add an object for each type to the array.", + "items": { + "type": "object", + "properties": { + "type": { + "type": "string", + "description": "The MIME type of the content assigned in the `value` property of this object (e.g., `text/plain` or `text/html`).", + "minLength": 1 + }, + "value": { + "type": "string", + "description": "The content of your message in the specified MIME type assigned in the `type` property of this object.", + "minLength": 1 + } + }, + "required": ["type", "value"] + } + }, + "attachments": { + "type": "array", + "description": "An array of objects where you can define any attachments to be included with the message. Each object contains a `content` property, which must be a Base64 encoded string of the attachment itself, and `type`, `filename`, `disposition`, and `content_id` properties that tell SendGrid how to handle the attachment.", + "items": { + "type": "object", + "properties": { + "content": { + "type": "string", + "description": "The Base64 encoded content of the attachment.", + "minLength": 1 + }, + "type": { + "type": "string", + "description": "The MIME type of the content you are attaching (e.g., `image/jpeg` or `application/pdf`).", + "minLength": 1 + }, + "filename": { + "type": "string", + "description": "The attachment's filename, including the file extension." + }, + "disposition": { + "type": "string", + "default": "attachment", + "description": "The attachment's content-disposition specifies how you would like the attachment to be displayed. For example, `inline` results in the attached file being displayed automatically within the message while `attachment` results in the attached file requiring some action to be taken before it is displayed such as opening or downloading the file.", + "$ref": "#/components/schemas/Disposition" + }, + "content_id": { + "type": "string", + "description": "The attachment's content ID. The `content_id` is used when the `disposition` is set to `inline` and the attachment is an image, allowing the file to be displayed within the body of the email." + } + }, + "required": ["content", "filename"] + } + }, + "template_id": { + "type": "string", + "description": "An email template ID. A template that contains a subject and content—either text or html—will override any subject and content values specified at the `personalizations` or message level. If a template ID begins with `d-`, it is a dynamic template and will work with the `dynamic_template_data` property. If the template ID does not begin with `d-`, it is a standard SendGrid template and will work with the `substitutions` property. See [**How to Send an Email with Dynamic Templates**](https://docs.sendgrid.com/ui/sending-email/how-to-send-an-email-with-dynamic-templates) for more information about working with templates." + }, + "headers": { + "description": "A collection of JSON property name and property value pairs allowing you to specify handling instructions for your email. You may not override the following headers: `x-sg-id`, `x-sg-eid`, `received`, `dkim-signature`, `Content-Type`, `Content-Transfer-Encoding`, `To`, `From`, `Subject`, `Reply-To`, `CC`, `BCC`.", + "type": "object" + }, + "categories": { + "type": "array", + "description": "An array of category names assigned to this message. Categories allow you to group messages by categories you define. Categories should be used sparingly to create general groups that are relevant to you. Categories are not meant to be used to track individual mail sends. For more granular categorization and tracking, use the `custom_args` property. A category name cannot exceed 255 characters. See [**Working with Categories**](https://docs.sendgrid.com/for-developers/sending-email/categories) for more information.", + "uniqueItems": true, + "maxItems": 10, + "items": { + "type": "string", + "maxLength": 255 + } + }, + "custom_args": { + "type": "string", + "description": "Values that are specific to the entire send that will be carried along with the email and its activity data. Substitutions will not be made on custom arguments, so any string that is assigned to this property will be assumed to be the custom argument that you would like to be used. This parameter is overridden by `custom_args` set at the personalizations level. Total `custom_args` size may not exceed 10,000 bytes." + }, + "send_at": { + "type": "integer", + "description": "A [unix timestamp](https://en.wikipedia.org/wiki/Unix_time) allowing you to specify when your email should be sent. A send cannot be scheduled more than 72 hours in advance. This property may be overridden by the `send_at` property set at the personalizations level." + }, + "batch_id": { + "type": "string", + "description": "An ID representing a batch of emails to be sent at the same time. Including a `batch_id` in your request allows you to include this email in that batch. It also enables you to cancel or pause the delivery of that batch. See the [Scheduled Sends API](https://sendgrid.com/docs/api-reference/) for more information about scheduling your email." + }, + "asm": { + "type": "object", + "description": "An object allowing you to specify how to handle unsubscribes. With SendGrid, an unsubscribe is the action an email recipient takes when they opt-out of receiving your messages. A suppression is the action you take as a sender to filter or suppress an unsubscribed address from your email send. From the perspective of the recipient, your suppression is the result of their unsubscribe. See [**Suppression Groups**](https://www.twilio.com/docs/sendgrid/api-reference/suppressions-unsubscribe-groups/create-a-new-suppression-group) for more information.", + "properties": { + "group_id": { + "type": "integer", + "description": "The unsubscribe group to associate with this email. See the [Suppressions API](https://docs.sendgrid.com/api-reference/suppressions/) to manage unsubscribe group IDs." + }, + "groups_to_display": { + "type": "array", + "description": "An array containing the unsubscribe groups that you would like to be displayed to a recipient on the unsubscribe preferences page. This page is displayed in the recipient's browser when they click the unsubscribe link in your message.", + "maxItems": 25, + "items": { + "type": "integer" + } + } + }, + "required": ["group_id"] + }, + "ip_pool_name": { + "type": "string", + "description": "The IP Pool that you would like to send this email from. IP Pools allow you to group your dedicated Twilio SendGrid IP addresses in order to have more control over your deliverability. See [**IP Pools**](https://docs.sendgrid.com/ui/account-and-settings/ip-pools) for more information.", + "minLength": 2, + "maxLength": 64 + }, + "mail_settings": { + "type": "object", + "description": "A collection of different mail settings that you can use to specify how you would like this email to be handled. Mail settings provide extra functionality to your mail send. See [**Mail Settings**](https://docs.sendgrid.com/ui/account-and-settings/mail) for more information.", + "properties": { + "bypass_list_management": { + "type": "object", + "description": "Allows you to bypass all unsubscribe groups and suppressions to ensure that the email is delivered to every single recipient. This should only be used in emergencies when it is absolutely necessary that every recipient receives your email. This filter cannot be combined with any other bypass filters. See the [the \"Bypass suppressions\" section of our **Suppressions Overview**](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + } + } + }, + "bypass_spam_management": { + "type": "object", + "description": "Allows you to bypass the spam report list to ensure that the email is delivered to recipients. Bounce and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypass_list_management` filter. See the [the \"Bypass suppressions\" section of our **Suppressions Overview**](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + } + } + }, + "bypass_bounce_management": { + "type": "object", + "description": "Allows you to bypass the bounce list to ensure that the email is delivered to recipients. Spam report and unsubscribe lists will still be checked; addresses on these other lists will not receive the message. This filter cannot be combined with the `bypass_list_management` filter. See the [the \"Bypass suppressions\" section of our **Suppressions Overview**](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + } + } + }, + "bypass_unsubscribe_management": { + "type": "object", + "description": "Allows you to bypass the global unsubscribe list to ensure that the email is delivered to recipients. Bounce and spam report lists will still be checked; addresses on these other lists will not receive the message. This filter applies only to global unsubscribes and will not bypass group unsubscribes. This filter cannot be combined with the `bypass_list_management` filter. See the [the \"Bypass suppressions\" section of our **Suppressions Overview**](https://sendgrid.com/docs/ui/sending-email/index-suppressions/#bypass-suppressions) for more about bypass filters.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + } + } + }, + "footer": { + "type": "object", + "description": "Inserts a custom footer at the bottom of the text and HTML bodies of your messages. Use the `html` and `text` properties to include the content of the footers to be inserted.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + }, + "text": { + "type": "string", + "description": "The plain text content of your footer." + }, + "html": { + "type": "string", + "description": "The HTML content of your footer." + } + } + }, + "sandbox_mode": { + "type": "object", + "description": "Sandbox Mode allows you to send a test email to ensure that your request body is valid and formatted correctly.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + } + } + } + } + }, + "tracking_settings": { + "type": "object", + "description": "Settings to determine how you would like to track the metrics of how your recipients interact with your email. See [**Tracking Settings**](https://docs.sendgrid.com/ui/account-and-settings/tracking) for more information.", + "properties": { + "click_tracking": { + "type": "object", + "description": "Allows you to track if a recipient clicked a link in your email.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + }, + "enable_text": { + "type": "boolean", + "description": "Indicates if this setting should be included in the `text/plain` portion of your email." + } + } + }, + "open_tracking": { + "type": "object", + "description": "Allows you to track if the email was opened by including a single transparent pixel image in the body of the message content. When the message is opened, a request for the pixel is sent. That request indicates to Twilio SendGrid that the message was opened.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + }, + "substitution_tag": { + "type": "string", + "description": "Allows you to specify a substitution tag that you can insert in the body of your email at a location that you desire. This tag will be replaced by the open tracking pixel." + } + } + }, + "subscription_tracking": { + "type": "object", + "description": "Allows you to insert a subscription management link at the bottom of the text and HTML bodies of your email. If you would like to specify the location of the link within your email, you may use the `substitution_tag` property.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + }, + "text": { + "type": "string", + "description": "Text to be appended to the email with the subscription tracking link." + }, + "html": { + "type": "string", + "description": "HTML to be appended to the email with the subscription tracking link." + }, + "substitution_tag": { + "type": "string", + "description": "A tag that will be replaced with the unsubscribe URL. If this property is used, it will override both the `text` and `html` properties. The URL of the link will be placed at the substitution tag's location in the message body with no additional formatting." + } + } + }, + "ganalytics": { + "type": "object", + "description": "Allows you to enable tracking provided by Google Analytics. See [**Google Analytics and SendGrid Statistics**](https://docs.sendgrid.com/ui/analytics-and-reporting/google-analytics) for more information about this property.", + "properties": { + "enable": { + "type": "boolean", + "description": "Indicates if this setting is enabled." + }, + "utm_source": { + "type": "string", + "description": "Name of the referrer source. (e.g., Google, SomeDomain.com, or Marketing Email)" + }, + "utm_medium": { + "type": "string", + "description": "Name of the marketing medium. (e.g., Email)" + }, + "utm_term": { + "type": "string", + "description": "Used to identify any paid keywords." + }, + "utm_content": { + "type": "string", + "description": "Used to differentiate your campaign from advertisements." + }, + "utm_campaign": { + "type": "string", + "description": "The name of the campaign." + } + } + } + } + } + }, + "required": ["personalizations", "from"] + }, + "examples": { + "MailSendDynamicTemplate": { + "description": "A Mail Send request that uses a SendGrid Dynamic Template.", + "value": { + "personalizations": [ + { + "to": [ + { + "email": "alex@example.com", + "name": "Alex" + }, + { + "email": "bola@example.com", + "name": "Bola" + } + ], + "dynamic_template_data": { + "subject": "Hello, Alex", + "customer_name": "Alex", + "confirmation_number": "123abc456def789hij0" + } + } + ], + "from": { + "email": "orders@example.com", + "name": "Example Order Confirmation" + }, + "reply_to": { + "email": "customer_service@example.com", + "name": "Example Customer Service Team" + }, + "attachments": [ + { + "content": "PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KCiAgICA8aGVhZD4KICAgICAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICAgICAgPG1ldGEgaHR0cC1lcXVpdj0iWC1VQS1Db21wYXRpYmxlIiBjb250ZW50PSJJRT1lZGdlIj4KICAgICAgICA8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEuMCI+CiAgICAgICAgPHRpdGxlPkRvY3VtZW50PC90aXRsZT4KICAgIDwvaGVhZD4KCiAgICA8Ym9keT4KCiAgICA8L2JvZHk+Cgo8L2h0bWw+Cg==", + "filename": "index.html", + "type": "text/html", + "disposition": "attachment" + } + ], + "template_id": "d-123abc456def789hij0klm123nop456qrs789tuv0xyz", + "categories": ["cake", "pie", "baking"], + "send_at": 1617260400, + "batch_id": "AsdFgHjklQweRTYuIopzXcVBNm0aSDfGHjklmZcVbNMqWert1znmOP2asDFjkl", + "asm": { + "group_id": 12345, + "groups_to_display": [12345] + }, + "ip_pool_name": "transactional email", + "mail_settings": { + "bypass_list_management": { + "enable": false + }, + "footer": { + "enable": false + }, + "sandbox_mode": { + "enable": false + } + }, + "tracking_settings": { + "click_tracking": { + "enable": true, + "enable_text": false + }, + "open_tracking": { + "enable": true, + "substitution_tag": "%open-track%" + }, + "subscription_tracking": { + "enable": false + } + } + } + }, + "MailSendNoTemplate": { + "description": "A Mail Send request with directly included content and no template.", + "value": { + "personalizations": [ + { + "to": [ + { + "email": "alex@example.com", + "name": "Alex" + }, + { + "email": "bola@example.com", + "name": "Bola" + } + ], + "cc": [ + { + "email": "charlie@example.com", + "name": "Charlie" + } + ], + "bcc": [ + { + "email": "dana@example.com", + "name": "Dana" + } + ] + }, + { + "from": { + "email": "sales@example.com", + "name": "Example Sales Team" + }, + "to": [ + { + "email": "ira@example.com", + "name": "Ira" + } + ], + "bcc": [ + { + "email": "lee@example.com", + "name": "Lee" + } + ] + } + ], + "from": { + "email": "orders@example.com", + "name": "Example Order Confirmation" + }, + "reply_to": { + "email": "customer_service@example.com", + "name": "Example Customer Service Team" + }, + "subject": "Your Example Order Confirmation", + "content": [ + { + "type": "text/html", + "value": "

Hello from Twilio SendGrid!

Sending with the email service trusted by developers and marketers for time-savings, scalability, and delivery expertise.

%open-track%

" + } + ], + "attachments": [ + { + "content": "PCFET0NUWVBFIGh0bWw+CjxodG1sIGxhbmc9ImVuIj4KCiAgICA8aGVhZD4KICAgICAgICA8bWV0YSBjaGFyc2V0PSJVVEYtOCI+CiAgICAgICAgPG1ldGEgaHR0cC1lcXVpdj0iWC1VQS1Db21wYXRpYmxlIiBjb250ZW50PSJJRT1lZGdlIj4KICAgICAgICA8bWV0YSBuYW1lPSJ2aWV3cG9ydCIgY29udGVudD0id2lkdGg9ZGV2aWNlLXdpZHRoLCBpbml0aWFsLXNjYWxlPTEuMCI+CiAgICAgICAgPHRpdGxlPkRvY3VtZW50PC90aXRsZT4KICAgIDwvaGVhZD4KCiAgICA8Ym9keT4KCiAgICA8L2JvZHk+Cgo8L2h0bWw+Cg==", + "filename": "index.html", + "type": "text/html", + "disposition": "attachment" + } + ], + "categories": ["cake", "pie", "baking"], + "send_at": 1617260400, + "batch_id": "AsdFgHjklQweRTYuIopzXcVBNm0aSDfGHjklmZcVbNMqWert1znmOP2asDFjkl", + "asm": { + "group_id": 12345, + "groups_to_display": [12345] + }, + "ip_pool_name": "transactional email", + "mail_settings": { + "bypass_list_management": { + "enable": false + }, + "footer": { + "enable": false + }, + "sandbox_mode": { + "enable": false + } + }, + "tracking_settings": { + "click_tracking": { + "enable": true, + "enable_text": false + }, + "open_tracking": { + "enable": true, + "substitution_tag": "%open-track%" + }, + "subscription_tracking": { + "enable": false + } + } + } + } + } + } + } + } + }, + "responses": { + "PostMailSend400": { + "description": "Mail Send bad response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "invalid request", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend401": { + "description": "Mail Send unauthorized response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "authorization required", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend403": { + "description": "Mail Send forbidden response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "access forbidden", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend404": { + "description": "Mail Send not found response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "not found", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend405": { + "description": "Mail Send method not allowed response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "method not allowed", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend413": { + "description": "Mail Send content too large response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "content too large", + "field": "null" + } + ] + } + } + } + } + } + }, + "PostMailSend500": { + "description": "Mail send internal server error response.", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/ErrorResponse" + }, + "examples": { + "Unauthorized request": { + "value": { + "errors": [ + { + "message": "internal server error" + } + ] + } + } + } + } + } + } + }, + "schemas": { + "ContentEncoding": { + "type": "string", + "enum": ["gzip"] + }, + "MailFrom": { + "title": "From Email Object", + "type": "object", + "properties": { + "email": { + "type": "string", + "format": "email", + "description": "The email address from which messages are sent. This address should be a verified sender in your Twilio SendGrid account. Email addresses specified in `personalizations` will override addresses set at the message level outside of the `personalizations` object." + }, + "name": { + "type": "string", + "description": "A name or title associated with the email address such as \"Support\" or \"Alex\"." + } + }, + "required": ["email"] + }, + "MailTo": { + "title": "To Email Object", + "type": "object", + "properties": { + "email": { + "type": "string", + "format": "email", + "description": "An email address to which a message is sent. Email addresses specified in `personalizations` will override addresses set at the message level outside of the `personalizations` object." + }, + "name": { + "type": "string", + "description": "A name or title associated with the email address such as \"Alex\"." + } + }, + "required": ["email"] + }, + "Disposition": { + "type": "string", + "enum": ["inline", "attachment"] + }, + "ErrorResponse": { + "type": "object", + "properties": { + "errors": { + "type": "array", + "items": { + "type": "object", + "properties": { + "message": { + "type": "string", + "description": "An error message." + }, + "field": { + "description": "When applicable, this property value will be the field that generated the error.", + "nullable": true, + "type": "string" + }, + "help": { + "type": "object", + "description": "When applicable, this property value will be helper text or a link to documentation to help you troubleshoot the error." + } + } + } + }, + "id": { + "type": "string", + "description": "When applicable, this property value will be an error ID." + } + }, + "example": { + "errors": [ + { + "field": "field_name", + "message": "error message" + } + ] + } + } + } + }, + "x-magic-mail-source": { + "url": "https://raw.githubusercontent.com/twilio/sendgrid-oai/51a0dee5a218634f0775cdc589e3d728136674de/spec/json/tsg_mail_v3.json", + "sha256": "1bf9b256780b4c32a48e054eb9a8f93c03b586f9586d12b0ebbcdde9c170fac3", + "retrieved": "2026-11-17", + "operations": ["POST /v3/mail/send"] + } +} diff --git a/tests/helpers/extract-openapi.js b/tests/helpers/extract-openapi.js new file mode 100644 index 0000000..d1e80c9 --- /dev/null +++ b/tests/helpers/extract-openapi.js @@ -0,0 +1,78 @@ +'use strict'; + +/** + * Extracts the operations Magic Mail calls from an official provider OpenAPI + * document into a small vendored copy (the operations plus every component + * they reference). The source file's SHA-256 and URL are written into the + * copy's `x-magic-mail-source`, so the copy can be re-generated and checked. + * + * Usage (development only, never at runtime): + * node tests/helpers/extract-openapi.js ... + * + * @sideeffect Writes . + */ + +const crypto = require('node:crypto'); +const fs = require('node:fs'); + +function extract(source, operations) { + const spec = JSON.parse(source); + const out = { + openapi: spec.openapi, + info: spec.info, + servers: spec.servers, + paths: {}, + components: {}, + }; + const pending = []; + const seen = new Set(); + const collectRefs = (node) => { + if (Array.isArray(node)) return node.forEach(collectRefs); + if (!node || typeof node !== 'object') return; + for (const [key, value] of Object.entries(node)) { + if (key === '$ref' && typeof value === 'string' && value.startsWith('#/')) { + if (!seen.has(value)) { + seen.add(value); + pending.push(value); + } + } else collectRefs(value); + } + }; + for (const operation of operations) { + const [method, path] = operation.split(' '); + const op = spec.paths?.[path]?.[method.toLowerCase()]; + if (!op) throw new Error(`Operation not in source: ${operation}`); + out.paths[path] = out.paths[path] || {}; + if (spec.paths[path].parameters) out.paths[path].parameters = spec.paths[path].parameters; + out.paths[path][method.toLowerCase()] = op; + collectRefs(op); + collectRefs(spec.paths[path].parameters); + } + while (pending.length > 0) { + const ref = pending.shift(); + const parts = ref.slice(2).split('/'); + let node = spec; + for (const part of parts) node = node?.[part.replace(/~1/g, '/').replace(/~0/g, '~')]; + if (node === undefined) throw new Error(`Unresolved reference ${ref}`); + let target = out; + for (const part of parts.slice(0, -1)) target = target[part] = target[part] || {}; + target[parts[parts.length - 1]] = node; + collectRefs(node); + } + return out; +} + +if (require.main === module) { + const [sourcePath, outPath, url, ...operations] = process.argv.slice(2); + const source = fs.readFileSync(sourcePath, 'utf8'); + const extracted = extract(source, operations); + extracted['x-magic-mail-source'] = { + url, + sha256: crypto.createHash('sha256').update(source).digest('hex'), + retrieved: new Date().toISOString().slice(0, 10), + operations, + }; + fs.writeFileSync(outPath, `${JSON.stringify(extracted, null, 2)}\n`); +} + +module.exports = { extract }; diff --git a/tests/helpers/openapi-contract.js b/tests/helpers/openapi-contract.js new file mode 100644 index 0000000..bb4876f --- /dev/null +++ b/tests/helpers/openapi-contract.js @@ -0,0 +1,262 @@ +'use strict'; + +/** + * Validates provider requests and responses against the vendored official + * OpenAPI documents (tests/fixtures/openapi, extracted by extract-openapi.js). + * + * Checks per request: the host is a documented server, the path matches a + * documented operation, every query parameter is declared and valid, required + * parameters are present, the JSON or multipart body matches the request + * schema, and no body field is sent that the schema does not declare. + * Checks per response: the status is documented and the JSON body matches it. + * + * Uses Ajv's JSON Schema 2020-12 validator (OpenAPI 3.1 schemas are JSON + * Schema 2020-12). Format keywords are not asserted. + */ + +const fs = require('node:fs'); +const path = require('node:path'); +const crypto = require('node:crypto'); +const Ajv2020 = require('ajv/dist/2020').default; + +const FIXTURES = path.join(__dirname, '..', 'fixtures', 'openapi'); + +/** + * @param {string} name - Fixture name without .json + * @returns {object} The vendored OpenAPI document + */ +function loadSpec(name) { + return JSON.parse(fs.readFileSync(path.join(FIXTURES, `${name}.json`), 'utf8')); +} + +/** Resolves a local JSON pointer `#/a/b`. */ +function resolvePointer(spec, ref) { + let node = spec; + for (const part of ref.slice(2).split('/')) { + node = node?.[part.replace(/~1/g, '/').replace(/~0/g, '~')]; + } + return node; +} + +const deref = (spec, node) => { + let current = node; + for (let i = 0; i < 20 && current && current.$ref; i += 1) { + current = resolvePointer(spec, current.$ref); + } + return current; +}; + +/** + * Walks a body and its schema and reports keys the schema does not declare + * (only where the schema lists `properties` and allows nothing else). + * + * @returns {string[]} Undeclared key paths + */ +function undeclaredKeys(spec, schema, value, at = '') { + const s = deref(spec, schema); + if (!s || typeof s !== 'object' || value === null || typeof value !== 'object') return []; + if (Array.isArray(value)) { + return s.items + ? value.flatMap((item, i) => undeclaredKeys(spec, s.items, item, `${at}[${i}]`)) + : []; + } + let props = { ...(s.properties || {}) }; + let open = s.additionalProperties !== undefined && s.additionalProperties !== false; + let patterns = s.patternProperties ? Object.keys(s.patternProperties) : []; + for (const part of [...(s.allOf || [])]) { + const p = deref(spec, part); + props = { ...props, ...(p?.properties || {}) }; + if (p?.additionalProperties !== undefined && p.additionalProperties !== false) open = true; + if (p?.patternProperties) patterns = patterns.concat(Object.keys(p.patternProperties)); + } + if (s.anyOf || s.oneOf) { + // Union: check against the branch that declares the most of the value's keys. + const branches = (s.anyOf || s.oneOf).map((b) => deref(spec, b)); + const best = branches + .map((b) => ({ b, misses: undeclaredKeys(spec, b, value, at).length })) + .sort((a, b) => a.misses - b.misses)[0]; + return best ? undeclaredKeys(spec, best.b, value, at) : []; + } + if (Object.keys(props).length === 0) return []; + const out = []; + for (const [key, child] of Object.entries(value)) { + if (props[key]) out.push(...undeclaredKeys(spec, props[key], child, `${at}.${key}`)); + else if (!open && !patterns.some((p) => new RegExp(p).test(key))) out.push(`${at}.${key}`); + } + return out; +} + +class OpenApiContract { + /** + * @param {string} name - Fixture name (sendgrid-templates, sendgrid-mail, mailgun) + */ + constructor(name) { + this.name = name; + this.spec = loadSpec(name); + this.strict = new Ajv2020({ strict: false, allErrors: true, validateFormats: false }); + this.coercing = new Ajv2020({ + strict: false, + allErrors: true, + validateFormats: false, + coerceTypes: 'array', + }); + this.strict.addSchema(this.spec, 'spec'); + this.coercing.addSchema(this.spec, 'spec'); + this.servers = (this.spec.servers || []).map((server) => new URL(server.url).host); + } + + /** + * Finds the documented operation for a URL. + * + * @param {string} method + * @param {URL} url + * @returns {{template: string, op: object, pathItem: object}|null} + */ + findOperation(method, url) { + for (const [template, pathItem] of Object.entries(this.spec.paths)) { + const pattern = new RegExp(`^${template.replace(/\{[^}]+\}/g, '[^/]+')}$`); + const op = pathItem[method.toLowerCase()]; + if (op && pattern.test(url.pathname)) return { template, op, pathItem }; + } + return null; + } + + validate(ajv, schema, value) { + // Local references point into the whole document, registered as "spec". + const rewrite = (node) => { + if (Array.isArray(node)) return node.map(rewrite); + if (!node || typeof node !== 'object') return node; + return Object.fromEntries( + Object.entries(node).map(([k, v]) => + k === '$ref' && typeof v === 'string' && v.startsWith('#/') + ? [k, `spec${v}`] + : [k, rewrite(v)] + ) + ); + }; + const key = JSON.stringify(schema); + this.cache = this.cache || new Map(); + const cacheKey = `${ajv === this.strict ? 's' : 'c'}${key}`; + let validator = this.cache.get(cacheKey); + if (!validator) { + validator = ajv.compile(rewrite(schema)); + this.cache.set(cacheKey, validator); + } + const data = JSON.parse(JSON.stringify(value)); + const ok = validator(data); + return ok ? [] : validator.errors.map((e) => `${e.instancePath || '/'} ${e.message}`); + } + + /** + * Validates a request the plugin built. + * + * @param {{method: string, url: string, json?: object, form?: Array<[string, string]>}} request + * @returns {string[]} Contract violations (empty = valid) + */ + checkRequest({ method, url, json, form }) { + const errors = []; + const parsed = new URL(url); + if (!this.servers.includes(parsed.host)) { + errors.push(`host ${parsed.host} is not a documented server`); + } + const found = this.findOperation(method, parsed); + if (!found) return [...errors, `${method} ${parsed.pathname} is not a documented operation`]; + const { op, pathItem } = found; + const params = [...(pathItem.parameters || []), ...(op.parameters || [])].map((p) => + deref(this.spec, p) + ); + const query = Object.fromEntries(parsed.searchParams); + for (const [name, value] of Object.entries(query)) { + const param = params.find((p) => p.in === 'query' && p.name === name); + if (!param) { + errors.push(`query parameter ${name} is not documented`); + continue; + } + const wrapped = { type: 'object', properties: { v: param.schema || {} } }; + errors.push( + ...this.validate(this.coercing, wrapped, { v: value }).map((e) => `query ${name}: ${e}`) + ); + } + for (const param of params) { + if (param.in === 'query' && param.required && !(param.name in query)) { + errors.push(`required query parameter ${param.name} is missing`); + } + } + const body = op.requestBody ? deref(this.spec, op.requestBody) : null; + if (json !== undefined) { + const schema = body?.content?.['application/json']?.schema; + if (!schema) errors.push('JSON body is not documented'); + else { + errors.push(...this.validate(this.strict, schema, json).map((e) => `body${e}`)); + errors.push( + ...undeclaredKeys(this.spec, schema, json).map((k) => `undeclared body key ${k}`) + ); + } + } + if (form !== undefined) { + const schema = deref(this.spec, body?.content?.['multipart/form-data']?.schema); + if (!schema) errors.push('multipart body is not documented'); + else { + const object = {}; + for (const [key, value] of form) { + const prop = deref(this.spec, schema.properties?.[key]); + if (prop?.type === 'array') (object[key] = object[key] || []).push(value); + else object[key] = value; + } + const declared = Object.keys(schema.properties || {}); + // Mailgun documents header and variable families with one example + // property each (`h:X-My-Header`, `v:my-var`). + const families = declared.filter((k) => /^[hv]:/.test(k)).map((k) => k.slice(0, 2)); + for (const key of Object.keys(object)) { + if (!declared.includes(key) && !families.includes(key.slice(0, 2))) { + errors.push(`form field ${key} is not documented`); + } + } + const known = Object.fromEntries( + Object.entries(object).filter(([k]) => declared.includes(k)) + ); + errors.push(...this.validate(this.coercing, schema, known).map((e) => `form${e}`)); + } + } + return errors; + } + + /** + * Validates a (fake) provider response against the documented response. + * + * @param {{method: string, url: string, status: number, json?: unknown}} response + * @returns {string[]} + */ + checkResponse({ method, url, status, json }) { + const found = this.findOperation(method, new URL(url)); + if (!found) return [`${method} ${url} is not a documented operation`]; + const responses = found.op.responses || {}; + const documented = + responses[String(status)] || responses[`${String(status)[0]}XX`] || responses.default; + if (!documented) return [`status ${status} is not documented`]; + const resolved = deref(this.spec, documented); + const schema = resolved?.content?.['application/json']?.schema; + if (!schema || json === undefined) return []; + return this.validate(this.strict, schema, json).map((e) => `response${e}`); + } + + /** SHA-256 recorded for the official source of this vendored copy. */ + get source() { + return this.spec['x-magic-mail-source']; + } +} + +/** + * SHA-256 of a vendored file (used to pin the copies). + * + * @param {string} name + * @returns {string} + */ +function fixtureSha256(name) { + return crypto + .createHash('sha256') + .update(fs.readFileSync(path.join(FIXTURES, `${name}.json`))) + .digest('hex'); +} + +module.exports = { OpenApiContract, fixtureSha256, undeclaredKeys }; From e44862b0beac4da3438511ce291a97e0a2d14c43 Mon Sep 17 00:00:00 2001 From: "Schero D." Date: Wed, 18 Nov 2026 07:33:52 +0100 Subject: [PATCH 03/10] feat(providers): SendGrid EU region and safer SendGrid/Mailgun send paths SendGrid - SG-2/ACC-SG-01: config.region 'us' | 'eu' (default/legacy 'us') maps to api.sendgrid.com / api.eu.sendgrid.com (utils/sendgrid-region.js); rejected on account create/update; wizard SingleSelect with i18n in 5 locales (same keys, values and hunks as feat/provider-templates); the failure log line names the region. - SG-1/SG-9: every address once across to, cc, bcc (case-insensitive, first wins, empty cc/bcc dropped) with MailTo.name kept. - SG-3: x-sg-id and x-sg-eid are reserved headers. - SG-7: request bodies of 30 MB or more are refused before fetch with ValidationError MAGIC_MAIL_MESSAGE_TOO_LARGE; HTTP 413 gets the code. - SG-5: on failure at most 4 KB of the body is read (2 s timeout); only allowlisted errors[].field paths are kept (error.providerFields), the verified-sender 403 is flagged as providerReason 'sender_identity' without keeping text; error.provider is set; message stays " API request failed: ". 429 X-RateLimit-Reset is a lower bound for the queue retry when it is an integer within 24 h. - SG-8: custom_args.magicmail_id = email-log documentId. - MG-SEND-3: tracking_settings open/click enable:false only for the parts Magic Mail applied. Mailgun - MG-SEND-1: estimated messages of 25 MB or more are refused before fetch. - MG-SEND-2: o:/h:/v:/t: options over 16 KB are refused on every send; caller headers are capped at 8 KB for every provider (zod + filter). - MG-SEND-3: o:tracking-opens/-clicks=no only for applied parts. - MG-SEND-4/SG-8: v:magicmail_email_type, v:magicmail_priority, v:magicmail_id and o:tag=. All providers: attachments are limited to 40 MB raw in total. Tests: golden payloads recorded from 4.5.1 stay identical except the listed additions; contract tests against the pinned specs; behaviour tests; opt-in live suite tests/live/provider-send.live.test.js (skips without ~/.config/magic-mail-live/.env). Docs read (2026-11-18): twilio.com/docs/sendgrid/api-reference/mail-send (Limitations, errors), .../how-to-use-the-sendgrid-v3-api/rate-limits, documentation.mailgun.com .../sending-messages/send-http, pinned tsg_mail_v3.json and mailgun.json (servers, PostMailSend, MailTo, ErrorResponse, tracking_settings, o:tracking-*, o:tag, v:, 16KB rule). Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 13 + README.md | 2 + .../AccountWizard/CredentialsStep.jsx | 27 + .../components/AccountWizard/wizardState.js | 5 + admin/src/translations/de.json | 6 +- admin/src/translations/en.json | 6 +- admin/src/translations/es.json | 6 +- admin/src/translations/fr.json | 6 +- admin/src/translations/pt.json | 6 +- docs/sending.md | 53 +- server/src/services/account-manager.js | 20 + server/src/services/analytics.js | 21 +- server/src/services/email-router.js | 453 +++++++++- server/src/services/queue.js | 27 +- server/src/utils/delivery-outcome.js | 17 + server/src/utils/sendgrid-region.js | 47 + server/src/validation.js | 12 + tests/delivery-webhooks.test.js | 5 + tests/helpers/provider-send-harness.js | 192 ++++ tests/live/provider-send.live.test.js | 401 +++++++++ tests/provider-send-contract.test.js | 406 +++++++++ tests/provider-send-paths.test.js | 842 ++++++++++++++++++ 22 files changed, 2524 insertions(+), 49 deletions(-) create mode 100644 server/src/utils/sendgrid-region.js create mode 100644 tests/helpers/provider-send-harness.js create mode 100644 tests/live/provider-send.live.test.js create mode 100644 tests/provider-send-contract.test.js create mode 100644 tests/provider-send-paths.test.js diff --git a/CHANGELOG.md b/CHANGELOG.md index d5bb789..9db5c1f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,8 @@ * **More delivery outcomes from SendGrid and Mailgun.** Besides bounces and spam complaints, the webhooks now record when a mail is delayed (**Deferred**), when the receiving server accepted it (new field `deliveryConfirmedAt`) and when a recipient unsubscribes through the provider (`unsubscribed`). To get them, select the extra events in your provider: SendGrid deferred, delivered, unsubscribe, group unsubscribe and group resubscribe; Mailgun Temporary Failure, Delivered and Unsubscribes. Without them nothing changes. Other plugins can listen to the new events `magic-mail.delivery.deferred`, `.delivered`, `.unsubscribed`, `.resubscribed`, `.blocked` and `.dropped`. * **Guide for checking the webhooks with your real accounts**: [docs/live-webhook-checks.md](https://github.com/Schero94/Magic-Mail/blob/main/docs/live-webhook-checks.md). +* **SendGrid EU regional subusers.** A SendGrid account now has a region: **Global** (default, `api.sendgrid.com`) or **EU** (`api.eu.sendgrid.com`). If your SendGrid key belongs to an EU regional subuser, open the account, choose region **EU** and save. Existing accounts keep the global host; nothing changes for them. An unknown region is rejected when the account is saved. +* **Mailgun sends carry Magic Mail metadata.** Each Mailgun mail gets the variables `magicmail_email_type`, `magicmail_priority` and `magicmail_id` (the email log id) and one tag with the email type (`transactional`, `marketing` or `notification`), so you can filter Mailgun's logs and webhooks by type. SendGrid mails carry `magicmail_id` as a custom argument. Mailgun shows variables to recipients in the `X-Mailgun-Variables` header; they contain no personal data. ### Fixed @@ -13,11 +15,22 @@ * **No more false bounces from SendGrid.** A SendGrid block (a temporary refusal, often reputation) and drops for sender-side reasons such as a broken template or an expired send are no longer shown as **Bounced**. They show as **Failed** with a reason code such as `SENDGRID_BLOCKED_500` or `SENDGRID_DROPPED_INVALID_TEMPLATE`. Drops because the address bounced before or is invalid still count as bounces; drops because of a spam report or unsubscribe are recorded as such. * **One bad cc address no longer marks the whole mail.** A bounce for a cc or bcc recipient is stored as an event for that address; the mail itself keeps its status. * **Late SendGrid bounces are matched.** Bounces that arrive without SendGrid's message id are matched by MagicMail's own id or the SMTP id when present; events that match no mail are counted in the log instead of disappearing silently. +* **Duplicate recipients no longer make SendGrid reject the whole email.** SendGrid refuses a mail when an address appears twice in to, cc or bcc. Magic Mail now sends every address once (the first occurrence wins, compared without case) and drops a cc or bcc list that only repeated other addresses. Other providers are unchanged (Mailgun ignores duplicates itself). +* **SendGrid keeps recipient names.** `Ada Lovelace ` arrives as "Ada Lovelace" instead of the bare address. +* **Oversized emails are rejected before upload with a clear message.** SendGrid accepts less than 30 MB and Mailgun 25 MB per message. Magic Mail now checks the size before calling the provider and answers with a validation error (`MAGIC_MAIL_MESSAGE_TOO_LARGE`) instead of uploading the whole mail and getting a vague rejection. All attachments of one email together may be at most 40 MB raw with every provider (each file stays limited to 25 MB). A provider's own "too large" answer (HTTP 413) gets the same code. +* **Magic Mail turns off Mailgun's and SendGrid's own open/click tracking when it tracks itself, so links are no longer wrapped twice** and opens are not counted twice. Only the part Magic Mail really applied is switched off; when Magic Mail does not track (tracking off, no public URL), the provider's tracking settings apply as before. +* **Custom headers can no longer break Mailgun sends.** Mailgun allows 16 KB for all headers and options of one message. Caller headers are now limited to 8 KB in total for every provider: the Content API answers 400 above that, and the service API drops the headers that do not fit. A Mailgun message whose headers still exceed 16 KB is refused before sending. +* **SendGrid's reserved headers are filtered.** A caller header `X-SG-ID` or `X-SG-EID` used to make SendGrid reject the mail; Magic Mail now drops them like its own reserved headers. +* **Clearer provider failures.** Failed SendGrid and Mailgun calls now carry the provider and, for SendGrid, the names of the rejected fields (for example `personalizations.0.cc`), never the provider's message text (it can contain addresses). The error message stays `SendGrid API request failed: `. The server log names the region. When SendGrid answers 429 with a reset time, a queued retry waits at least until then. ### Migration * Nothing to do for most installs. New optional columns are added on start; no data is changed or removed. * If your code listens to `magic-mail.delivery.bounced`: SendGrid blocks and sender-side drops now arrive as `magic-mail.delivery.blocked` and `.dropped`. If your code checks `deliveryStatus`, it can now also be `blocked` (shown as **Failed** in the admin). +* If you use a SendGrid EU regional subuser, set that account's region to **EU**. +* Content API callers that send more than 8 KB of custom headers get a 400 now; send fewer or shorter headers. +* If you listen to SendGrid or Mailgun webhooks yourself, you will see the new `magicmail_*` custom arguments / variables and the Mailgun tag. + ## [4.5.1](https://github.com/Schero94/Magic-Mail/compare/v4.5.0...v4.5.1) (2026-11-17) diff --git a/README.md b/README.md index 9a9cd41..6f0bec0 100644 --- a/README.md +++ b/README.md @@ -247,6 +247,8 @@ npm run verify npm run verify:runtime ``` +`npm run test:live` runs the opt-in suite against the real SendGrid and Mailgun APIs (SendGrid sandbox mode and Mailgun test mode, nothing is delivered; Mailgun bills test-mode messages). It reads `~/.config/magic-mail-live/.env` with `SENDGRID_API_KEY`, `SENDGRID_FROM`, `MAILGUN_API_KEY`, `MAILGUN_DOMAIN`, `MAILGUN_REGION`, `LIVE_TEST_RECIPIENT` and optionally `SENDGRID_REGION`, `SENDGRID_EU_API_KEY`, `SENDGRID_EU_FROM`, `MAILGUN_FROM`, `MAILGUN_EU_DOMAIN`, `MAILGUN_EU_API_KEY`; without the file every live test is skipped. Never commit that file. + `npm run test:multi-instance` runs the multi-process suite (set `MAGIC_MAIL_TEST_PG_URL` for PostgreSQL). `npm run watch` (or `npm run watch:link` with yalc) rebuilds the admin and the server bundle on change. CI runs the same checks on Node 22 and 24 for every pull request and every push to `main`. Use [Conventional Commits](https://www.conventionalcommits.org/) (`fix:`, `feat:`, `docs:`); releases are cut from `main` by semantic-release. **Dependency audits.** Run `npm audit` from your Strapi project root to check the complete installed tree; npm applies overrides from the root project only. MagicMail validates every request with its own zod (`^4.6.7`) and bounds all collections. Strapi itself ships other zod copies inside `@strapi/*` packages; if `npm audit` in your project reports one of them, the fix comes with a Strapi update. diff --git a/admin/src/components/AccountWizard/CredentialsStep.jsx b/admin/src/components/AccountWizard/CredentialsStep.jsx index 525211a..76a0a75 100644 --- a/admin/src/components/AccountWizard/CredentialsStep.jsx +++ b/admin/src/components/AccountWizard/CredentialsStep.jsx @@ -967,6 +967,33 @@ export const CredentialsStep = ({ )} + {provider === 'sendgrid' && ( + + + {t('accountModal.sendgrid.region', 'SendGrid region')} + onChange('sendgridRegion', value)} + > + + {t('accountModal.sendgrid.regionGlobal', 'Global (api.sendgrid.com)')} + + + {t('accountModal.sendgrid.regionEu', 'EU (api.eu.sendgrid.com)')} + + + + + + )} + {provider === 'mailgun' && ( ({ apiKey: '', mailgunDomain: '', mailgunRegion: 'us', + sendgridRegion: 'us', webhookPublicKey: '', webhookSigningKey: '', microsoftTenantId: '', @@ -142,6 +143,8 @@ export const accountToForm = (account = {}) => { mailgunDomain: stringOr(config.domain), // Accounts saved before regions existed use the US endpoint. mailgunRegion: config.region === 'eu' ? 'eu' : 'us', + // SendGrid EU regional subusers use api.eu.sendgrid.com. + sendgridRegion: config.region === 'eu' ? 'eu' : 'us', // Optional bounce/complaint webhook secrets (SendGrid key is public). webhookPublicKey: stringOr(config.webhookPublicKey), webhookSigningKey: stringOr(config.webhookSigningKey), @@ -317,6 +320,8 @@ export const buildConfig = (provider, form) => { case 'sendgrid': return { apiKey: form.apiKey.trim(), + // "us" = api.sendgrid.com (global), "eu" = api.eu.sendgrid.com. + region: form.sendgridRegion === 'eu' ? 'eu' : 'us', webhookPublicKey: (form.webhookPublicKey || '').trim(), }; case 'mailgun': diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index 73209ac..2090825 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -913,5 +913,9 @@ "suppressions.empty.description": "Empfänger erscheinen hier nach einem dauerhaften Bounce.", "suppressions.pagination": "Seiten der Sperrliste", "suppressions.confirm.title": "Aus der Sperrliste entfernen?", - "suppressions.confirm.body": "E-Mails an {address} werden wieder versendet. Nur entfernen, wenn die Adresse korrigiert wurde." + "suppressions.confirm.body": "E-Mails an {address} werden wieder versendet. Nur entfernen, wenn die Adresse korrigiert wurde.", + "accountModal.sendgrid.regionHint": "Wählen Sie EU nur für einen regionalen EU-Subuser. EU-Konten werden über api.eu.sendgrid.com aufgerufen, alle anderen über api.sendgrid.com.", + "accountModal.sendgrid.region": "SendGrid-Region", + "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" } diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index ec99924..0f9dee6 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -913,5 +913,9 @@ "suppressions.empty.description": "Recipients appear here after a permanent bounce.", "suppressions.pagination": "Suppression list pages", "suppressions.confirm.title": "Remove from the suppression list?", - "suppressions.confirm.body": "Emails to {address} are sent again. Only do this when the address was fixed." + "suppressions.confirm.body": "Emails to {address} are sent again. Only do this when the address was fixed.", + "accountModal.sendgrid.regionHint": "Use EU only for an EU regional subuser. EU accounts are called through api.eu.sendgrid.com, all others through api.sendgrid.com.", + "accountModal.sendgrid.region": "SendGrid region", + "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" } diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index bf52773..44d642b 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -913,5 +913,9 @@ "suppressions.empty.description": "Los destinatarios aparecen aquí tras un rebote permanente.", "suppressions.pagination": "Páginas de la lista de bloqueo", "suppressions.confirm.title": "¿Quitar de la lista de bloqueo?", - "suppressions.confirm.body": "Los correos a {address} se volverán a enviar. Hazlo solo si la dirección se ha corregido." + "suppressions.confirm.body": "Los correos a {address} se volverán a enviar. Hazlo solo si la dirección se ha corregido.", + "accountModal.sendgrid.regionHint": "Elija EU solo para un subusuario regional de la EU. Las cuentas de la EU se llaman a través de api.eu.sendgrid.com; todas las demás, a través de api.sendgrid.com.", + "accountModal.sendgrid.region": "Región de SendGrid", + "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" } diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index bbce51d..177cea2 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -913,5 +913,9 @@ "suppressions.empty.description": "Les destinataires apparaissent ici après un rebond permanent.", "suppressions.pagination": "Pages de la liste de blocage", "suppressions.confirm.title": "Retirer de la liste de blocage ?", - "suppressions.confirm.body": "Les e-mails vers {address} seront de nouveau envoyés. À faire uniquement si l'adresse a été corrigée." + "suppressions.confirm.body": "Les e-mails vers {address} seront de nouveau envoyés. À faire uniquement si l'adresse a été corrigée.", + "accountModal.sendgrid.regionHint": "Choisissez EU uniquement pour un sous-utilisateur régional EU. Les comptes EU sont appelés via api.eu.sendgrid.com, tous les autres via api.sendgrid.com.", + "accountModal.sendgrid.region": "Région SendGrid", + "accountModal.sendgrid.regionGlobal": "Mondiale (api.sendgrid.com)", + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" } diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 275b01c..f835932 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -913,5 +913,9 @@ "suppressions.empty.description": "Os destinatários aparecem aqui após uma devolução permanente.", "suppressions.pagination": "Páginas da lista de bloqueio", "suppressions.confirm.title": "Remover da lista de bloqueio?", - "suppressions.confirm.body": "Os e-mails para {address} voltam a ser enviados. Faça-o apenas se o endereço foi corrigido." + "suppressions.confirm.body": "Os e-mails para {address} voltam a ser enviados. Faça-o apenas se o endereço foi corrigido.", + "accountModal.sendgrid.regionHint": "Escolha EU apenas para um subusuário regional da EU. As contas da EU são chamadas por meio de api.eu.sendgrid.com; todas as outras, por meio de api.sendgrid.com.", + "accountModal.sendgrid.region": "Região do SendGrid", + "accountModal.sendgrid.regionGlobal": "Global (api.sendgrid.com)", + "accountModal.sendgrid.regionEu": "EU (api.eu.sendgrid.com)" } diff --git a/docs/sending.md b/docs/sending.md index c5e100c..d2bb1b5 100644 --- a/docs/sending.md +++ b/docs/sending.md @@ -54,22 +54,22 @@ See [Content API](./api.md#content-api) for `POST /api/magic-mail/send` and `/se The same fields work for the router, the Strapi email service and `POST /api/magic-mail/send`. -| Field | Description | -| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `to`, `cc`, `bcc` | Address, array or comma-separated list (max. 100 `to`, 50 `cc`/`bcc`). Display names allowed | -| `subject`, `text`, `html` | `subject` is required unless a template provides it; `text` or `html` is required. HTML is sanitised (no scripts, event handlers or `javascript:` URLs; email layout is kept) | -| `from` | Optional. Must be the sending account's address; only its display name is used | -| `replyTo` | A valid address | -| `type` | `transactional` (default), `marketing` or `notification`. Without `type`, a template's category is used | -| `priority` | `normal` (default), `high` or `low`. `high` adds `X-Priority` and `Importance` headers | -| `accountName` | Force one account | -| `templateId` / `templateReferenceId`, `templateData` | Render a MagicMail template by its Reference ID with Mustache data (`data` is accepted as an alias of `templateData`) | -| `unsubscribeUrl` | Per-email unsubscribe URL | -| `enableTracking: false`, `skipLinkTracking: true` | Disable open and click tracking, or only click tracking, for this email | -| `customField` | Value matched by routing rules of type _Custom_ | -| `headers` | Up to 20 custom headers: `X-*` (except MagicMail's own) plus `List-Id`, `Precedence`, `Auto-Submitted`, `In-Reply-To`, `References`. Others are dropped | -| `attachments` | Up to 20, 25 MB each, with `filename`, `content`, `contentType`, `encoding`, `cid` | -| `userId`, `recipientName` | Stored on the email log | +| Field | Description | +| ---------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `to`, `cc`, `bcc` | Address, array or comma-separated list (max. 100 `to`, 50 `cc`/`bcc`). Display names allowed | +| `subject`, `text`, `html` | `subject` is required unless a template provides it; `text` or `html` is required. HTML is sanitised (no scripts, event handlers or `javascript:` URLs; email layout is kept) | +| `from` | Optional. Must be the sending account's address; only its display name is used | +| `replyTo` | A valid address | +| `type` | `transactional` (default), `marketing` or `notification`. Without `type`, a template's category is used | +| `priority` | `normal` (default), `high` or `low`. `high` adds `X-Priority` and `Importance` headers | +| `accountName` | Force one account | +| `templateId` / `templateReferenceId`, `templateData` | Render a MagicMail template by its Reference ID with Mustache data (`data` is accepted as an alias of `templateData`) | +| `unsubscribeUrl` | Per-email unsubscribe URL | +| `enableTracking: false`, `skipLinkTracking: true` | Disable open and click tracking, or only click tracking, for this email | +| `customField` | Value matched by routing rules of type _Custom_ | +| `headers` | Up to 20 custom headers, 8 KB in total (names plus values): `X-*` (except MagicMail's own and SendGrid's `X-SG-ID`/`X-SG-EID`) plus `List-Id`, `Precedence`, `Auto-Submitted`, `In-Reply-To`, `References`. Others are dropped; the Content API answers 400 above 8 KB | +| `attachments` | Up to 20, 25 MB each and 40 MB together, with `filename`, `content`, `contentType`, `encoding`, `cid`. SendGrid and Mailgun have lower message limits (see below) | +| `userId`, `recipientName` | Stored on the email log | ### Attachments @@ -178,6 +178,21 @@ The provider value `nodemailer` is an alias of `smtp`. 1. In SendGrid go to **Settings → API Keys** and create a key with the **Mail Send** permission. 2. In MagicMail choose **SendGrid** and paste the key. The sender address must be verified in SendGrid. +3. Choose the region. **Global** fits every account except EU regional subusers, which need **EU**. + +| `config.region` | API host | +| --------------- | ----------------------------- | +| `us` (default) | `https://api.sendgrid.com` | +| `eu` | `https://api.eu.sendgrid.com` | + +Any other value is rejected when the account is created or updated. Accounts saved without a region keep using the global host. + +What MagicMail sends to SendGrid: + +- Every address once across to, cc and bcc (SendGrid rejects duplicates), with its display name. +- `custom_args`: `magicmail_version`, `email_type`, `priority` and `magicmail_id` (the email log id, used to match webhook events). +- `tracking_settings.open_tracking` / `click_tracking` with `enable: false` for the parts MagicMail tracks itself, so SendGrid does not track them a second time. +- Messages are refused before the request when the request body would be 30 MB or more (SendGrid accepts "less than 30MB" including attachments). ### Mailgun @@ -193,6 +208,12 @@ A Mailgun domain can only be used through the API host of its region. MagicMail Any other value is rejected with a validation error when the account is created or updated. Accounts saved without a region keep using the US host. +What MagicMail adds to each Mailgun message: + +- `o:tracking-opens=no` / `o:tracking-clicks=no` for the parts MagicMail tracks itself (no double-wrapped links). +- The variables `v:magicmail_email_type`, `v:magicmail_priority` and `v:magicmail_id` (the email log id), and `o:tag` with the email type. Mailgun shows variables to the recipient in the `X-Mailgun-Variables` header; they contain no personal data. +- Messages are refused before the request when headers and options exceed Mailgun's 16 KB limit or the estimated message size is 25 MB or more. + ### Provider comparison | Provider | Authentication | Transport | DKIM | diff --git a/server/src/services/account-manager.js b/server/src/services/account-manager.js index 1f89539..4774b8a 100644 --- a/server/src/services/account-manager.js +++ b/server/src/services/account-manager.js @@ -5,6 +5,7 @@ const { encryptCredentials, decryptCredentials } = require('../utils/encryption' const { toAccountListDTO, toAccountEditDTO } = require('../utils/account-dto'); const { toClientSendMessage, describeErrorForLog } = require('../utils/client-errors'); const { MAILGUN_REGIONS, resolveMailgunRegion } = require('../utils/mailgun-region'); +const { SENDGRID_REGIONS, resolveSendGridRegion } = require('../utils/sendgrid-region'); const coordination = require('../utils/coordination'); /** @@ -78,6 +79,23 @@ const assertMailgunRegion = (provider, config) => { }); }; +/** + * Rejects an unsupported SendGrid `config.region` ("us" global, "eu" for EU + * regional subusers). An omitted region keeps the global endpoint. + * + * @param {string} provider - effective provider of the account + * @param {object|undefined|null} config - incoming plain config + * @throws {errors.ValidationError} + */ +const assertSendGridRegion = (provider, config) => { + if (provider !== 'sendgrid' || !config || !('region' in config)) return; + if (resolveSendGridRegion(config.region)) return; + throw new errors.ValidationError( + `SendGrid region must be one of: ${SENDGRID_REGIONS.join(', ')}`, + { config: [`region: must be one of ${SENDGRID_REGIONS.join(', ')}`] } + ); +}; + const escapeHtml = (value) => String(value ?? '') .replace(/&/g, '&') @@ -140,6 +158,7 @@ module.exports = ({ strapi }) => ({ strapi.log.info(`[magic-mail] Creating account: ${name} (${provider})`); assertMailgunRegion(provider, config); + assertSendGridRegion(provider, config); assertBounceMode(provider, bounceMonitor); // Encrypt sensitive config data @@ -222,6 +241,7 @@ module.exports = ({ strapi }) => ({ } assertMailgunRegion(provider ?? existingAccount.provider, config); + assertSendGridRegion(provider ?? existingAccount.provider, config); assertBounceMode(provider ?? existingAccount.provider, bounceMonitor); let encryptedConfig = existingAccount.config; diff --git a/server/src/services/analytics.js b/server/src/services/analytics.js index 648ed43..de0b424 100644 --- a/server/src/services/analytics.js +++ b/server/src/services/analytics.js @@ -958,14 +958,20 @@ module.exports = ({ strapi }) => ({ * @param {string} html * @param {string} emailId * @param {string} recipientHash - * @param {{openTracking?: boolean, linkTracking?: boolean, settings?: object}} [options] + * When `options.applied` is given, its `opens` / `clicks` flags are set to + * true for the parts that really changed the HTML (pixel injected, at least + * one link rewritten), so the send path can switch off the provider's own + * tracking for exactly those parts. + * + * @param {{openTracking?: boolean, linkTracking?: boolean, settings?: object, applied?: {opens?: boolean, clicks?: boolean}}} [options] * @returns {Promise} + * @sideeffect Sets `options.applied.opens` / `.clicks` when given. */ async addTracking( html, emailId, recipientHash, - { openTracking = true, linkTracking = true, settings } = {} + { openTracking = true, linkTracking = true, settings, applied } = {} ) { let pluginSettings = settings; if (!pluginSettings) { @@ -979,9 +985,16 @@ module.exports = ({ strapi }) => ({ const endpoint = resolveTrackingEndpoint(strapi, pluginSettings); if (!endpoint) return html; let result = html; - if (linkTracking) + if (linkTracking) { + const before = result; result = await this.rewriteLinksForTracking(result, emailId, recipientHash, { endpoint }); - if (openTracking) result = this.injectTrackingPixel(result, emailId, recipientHash, endpoint); + if (applied && result !== before) applied.clicks = true; + } + if (openTracking) { + const before = result; + result = this.injectTrackingPixel(result, emailId, recipientHash, endpoint); + if (applied && result !== before) applied.opens = true; + } return result; }, diff --git a/server/src/services/email-router.js b/server/src/services/email-router.js index 3af6600..3d6c178 100644 --- a/server/src/services/email-router.js +++ b/server/src/services/email-router.js @@ -6,6 +6,7 @@ const sanitizeHtml = require('sanitize-html'); const { decryptCredentials } = require('../utils/encryption'); const { normalizeMessageId } = require('../utils/message-id'); const { mailgunApiBaseUrl, resolveMailgunRegion } = require('../utils/mailgun-region'); +const { resolveSendGridRegion, sendGridApiBaseUrl } = require('../utils/sendgrid-region'); const { routingRuleEvaluationSort } = require('../utils/routing-order'); const coordination = require('../utils/coordination'); const { checkRecipientDomains } = require('../utils/recipient-domains'); @@ -37,6 +38,40 @@ const MAX_ATTACHMENT_BYTES = 25 * 1024 * 1024; const MAX_CUSTOM_HEADERS = 20; const MAX_ROUTING_CANDIDATES = 25; +// Provider size limits (official docs, checked 2026-11-18): +// - SendGrid: "The total size of your email, including attachments, must be +// less than 30MB" (Mail Send reference, Limitations). The docs do not say +// whether the encoded or the raw size counts, so the JSON request body is +// measured against the decimal value. +// - Mailgun: "The maximum message size Mailgun supports is 25MB ... enforced +// on the uncompressed body" (Sending messages over HTTP), and "Send options +// (parameters starting with o:, h:, v:, or t:) are limited to 16KB total" +// (API reference, POST /v3/{domain_name}/messages). +const SENDGRID_MAX_MESSAGE_BYTES = 30_000_000; +const MAILGUN_MAX_MESSAGE_BYTES = 25_000_000; +const MAILGUN_MAX_OPTIONS_BYTES = 16 * 1024; +/** Raw (decoded) size of all attachments of one message, for every provider. */ +const MAX_TOTAL_ATTACHMENT_BYTES = 40 * 1024 * 1024; +/** Bytes of all caller headers (names plus values), for every provider. */ +const MAX_CUSTOM_HEADER_BYTES = 8 * 1024; +/** A provider error body is read up to this size, parsed, then discarded. */ +const PROVIDER_ERROR_BODY_MAX_BYTES = 4 * 1024; +const PROVIDER_ERROR_BODY_TIMEOUT_MS = 2_000; +/** SendGrid X-RateLimit-Reset is used only when it lies within this window. */ +const MAX_RATE_LIMIT_RESET_MS = 24 * 60 * 60 * 1000; +/** Delivery-log documentId sent as SendGrid custom arg / Mailgun variable `magicmail_id`. */ +const MAGICMAIL_ID_PATTERN = /^[A-Za-z0-9]{1,64}$/; +/** Mailgun tag: ASCII, at most 128 characters (Mailgun Tagging guide). */ +const MAILGUN_TAG_MAX_LENGTH = 128; +/** + * SendGrid `errors[].field` paths kept on a failed send. Anything else + * (unknown paths, free text) is dropped; the error message text is never + * kept because it can contain addresses. + */ +const SENDGRID_ERROR_FIELD = + /^(?:personalizations(?:\.\d{1,4})?(?:\.(?:to|cc|bcc|headers|subject|custom_args|substitutions|dynamic_template_data|send_at)(?:\.\d{1,4})?(?:\.(?:email|name))?)?|from(?:\.(?:email|name))?|reply_to(?:\.(?:email|name))?|reply_to_list(?:\.\d{1,4})?(?:\.(?:email|name))?|subject|content(?:\.\d{1,4})?(?:\.(?:type|value))?|attachments(?:\.\d{1,4})?(?:\.(?:content|type|filename|disposition|content_id))?|headers|custom_args|template_id|categories|send_at|batch_id|asm(?:\.(?:group_id|groups_to_display))?|ip_pool_name|mail_settings(?:\.[a-z_]{1,40}){0,2}|tracking_settings(?:\.[a-z_]{1,40}){0,2})$/; +const MAX_PROVIDER_FIELDS = 10; + // Refresh OAuth tokens this long before they expire (clock skew, slow sends). const OAUTH_EXPIRY_SKEW_MS = 60_000; // In-flight token refreshes per account (single-flight per process; the @@ -203,6 +238,10 @@ const RESERVED_X_HEADERS = new Set([ 'x-entity-ref-id', 'x-content-type-options', 'x-magicmail-outbox', + // SendGrid rejects requests that set these ("You may not override the + // following headers: x-sg-id, x-sg-eid, ...", tsg_mail_v3.json headers). + 'x-sg-id', + 'x-sg-eid', ]); /** Bounded timeouts for queue (worker) sends; the lease must exceed their sum. */ @@ -306,12 +345,237 @@ function accountConfigError(message) { * @param {number} status * @returns {Error} */ -function providerHttpError(provider, status) { +function providerHttpError(provider, status, details = {}) { const error = new Error(`${provider} API request failed: ${status}`); error.status = status; + error.provider = String(provider).toLowerCase(); + if (status === 413) error.code = 'MAGIC_MAIL_MESSAGE_TOO_LARGE'; + if (Array.isArray(details.providerFields) && details.providerFields.length > 0) { + error.providerFields = details.providerFields; + } + if (details.providerReason) error.providerReason = details.providerReason; + if (Number.isInteger(details.retryAfterMs) && details.retryAfterMs > 0) { + error.retryAfterMs = details.retryAfterMs; + } + return error; +} + +/** + * ValidationError (400) for a message that is larger than a limit. Thrown + * before any provider request, so nothing was sent. + * + * @param {string} message - Client-safe message without personal data + * @returns {Error} with code MAGIC_MAIL_MESSAGE_TOO_LARGE + */ +function messageTooLargeError(message) { + const error = validationError(message); + error.code = 'MAGIC_MAIL_MESSAGE_TOO_LARGE'; return error; } +/** + * Reads at most PROVIDER_ERROR_BODY_MAX_BYTES of a failed provider response + * within PROVIDER_ERROR_BODY_TIMEOUT_MS. Never throws: a missing, slow or + * unreadable body gives null. The text is only parsed by the caller, never + * logged, stored or returned (it can contain recipient addresses). + * + * @param {Response|object} response + * @returns {Promise} + */ +async function readProviderErrorBody(response) { + let timer; + let reader = null; + try { + const timeout = new Promise((resolve) => { + timer = setTimeout(() => resolve(null), PROVIDER_ERROR_BODY_TIMEOUT_MS); + }); + const read = (async () => { + if (response?.body && typeof response.body.getReader === 'function') { + reader = response.body.getReader(); + const chunks = []; + let total = 0; + while (total < PROVIDER_ERROR_BODY_MAX_BYTES) { + const { done, value } = await reader.read(); + if (done) break; + chunks.push(Buffer.from(value)); + total += value.byteLength; + } + return Buffer.concat(chunks).subarray(0, PROVIDER_ERROR_BODY_MAX_BYTES).toString('utf8'); + } + if (typeof response?.text === 'function') { + const text = await response.text(); + return typeof text === 'string' ? text.slice(0, PROVIDER_ERROR_BODY_MAX_BYTES) : null; + } + return null; + })(); + return await Promise.race([read, timeout]); + } catch { + return null; + } finally { + clearTimeout(timer); + if (reader) reader.cancel().catch(() => {}); + } +} + +/** + * Safe details of a SendGrid error body (`ErrorResponse` + * `{ errors: [{ message, field, help }] }`): the allowlisted `field` paths + * and, for a 403, whether the documented "From address doesn't match + * Verified Sender Identity" case applies. The message text itself is only + * compared, never kept. + * + * @param {string|null} text - Bounded body from readProviderErrorBody + * @param {number} status + * @returns {{providerFields: string[], providerReason: string|null}} + */ +function sendGridErrorDetails(text, status) { + const result = { providerFields: [], providerReason: null }; + if (typeof text !== 'string' || text.length === 0) return result; + let parsed; + try { + parsed = JSON.parse(text); + } catch { + return result; + } + const errors = Array.isArray(parsed?.errors) ? parsed.errors.slice(0, 50) : []; + for (const entry of errors) { + const raw = typeof entry?.field === 'string' ? entry.field : ''; + if (raw && raw.length <= 100) { + const field = raw.replace(/\[(\d{1,4})\]/g, '.$1'); + if ( + SENDGRID_ERROR_FIELD.test(field) && + !result.providerFields.includes(field) && + result.providerFields.length < MAX_PROVIDER_FIELDS + ) { + result.providerFields.push(field); + } + } + const message = typeof entry?.message === 'string' ? entry.message.slice(0, 500) : ''; + if (status === 403 && /verified sender identity/i.test(message)) { + result.providerReason = 'sender_identity'; + } + } + return result; +} + +/** + * Milliseconds until SendGrid's `X-RateLimit-Reset` (epoch seconds in the + * documented example; the rate-limits page does not define the format), or 0 + * when the header is missing, not an integer, in the past or more than 24 h + * ahead. Used only as a lower bound for the next queue attempt. + * + * @param {Response|object} response + * @param {number} [nowMs=Date.now()] + * @returns {number} + */ +function rateLimitResetMs(response, nowMs = Date.now()) { + const raw = response?.headers?.get?.('x-ratelimit-reset'); + if (typeof raw !== 'string' || !/^\d{1,12}$/.test(raw.trim())) return 0; + const delta = Number(raw.trim()) * 1000 - nowMs; + return delta > 0 && delta <= MAX_RATE_LIMIT_RESET_MS ? Math.ceil(delta) : 0; +} + +/** + * SendGrid recipient lists. Every address appears once across to, then cc, + * then bcc (case-insensitive; the first occurrence wins), because SendGrid + * answers 400 when "Each unique email address in the personalization block" + * is not "only included once" (Mail Send errors). Display names are kept as + * `MailTo.name`. Empty cc/bcc lists are left out by the caller. + * + * @param {object} emailData + * @returns {{to: {email: string, name?: string}[], cc: {email: string, name?: string}[], bcc: {email: string, name?: string}[]}} + */ +function sendGridRecipients(emailData) { + const seen = new Set(); + const pick = (value) => { + const out = []; + for (const entry of parseAddressList(value)) { + const email = (entry.address || '').toLowerCase(); + if (!email || seen.has(email)) continue; + seen.add(email); + const name = stripHeaderInjection(entry.name || ''); + out.push(name ? { email, name } : { email }); + } + return out; + }; + return { to: pick(emailData.to), cc: pick(emailData.cc), bcc: pick(emailData.bcc) }; +} + +/** + * What Magic Mail's own tracking really changed in this message (set by + * applyTracking). Only those parts switch off the provider's tracking, so + * provider-side tracking keeps working when Magic Mail does not track. + * + * @param {object} emailData + * @returns {{opens: boolean, clicks: boolean}} + */ +function trackingAppliedOf(emailData) { + const applied = emailData?.__trackingApplied; + return { + opens: applied?.opens === true, + clicks: applied?.clicks === true, + }; +} + +/** + * Delivery-log documentId for provider correlation, or null. + * + * @param {object} emailData + * @returns {string|null} + */ +function magicmailIdOf(emailData) { + const id = emailData?.__logDocumentId; + return typeof id === 'string' && MAGICMAIL_ID_PATTERN.test(id) ? id : null; +} + +/** + * Mailgun tag for an email type: ASCII letters, digits, `_`, `.`, `-`, at + * most 128 characters; '' when nothing is left. + * + * @param {unknown} value + * @returns {string} + */ +function mailgunTag(value) { + if (typeof value !== 'string') return ''; + return value.replace(/[^A-Za-z0-9_.-]/g, '').slice(0, MAILGUN_TAG_MAX_LENGTH); +} + +/** + * Bytes of all Mailgun send options (o:, h:, v:, t: form fields). + * + * @param {FormData} form + * @returns {number} + */ +function mailgunOptionBytes(form) { + let total = 0; + for (const [name, value] of form.entries()) { + if (/^[ohvt]:/.test(name) && typeof value === 'string') { + total += Buffer.byteLength(name) + Buffer.byteLength(value); + } + } + return total; +} + +/** + * Estimated size of the MIME message Mailgun builds from a form: text fields + * as UTF-8, files base64-encoded with line breaks every 76 characters. + * + * @param {FormData} form + * @returns {number} + */ +function estimateMailgunMessageBytes(form) { + let total = 0; + for (const [name, value] of form.entries()) { + if (typeof value === 'string') { + total += Buffer.byteLength(name) + Buffer.byteLength(value); + } else if (value && typeof value.size === 'number') { + const encoded = Math.ceil(value.size / 3) * 4; + total += encoded + Math.ceil(encoded / 76) * 2; + } + } + return total; +} + /** * Returns true when a send error guarantees that no provider accepted the * message, so trying the next account cannot cause duplicate delivery. @@ -545,6 +809,7 @@ function normalizeAttachments(list) { if (!Array.isArray(list)) throw validationError('attachments must be an array'); if (list.length > MAX_ATTACHMENTS) throw validationError('Too many attachments'); + let totalBytes = 0; return list.map((attachment, index) => { if (!attachment || typeof attachment !== 'object') { throw validationError('Invalid attachment'); @@ -564,6 +829,10 @@ function normalizeAttachments(list) { const content = decodeAttachmentContent(attachment.content, attachment.encoding); if (content.length > MAX_ATTACHMENT_BYTES) throw validationError('Attachment is too large'); + totalBytes += content.length; + if (totalBytes > MAX_TOTAL_ATTACHMENT_BYTES) { + throw messageTooLargeError('Attachments are too large in total (40 MB at most)'); + } let cid; if (attachment.cid !== undefined && attachment.cid !== null && attachment.cid !== '') { @@ -609,7 +878,10 @@ function toNodemailerAttachments(attachments) { /** * Filters caller headers to the allowlist (`X-*` except plugin-owned ones, - * List-Id, Precedence, Auto-Submitted, In-Reply-To, References). + * List-Id, Precedence, Auto-Submitted, In-Reply-To, References). At most + * MAX_CUSTOM_HEADERS headers and MAX_CUSTOM_HEADER_BYTES bytes (names plus + * values) are kept, so caller headers fit every provider (Mailgun allows + * 16 KB for all send options). Headers beyond either limit are dropped. * * @param {*} source * @returns {Record} @@ -619,6 +891,7 @@ function filterCustomHeaders(source) { if (!source || typeof source !== 'object' || Array.isArray(source)) return out; let count = 0; + let bytes = 0; for (const [rawName, rawValue] of Object.entries(source)) { if (count >= MAX_CUSTOM_HEADERS) break; const name = stripHeaderInjection(rawName); @@ -633,6 +906,9 @@ function filterCustomHeaders(source) { else if (lower.startsWith('x-') && !RESERVED_X_HEADERS.has(lower)) canonical = name; if (!canonical) continue; + const size = Buffer.byteLength(canonical) + Buffer.byteLength(value); + if (bytes + size > MAX_CUSTOM_HEADER_BYTES) break; + bytes += size; out[canonical] = value; count += 1; } @@ -1112,6 +1388,9 @@ module.exports = ({ strapi }) => ({ // One delivery log per attempt, whether or not tracking is enabled. const emailLog = await this.createDeliveryLog(data, renderedTemplate, source); + // Correlation id for provider webhooks (SendGrid custom arg / Mailgun + // variable `magicmail_id`); an opaque id, no personal data. + if (typeof emailLog?.documentId === 'string') data.__logDocumentId = emailLog.documentId; const trackingEnabled = data.enableTracking !== false; if (emailLog && trackingEnabled && data.html) { data.html = await this.applyTracking(data, emailLog, pluginSettings); @@ -1495,10 +1774,23 @@ module.exports = ({ strapi }) => ({ /** * Injects the open pixel and rewrites links (subject to global settings). + * + * Reports what was really applied in `data.__trackingApplied` + * (`{ opens, clicks }`): a part counts only when it changed the HTML (no + * public tracking URL, no eligible link or a failure leave it false). The + * SendGrid and Mailgun adapters switch off the provider's own open/click + * tracking for exactly these parts, so links are not wrapped twice. + * + * @param {object} data - Working copy of the message + * @param {{emailId: string}} emailLog - Delivery log of this send + * @param {object} pluginSettings - enableOpenTracking / enableLinkTracking * @returns {Promise} Tracked HTML (original HTML on failure) + * @sideeffect Sets `data.__trackingApplied`; stores click-tracking link mappings. */ async applyTracking(data, emailLog, pluginSettings) { let html = data.html; + const applied = { opens: false, clicks: false }; + data.__trackingApplied = applied; try { const analyticsService = strapi.plugin('magic-mail').service('analytics'); const recipientHash = analyticsService.generateRecipientHash(emailLog.emailId, data.to); @@ -1509,20 +1801,32 @@ module.exports = ({ strapi }) => ({ if (typeof analyticsService.addTracking === 'function') { // One resolved public URL for pixel and links; without a public URL the // mail is sent untracked (never pointing at localhost in production). - return await analyticsService.addTracking(html, emailLog.emailId, recipientHash, { + const reported = { opens: false, clicks: false }; + const tracked = await analyticsService.addTracking(html, emailLog.emailId, recipientHash, { openTracking, linkTracking, settings: pluginSettings, + applied: reported, }); + Object.assign(applied, reported); + return tracked; } - if (openTracking) + const reported = { opens: false, clicks: false }; + if (openTracking) { + const before = html; html = analyticsService.injectTrackingPixel(html, emailLog.emailId, recipientHash); - if (linkTracking) + reported.opens = html !== before; + } + if (linkTracking) { + const before = html; html = await analyticsService.rewriteLinksForTracking( html, emailLog.emailId, recipientHash ); + reported.clicks = html !== before; + } + Object.assign(applied, reported); return html; } catch (error) { strapi.log.error( @@ -2387,26 +2691,43 @@ module.exports = ({ strapi }) => ({ } }, - /** Send via the SendGrid v3 API. */ + /** + * Sends through the SendGrid v3 Mail Send API (global or EU host). + * + * Every address is sent once across to/cc/bcc with its display name; + * `custom_args.magicmail_id` carries the delivery-log documentId; SendGrid's + * own open/click tracking is switched off for the parts Magic Mail tracks. + * A request body of 30 MB or more is refused before any network call. + * + * @param {object} account - SendGrid account (encrypted config with apiKey, optional region) + * @param {object} emailData - Prepared message (validated again here) + * @returns {Promise<{messageId: string|null, response: string}>} X-Message-Id + * (null when SendGrid sends none, e.g. sandbox mode) + * @throws {Error} Account configuration error (no key, unknown region) + * @throws {errors.ValidationError} Invalid message, or MAGIC_MAIL_MESSAGE_TOO_LARGE + * @throws {Error} "SendGrid API request failed: " with `status`, + * `provider`, and when known `providerFields`, `providerReason`, `retryAfterMs` + * @sideeffect One HTTPS request to SendGrid with the recipients and content. + */ async sendViaSendGrid(account, emailData) { const config = readAccountSecret(account.config); if (!config.apiKey) throw accountConfigError('SendGrid API key not configured'); + const region = resolveSendGridRegion(config.region); + if (!region) throw accountConfigError('SendGrid region must be "us" or "eu"'); this.validateEmailSecurity(emailData); try { - const toRecipientList = (value) => listAddresses(value).map((email) => ({ email })); - - const personalization = { to: toRecipientList(emailData.to) }; + const recipients = sendGridRecipients(emailData); + const personalization = { to: recipients.to }; if (personalization.to.length === 0) { throw validationError('SendGrid send requires at least one valid recipient'); } - const ccRecipients = toRecipientList(emailData.cc); - if (ccRecipients.length > 0) personalization.cc = ccRecipients; - const bccRecipients = toRecipientList(emailData.bcc); - if (bccRecipients.length > 0) personalization.bcc = bccRecipients; + if (recipients.cc.length > 0) personalization.cc = recipients.cc; + if (recipients.bcc.length > 0) personalization.bcc = recipients.bcc; const sender = senderFor(account, emailData); + const magicmailId = magicmailIdOf(emailData); const msg = { personalizations: [personalization], from: { email: sender.address, ...(sender.name ? { name: sender.name } : {}) }, @@ -2415,15 +2736,24 @@ module.exports = ({ strapi }) => ({ ...(emailData.text ? [{ type: 'text/plain', value: emailData.text }] : []), ...(emailData.html ? [{ type: 'text/html', value: emailData.html }] : []), ], - // SendGrid v3 uses snake_case `custom_args`. + // SendGrid v3 uses snake_case `custom_args`; values must be strings. custom_args: { magicmail_version: '1.0', email_type: emailData.type || 'transactional', priority: emailData.priority || 'normal', + ...(magicmailId ? { magicmail_id: magicmailId } : {}), }, headers: buildOutboundHeaders(emailData), }; + const tracking = trackingAppliedOf(emailData); + if (tracking.opens || tracking.clicks) { + msg.tracking_settings = { + ...(tracking.clicks ? { click_tracking: { enable: false } } : {}), + ...(tracking.opens ? { open_tracking: { enable: false } } : {}), + }; + } + const replyTo = resolveReplyTo(emailData.replyTo || account.replyTo); if (replyTo && replyTo.length === 1) { msg.reply_to = { @@ -2448,23 +2778,40 @@ module.exports = ({ strapi }) => ({ })); } - const response = await fetch('https://api.sendgrid.com/v3/mail/send', { + const body = JSON.stringify(msg); + if (Buffer.byteLength(body) >= SENDGRID_MAX_MESSAGE_BYTES) { + throw messageTooLargeError( + 'The message is larger than SendGrid accepts (30 MB including attachments)' + ); + } + + const response = await fetch(`${sendGridApiBaseUrl(region)}/v3/mail/send`, { ...fetchBounds(emailData), method: 'POST', headers: { Authorization: `Bearer ${config.apiKey}`, 'Content-Type': 'application/json', }, - body: JSON.stringify(msg), + body, }); if (!response.ok) { - strapi.log.error(`[magic-mail] SendGrid API request failed: ${response.status}`); - throw providerHttpError('SendGrid', response.status); + const details = sendGridErrorDetails( + await readProviderErrorBody(response), + response.status + ); + strapi.log.error( + `[magic-mail] SendGrid API request failed: ${response.status} (region ${region})` + ); + throw providerHttpError('SendGrid', response.status, { + ...details, + retryAfterMs: response.status === 429 ? rateLimitResetMs(response) : 0, + }); } return { // SendGrid's id; its webhooks report it as the `sg_message_id` prefix. + // Sandbox mode answers 200 without X-Message-Id: then null. messageId: normalizeMessageId(response.headers?.get?.('x-message-id')), response: 'Accepted', }; @@ -2474,7 +2821,25 @@ module.exports = ({ strapi }) => ({ } }, - /** Send via the Mailgun API. */ + /** + * Sends through the Mailgun messages API (US or EU host). + * + * Adds `o:tracking-opens=no` / `o:tracking-clicks=no` only for the parts + * Magic Mail tracks itself, the metadata variables `v:magicmail_email_type`, + * `v:magicmail_priority` and `v:magicmail_id` (delivery-log documentId; + * Mailgun shows variables in the X-Mailgun-Variables header and in + * webhooks, so only allowlisted values and an opaque id are sent) and one + * `o:tag` with the email type. Refuses, before any network call, send + * options over 16 KB and messages estimated at 25 MB or more. + * + * @param {object} account - Mailgun account (encrypted config with apiKey, domain, region) + * @param {object} emailData - Prepared message (validated again here) + * @returns {Promise<{messageId: string|null, response: string}>} Mailgun id without angle brackets + * @throws {Error} Account configuration error (key, domain, region) + * @throws {errors.ValidationError} Invalid message, or MAGIC_MAIL_MESSAGE_TOO_LARGE + * @throws {Error} "Mailgun API request failed: " with `status` and `provider` + * @sideeffect One HTTPS request to Mailgun with the recipients and content. + */ async sendViaMailgun(account, emailData) { const config = readAccountSecret(account.config); if (!config.apiKey || !config.domain) { @@ -2514,6 +2879,26 @@ module.exports = ({ strapi }) => ({ form.append(`h:${name}`, value); } + // Magic Mail tracks these parts itself: Mailgun must not track them again. + const tracking = trackingAppliedOf(emailData); + if (tracking.opens) form.append('o:tracking-opens', 'no'); + if (tracking.clicks) form.append('o:tracking-clicks', 'no'); + // Metadata for Mailgun events/webhooks: allowlisted values only. + const type = EMAIL_TYPES.includes(emailData.type) ? emailData.type : 'transactional'; + const priority = PRIORITIES.includes(emailData.priority) ? emailData.priority : 'normal'; + form.append('v:magicmail_email_type', type); + form.append('v:magicmail_priority', priority); + const magicmailId = magicmailIdOf(emailData); + if (magicmailId) form.append('v:magicmail_id', magicmailId); + const tag = mailgunTag(type); + if (tag) form.append('o:tag', tag); + + if (mailgunOptionBytes(form) > MAILGUN_MAX_OPTIONS_BYTES) { + throw messageTooLargeError( + 'Headers and send options are larger than Mailgun accepts (16 KB in total)' + ); + } + for (const attachment of normalizeAttachments(emailData.attachments)) { form.append( attachment.cid ? 'inline' : 'attachment', @@ -2522,6 +2907,12 @@ module.exports = ({ strapi }) => ({ ); } + if (estimateMailgunMessageBytes(form) >= MAILGUN_MAX_MESSAGE_BYTES) { + throw messageTooLargeError( + 'The message is larger than Mailgun accepts (25 MB including attachments)' + ); + } + // fetch derives the multipart boundary from the FormData body. const response = await fetch( `${mailgunApiBaseUrl(region)}/v3/${encodeURIComponent(domain)}/messages`, @@ -2536,7 +2927,16 @@ module.exports = ({ strapi }) => ({ ); if (!response.ok) { - strapi.log.error(`[magic-mail] Mailgun API request failed: ${response.status}`); + // The body (JSON `message` or the plain text "Forbidden") is not read: + // it can echo addresses and adds nothing a fixed hint does not say. + try { + await response.body?.cancel?.(); + } catch { + // nothing to release + } + strapi.log.error( + `[magic-mail] Mailgun API request failed: ${response.status} (region ${region})` + ); throw providerHttpError('Mailgun', response.status); } @@ -2854,6 +3254,19 @@ module.exports = ({ strapi }) => ({ module.exports.__test__ = { HTML_SANITIZE_OPTIONS, + MAILGUN_MAX_MESSAGE_BYTES, + MAILGUN_MAX_OPTIONS_BYTES, + MAX_CUSTOM_HEADER_BYTES, + MAX_TOTAL_ATTACHMENT_BYTES, + SENDGRID_MAX_MESSAGE_BYTES, + estimateMailgunMessageBytes, + mailgunOptionBytes, + mailgunTag, + providerHttpError, + rateLimitResetMs, + readProviderErrorBody, + sendGridErrorDetails, + sendGridRecipients, createMessageId, buildOutboundHeaders, filterCustomHeaders, diff --git a/server/src/services/queue.js b/server/src/services/queue.js index 3dc2cdb..2cf54e9 100644 --- a/server/src/services/queue.js +++ b/server/src/services/queue.js @@ -6,6 +6,7 @@ const store = require('../utils/outbox-store'); const { encryptPayload, decryptPayload, purposeHmac } = require('../utils/encryption'); const { backoffDelay, + retryLowerBoundMs, combineOutcome, classifyDeliveryError, sanitizeErrorCode, @@ -50,6 +51,8 @@ const PAYLOAD_FIELDS = [ 'accountName', 'unsubscribeUrl', '__forceUnsubscribe', + // { opens, clicks } Magic Mail tracking really applied (provider tracking off). + '__trackingApplied', 'templateReferenceId', 'templateName', 'templateId', @@ -441,7 +444,13 @@ module.exports = ({ strapi }) => { const errorClass = options.errorClass; const code = sanitizeErrorCode(options.error); const status = errorClass === 'ambiguous' ? 'uncertain' : 'pending'; - let nextAttemptAt = at + backoffDelay(1, cfg.backoffMs, cfg.jitterRatio, state.random); + // A provider rate-limit reset (SendGrid 429) is a lower bound for the retry. + let nextAttemptAt = + at + + Math.max( + backoffDelay(1, cfg.backoffMs, cfg.jitterRatio, state.random), + retryLowerBoundMs(options.error) + ); if (errorClass === 'capacity') nextAttemptAt = nextQuotaWindow(at); try { const { row, duplicate } = await insertPrepared(data, { @@ -570,6 +579,10 @@ module.exports = ({ strapi }) => { ...message, __outboxId: row.documentId, __messageIdLocal: messageIdLocal, + // Delivery-log documentId for provider correlation (`magicmail_id`). + ...(typeof row.emailLogDocumentId === 'string' + ? { __logDocumentId: row.emailLogDocumentId } + : {}), }; let defaultFromName; @@ -636,6 +649,7 @@ module.exports = ({ strapi }) => { code: sanitizeErrorCode(error), errorClass, account: ctx.attempted.length ? ctx.attempted.at(-1) : null, + retryAfterMs: retryLowerBoundMs(error), }, !dispatched && errorClass !== 'capacity' ); @@ -715,11 +729,12 @@ module.exports = ({ strapi }) => { * Records a failed queue attempt (fenced). * * @param {object} row - claimed row - * @param {{code: string, errorClass: string, account?: string|null}} outcome + * @param {{code: string, errorClass: string, account?: string|null, retryAfterMs?: number}} outcome + * `retryAfterMs`: provider rate-limit reset, a lower bound for the next attempt * @param {boolean} countAttempt - add an attempt (no provider call happened) * @returns {Promise} resulting status */ - async finishFailure(row, { code, errorClass, account = null }, countAttempt) { + async finishFailure(row, { code, errorClass, account = null, retryAfterMs = 0 }, countAttempt) { const cfg = config(); const at = now(); const attempts = (row.attempts || 0) + (countAttempt ? 1 : 0); @@ -753,7 +768,11 @@ module.exports = ({ strapi }) => { leaseToken: null, claimedBy: null, nextAttemptAt: - at + backoffDelay(retryNumber, cfg.backoffMs, cfg.jitterRatio, state.random), + at + + Math.max( + backoffDelay(retryNumber, cfg.backoffMs, cfg.jitterRatio, state.random), + retryLowerBoundMs({ retryAfterMs }) + ), }; } else if (errorClass === 'ambiguous') { status = 'uncertain'; diff --git a/server/src/utils/delivery-outcome.js b/server/src/utils/delivery-outcome.js index e354d52..0b15094 100644 --- a/server/src/utils/delivery-outcome.js +++ b/server/src/utils/delivery-outcome.js @@ -214,6 +214,22 @@ function sanitizeErrorCode(error) { return 'UNKNOWN'; } +/** Upper bound for a provider-reported retry delay (SendGrid X-RateLimit-Reset). */ +const MAX_RETRY_LOWER_BOUND_MS = 24 * 60 * 60 * 1000; + +/** + * Provider-reported minimum delay before the next attempt (set by the + * SendGrid adapter from X-RateLimit-Reset on a 429), or 0. Only a positive + * integer of at most 24 h counts; anything else is ignored. + * + * @param {*} error - Error thrown by a provider adapter + * @returns {number} milliseconds + */ +function retryLowerBoundMs(error) { + const value = error && typeof error === 'object' ? error.retryAfterMs : undefined; + return Number.isInteger(value) && value > 0 && value <= MAX_RETRY_LOWER_BOUND_MS ? value : 0; +} + /** * Delay before retry number `retryNumber` (1-based) with symmetric jitter. * @@ -367,6 +383,7 @@ module.exports = { combineOutcome, sanitizeErrorCode, backoffDelay, + retryLowerBoundMs, createSmtpProbe, tagSmtpStage, tagPreDispatch, diff --git a/server/src/utils/sendgrid-region.js b/server/src/utils/sendgrid-region.js new file mode 100644 index 0000000..233fff8 --- /dev/null +++ b/server/src/utils/sendgrid-region.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * SendGrid API regions. + * + * SendGrid serves global users and subusers from https://api.sendgrid.com and + * EU regional subusers from https://api.eu.sendgrid.com (`servers` of + * twilio/sendgrid-oai tsg_mail_v3.json, pinned in + * tests/fixtures/openapi/sendgrid-mail.json; Mail Send reference: + * "EU Regional Email sending requires use of an EU IP address and EU + * subuser"). Checked 2026-11-18. + * + * The account stores `config.region` as 'us' (global) or 'eu'. Only these two + * fixed hosts are ever used, so a stored value can never send the API key to + * another server. + */ + +const SENDGRID_API_BASE_URLS = Object.freeze({ + us: 'https://api.sendgrid.com', + eu: 'https://api.eu.sendgrid.com', +}); +const SENDGRID_REGIONS = Object.freeze(Object.keys(SENDGRID_API_BASE_URLS)); + +/** + * Resolves a stored SendGrid `config.region`. Accounts saved before regions + * existed have none and keep the global endpoint. + * + * @param {unknown} value + * @returns {'us'|'eu'|null} the region, or null for an unsupported value + */ +const resolveSendGridRegion = (value) => { + if (value === undefined || value === null || value === '') return 'us'; + return typeof value === 'string' && SENDGRID_REGIONS.includes(value) ? value : null; +}; + +/** + * @param {'us'|'eu'} region - a value returned by resolveSendGridRegion() + * @returns {string} base URL without a trailing slash + */ +const sendGridApiBaseUrl = (region) => SENDGRID_API_BASE_URLS[region]; + +module.exports = { + SENDGRID_API_BASE_URLS, + SENDGRID_REGIONS, + resolveSendGridRegion, + sendGridApiBaseUrl, +}; diff --git a/server/src/validation.js b/server/src/validation.js index 442846c..f7a902b 100644 --- a/server/src/validation.js +++ b/server/src/validation.js @@ -609,6 +609,18 @@ const schemas = { .refine((value) => Object.keys(value).length <= 20, { message: 'At most 20 custom headers', }) + // Names plus values; keeps caller headers inside every provider's + // limit (Mailgun: 16 KB for all send options). + .refine( + (value) => + Object.entries(value).reduce( + (total, [name, header]) => + total + Buffer.byteLength(name) + Buffer.byteLength(String(header)), + 0 + ) <= + 8 * 1024, + { message: 'Custom headers may use at most 8 KB in total' } + ) .optional(), }) .strict(), diff --git a/tests/delivery-webhooks.test.js b/tests/delivery-webhooks.test.js index 4d3c0aa..77a977e 100644 --- a/tests/delivery-webhooks.test.js +++ b/tests/delivery-webhooks.test.js @@ -599,8 +599,13 @@ test('wizard builds the webhook URL only for saved SendGrid/Mailgun accounts', ( assert.equal(getWebhookUrl('smtp', 'abc', { origin: 'https://x.test' }), null); assert.deepEqual(buildConfig('sendgrid', { apiKey: ' SG.k ', webhookPublicKey: ' KEY ' }), { apiKey: 'SG.k', + region: 'us', webhookPublicKey: 'KEY', }); + assert.equal( + buildConfig('sendgrid', { apiKey: 'SG.k', sendgridRegion: 'eu', webhookPublicKey: '' }).region, + 'eu' + ); }); test('a failing eventHub listener does not fail the webhook', async () => { 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, +}; diff --git a/tests/live/provider-send.live.test.js b/tests/live/provider-send.live.test.js new file mode 100644 index 0000000..bcf5a2f --- /dev/null +++ b/tests/live/provider-send.live.test.js @@ -0,0 +1,401 @@ +'use strict'; + +// Opt-in live suite for the SendGrid and Mailgun SEND PATHS against the REAL +// provider APIs. Not part of `npm test`. +// +// Run: npm run test:live +// Needs: ~/.config/magic-mail-live/.env (created by the maintainer, never +// committed). Variable NAMES (values never appear in code or logs): +// Required +// SENDGRID_API_KEY SendGrid key with the Mail Send permission +// SENDGRID_FROM a verified SendGrid Sender Identity address +// MAILGUN_API_KEY Mailgun Domain Sending Key (or an account key) +// MAILGUN_DOMAIN sending domain, e.g. mg.example.com +// MAILGUN_REGION us | eu (region of MAILGUN_DOMAIN) +// LIVE_TEST_RECIPIENT address used as recipient (nothing is delivered) +// Optional +// SENDGRID_REGION us | eu (region of SENDGRID_API_KEY, default us) +// SENDGRID_EU_API_KEY key of an EU regional subuser; enables the EU host test +// SENDGRID_EU_FROM verified sender of that subuser (default SENDGRID_FROM) +// MAILGUN_FROM sender address (default magic-mail-live@MAILGUN_DOMAIN) +// MAILGUN_EU_DOMAIN an EU domain (+ MAILGUN_EU_API_KEY) for the +// MAILGUN_EU_API_KEY "EU domain on the US host" test when MAILGUN_REGION=us +// The same file serves tests/live/provider-templates.live.test.js +// (provider-templates branch), which needs further variables. +// +// Nothing is delivered: +// - every SendGrid mail/send request gets mail_settings.sandbox_mode.enable = +// true; SendGrid then validates the full request and answers 200 without +// delivering or emitting events (Sandbox Mode docs); +// - every Mailgun messages request gets o:testmode=yes ("will accept the +// message but will not send it"; note: Mailgun bills test-mode messages). +// The switches are added by this file's fetch wrapper; the plugin code under +// test is unchanged. Requests may only go to the four provider hosts. +// +// Secrets and addresses are never printed: values stay in memory, assertion +// messages never include them and provider bodies are not logged. Without +// the file every test is skipped with a message (CI never has it). + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const os = require('node:os'); +const path = require('node:path'); +const crypto = require('node:crypto'); + +const ENV_FILE = path.join(os.homedir(), '.config', 'magic-mail-live', '.env'); +const ALLOWED_HOSTS = new Set([ + 'api.sendgrid.com', + 'api.eu.sendgrid.com', + 'api.mailgun.net', + 'api.eu.mailgun.net', +]); +const REQUIRED = [ + 'SENDGRID_API_KEY', + 'SENDGRID_FROM', + 'MAILGUN_API_KEY', + 'MAILGUN_DOMAIN', + 'MAILGUN_REGION', + 'LIVE_TEST_RECIPIENT', +]; + +/** + * Reads KEY=value lines (no expansion, no export, quotes stripped). + * + * @returns {Record|null} null when the file does not exist + */ +function readLiveEnv() { + if (!fs.existsSync(ENV_FILE)) return null; + const out = {}; + for (const line of fs.readFileSync(ENV_FILE, 'utf8').split(/\r?\n/)) { + const match = /^\s*([A-Z0-9_]+)\s*=\s*(.*)\s*$/.exec(line); + if (!match || line.trim().startsWith('#')) continue; + out[match[1]] = match[2].replace(/^(['"])(.*)\1$/, '$2'); + } + return out; +} + +const env = readLiveEnv(); +const missing = env ? REQUIRED.filter((key) => !env[key]) : REQUIRED; +const skipReason = !env + ? `live suite skipped: ${ENV_FILE} does not exist (see the variable names at the top of this file)` + : missing.length > 0 + ? `live suite skipped: missing ${missing.join(', ')} in ${ENV_FILE}` + : null; +if (skipReason) console.log(skipReason); + +/** Registers a live test; skipped with the reason when credentials are missing. */ +const live = (name, fn) => test(name, { skip: skipReason || false }, fn); + +const results = []; +const sent = { sendgrid: [], mailgun: [] }; +let restoreFetch; +let restoreKey; + +test.before(() => { + if (skipReason) return; + const previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = crypto.randomBytes(32).toString('hex'); + restoreKey = () => { + if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey; + }; + const original = global.fetch; + global.fetch = async (input, init = {}) => { + const url = new URL(typeof input === 'string' ? input : input.url); + if (!ALLOWED_HOSTS.has(url.hostname)) throw new TypeError('live suite: host not allowed'); + let body = init.body; + if (url.pathname === '/v3/mail/send' && typeof body === 'string') { + const json = JSON.parse(body); + json.mail_settings = { ...(json.mail_settings || {}), sandbox_mode: { enable: true } }; + body = JSON.stringify(json); + sent.sendgrid.push(json); + } + if (/\/messages$/.test(url.pathname) && body instanceof FormData) { + body.set('o:testmode', 'yes'); + sent.mailgun.push( + [...body.entries()].map(([k, v]) => [k, typeof v === 'string' ? v : '']) + ); + } + const response = await original(input, { ...init, body }); + results.push({ + host: url.hostname, + path: url.pathname.replace(/\/v3\/[^/]+\/messages$/, '/v3//messages'), + status: response.status, + }); + return response; + }; + restoreFetch = () => { + global.fetch = original; + }; +}); + +test.after(() => { + if (skipReason) return; + restoreFetch(); + restoreKey(); + // Request log without secrets or addresses: host, path, status. + console.log(JSON.stringify({ liveRequests: results }, null, 1)); +}); + +/** Region of the main SendGrid key. */ +const sgRegion = () => (env.SENDGRID_REGION === 'eu' ? 'eu' : 'us'); +const mgRegion = () => (env.MAILGUN_REGION === 'eu' ? 'eu' : 'us'); + +/** + * Live accounts built from the .env values (config encrypted in memory). + * + * @param {{sendgrid?: object, mailgun?: object}} [overrides] - config overrides + * @returns {object[]} + */ +function liveAccounts(overrides = {}) { + const { encryptCredentials } = require('../../server/src/utils/encryption'); + return [ + { + documentId: 'livesendgrid', + name: 'live-sendgrid', + provider: 'sendgrid', + fromEmail: overrides.sendgridFrom || env.SENDGRID_FROM, + isActive: true, + priority: 5, + config: encryptCredentials({ + apiKey: env.SENDGRID_API_KEY, + region: sgRegion(), + ...(overrides.sendgrid || {}), + }), + }, + { + documentId: 'livemailgun', + name: 'live-mailgun', + provider: 'mailgun', + fromEmail: env.MAILGUN_FROM || `magic-mail-live@${env.MAILGUN_DOMAIN}`, + isActive: true, + priority: 4, + config: encryptCredentials({ + apiKey: env.MAILGUN_API_KEY, + domain: env.MAILGUN_DOMAIN, + region: mgRegion(), + ...(overrides.mailgun || {}), + }), + }, + ]; +} + +/** + * Harness with one live account of `provider` (Magic Mail tracking applied + * by the fake analytics service, as in production with a public URL). + */ +function harnessFor(provider, overrides = {}, options = {}) { + const { createHarness } = require('../helpers/provider-send-harness'); + const accounts = liveAccounts(overrides).filter((account) => account.provider === provider); + return { ...createHarness(accounts, options), account: accounts[0] }; +} + +const message = (extra = {}) => ({ + to: env.LIVE_TEST_RECIPIENT, + subject: 'Magic Mail live send-path test', + text: 'Magic Mail live test. Sandbox / test mode: not delivered.', + ...extra, +}); + +/** Recipient address with a plus tag (same mailbox, distinct address). */ +const tagged = (tag) => env.LIVE_TEST_RECIPIENT.replace('@', `+${tag}@`); + +// ── SendGrid (sandbox mode) ─────────────────────────────────────────────── + +live('SG-1: duplicate to/cc addresses are accepted (sent once)', async () => { + const { router } = harnessFor('sendgrid'); + const result = await router.send( + message({ cc: env.LIVE_TEST_RECIPIENT.toUpperCase(), bcc: env.LIVE_TEST_RECIPIENT }) + ); + assert.equal(result.success, true); + const p = sent.sendgrid.at(-1).personalizations[0]; + assert.equal(p.to.length, 1); + assert.equal(p.cc, undefined); + assert.equal(p.bcc, undefined); +}); + +live('SG-3: an X-SG-ID header from the caller is stripped and the send is accepted', async () => { + const { router } = harnessFor('sendgrid'); + const result = await router.send(message({ headers: { 'X-SG-ID': 'x', 'X-Live-Test': '1' } })); + assert.equal(result.success, true); + const headers = Object.keys(sent.sendgrid.at(-1).headers).map((name) => name.toLowerCase()); + assert.ok(!headers.includes('x-sg-id')); + assert.ok(headers.includes('x-live-test')); +}); + +live('SG-9: display names are sent and accepted', async () => { + const { router } = harnessFor('sendgrid'); + const result = await router.send( + message({ to: `Live Test <${env.LIVE_TEST_RECIPIENT}>`, cc: `"Ops, Live" <${tagged('cc')}>` }) + ); + assert.equal(result.success, true); + const p = sent.sendgrid.at(-1).personalizations[0]; + assert.equal(p.to[0].name, 'Live Test'); + assert.equal(p.cc[0].name, 'Ops, Live'); +}); + +live('several replyTo addresses (reply_to_list) are accepted', async () => { + const { router } = harnessFor('sendgrid'); + const result = await router.send(message({ replyTo: [tagged('r1'), tagged('r2')] })); + assert.equal(result.success, true); + assert.equal(sent.sendgrid.at(-1).reply_to_list.length, 2); +}); + +live('inline cid image plus attachment are accepted by both providers', async () => { + const { PIXEL_PNG } = require('../helpers/provider-send-harness'); + const extra = { + html: '

Inline

', + attachments: [ + { cid: 'logo.png', content: PIXEL_PNG, encoding: 'base64', contentType: 'image/png' }, + { filename: 'live.txt', content: 'live attachment', contentType: 'text/plain' }, + ], + }; + for (const provider of ['sendgrid', 'mailgun']) { + const { router } = harnessFor(provider); + const result = await router.send(message(extra)); + assert.equal(result.success, true, provider); + } +}); + +live('MG-SEND-3: provider tracking switched off where Magic Mail tracks is accepted', async () => { + const html = '

Track

Shop'; + for (const provider of ['sendgrid', 'mailgun']) { + const { router } = harnessFor(provider, {}, { tracking: 'all' }); + const result = await router.send(message({ html })); + assert.equal(result.success, true, provider); + } + assert.deepEqual(sent.sendgrid.at(-1).tracking_settings, { + click_tracking: { enable: false }, + open_tracking: { enable: false }, + }); + const form = sent.mailgun.at(-1); + assert.ok(form.some(([k, v]) => k === 'o:tracking-opens' && v === 'no')); + assert.ok(form.some(([k, v]) => k === 'o:tracking-clicks' && v === 'no')); +}); + +live('SendGrid sandbox: a 200 without X-Message-Id still logs a success', async () => { + const { router } = harnessFor('sendgrid'); + const result = await router.send(message()); + assert.equal(result.success, true); + assert.ok(result.messageId === null || typeof result.messageId === 'string'); +}); + +live('SendGrid: a wrong key gives 401 and the mapped hint, without provider text', async () => { + const { router, accountManager, account } = harnessFor('sendgrid', { + sendgrid: { apiKey: `SG.invalid-${crypto.randomBytes(8).toString('hex')}` }, + }); + const error = await router.sendViaSendGrid(account, message()).catch((e) => e); + assert.equal(error.status, 401); + assert.equal(error.provider, 'sendgrid'); + assert.equal(error.message, 'SendGrid API request failed: 401'); + const outcome = await accountManager.testAccount(account.documentId, env.LIVE_TEST_RECIPIENT); + assert.equal(outcome.success, false); + assert.equal(outcome.message, 'SendGrid API request failed: 401'); + // PR #22 adds `hintCode` (client-errors providerErrorHint); checked once it is merged. + if ('hintCode' in outcome) assert.equal(outcome.hintCode, 'SENDGRID_UNAUTHORIZED'); +}); + +live('SG-2: the EU host accepts an EU regional subuser key (optional)', async (t) => { + if (!env.SENDGRID_EU_API_KEY) { + t.skip('SENDGRID_EU_API_KEY not set'); + return; + } + const { router } = harnessFor('sendgrid', { + sendgrid: { apiKey: env.SENDGRID_EU_API_KEY, region: 'eu' }, + sendgridFrom: env.SENDGRID_EU_FROM || env.SENDGRID_FROM, + }); + const result = await router.send(message()); + assert.equal(result.success, true); + assert.equal(results.at(-1).host, 'api.eu.sendgrid.com'); +}); + +// ── Size prechecks (local only: no request may be made) ─────────────────── + +live('SG-7/MG-SEND-1: oversized messages are refused before any request', async () => { + const before = results.length; + for (const [provider, bytes] of [ + ['sendgrid', 23_000_000], + ['mailgun', 19_000_000], + ]) { + const { router } = harnessFor(provider); + await assert.rejects( + router.send( + message({ attachments: [{ filename: 'big.bin', content: Buffer.alloc(bytes, 1) }] }) + ), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' + ); + } + assert.equal(results.length, before, 'no provider request was made'); +}); + +// ── Mailgun (test mode) ─────────────────────────────────────────────────── + +live('MG-SEND-2: send options just under 16 KB are accepted', async () => { + const { router } = harnessFor('mailgun'); + const headers = { 'X-Pad-1': 'p'.repeat(3990), 'X-Pad-2': 'p'.repeat(3990) }; + const result = await router.send(message({ headers })); + assert.equal(result.success, true); + const bytes = sent.mailgun + .at(-1) + .filter(([k]) => /^[ohvt]:/.test(k)) + .reduce((sum, [k, v]) => sum + Buffer.byteLength(k) + Buffer.byteLength(v), 0); + assert.ok(bytes > 8000 && bytes <= 16384); +}); + +live('MG-SEND-4: v: metadata, magicmail_id and o:tag are accepted', async () => { + const { router } = harnessFor('mailgun'); + const result = await router.send(message({ type: 'notification', priority: 'low' })); + assert.equal(result.success, true); + assert.match(result.messageId, /^[^<>]+$/, 'id without angle brackets'); + const form = sent.mailgun.at(-1); + for (const [key, value] of [ + ['v:magicmail_email_type', 'notification'], + ['v:magicmail_priority', 'low'], + ['v:magicmail_id', 'logdoc123'], + ['o:tag', 'notification'], + ]) { + assert.ok( + form.some(([k, v]) => k === key && v === value), + key + ); + } +}); + +live('Mailgun: an EU domain on the US host is a classified error', async (t) => { + const domain = mgRegion() === 'eu' ? env.MAILGUN_DOMAIN : env.MAILGUN_EU_DOMAIN; + const apiKey = mgRegion() === 'eu' ? env.MAILGUN_API_KEY : env.MAILGUN_EU_API_KEY; + if (!domain || !apiKey) { + t.skip('no EU Mailgun domain configured'); + return; + } + const { router, account } = harnessFor('mailgun', { + mailgun: { domain, apiKey, region: 'us' }, + }); + const error = await router.sendViaMailgun(account, message()).catch((e) => e); + assert.equal(error.provider, 'mailgun'); + assert.ok(error.status >= 400 && error.status < 500, 'a 4xx answer'); + const { classifyDeliveryError } = require('../../server/src/utils/delivery-outcome'); + assert.notEqual(classifyDeliveryError(error), 'ambiguous'); + assert.equal(error.message, `Mailgun API request failed: ${error.status}`); +}); + +// ── Account connection checks (account test path) ───────────────────────── + +live('ACC: a valid SendGrid key and the Mailgun key pass the account test', async () => { + for (const provider of ['sendgrid', 'mailgun']) { + const { accountManager, account } = harnessFor(provider); + const outcome = await accountManager.testAccount(account.documentId, env.LIVE_TEST_RECIPIENT); + assert.equal(outcome.success, true, `${provider} account test`); + } +}); + +live('ACC: an invalid Mailgun key yields the mapped hint', async () => { + const { accountManager, account } = harnessFor('mailgun', { + mailgun: { apiKey: `invalid-${crypto.randomBytes(8).toString('hex')}` }, + }); + const outcome = await accountManager.testAccount(account.documentId, env.LIVE_TEST_RECIPIENT); + assert.equal(outcome.success, false); + assert.equal(outcome.message, 'Mailgun API request failed: 401'); + if ('hintCode' in outcome) assert.equal(outcome.hintCode, 'MAILGUN_UNAUTHORIZED'); +}); diff --git a/tests/provider-send-contract.test.js b/tests/provider-send-contract.test.js new file mode 100644 index 0000000..a27e202 --- /dev/null +++ b/tests/provider-send-contract.test.js @@ -0,0 +1,406 @@ +'use strict'; + +// Contract tests for normal (non-template) sends: every SendGrid and Mailgun +// request the send path builds, and every fake provider response, is checked +// against the official OpenAPI documents vendored in tests/fixtures/openapi +// (byte-identical copies of the provider-templates branch, pinned below): +// - SendGrid: twilio/sendgrid-oai tsg_mail_v3.json, POST /v3/mail/send +// - Mailgun: documentation.mailgun.com/_bundle/docs/mailgun/api-reference/send/mailgun.json, +// POST /v3/{domain_name}/messages +// Rules the schemas can not express (unique recipients, reserved headers, +// size limits, 16 KB of Mailgun send options) are asserted directly. +// Synthetic data only; fetch is faked. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { OpenApiContract, fixtureSha256 } = require('./helpers/openapi-contract'); +const { + PIXEL_PNG, + accountFor, + createHarness, + fakeFetch, + jsonResponse, + withEncryptionKey, +} = require('./helpers/provider-send-harness'); +const { classifyDeliveryError } = require('../server/src/utils/delivery-outcome'); +const { toClientSendMessage } = require('../server/src/utils/client-errors'); + +/** SHA-256 of the vendored files and of the official sources they were extracted from. */ +const PINNED = { + 'sendgrid-mail': { + file: '9364edadd1565ffc917cb1d8eaf14e6d6967f86f9eed6bfd9d19653efc7302f5', + source: '1bf9b256780b4c32a48e054eb9a8f93c03b586f9586d12b0ebbcdde9c170fac3', + }, + mailgun: { + file: '8d7672d8215cec03e04f581834d9b5aad5cf4d8372afb55348f8a9af9ecf5d4b', + source: '3bf29afd36c06a9a7998ed492838ed3fd4a1f4578799af285998ad73de1f8151', + }, +}; + +/** + * Where the official OpenAPI document contradicts long-standing API + * behaviour. Everything else must match the spec exactly. + */ +const KNOWN_DEVIATIONS = [ + { + contract: 'sendgrid-mail', + pattern: /^body\/custom_args must be string$/, + reason: + 'Pre-existing (4.x): Magic Mail sends top-level custom_args as an object of strings. The spec types it as a string; the personalization-level custom_args is an object and the Mail Send docs describe both as key/value pairs.', + }, +]; + +const sgMail = new OpenApiContract('sendgrid-mail'); +const mailgun = new OpenApiContract('mailgun'); + +const withoutKnown = (contract, errors) => + errors.filter( + (error) => !KNOWN_DEVIATIONS.some((d) => d.contract === contract.name && d.pattern.test(error)) + ); + +/** Headers SendGrid reserves (tsg_mail_v3.json `headers` description, Mail Send errors). */ +const SENDGRID_RESERVED_HEADERS = [ + 'x-sg-id', + 'x-sg-eid', + 'received', + 'dkim-signature', + 'content-type', + 'content-transfer-encoding', + 'to', + 'from', + 'subject', + 'reply-to', + 'cc', + 'bcc', +]; + +/** + * Sends `message` through send() with one account and returns the request. + * + * @param {'sendgrid'|'mailgun'} provider + * @param {object} message + * @param {object} [config] - Extra account config + * @returns {Promise} The recorded request + */ +async function capture(provider, message, config = {}) { + const restoreKey = withEncryptionKey(); + const fake = fakeFetch(); + try { + const { router } = createHarness([accountFor(provider, config)]); + await router.send(message); + assert.equal(fake.calls.length, 1); + return fake.calls[0]; + } finally { + fake.restore(); + restoreKey(); + } +} + +/** Asserts that a recorded SendGrid request satisfies the contract and invariants. */ +function assertSendGridRequest(call) { + assert.deepEqual( + withoutKnown( + sgMail, + sgMail.checkRequest({ method: call.method, url: call.url, json: call.json }) + ), + [], + 'SendGrid request matches tsg_mail_v3.json' + ); + const body = call.json; + const addresses = body.personalizations.flatMap((p) => + [...(p.to || []), ...(p.cc || []), ...(p.bcc || [])].map((entry) => entry.email.toLowerCase()) + ); + assert.equal(new Set(addresses).size, addresses.length, 'every address appears once'); + for (const name of Object.keys(body.headers || {})) { + assert.ok(!SENDGRID_RESERVED_HEADERS.includes(name.toLowerCase()), `reserved header ${name}`); + } + assert.ok(Object.values(body.custom_args).every((value) => typeof value === 'string')); + assert.ok(call.bodyBytes < 30_000_000); + assert.ok(!(body.reply_to && body.reply_to_list), 'reply_to and reply_to_list are exclusive'); +} + +/** Asserts that a recorded Mailgun request satisfies the contract and the 16 KB rule. */ +function assertMailgunRequest(call) { + assert.deepEqual( + mailgun.checkRequest({ method: call.method, url: call.url, form: call.form }), + [], + 'Mailgun request matches the messages operation' + ); + const optionBytes = call.form + .filter(([name]) => /^[ohvt]:/.test(name)) + .reduce((sum, [name, value]) => sum + Buffer.byteLength(name) + Buffer.byteLength(value), 0); + assert.ok(optionBytes <= 16384, 'send options are at most 16 KB'); + for (const [name, value] of call.form.filter(([n]) => n === 'o:tag')) { + assert.match(value, /^[A-Za-z0-9_.-]{1,128}$/, name); + } +} + +test('the vendored OpenAPI files are the pinned copies', () => { + for (const [name, pin] of Object.entries(PINNED)) { + assert.equal(fixtureSha256(name), pin.file, `${name}.json changed`); + const contract = name === 'mailgun' ? mailgun : sgMail; + assert.equal(contract.source.sha256, pin.source, `${name} official source`); + } + // The known deviation is still in the spec; remove it here once fixed upstream. + assert.equal( + sgMail.spec.components.requestBodies.PostMailSend.content['application/json'].schema.properties + .custom_args.type, + 'string' + ); +}); + +test('SendGrid: several replyTo addresses become reply_to_list (no reply_to)', async () => { + const call = await capture('sendgrid', { + to: 'a@example.test', + subject: 's', + text: 't', + replyTo: ['Support ', 'ops@example.test'], + }); + assertSendGridRequest(call); + assert.equal(call.json.reply_to, undefined); + assert.deepEqual(call.json.reply_to_list, [ + { email: 'support@example.test', name: 'Support' }, + { email: 'ops@example.test' }, + ]); +}); + +test('SendGrid: one replyTo address becomes reply_to', async () => { + const call = await capture('sendgrid', { + to: 'a@example.test', + subject: 's', + text: 't', + replyTo: 'support@example.test', + }); + assertSendGridRequest(call); + assert.deepEqual(call.json.reply_to, { email: 'support@example.test' }); + assert.equal(call.json.reply_to_list, undefined); +}); + +test('SendGrid: inline cid image, attachment, text before html, cc/bcc, names, metadata', async () => { + const call = await capture('sendgrid', { + to: ['Ada ', 'ADA@example.test'], + cc: 'Bob , ada@example.test', + bcc: ['carol@example.test'], + subject: 'All fields', + text: 'plain', + html: '

Hi

Shop', + headers: { 'X-SG-ID': 'spoof', 'X-SG-EID': 'spoof', 'X-Campaign': 'c1' }, + attachments: [ + { cid: 'logo', content: PIXEL_PNG, encoding: 'base64', contentType: 'image/png' }, + { filename: 'r.txt', content: 'receipt', contentType: 'text/plain' }, + ], + }); + assertSendGridRequest(call); + const body = call.json; + assert.deepEqual(body.personalizations[0].to, [{ email: 'ada@example.test', name: 'Ada' }]); + assert.deepEqual(body.personalizations[0].cc, [{ email: 'bob@example.test', name: 'Bob' }]); + assert.deepEqual(body.personalizations[0].bcc, [{ email: 'carol@example.test' }]); + assert.deepEqual( + body.content.map((part) => part.type), + ['text/plain', 'text/html'] + ); + assert.deepEqual( + body.attachments.map(({ content, ...rest }) => rest), + [ + { filename: 'logo', type: 'image/png', disposition: 'inline', content_id: 'logo' }, + { filename: 'r.txt', type: 'text/plain', disposition: 'attachment' }, + ] + ); + assert.equal(body.headers['X-Campaign'], 'c1'); + assert.equal(body.custom_args.magicmail_id, 'logdoc123'); + assert.deepEqual(body.tracking_settings, { + click_tracking: { enable: false }, + open_tracking: { enable: false }, + }); +}); + +test('SendGrid: EU accounts call a host listed in the spec servers', async () => { + const eu = await capture( + 'sendgrid', + { to: 'a@example.test', subject: 's', text: 't' }, + { + region: 'eu', + } + ); + const us = await capture('sendgrid', { to: 'a@example.test', subject: 's', text: 't' }); + assertSendGridRequest(eu); + assertSendGridRequest(us); + assert.deepEqual( + sgMail.spec.servers.map((server) => `${server.url}/v3/mail/send`).sort(), + [eu.url, us.url].sort() + ); +}); + +test('SendGrid: a body of 30 MB or more never reaches fetch', async () => { + const restoreKey = withEncryptionKey(); + const fake = fakeFetch(); + try { + const { router } = createHarness([accountFor('sendgrid')]); + await assert.rejects( + router.send({ + to: 'a@example.test', + subject: 's', + text: 't', + attachments: [{ filename: 'big.bin', content: Buffer.alloc(23_000_000, 1) }], + }), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' + ); + assert.equal(fake.calls.length, 0); + } finally { + fake.restore(); + restoreKey(); + } +}); + +/** Spec example body of a SendGrid response (components.responses.PostMailSend). */ +function sendGridExample(status) { + const response = sgMail.spec.components.responses[`PostMailSend${status}`]; + return Object.values(response.content['application/json'].examples)[0].value; +} + +test('SendGrid responses: 202 with X-Message-Id, documented errors, sandbox 200', async () => { + const restoreKey = withEncryptionKey(); + try { + const url = 'https://api.sendgrid.com/v3/mail/send'; + assert.deepEqual(sgMail.checkResponse({ method: 'POST', url, status: 202 }), []); + let fake = fakeFetch(() => jsonResponse(202, undefined, { 'x-message-id': 'sgid-1' })); + const { router } = createHarness([]); + const message = () => ({ to: 'a@example.test', subject: 's', text: 't' }); + assert.equal( + (await router.sendViaSendGrid(accountFor('sendgrid'), message())).messageId, + 'sgid-1' + ); + fake.restore(); + + for (const status of [400, 401, 403, 413]) { + const example = sendGridExample(status); + // A body that echoes an address must never reach the caller. + const body = { + errors: [ + ...example.errors, + { message: 'leak@example.test is invalid', field: 'personalizations.0.to.0.email' }, + ], + }; + assert.deepEqual(sgMail.checkResponse({ method: 'POST', url, status, json: body }), []); + fake = fakeFetch(() => jsonResponse(status, body)); + const error = await router.sendViaSendGrid(accountFor('sendgrid'), message()).catch((e) => e); + fake.restore(); + assert.equal(error.status, status); + assert.equal(error.provider, 'sendgrid'); + assert.deepEqual(error.providerFields, ['personalizations.0.to.0.email']); + const client = toClientSendMessage(error); + assert.equal(client, `SendGrid API request failed: ${status}`); + assert.ok(!JSON.stringify({ ...error, client }).includes('leak@example.test')); + assert.equal( + classifyDeliveryError(error), + status === 401 || status === 403 ? 'transient' : 'permanent' + ); + } + + // Sandbox mode answers 200 without X-Message-Id (Sandbox Mode docs); + // the spec lists only 202, so the response is not contract-checked. + fake = fakeFetch(() => jsonResponse(200)); + assert.deepEqual(await router.sendViaSendGrid(accountFor('sendgrid'), message()), { + messageId: null, + response: 'Accepted', + }); + fake.restore(); + } finally { + restoreKey(); + } +}); + +test('Mailgun: the full form matches the spec (h:, inline, attachment, o:tracking-*, o:tag, v:)', async () => { + const call = await capture( + 'mailgun', + { + to: ['Ada ', 'bob@example.test'], + cc: 'carol@example.test', + bcc: 'dave@example.test', + subject: 'All fields', + text: 'plain', + html: '

Hi

Shop', + replyTo: 'support@example.test', + headers: { 'X-Campaign': 'c1' }, + type: 'marketing', + priority: 'low', + unsubscribeUrl: 'https://example.test/u', + attachments: [ + { cid: 'logo.png', content: PIXEL_PNG, encoding: 'base64', contentType: 'image/png' }, + { filename: 'r.txt', content: 'receipt', contentType: 'text/plain' }, + ], + }, + { region: 'eu' } + ); + assertMailgunRequest(call); + const values = (name) => call.form.filter(([key]) => key === name).map(([, value]) => value); + assert.deepEqual(values('h:Reply-To'), ['support@example.test']); + assert.deepEqual(values('h:X-Campaign'), ['c1']); + assert.deepEqual(values('o:tracking-opens'), ['no']); + assert.deepEqual(values('o:tracking-clicks'), ['no']); + assert.deepEqual(values('o:tag'), ['marketing']); + assert.deepEqual(values('v:magicmail_email_type'), ['marketing']); + assert.deepEqual(values('v:magicmail_priority'), ['low']); + assert.deepEqual(values('v:magicmail_id'), ['logdoc123']); + assert.deepEqual(call.files, [ + { field: 'inline', filename: 'logo.png', type: 'image/png', size: 68 }, + { field: 'attachment', filename: 'r.txt', type: 'text/plain', size: 7 }, + ]); + assert.equal(call.url, 'https://api.eu.mailgun.net/v3/mg.example.test/messages'); +}); + +test('Mailgun: region URLs are the spec servers', async () => { + const us = await capture('mailgun', { to: 'a@example.test', subject: 's', text: 't' }); + const eu = await capture( + 'mailgun', + { to: 'a@example.test', subject: 's', text: 't' }, + { + region: 'eu', + } + ); + assertMailgunRequest(us); + assertMailgunRequest(eu); + assert.deepEqual( + mailgun.spec.servers.map((server) => new URL(server.url).host).sort(), + [new URL(us.url).host, new URL(eu.url).host].sort() + ); +}); + +test('Mailgun responses: 200 id without brackets; 400 permanent; 401 "Forbidden" and 429 transient; 500 ambiguous', async () => { + const restoreKey = withEncryptionKey(); + try { + const url = 'https://api.mailgun.net/v3/mg.example.test/messages'; + const op = mailgun.spec.paths['/v3/{domain_name}/messages'].post; + const example = (status) => + Object.values(op.responses[status].content['application/json'].examples)[0].value; + const { router } = createHarness([]); + const message = () => ({ to: 'a@example.test', subject: 's', text: 't' }); + + const ok = { id: '<20261118.1@mg.example.test>', message: 'Queued. Thank you.' }; + assert.deepEqual(mailgun.checkResponse({ method: 'POST', url, status: 200, json: ok }), []); + let fake = fakeFetch(() => jsonResponse(200, ok)); + const result = await router.sendViaMailgun(accountFor('mailgun'), message()); + fake.restore(); + assert.equal(result.messageId, '20261118.1@mg.example.test'); + + const expected = { 400: 'permanent', 401: 'transient', 429: 'transient', 500: 'ambiguous' }; + for (const [status, errorClass] of Object.entries(expected)) { + const body = example(status); + assert.deepEqual( + mailgun.checkResponse({ method: 'POST', url, status: Number(status), json: body }), + [], + `fake ${status} matches the spec` + ); + fake = fakeFetch(() => jsonResponse(Number(status), body)); + const error = await router.sendViaMailgun(accountFor('mailgun'), message()).catch((e) => e); + fake.restore(); + assert.equal(error.status, Number(status)); + assert.equal(error.provider, 'mailgun'); + assert.equal(classifyDeliveryError(error), errorClass, `status ${status}`); + assert.equal(toClientSendMessage(error), `Mailgun API request failed: ${status}`); + } + } finally { + restoreKey(); + } +}); diff --git a/tests/provider-send-paths.test.js b/tests/provider-send-paths.test.js new file mode 100644 index 0000000..f6372f2 --- /dev/null +++ b/tests/provider-send-paths.test.js @@ -0,0 +1,842 @@ +'use strict'; + +// Behaviour tests for the SendGrid and Mailgun send paths: recipient +// de-duplication and display names, reserved headers, size and option +// limits, provider error handling, correlation id, provider tracking +// switches, Mailgun metadata, inline files and the SendGrid EU region. +// Synthetic data only; every provider call goes to a fake fetch. + +const test = require('node:test'); +const assert = require('node:assert/strict'); + +const { + PIXEL_PNG, + accountFor, + createHarness, + fakeFetch, + jsonResponse, + withEncryptionKey, +} = require('./helpers/provider-send-harness'); + +const routerInternals = () => require('../server/src/services/email-router').__test__; + +/** + * Runs `fn` with an encryption key and a fake fetch, restoring both. + * + * @param {Function} [respond] + * @param {(fetchCalls: object[]) => Promise} fn + */ +async function withFetch(respond, fn) { + const restoreKey = withEncryptionKey(); + const fake = fakeFetch(respond); + try { + await fn(fake.calls); + } finally { + fake.restore(); + restoreKey(); + } +} + +const formValues = (call, name) => call.form.filter(([key]) => key === name).map(([, v]) => v); + +// ── SG-1 / SG-9: recipients ──────────────────────────────────────────────── + +test('SG-1: every address is sent once across to, cc and bcc (first occurrence wins)', async () => { + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('sendgrid')]); + await router.send({ + to: ['dup@example.test', 'other@example.test', 'OTHER@example.test'], + cc: ['DUP@example.test', 'carol@example.test'], + bcc: 'carol@example.test, Dup@Example.test', + subject: 'Dedupe', + text: 'body', + }); + const [personalization] = calls[0].json.personalizations; + assert.deepEqual(personalization.to, [ + { email: 'dup@example.test' }, + { email: 'other@example.test' }, + ]); + assert.deepEqual(personalization.cc, [{ email: 'carol@example.test' }]); + assert.equal(personalization.bcc, undefined, 'an empty bcc list is left out'); + }); +}); + +test('SG-1: a cc list that only repeats to-addresses is left out', async () => { + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('sendgrid')]); + await router.sendViaSendGrid(accountFor('sendgrid'), { + to: 'a@example.test', + cc: 'A@EXAMPLE.TEST', + subject: 'x', + text: 'y', + }); + assert.equal(calls[0].json.personalizations[0].cc, undefined); + }); +}); + +test('SG-9: SendGrid recipients keep their display names', async () => { + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('sendgrid')]); + await router.send({ + to: 'Ada Lovelace ', + cc: ['"Bob, Ops" '], + bcc: 'carol@example.test', + subject: 'Names', + text: 'body', + }); + const [personalization] = calls[0].json.personalizations; + // send() lower-cases addresses for every provider (unchanged 4.x behaviour). + assert.deepEqual(personalization.to, [{ email: 'ada@example.test', name: 'Ada Lovelace' }]); + assert.deepEqual(personalization.cc, [{ email: 'bob@example.test', name: 'Bob, Ops' }]); + assert.deepEqual(personalization.bcc, [{ email: 'carol@example.test' }]); + }); +}); + +test('sendGridRecipients strips CR/LF from names and ignores groups', () => { + const { sendGridRecipients } = routerInternals(); + const result = sendGridRecipients({ + to: [{ name: 'Eve\r\nBcc: x@example.test', address: 'eve@example.test' }], + cc: 'Team: a@example.test;', + }); + assert.deepEqual(result.to, [{ email: 'eve@example.test', name: 'EveBcc: x@example.test' }]); + assert.deepEqual(result.cc, []); +}); + +// ── SG-3: reserved headers ──────────────────────────────────────────────── + +test('SG-3: X-SG-ID and X-SG-EID are never passed on, in any spelling', async () => { + const { buildOutboundHeaders } = routerInternals(); + const headers = buildOutboundHeaders({ + type: 'transactional', + headers: { 'X-SG-ID': 'a', 'x-sg-eid': 'b', 'X-Sg-Id': 'c', 'X-Custom': 'z' }, + }); + assert.equal(headers['X-Custom'], 'z'); + assert.deepEqual( + Object.keys(headers).filter((name) => /^x-sg-/i.test(name)), + [] + ); + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('sendgrid')]); + await router.send({ + to: 'a@example.test', + subject: 's', + text: 't', + headers: { 'X-SG-ID': 'spoof' }, + }); + assert.ok(!Object.keys(calls[0].json.headers).some((name) => /^x-sg-/i.test(name))); + }); +}); + +// ── MG-SEND-2: header budget ────────────────────────────────────────────── + +test('MG-SEND-2: caller headers are limited to 8 KB in total (service and Content API)', () => { + const { filterCustomHeaders, MAX_CUSTOM_HEADER_BYTES } = routerInternals(); + assert.equal(MAX_CUSTOM_HEADER_BYTES, 8192); + const big = {}; + for (let i = 0; i < 5; i += 1) big[`X-Big-${i}`] = 'v'.repeat(3000); + const kept = filterCustomHeaders(big); + const bytes = Object.entries(kept).reduce( + (sum, [k, v]) => sum + Buffer.byteLength(k) + Buffer.byteLength(v), + 0 + ); + assert.equal(Object.keys(kept).length, 2); + assert.ok(bytes <= 8192); + + // Content API: each value is at most 1000 characters; 9 of them exceed 8 KB. + const { validate } = require('../server/src/validation'); + const headersOf = (count) => + Object.fromEntries(Array.from({ length: count }, (_, i) => [`X-H${i}`, 'v'.repeat(1000)])); + assert.throws( + () => + validate('content.send', { + to: 'a@example.test', + subject: 's', + text: 't', + headers: headersOf(9), + }), + (error) => + error.name === 'ValidationError' && + JSON.stringify(error.details).includes('at most 8 KB in total') + ); + const ok = validate('content.send', { + to: 'a@example.test', + subject: 's', + text: 't', + headers: headersOf(8), + }); + assert.equal(Object.keys(ok.headers).length, 8); +}); + +test('MG-SEND-2: Mailgun send options above 16 KB are refused before any request', async () => { + const { mailgunOptionBytes } = routerInternals(); + const form = new FormData(); + form.append('to', 'x'.repeat(20000)); + form.append('h:X-A', 'abc'); + form.append('v:magicmail_priority', 'é'); + assert.equal(mailgunOptionBytes(form), 'h:X-A'.length + 3 + 'v:magicmail_priority'.length + 2); + + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('mailgun')]); + // 10 addresses of 300+ characters each in h:Reply-To push the options over 16 KB. + const replyTo = Array.from( + { length: 10 }, + (_, i) => `${String(i).padStart(2, '0')}${'r'.repeat(250)}@${'d'.repeat(60)}.example.test` + ); + const headers = { 'X-Pad-1': 'p'.repeat(3900), 'X-Pad-2': 'p'.repeat(3900) }; + await assert.rejects( + router.sendViaMailgun(accountFor('mailgun'), { + to: 'a@example.test', + subject: 's', + text: 't', + replyTo, + headers, + unsubscribeUrl: `https://example.test/u?${'q'.repeat(6000)}`, + type: 'marketing', + }), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' && error.name === 'ValidationError' + ); + assert.equal(calls.length, 0, 'no request was made'); + }); +}); + +test('MG-SEND-2: options just under 16 KB still reach Mailgun', async () => { + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('mailgun')]); + await router.sendViaMailgun(accountFor('mailgun'), { + to: 'a@example.test', + subject: 's', + text: 't', + headers: { 'X-Pad-1': 'p'.repeat(3990), 'X-Pad-2': 'p'.repeat(3990) }, + }); + assert.equal(calls.length, 1); + }); +}); + +// ── SG-7 / MG-SEND-1: message size ──────────────────────────────────────── + +test('SG-7/MG-SEND-1: attachments over 40 MB in total are refused for every provider', () => { + const { normalizeAttachments, MAX_TOTAL_ATTACHMENT_BYTES } = routerInternals(); + const chunk = Buffer.alloc(15 * 1024 * 1024, 1); + assert.equal(normalizeAttachments([{ content: chunk }, { content: chunk }]).length, 2); + assert.throws( + () => normalizeAttachments([{ content: chunk }, { content: chunk }, { content: chunk }]), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' && error.name === 'ValidationError' + ); + assert.equal(MAX_TOTAL_ATTACHMENT_BYTES, 40 * 1024 * 1024); +}); + +test('SG-7: a SendGrid body of 30 MB or more never reaches fetch', async () => { + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('sendgrid')]); + await assert.rejects( + router.sendViaSendGrid(accountFor('sendgrid'), { + to: 'a@example.test', + subject: 's', + text: 't', + // 23 MB raw is about 30.7 MB as base64 JSON. + attachments: [{ filename: 'big.bin', content: Buffer.alloc(23 * 1000 * 1000, 7) }], + }), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' + ); + assert.equal(calls.length, 0); + await router.sendViaSendGrid(accountFor('sendgrid'), { + to: 'a@example.test', + subject: 's', + text: 't', + attachments: [{ filename: 'ok.bin', content: Buffer.alloc(20 * 1000 * 1000, 7) }], + }); + assert.equal(calls.length, 1); + assert.ok(calls[0].bodyBytes < 30_000_000); + }); +}); + +test('MG-SEND-1: a Mailgun message estimated at 25 MB or more never reaches fetch', async () => { + const { estimateMailgunMessageBytes } = routerInternals(); + const form = new FormData(); + form.append('text', 'abc'); + form.append('attachment', new Blob([Buffer.alloc(3000)]), 'a.bin'); + assert.equal(estimateMailgunMessageBytes(form), 4 + 3 + 4000 + Math.ceil(4000 / 76) * 2); + + await withFetch(undefined, async (calls) => { + const { router } = createHarness([accountFor('mailgun')]); + await assert.rejects( + router.sendViaMailgun(accountFor('mailgun'), { + to: 'a@example.test', + subject: 's', + text: 't', + attachments: [{ filename: 'big.bin', content: Buffer.alloc(19 * 1000 * 1000, 7) }], + }), + (error) => error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' + ); + assert.equal(calls.length, 0); + }); +}); + +test('SG-7/MG-SEND-1: HTTP 413 maps to MAGIC_MAIL_MESSAGE_TOO_LARGE for both providers', async () => { + for (const provider of ['sendgrid', 'mailgun']) { + await withFetch( + () => jsonResponse(413, { errors: [{ message: 'content too large', field: null }] }), + async () => { + const { router } = createHarness([accountFor(provider)]); + const send = provider === 'sendgrid' ? router.sendViaSendGrid : router.sendViaMailgun; + await assert.rejects( + send.call(router, accountFor(provider), { + to: 'a@example.test', + subject: 's', + text: 't', + }), + (error) => + error.status === 413 && + error.code === 'MAGIC_MAIL_MESSAGE_TOO_LARGE' && + error.message === + `${provider === 'sendgrid' ? 'SendGrid' : 'Mailgun'} API request failed: 413` + ); + } + ); + } +}); + +// ── SG-5: provider errors ───────────────────────────────────────────────── + +test('SG-5: SendGrid errors keep status, provider and allowlisted fields, never the text', async () => { + const body = { + errors: [ + { message: 'Invalid address dup@example.test', field: 'personalizations.0.cc.0.email' }, + { message: 'x', field: 'personalizations[1].to' }, + { message: 'x', field: 'evil