diff --git a/CHANGELOG.md b/CHANGELOG.md index 6c9df5e..d79e1ee 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,15 @@ ## [Unreleased] +### Added + +* **Admin password reset through a provider template.** The admin panel's "Forgot password?" mail is the third core email (`admin-forgot-password`). Magic Mail recognises the `sendTemplatedEmail` call of `@strapi/admin` 5.x and, when a SendGrid or Mailgun template is chosen under **Email Templates → Core emails → Design** (super admins only), sends it with payload v1 `{ user, url, token, adminUrl, serverUrl, meta }`. Strict by default; **send the Strapi admin email instead** is the opt-in fallback. Without a choice nothing changes. +* **Startup check of core-email templates.** About 20 seconds after start (non-blocking) every core email that uses a provider template is checked; a stale template list is synced first. Unsynced or unusable templates, and Mailgun templates without a Subject header (`MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT`; core emails do not pass the Strapi subject on), are logged with type, key and code (never values), and the dashboard and Core emails notices name each affected mail with its reason and the time of the check. +* **Events** `magic-mail.provider-template.failed` and `magic-mail.provider-template.fallback` on `strapi.eventHub` with `{ key, code, coreEmailType, fallback? }` (no personal data). +* **`meta.strapiVersion`** in the core-email payload v1 (additive), and a one-time warning per core email when `url` can not be built because the base URL is empty or relative. +* **SendGrid subject for dynamic templates.** A `subject` passed with a SendGrid provider template is copied into `dynamic_template_data.subject` when the data has none, so a template whose subject line is `{{subject}}` renders it (SendGrid ignores the top-level subject for dynamic templates). +* **Test sends** of a provider template used by several core emails include sample values for every one of them. +* **Docs:** what a provider template replaces for core emails (subject, body, shipper email) and how Reply-To is kept; a short hint in the Core emails tab. + ### Fixed * **Mailgun: a template deleted at Mailgun is no longer logged as sent.** Mailgun accepts a send that names a template it does not have (200 "Queued") and drops the message afterwards (event `failed`, delivery-status 621 "Template not found", retried every 10 minutes). Before a template send MagicMail now checks the template at Mailgun (`GET /v3/{domain}/templates/{name}?active=yes`, account-level templates `GET /v4/templates/{name}?active=yes`). A deleted template, or one without an active version, fails with `MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE` before any message is sent: another account that still has the template sends instead, else the configured Magic Mail fallback template, else the error is returned and the delivery log row is `failed`. A successful check is cached for 60 seconds per account and template (one extra request per template and minute for bulk sends, parallel sends share one check). If the check itself fails (network, timeout, 401/403, 429, 5xx), the send goes ahead and a warning is logged. @@ -8,6 +18,8 @@ ### Migration * Nothing to do. Mailgun template sends make one extra read request per template and minute; the API key needs read access to templates, which provider-template sync already requires. Addresses suppressed earlier because of a Mailgun `espblock` can be removed under **Plugin Settings → Bounces and recipient checks → Suppressed recipients** (source `mailgun`, reason code `MAILGUN_ESPBLOCK_*`). +* Nothing to do. Core-email payload v1 only gains keys (`meta.strapiVersion`); existing keys and the golden SendGrid/Mailgun payloads are unchanged. `GET /designer/core-designs` returns a third entry `admin-forgot-password` and new fields (`problem`, `lastSyncedAt`, `checkedAt`, `editable`). SendGrid template sends with a `subject` and no `subject` in `data` now carry `subject` in `dynamic_template_data`; templates that do not use `{{subject}}` render as before. + # [4.9.0](https://github.com/Schero94/Magic-Mail/compare/v4.8.0...v4.9.0) (2026-11-19) diff --git a/README.md b/README.md index 459073b..243177b 100644 --- a/README.md +++ b/README.md @@ -27,7 +27,7 @@ MagicMail sends email only. It is MIT licensed, with no license key, tiers or us - **Outbox with retries.** Opt-in per send or for every failed send: 3 retries by default (after 1, 5 and 15 minutes, configurable from 1 to 10), idempotency keys, and an Outbox tab where you retry, discard or mark uncertain mails as sent. - **Delivery webhooks.** Verified SendGrid, Mailgun, Brevo and Amazon SES (SNS) webhooks record bounces, blocks, complaints, deferrals, deliveries and unsubscribes on the delivery log, feed the suppression list and emit events other plugins can listen to. - **Templates.** A visual editor (Unlayer) or plain HTML and text, Mustache variables, versions with restore, import and export, plus the Users & Permissions reset and confirmation mails. -- **Provider templates.** Keep designing in SendGrid, Mailgun, Brevo or Amazon SES: their templates appear read-only in MagicMail, with preview, test send, language versions and the same template data your code already passes. Routing, failover and logs stay in MagicMail, and the password-reset and confirmation mails can use them too. +- **Provider templates.** Keep designing in SendGrid, Mailgun, Brevo or Amazon SES: their templates appear read-only in MagicMail, with preview, test send, language versions and the same template data your code already passes. Routing, failover and logs stay in MagicMail, and the password-reset, confirmation and admin password-reset mails can use them too ([core emails](https://github.com/Schero94/Magic-Mail/blob/main/docs/sending.md#provider-templates-sendgrid-mailgun-brevo-amazon-ses)). - **Analytics.** A delivery log with server-side search, open and click tracking with truncated IPs and configurable retention. - **Several instances.** Railway replicas or pm2 workers on one database work without sticky sessions or Redis. - **Admin in five languages.** English, German, French, Spanish and Portuguese, in light and dark mode. diff --git a/admin/src/pages/EmailDesigner/TemplateList.jsx b/admin/src/pages/EmailDesigner/TemplateList.jsx index eb0d973..e4801f2 100644 --- a/admin/src/pages/EmailDesigner/TemplateList.jsx +++ b/admin/src/pages/EmailDesigner/TemplateList.jsx @@ -72,6 +72,7 @@ import { useProviderTemplates } from './providerTemplates/useProviderTemplates'; import { ProviderTemplatesSection } from './providerTemplates/ProviderTemplatesSection'; import { ProviderTemplateDialog } from './providerTemplates/ProviderTemplateDialog'; import { CoreDesignDialog } from './providerTemplates/CoreDesignDialog'; +import { CORE_DESIGN_PROBLEMS } from './providerTemplates/CoreDesignAlert'; import { Notice } from './providerTemplates/Notice'; import { providerName, statusInfo } from './providerTemplates/providerTemplateUtils'; import { @@ -173,6 +174,16 @@ const TemplateList = () => { 'Sent to confirm a user email address' ), }, + { + type: 'admin-forgot-password', + name: t('templates.core.adminForgotPassword.name', 'Admin password reset'), + description: t( + 'templates.core.adminForgotPassword.description', + 'Sent when an admin panel user requests a password reset. The local version comes from the Strapi admin configuration.' + ), + // Rendered by @strapi/admin from config; Magic Mail only offers the design choice. + designOnly: true, + }, ]; // Without read permission nothing is requested, so nothing is loading. @@ -781,6 +792,10 @@ const TemplateList = () => { }; const showDesignColumn = providerEnabled && coreDesigns !== null; + // The admin password reset has no Magic Mail editor: listed only with the design column. + const visibleCoreEmails = coreEmailTypes.filter( + (coreEmail) => !coreEmail.designOnly || showDesignColumn + ); const unusableCoreDesigns = showDesignColumn ? coreEmailTypes.filter((coreEmail) => coreDesigns[coreEmail.type]?.usable === false) : []; @@ -795,7 +810,11 @@ const TemplateList = () => { ); } - const status = statusInfo(design.status); + // A usable template can still be unusable for core emails (Mailgun without Subject header). + const status = + design.problem === 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT' + ? { tone: 'danger', id: 'templates.coreDesign.badge.noSubject', label: 'No Subject header' } + : statusInfo(design.status); return ( @@ -887,6 +906,14 @@ const TemplateList = () => { 'Design the default Strapi system emails (password reset and email confirmation).' )} + {showDesignColumn ? ( + + {t( + 'templates.core.providerHint', + 'With a provider template, the subject and body from Users & Permissions or the admin configuration are not used; the provider template renders them. The sender address is always the verified address of the Magic Mail account. A Reply-To set in Strapi is kept.' + )} + + ) : null} {unusableCoreDesigns.length > 0 ? ( @@ -902,14 +929,30 @@ const TemplateList = () => { {t( 'templates.coreDesign.staleBody', '{names}: these emails fail until the template is available again and synced, or until you switch back to the Magic Mail designer.', - { names: unusableCoreDesigns.map((coreEmail) => coreEmail.name).join(', ') } + { + names: unusableCoreDesigns + .map((coreEmail) => { + const problem = + CORE_DESIGN_PROBLEMS[coreDesigns?.[coreEmail.type]?.problem]; + return problem + ? t('templates.coreDesign.problemItem', '{name} ({reason})', { + name: coreEmail.name, + reason: t(problem.id, problem.label), + }) + : coreEmail.name; + }) + .join(', '), + } )} ) : null} - + {t('templates.core.table.type', 'Email type')} @@ -922,7 +965,7 @@ const TemplateList = () => { - {coreEmailTypes.map((coreEmail) => ( + {visibleCoreEmails.map((coreEmail) => ( { ) : null} - {showDesignColumn && canManage ? ( + {showDesignColumn && + canManage && + coreDesigns?.[coreEmail.type]?.editable !== false ? ( { ) : null} - - navigate(`/plugins/magic-mail/designer/core/${coreEmail.type}`) - } - > - {canManage ? + {coreEmail.designOnly ? null : ( + + navigate(`/plugins/magic-mail/designer/core/${coreEmail.type}`) + } + > + {canManage ? ( + + )} diff --git a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx index 1690081..ad968cd 100644 --- a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx +++ b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignAlert.jsx @@ -4,6 +4,7 @@ import { useNavigate } from 'react-router-dom'; import { Box } from '@strapi/design-system'; import { TertiaryButton } from '../../../components/StyledButtons'; import { useMagicMailIntl } from '../../../hooks/useMagicMailIntl'; +import { useFormatters } from '../../../hooks/useFormatters'; import { Notice } from './Notice'; const CORE_NAMES = { @@ -12,18 +13,41 @@ const CORE_NAMES = { id: 'templates.core.emailConfirmation.name', label: 'Email address confirmation', }, + 'admin-forgot-password': { + id: 'templates.core.adminForgotPassword.name', + label: 'Admin password reset', + }, +}; + +/** Reason text per problem code of a core email design. */ +export const CORE_DESIGN_PROBLEMS = { + MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN: { + id: 'templates.coreDesign.problem.unknown', + label: 'not synced', + }, + MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE: { + id: 'templates.coreDesign.problem.unavailable', + label: 'deleted or unpublished at the provider', + }, + MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT: { + id: 'templates.coreDesign.problem.noSubject', + label: 'the Mailgun template has no Subject header', + }, }; /** - * Dashboard notice: a core email uses a provider template that is deleted or - * has no active version, so those emails fail. Renders nothing otherwise, and - * nothing without a SendGrid or Mailgun account (`enabled`). + * Dashboard notice: a core email uses a provider template that is not synced, + * deleted or has no active version, so those emails fail. Names each core + * email with the reason (the same check the server runs after start) and the + * time of the last check. Renders nothing otherwise, and nothing without a + * provider-template account (`enabled`). * * @param {{enabled: boolean}} props * @returns {import('react').ReactElement|null} */ export const CoreDesignAlert = ({ enabled }) => { const { t } = useMagicMailIntl(); + const { formatDateTime } = useFormatters(); const { get } = useFetchClient(); const navigate = useNavigate(); const [designs, setDesigns] = useState(null); @@ -47,6 +71,22 @@ export const CoreDesignAlert = ({ enabled }) => { const broken = Object.entries(designs ?? {}).filter(([, design]) => design?.usable === false); if (!enabled || broken.length === 0) return null; + const describe = ([type, design]) => { + const name = t(CORE_NAMES[type]?.id ?? type, CORE_NAMES[type]?.label ?? type); + const problem = CORE_DESIGN_PROBLEMS[design?.problem]; + return problem + ? t('templates.coreDesign.problemItem', '{name} ({reason})', { + name, + reason: t(problem.id, problem.label), + }) + : name; + }; + const checkedAt = broken + .map(([, design]) => design?.checkedAt) + .filter((value) => typeof value === 'string' && !Number.isNaN(Date.parse(value))) + .sort() + .pop(); + return ( { {t( 'templates.coreDesign.staleBody', '{names}: these emails fail until the template is available again and synced, or until you switch back to the Magic Mail designer.', - { - names: broken - .map(([type]) => t(CORE_NAMES[type]?.id ?? type, CORE_NAMES[type]?.label ?? type)) - .join(', '), - } + { names: broken.map(describe).join(', ') } )} + {checkedAt ? ( + <> + {' '} + {t('templates.coreDesign.checkedAt', 'Last checked: {date}.', { + date: formatDateTime(checkedAt), + })} + + ) : null} ); diff --git a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx index 9141676..d5318f4 100644 --- a/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx +++ b/admin/src/pages/EmailDesigner/providerTemplates/CoreDesignDialog.jsx @@ -182,6 +182,18 @@ export const CoreDesignDialog = ({ coreEmail, design, templates, onClose, onSave ) : null} + {choice !== DESIGNER && + selected?.usable && + selected.provider === 'mailgun' && + !selected.subject ? ( + + {t( + 'templates.coreDesign.noSubject', + 'This Mailgun template has no Subject header. Core emails sent with it fail; add a Subject header to the template at Mailgun and sync.' + )} + + ) : null} + {choice !== DESIGNER ? ( <> @@ -230,10 +242,15 @@ export const CoreDesignDialog = ({ coreEmail, design, templates, onClose, onSave onCheckedChange={(value) => setFallback(value === true)} disabled={saving} > - {t( - 'templates.coreDesign.fallback', - 'If the provider template fails, send the Magic Mail designer version instead' - )} + {coreEmail?.type === 'admin-forgot-password' + ? t( + 'templates.coreDesign.fallbackAdmin', + 'If the provider template fails, send the Strapi admin email instead' + ) + : t( + 'templates.coreDesign.fallback', + 'If the provider template fails, send the Magic Mail designer version instead' + )} diff --git a/admin/src/translations/de.json b/admin/src/translations/de.json index 1d27b9e..03592f4 100644 --- a/admin/src/translations/de.json +++ b/admin/src/translations/de.json @@ -1151,5 +1151,16 @@ "accounts.test.hint.credentials": "Die gespeicherten Zugangsdaten können nicht gelesen werden. Öffnen Sie das Konto, geben Sie die Zugangsdaten erneut ein und speichern Sie.", "accounts.test.hint.auth": "Der Anbieter hat die Zugangsdaten abgelehnt. Prüfen Sie den Schlüssel und seine Berechtigungen.", "accounts.test.hint.unavailable": "Der Anbieter war nicht erreichbar. Prüfen Sie die Netzwerkverbindung des Servers und versuchen Sie es erneut.", - "accountModal.providers.beta": "Beta" + "accountModal.providers.beta": "Beta", + "templates.core.adminForgotPassword.name": "Admin-Passwort zurücksetzen", + "templates.core.adminForgotPassword.description": "Wird gesendet, wenn ein Benutzer des Admin-Panels ein neues Passwort anfordert. Die lokale Version stammt aus der Strapi-Admin-Konfiguration.", + "templates.core.providerHint": "Mit einer Anbietervorlage werden Betreff und Inhalt aus Users & Permissions bzw. der Admin-Konfiguration nicht verwendet; die Anbietervorlage erzeugt sie. Als Absenderadresse dient immer die verifizierte Adresse des Magic-Mail-Kontos. Eine in Strapi festgelegte Antwortadresse (Reply-To) bleibt erhalten.", + "templates.coreDesign.fallbackAdmin": "Wenn die Anbietervorlage fehlschlägt, stattdessen die Strapi-Admin-E-Mail senden", + "templates.coreDesign.problem.unknown": "nicht synchronisiert", + "templates.coreDesign.problem.unavailable": "beim Anbieter gelöscht oder nicht veröffentlicht", + "templates.coreDesign.problemItem": "{name} ({reason})", + "templates.coreDesign.checkedAt": "Zuletzt geprüft: {date}.", + "templates.coreDesign.problem.noSubject": "die Mailgun-Vorlage hat keinen Subject-Header", + "templates.coreDesign.noSubject": "Diese Mailgun-Vorlage hat keinen Subject-Header. Kern-E-Mails mit dieser Vorlage schlagen fehl; ergänzen Sie bei Mailgun einen Subject-Header und synchronisieren Sie anschließend.", + "templates.coreDesign.badge.noSubject": "Kein Subject-Header" } diff --git a/admin/src/translations/en.json b/admin/src/translations/en.json index bc6dd88..83a2e87 100644 --- a/admin/src/translations/en.json +++ b/admin/src/translations/en.json @@ -1151,5 +1151,16 @@ "accounts.test.hint.credentials": "The stored credentials can not be read. Open the account, enter the credentials again and save.", "accounts.test.hint.auth": "The provider rejected the credentials. Check the key and its permissions.", "accounts.test.hint.unavailable": "The provider could not be reached. Check the network connection of the server and try again.", - "accountModal.providers.beta": "Beta" + "accountModal.providers.beta": "Beta", + "templates.core.adminForgotPassword.name": "Admin password reset", + "templates.core.adminForgotPassword.description": "Sent when an admin panel user requests a password reset. The local version comes from the Strapi admin configuration.", + "templates.core.providerHint": "With a provider template, the subject and body from Users & Permissions or the admin configuration are not used; the provider template renders them. The sender address is always the verified address of the Magic Mail account. A Reply-To set in Strapi is kept.", + "templates.coreDesign.fallbackAdmin": "If the provider template fails, send the Strapi admin email instead", + "templates.coreDesign.problem.unknown": "not synced", + "templates.coreDesign.problem.unavailable": "deleted or unpublished at the provider", + "templates.coreDesign.problemItem": "{name} ({reason})", + "templates.coreDesign.checkedAt": "Last checked: {date}.", + "templates.coreDesign.problem.noSubject": "the Mailgun template has no Subject header", + "templates.coreDesign.noSubject": "This Mailgun template has no Subject header. Core emails sent with it fail; add a Subject header to the template at Mailgun and sync.", + "templates.coreDesign.badge.noSubject": "No Subject header" } diff --git a/admin/src/translations/es.json b/admin/src/translations/es.json index dba8de9..8d23e7e 100644 --- a/admin/src/translations/es.json +++ b/admin/src/translations/es.json @@ -1151,5 +1151,16 @@ "accounts.test.hint.credentials": "No se pueden leer las credenciales guardadas. Abra la cuenta, vuelva a introducir las credenciales y guarde.", "accounts.test.hint.auth": "El proveedor ha rechazado las credenciales. Compruebe la clave y sus permisos.", "accounts.test.hint.unavailable": "No se pudo contactar con el proveedor. Compruebe la conexión de red del servidor y vuelva a intentarlo.", - "accountModal.providers.beta": "Beta" + "accountModal.providers.beta": "Beta", + "templates.core.adminForgotPassword.name": "Restablecer contraseña de administrador", + "templates.core.adminForgotPassword.description": "Se envía cuando un usuario del panel de administración solicita restablecer su contraseña. La versión local procede de la configuración de administración de Strapi.", + "templates.core.providerHint": "Con una plantilla del proveedor no se usan el asunto ni el cuerpo de Users & Permissions o de la configuración de administración; los genera la plantilla del proveedor. La dirección del remitente es siempre la dirección verificada de la cuenta de Magic Mail. Se mantiene el Reply-To configurado en Strapi.", + "templates.coreDesign.fallbackAdmin": "Si la plantilla del proveedor falla, enviar en su lugar el correo de administración de Strapi", + "templates.coreDesign.problem.unknown": "no sincronizada", + "templates.coreDesign.problem.unavailable": "eliminada o no publicada en el proveedor", + "templates.coreDesign.problemItem": "{name} ({reason})", + "templates.coreDesign.checkedAt": "Última comprobación: {date}.", + "templates.coreDesign.problem.noSubject": "la plantilla de Mailgun no tiene encabezado Subject", + "templates.coreDesign.noSubject": "Esta plantilla de Mailgun no tiene encabezado Subject. Los correos principales enviados con ella fallan; añada un encabezado Subject a la plantilla en Mailgun y sincronice.", + "templates.coreDesign.badge.noSubject": "Sin encabezado Subject" } diff --git a/admin/src/translations/fr.json b/admin/src/translations/fr.json index 30a487a..b34290f 100644 --- a/admin/src/translations/fr.json +++ b/admin/src/translations/fr.json @@ -1151,5 +1151,16 @@ "accounts.test.hint.credentials": "Les identifiants enregistrés ne peuvent pas être lus. Ouvrez le compte, saisissez de nouveau les identifiants et enregistrez.", "accounts.test.hint.auth": "Le fournisseur a refusé les identifiants. Vérifiez la clé et ses autorisations.", "accounts.test.hint.unavailable": "Le fournisseur n’a pas pu être joint. Vérifiez la connexion réseau du serveur, puis réessayez.", - "accountModal.providers.beta": "Bêta" + "accountModal.providers.beta": "Bêta", + "templates.core.adminForgotPassword.name": "Réinitialisation du mot de passe administrateur", + "templates.core.adminForgotPassword.description": "Envoyé lorsqu'un utilisateur du panneau d'administration demande la réinitialisation de son mot de passe. La version locale provient de la configuration d'administration de Strapi.", + "templates.core.providerHint": "Avec un modèle du fournisseur, l'objet et le corps de Users & Permissions ou de la configuration d'administration ne sont pas utilisés ; le modèle du fournisseur les génère. L'adresse d'expéditeur est toujours l'adresse vérifiée du compte Magic Mail. Le Reply-To défini dans Strapi est conservé.", + "templates.coreDesign.fallbackAdmin": "Si le modèle du fournisseur échoue, envoyer plutôt l'e-mail d'administration de Strapi", + "templates.coreDesign.problem.unknown": "non synchronisé", + "templates.coreDesign.problem.unavailable": "supprimé ou non publié chez le fournisseur", + "templates.coreDesign.problemItem": "{name} ({reason})", + "templates.coreDesign.checkedAt": "Dernière vérification : {date}.", + "templates.coreDesign.problem.noSubject": "le modèle Mailgun n'a pas d'en-tête Subject", + "templates.coreDesign.noSubject": "Ce modèle Mailgun n'a pas d'en-tête Subject. Les e-mails principaux envoyés avec lui échouent ; ajoutez un en-tête Subject au modèle chez Mailgun, puis synchronisez.", + "templates.coreDesign.badge.noSubject": "Pas d'en-tête Subject" } diff --git a/admin/src/translations/pt.json b/admin/src/translations/pt.json index 3128571..a0a0b2d 100644 --- a/admin/src/translations/pt.json +++ b/admin/src/translations/pt.json @@ -1151,5 +1151,16 @@ "accounts.test.hint.credentials": "Não é possível ler as credenciais armazenadas. Abra a conta, informe as credenciais novamente e salve.", "accounts.test.hint.auth": "O provedor recusou as credenciais. Verifique a chave e as permissões dela.", "accounts.test.hint.unavailable": "Não foi possível acessar o provedor. Verifique a conexão de rede do servidor e tente novamente.", - "accountModal.providers.beta": "Beta" + "accountModal.providers.beta": "Beta", + "templates.core.adminForgotPassword.name": "Redefinição de senha do administrador", + "templates.core.adminForgotPassword.description": "Enviado quando um usuário do painel de administração solicita a redefinição da senha. A versão local vem da configuração de administração do Strapi.", + "templates.core.providerHint": "Com um modelo do provedor, o assunto e o corpo de Users & Permissions ou da configuração de administração não são usados; o modelo do provedor os gera. O endereço do remetente é sempre o endereço verificado da conta do Magic Mail. O Reply-To definido no Strapi é mantido.", + "templates.coreDesign.fallbackAdmin": "Se o modelo do provedor falhar, enviar o e-mail de administração do Strapi", + "templates.coreDesign.problem.unknown": "não sincronizado", + "templates.coreDesign.problem.unavailable": "excluído ou não publicado no provedor", + "templates.coreDesign.problemItem": "{name} ({reason})", + "templates.coreDesign.checkedAt": "Última verificação: {date}.", + "templates.coreDesign.problem.noSubject": "o modelo do Mailgun não tem cabeçalho Subject", + "templates.coreDesign.noSubject": "Este modelo do Mailgun não tem cabeçalho Subject. Os e-mails principais enviados com ele falham; adicione um cabeçalho Subject ao modelo no Mailgun e sincronize.", + "templates.coreDesign.badge.noSubject": "Sem cabeçalho Subject" } diff --git a/docs/api.md b/docs/api.md index 3ff8cd1..8aa0085 100644 --- a/docs/api.md +++ b/docs/api.md @@ -108,7 +108,7 @@ All admin routes live under `/magic-mail` on the Strapi server (not `/api`), req | | `POST /designer/templates`, `PUT`/`DELETE /designer/templates/:id`, `POST /designer/templates/:id/duplicate`, `POST /designer/import`, version restore/delete routes | `manage` | | | `POST /designer/templates/:id/test-send` | `test-send` | | | `GET`/`PUT /designer/core/:coreEmailType` | `read`/`manage` + users-permissions email-template permission | -| | `GET /designer/core-designs` / `PUT /designer/core/:coreEmailType/design` | `read`/`manage` + users-permissions email-template permission | +| | `GET /designer/core-designs` / `PUT /designer/core/:coreEmailType/design` (`reset-password`, `email-confirmation`, `admin-forgot-password`; the last one only for super admins, otherwise 403; each design reports `usable`, `problem`, `checkedAt` and `editable`) | `read`/`manage` + users-permissions email-template permission | | | `GET /designer/templates/:id/provider-html` | `read` | | Provider templates | `GET /provider-templates`, `GET /provider-templates/:key`, `POST /provider-templates/sync` (read-only at the provider, 6 per minute per admin) | `read` | | | `PUT /provider-templates/:key/settings`, `POST /provider-templates/:key/copy` | `manage` | diff --git a/docs/sending.md b/docs/sending.md index b37c5bc..2e02529 100644 --- a/docs/sending.md +++ b/docs/sending.md @@ -480,32 +480,74 @@ await strapi The `data` object is the one a local template gets: MagicMail sends it as SendGrid `dynamic_template_data`, Mailgun `t:variables`, Brevo `params` or SES `TemplateData`. SendGrid, Mailgun and SES use Handlebars with top-level keys, so `{{name}}`, `{{user.email}}` and `{{{html}}}` keep their names. Brevo templates read the same data under `params`: a Brevo template writes `{{ params.name }}` and you still pass `name`; the dialog lists the variables without the `params.` prefix. Before sending, the data is converted to plain JSON: dates become ISO strings, functions and `undefined` are dropped, cycles and values such as `Map` or `BigInt` are rejected with a 400 that names the field, never the value. -| Rule | Behaviour | -| ------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Which accounts send | Only accounts where the sync found the template. Routing rules, the primary account and failover work as usual among those accounts. An explicit `accountName` without the template is an error. | -| Subject | The template's subject. SendGrid always uses the template subject (use `{{subject}}` in it and pass `subject` in `data` for a per-mail subject). Mailgun uses `subject` when you pass one and the template's Subject header otherwise; a Mailgun template without a Subject header needs `subject`. | -| Sender | The MagicMail account's verified From, as for every other mail. | -| Missing or unpublished template | A clear error naming the template (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, `MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN`). No other body is sent. Mailgun accepts a send with a template it does not have and drops the mail later, so before a Mailgun template send MagicMail checks that the template still exists with an active version (cached for 60 seconds after a successful check; if the check itself fails, the send goes ahead). | -| Fallback | Optional, per template: **Fallback template** in the dialog sends a local MagicMail template with the same `data` instead, but only when no provider accepted the message (missing template, provider refusal, no account available). An ambiguous error (for example a timeout after sending) never triggers it. | -| Size limits | Mailgun accepts 16 KB for all send options (`t:variables` plus headers); SendGrid accepts messages under 30 MB. MagicMail also bounds template data to 1 MB. Larger mails fail before anything is sent with `MAGIC_MAIL_PROVIDER_TEMPLATE_TOO_LARGE`. For Mailgun the 16 KB also include the `v:magicmail_*` variables and `o:tag` that MagicMail adds to every send. | -| Tracking | The provider renders the body, so MagicMail adds no open pixel or link tracking. With **Count provider opens and clicks** (Plugin Settings, off by default) MagicMail asks SendGrid, Mailgun and SES to track the template mail and counts their open and click webhook events in Email Analytics; Brevo tracks at account level and its `opened`/`click` events are counted the same way. See [provider opens and clicks](./delivery.md#provider-opens-and-clicks). | -| Language versions | Optional, per template: see [Language versions](#language-versions) below. | -| Log | The delivery log stores the template key and the variable names, never the values. | -| Not available | The public Content API (`/api/magic-mail/send`) does not accept `providerTemplate`; the outbox does not queue provider-template mails in this release. SMTP and OAuth accounts have no provider templates. Brevo templates can not be copied as Magic Mail templates (Brevo's own template language does not map to Mustache). SES ignores a caller `subject` for templates (SES does not allow one). | - -**Password reset and email confirmation** - -**Email Templates → Core emails → Design** chooses, per core email, the MagicMail designer (default) or a provider template. MagicMail then sends these variables (payload version 1; keys are only ever added): - -| Variable | Value | -| -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- | -| `URL`, `SERVER_URL`, `ADMIN_URL`, `TOKEN` (reset) or `CODE` (confirmation) | The same values Users & Permissions uses | -| `USER` and `user` | `id`, `email`, `username` and, when present, `firstname` and `lastname`. Never the whole user. | -| `url` | The finished link: `URL` with `code=TOKEN` (reset) or `confirmation=CODE` (confirmation), built with `URL`/`searchParams` | -| `baseUrl`, `serverUrl`, `adminUrl`, `token` or `code` | camelCase copies | -| `meta` | `templateKey`, `payloadVersion: 1`, `coreEmailType` and, when the user has a stored locale, `locale` | - -The dialog lists these names and warns about variables the template uses that MagicMail does not send. By default a failing provider template is reported as an error; tick **send the Magic Mail designer version instead** to fall back. When the chosen template is deleted or unpublished at the provider, the Core emails tab and the MagicMail dashboard show a red notice. +| Rule | Behaviour | +| ------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| Which accounts send | Only accounts where the sync found the template. Routing rules, the primary account and failover work as usual among those accounts. An explicit `accountName` without the template is an error. | +| Subject | The template's subject. SendGrid always takes the subject from the template version and ignores a top-level `subject`, so MagicMail copies a `subject` you pass into `dynamic_template_data.subject` (only when `data` has no `subject` of its own; CR/LF are removed). Write `{{subject}}` (or `{{{subject}}}` to skip HTML escaping) in the template's subject line to use it; a template without that placeholder keeps its fixed subject. Mailgun uses `subject` when you pass one and the template's Subject header otherwise; a Mailgun template without a Subject header needs `subject`. | +| Sender | The MagicMail account's verified From, as for every other mail. | +| Missing or unpublished template | A clear error naming the template (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`, `MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN`). No other body is sent. Mailgun accepts a send with a template it does not have and drops the mail later, so before a Mailgun template send MagicMail checks that the template still exists with an active version (cached for 60 seconds after a successful check; if the check itself fails, the send goes ahead). | +| Fallback | Optional, per template: **Fallback template** in the dialog sends a local MagicMail template with the same `data` instead, but only when no provider accepted the message (missing template, provider refusal, no account available). An ambiguous error (for example a timeout after sending) never triggers it. | +| Size limits | Mailgun accepts 16 KB for all send options (`t:variables` plus headers); SendGrid accepts messages under 30 MB. MagicMail also bounds template data to 1 MB. Larger mails fail before anything is sent with `MAGIC_MAIL_PROVIDER_TEMPLATE_TOO_LARGE`. For Mailgun the 16 KB also include the `v:magicmail_*` variables and `o:tag` that MagicMail adds to every send. | +| Tracking | The provider renders the body, so MagicMail adds no open pixel or link tracking. With **Count provider opens and clicks** (Plugin Settings, off by default) MagicMail asks SendGrid, Mailgun and SES to track the template mail and counts their open and click webhook events in Email Analytics; Brevo tracks at account level and its `opened`/`click` events are counted the same way. See [provider opens and clicks](./delivery.md#provider-opens-and-clicks). | +| Language versions | Optional, per template: see [Language versions](#language-versions) below. | +| Log | The delivery log stores the template key and the variable names, never the values. | +| Not available | The public Content API (`/api/magic-mail/send`) does not accept `providerTemplate`; the outbox does not queue provider-template mails in this release. SMTP and OAuth accounts have no provider templates. Brevo templates can not be copied as Magic Mail templates (Brevo's own template language does not map to Mustache). SES ignores a caller `subject` for templates (SES does not allow one). | + +**Core emails: password reset, email confirmation and admin password reset** + +**Email Templates → Core emails → Design** chooses, per core email, the MagicMail designer (default) or a provider template. The three core emails are the Users & Permissions password reset and email confirmation and, when a provider-template account exists, the **admin password reset** (the "Forgot password?" mail of the Strapi admin panel). The admin password reset has no MagicMail editor: its local version is Strapi's own template (`admin.forgotPassword.emailTemplate` in `config/admin`), and only super admins can change its design (the setting decides which template resets admin accounts). + +MagicMail sends these variables (payload version 1; keys are only ever added, never removed or renamed): + +| Variable | Value | +| -------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `URL`, `SERVER_URL`, `ADMIN_URL`, `TOKEN` (reset) or `CODE` (confirmation) | Users & Permissions mails only: the same values Users & Permissions uses | +| `USER` and `user` | `id`, `email`, `username` and, when present, `firstname` and `lastname`. Never the whole user. The admin mail has `user` only. | +| `url` | The finished link: `URL` with `code=TOKEN` (reset) or `confirmation=CODE` (confirmation), built with `URL`/`searchParams`; for the admin mail the reset link Strapi built (`/auth/reset-password?code=…`). `""` when the base URL is empty or not an absolute http(s) URL; MagicMail then logs one warning per core email naming the setting to fix | +| `token` / `code` | The reset token (password reset and admin password reset) or the confirmation code | +| `baseUrl`, `serverUrl`, `adminUrl` | camelCase copies; the admin mail has `adminUrl` and `serverUrl` | +| `meta` | `templateKey`, `payloadVersion: 1`, `coreEmailType` (`reset-password`, `email-confirmation` or `admin-forgot-password`), `locale` when known (the user's stored locale; for the admin mail the admin's interface language) and `strapiVersion` | + +Example payload of the admin password reset: + +```json +{ + "user": { "id": 3, "email": "admin@example.com", "firstname": "Grace", "lastname": "Hopper" }, + "url": "https://cms.example.com/admin/auth/reset-password?code=…", + "token": "…", + "adminUrl": "https://cms.example.com/admin", + "serverUrl": "https://cms.example.com", + "meta": { + "templateKey": "sendgrid:admin-reset", + "payloadVersion": 1, + "coreEmailType": "admin-forgot-password", + "locale": "en", + "strapiVersion": "5.63.0" + } +} +``` + +**What a provider template replaces.** With a provider template, the **subject and body** configured in Users & Permissions (Settings → Email templates) or in `admin.forgotPassword.emailTemplate` are not used; the provider template renders them (Mailgun: the template's Subject header, so a Mailgun template for a core email needs one; SendGrid: the template's subject; MagicMail does not pass the Strapi subject on). The Users & Permissions **shipper email** is ignored as for every MagicMail send: the sender address is always the verified address of the MagicMail account that sends; the shipper name is used only when the shipper email equals that address. **Reply-To**: the Users & Permissions "Response email" (or `admin.forgotPassword.replyTo`) is kept when set; otherwise the account's Reply-To applies. The Core emails tab shows this as a short hint. + +The dialog lists these names and warns about variables the template uses that MagicMail does not send. **Send test** of a provider template that core emails use sends sample values for every core email that uses it (for names two core emails share, such as `url`, the first wins). + +**Failures.** By default a failing provider template is reported as an error and nothing else is sent (users-permissions and the admin panel then handle the error as they do today). Tick **send the Magic Mail designer version instead** (admin mail: **send the Strapi admin email instead**) to fall back when no provider accepted the message. + +**Checked at start.** About 20 seconds after Strapi starts (without delaying the boot), MagicMail checks every core email that uses a provider template. A template list older than 10 minutes is synced first (read-only at the provider). Each core email whose template is not synced (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN`) or deleted, unpublished or only on inactive accounts (`MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE`), or that is a Mailgun template without a Subject header (`MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT`; Magic Mail does not pass the Strapi subject on, and Mailgun needs one) is logged as a warning with its type, key and code, for example: + +``` +[magic-mail] Core email reset-password uses provider template sendgrid:reset-password, which is not usable (MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE). … +``` + +The Core emails tab and the MagicMail dashboard show a red notice naming each affected core email, the reason and the time of the last check. + +**Events.** `strapi.eventHub` emits `magic-mail.provider-template.failed` when a provider-template send fails (template not synced or unusable, provider refusal, no account) and `magic-mail.provider-template.fallback` when another body was sent instead (`fallback: 'magic-mail-template'` for the per-template local fallback, `'designer'` for a core email's designer or Strapi version). The payload is `{ key, code, coreEmailType, fallback? }` (`coreEmailType` is `null` for other mails): no addresses, subjects, tokens or template data. A failing listener never changes the send. + +```javascript +strapi.eventHub.on('magic-mail.provider-template.failed', ({ key, code, coreEmailType }) => { + strapi.log.warn(`Provider template ${key} failed (${code}) ${coreEmailType ?? ''}`); +}); +``` ### Language versions @@ -525,7 +567,7 @@ await strapi }); ``` -1. The language: `locale` passed to `send()`; otherwise the recipient's stored locale, when the Users & Permissions user content type has a `locale` attribute (string or enumeration) and the mail has exactly one recipient. Core emails (password reset, email confirmation) use the user's stored locale the same way and send it as `meta.locale`. **Send test** uses your admin interface language. +1. The language: `locale` passed to `send()`; otherwise the recipient's stored locale, when the Users & Permissions user content type has a `locale` attribute (string or enumeration) and the mail has exactly one recipient. Core emails (password reset, email confirmation) use the user's stored locale the same way and send it as `meta.locale`; the admin password reset uses the admin's interface language. **Send test** uses your admin interface language. 2. The version: the exact language tag (`de-AT`), then its language (`de`), then the default template. A version that is deleted or unpublished at the provider is skipped, and the next candidate is used, so a broken translation never blocks the mail. 3. Rules: versions must come from the same provider and are picked from the synced list (no ids are typed); a version can not have versions of its own. The delivery log records the requested key, the sent version and the language. An invalid `locale` is a 400. diff --git a/server/src/bootstrap.js b/server/src/bootstrap.js index 2ef6c10..712889b 100644 --- a/server/src/bootstrap.js +++ b/server/src/bootstrap.js @@ -3,12 +3,17 @@ const crypto = require('crypto'); const { createLogger } = require('./utils/logger'); const coordination = require('./utils/coordination'); +const { canonicalLocale } = require('./utils/locale'); +const { emitProviderTemplateEvent } = require('./utils/provider-template-events'); +const { sanitizeErrorCode } = require('./utils/delivery-outcome'); const { buildCoreMailPayload, createCoreMailCapture } = require('./utils/core-mail-payload'); /** Marks functions installed by MagicMail so hot reloads never stack wrappers. */ const WRAPPED = Symbol.for('magic-mail.email.send.wrapped'); const QUOTA_REFRESH_INTERVAL_MS = 5 * 60 * 1000; const TRACKING_MAINTENANCE_INTERVAL_MS = 6 * 60 * 60 * 1000; +/** Delay of the core-mail provider-template check after start (server is listening). */ +const CORE_DESIGN_CHECK_DELAY_MS = 20 * 1000; /** Random start delay so replicas and pm2 workers do not hit the database together. */ const jitter = (maxMs) => Math.floor(Math.random() * maxMs); @@ -144,6 +149,16 @@ module.exports = async ({ strapi }) => { log.error('[BOOTSTRAP] Bounce monitoring could not start:', err?.name || 'Error'); } + // Core emails set to a provider template: checked once after start (not + // blocking the boot). Unusable or unsynced templates are logged with their + // key and code; a stale template list is synced first. + registerTimer( + setTimeout( + () => checkCoreDesignsAtStart(strapi, log), + CORE_DESIGN_CHECK_DELAY_MS + jitter(10 * 1000) + ) + ); + // Roles that could read or manage Magic Mail before the outbox existed get // the matching outbox permission once (super admins get it from Strapi). try { @@ -231,7 +246,16 @@ function installEmailInterception(strapi, log) { if (typeof original !== 'function' || original[WRAPPED]) continue; const shim = function magicMailServiceShim(...args) { wrapProvider(); - return original.apply(this && this !== globalThis ? this : service, args); + const self = this && this !== globalThis ? this : service; + if (method === 'sendTemplatedEmail') { + const adminMail = adminForgotPasswordMail(strapi, args); + if (adminMail) { + return sendAdminForgotPassword(strapi, log, adminMail, args[0], () => + original.apply(self, args) + ); + } + } + return original.apply(self, args); }; shim[WRAPPED] = true; registry.originalServiceMethods[method] = original; @@ -300,22 +324,174 @@ function installCoreMailCapture(strapi, log) { } /** - * Sends a core mail (password reset, email confirmation) through the - * provider template chosen for it, with the v1 core-mail payload. + * Recognises the admin panel's forgot-password mail in a + * `sendTemplatedEmail(options, template, data)` call. + * + * @strapi/admin 5.x (services/auth.js `forgotPassword`) calls + * `sendTemplatedEmail({ to, from, replyTo }, config('admin.forgotPassword.emailTemplate'), + * { url: `${admin.absoluteUrl}/auth/reset-password?code=TOKEN`, user })`. + * The call is recognised when the data has exactly `url` and `user` and + * either the template is the configured admin template (same object) or the + * link is the admin reset-password link. + * + * @param {object} strapi + * @param {unknown[]} args - sendTemplatedEmail arguments + * @returns {{url: string, user: object, adminUrl: string, serverUrl: string}|null} + */ +function adminForgotPasswordMail(strapi, args) { + const [options, template, data] = args; + if (!options || typeof options !== 'object' || !data || typeof data !== 'object') return null; + const keys = Object.keys(data); + if (keys.length !== 2 || typeof data.url !== 'string' || !data.user) return null; + if (typeof data.user !== 'object' || Array.isArray(data.user)) return null; + const config = (key) => { + try { + return strapi.config?.get?.(key); + } catch { + return undefined; + } + }; + const adminUrl = + typeof config('admin.absoluteUrl') === 'string' ? config('admin.absoluteUrl') : ''; + const configuredTemplate = config('admin.forgotPassword.emailTemplate'); + const sameTemplate = Boolean(template) && template === configuredTemplate; + const resetLink = + Boolean(adminUrl) && data.url.startsWith(`${adminUrl}/auth/reset-password?code=`); + if (!sameTemplate && !resetLink) return null; + const serverUrl = config('server.absoluteUrl'); + return { + url: data.url, + user: data.user, + adminUrl, + serverUrl: typeof serverUrl === 'string' ? serverUrl : '', + }; +} + +/** + * Admin user facts for the admin forgot-password payload: the id and the + * interface language (`preferedLanguage`). Best effort; never throws. + * + * @param {object} strapi + * @param {unknown} email - Recipient address + * @returns {Promise<{id?: number, locale?: string}>} + */ +async function adminUserFacts(strapi, email) { + try { + if (typeof email !== 'string' || !email) return {}; + const user = await strapi.db.query('admin::user').findOne({ + where: { email }, + select: ['id', 'preferedLanguage'], + }); + if (!user) return {}; + return { + ...(Number.isInteger(user.id) ? { id: user.id } : {}), + ...(canonicalLocale(user.preferedLanguage) + ? { locale: canonicalLocale(user.preferedLanguage) } + : {}), + }; + } catch { + return {}; + } +} + +/** + * Sends the admin forgot-password mail through its provider template when + * one is chosen; otherwise (or on opt-in fallback) Strapi renders and sends + * the local template as before. + * + * @param {object} strapi + * @param {object} log + * @param {{url: string, user: object, adminUrl: string, serverUrl: string}} adminMail + * @param {object} options - Addressing from @strapi/admin ({ to, from, replyTo }) + * @param {() => Promise} sendLocal - The original sendTemplatedEmail call + * @returns {Promise} + * @throws {Error} The provider-template error (strict mode) + */ +async function sendAdminForgotPassword(strapi, log, adminMail, options, sendLocal) { + let design; + try { + design = await strapi + .plugin('magic-mail') + .service('provider-templates') + .coreDesignFor('admin-forgot-password'); + } catch { + design = null; + } + // No provider template chosen: Strapi renders and sends as before. + if (!design) return sendLocal(); + const facts = await adminUserFacts(strapi, options?.to); + const coreMail = { + coreEmailType: 'admin-forgot-password', + data: { + ...adminMail, + user: { ...(facts.id !== undefined ? { id: facts.id } : {}), ...adminMail.user }, + }, + locale: facts.locale, + }; + const routed = await routeCoreMailToProviderTemplate( + strapi, + log, + coreMail, + { ...options }, + sendLocal, + { sendDesignerVersion: sendLocal } + ); + return routed ? routed.result : sendLocal(); +} + +/** Where the base URL of each core mail's link comes from (for the warning). */ +const CORE_URL_SOURCES = Object.freeze({ + 'reset-password': 'Users & Permissions > Advanced settings > Reset password page', + 'email-confirmation': 'config/server (url) and the REST API prefix', + 'admin-forgot-password': 'config/admin (url) and config/server (url)', +}); + +/** + * Warns once per process and core mail when the payload has no `url` + * (empty or relative base URL). Names the setting, never values. + * + * @param {object} strapi + * @param {object} log + * @param {string} coreEmailType + */ +function warnMissingCoreUrlOnce(strapi, log, coreEmailType) { + const registry = strapi.magicMail || (strapi.magicMail = {}); + registry.coreUrlWarned = registry.coreUrlWarned || new Set(); + if (registry.coreUrlWarned.has(coreEmailType)) return; + registry.coreUrlWarned.add(coreEmailType); + log.warn( + `[EMAIL] Core email ${coreEmailType}: "url" can not be built because the base URL is empty or not an absolute http(s) URL. The template gets url "" until ${CORE_URL_SOURCES[coreEmailType] || 'the base URL'} is set` + ); +} + +/** + * Sends a core mail (password reset, email confirmation, admin forgot + * password) through the provider template chosen for it, with the v1 + * core-mail payload. * - * Strict by default: a provider-template error reaches users-permissions and - * no other body is sent. With "send the Magic Mail designer version instead" - * enabled, the original mail is sent when no provider accepted the message. + * Strict by default: a provider-template error reaches the caller and no + * other body is sent. With "send the Magic Mail designer version instead" + * enabled, the local version is sent when no provider accepted the message, + * and `magic-mail.provider-template.fallback` is emitted. * * @param {object} strapi * @param {object} log - * @param {{coreEmailType: string, data: object}} coreMail - Recorded variables - * @param {object} payload - The mail users-permissions sends + * @param {{coreEmailType: string, data: object, locale?: string}} coreMail - Recorded variables + * @param {object} payload - The mail users-permissions sends (or the admin addressing) * @param {() => Promise} callOriginal - Native provider send + * @param {{sendDesignerVersion?: () => Promise}} [options] - How to send + * the local version on fallback (default: the payload through Magic Mail) * @returns {Promise<{result: object}|null>} null when the core mail uses the designer * @throws {Error} The provider-template error (strict mode) */ -async function routeCoreMailToProviderTemplate(strapi, log, coreMail, payload, callOriginal) { +async function routeCoreMailToProviderTemplate( + strapi, + log, + coreMail, + payload, + callOriginal, + options = {} +) { let design; try { design = await strapi @@ -331,25 +507,38 @@ async function routeCoreMailToProviderTemplate(strapi, log, coreMail, payload, c const router = strapi.plugin('magic-mail').service('email-router'); // The designer body and subject are replaced by the provider template. const { html, text, subject, data, templateData, ...rest } = payload; - // The user's stored locale (when the user content type has a `locale` - // attribute) picks the language version and is sent as meta.locale. - let locale; + // Users & Permissions mails: the user's stored locale (when the user + // content type has a `locale` attribute). Admin mails: the admin's + // interface language. It picks the language version and is sent as + // meta.locale. + let locale = coreMail.locale || null; + if (!locale && coreMail.coreEmailType !== 'admin-forgot-password') { + try { + locale = + typeof router.recipientLocale === 'function' + ? await router.recipientLocale(payload.to) + : null; + } catch { + locale = null; + } + } + let strapiVersion; try { - locale = - typeof router.recipientLocale === 'function' - ? await router.recipientLocale(payload.to) - : null; + strapiVersion = strapi.config?.get?.('info.strapi'); } catch { - locale = null; + strapiVersion = undefined; } + const coreData = buildCoreMailPayload(coreMail.coreEmailType, coreMail.data, { + templateKey: design.providerTemplate, + ...(locale ? { locale } : {}), + ...(typeof strapiVersion === 'string' ? { strapiVersion } : {}), + }); + if (!coreData.url) warnMissingCoreUrlOnce(strapi, log, coreMail.coreEmailType); const providerPayload = { ...rest, providerTemplate: design.providerTemplate, ...(locale ? { locale } : {}), - templateData: buildCoreMailPayload(coreMail.coreEmailType, coreMail.data, { - templateKey: design.providerTemplate, - ...(locale ? { locale } : {}), - }), + templateData: coreData, }; log.debug('[EMAIL] Routing a core email through its provider template'); try { @@ -357,6 +546,7 @@ async function routeCoreMailToProviderTemplate(strapi, log, coreMail, payload, c result: await router.send(providerPayload, { source: 'strapi-email', providerTemplateFallback: false, + coreEmailType: coreMail.coreEmailType, }), }; } catch (error) { @@ -364,6 +554,15 @@ async function routeCoreMailToProviderTemplate(strapi, log, coreMail, payload, c log.warn( '[EMAIL] Provider template for a core email failed; sending the Magic Mail designer version' ); + await emitProviderTemplateEvent(strapi, 'fallback', { + key: design.providerTemplate, + code: sanitizeErrorCode(error), + coreEmailType: coreMail.coreEmailType, + fallback: 'designer', + }); + if (typeof options.sendDesignerVersion === 'function') { + return { result: await options.sendDesignerVersion() }; + } return { result: await router.send(payload, { source: 'strapi-email', fallbackSend: callOriginal }), }; @@ -372,6 +571,28 @@ async function routeCoreMailToProviderTemplate(strapi, log, coreMail, payload, c } } +/** + * Startup check of the core emails that use a provider template: syncs a + * stale template list (read-only at the provider) and logs every core email + * whose template is not synced or not usable, with key and code only. + * Never throws; runs after the server started. + * + * @param {object} strapi + * @param {object} log + * @returns {Promise} + * @sideeffect May sync provider templates; writes the check result to the + * plugin store (shown on the dashboard). + */ +async function checkCoreDesignsAtStart(strapi, log) { + try { + const service = strapi.plugin('magic-mail').service('provider-templates'); + if (!service || typeof service.checkCoreDesigns !== 'function') return; + await service.checkCoreDesigns({ syncIfStale: true }); + } catch (error) { + log.warn(`[EMAIL] Core email template check did not complete: ${error?.name || 'Error'}`); + } +} + /** * Restores everything installEmailInterception() replaced. * @param {object} strapi @@ -559,6 +780,10 @@ function logSecretFingerprints(strapi) { module.exports.installEmailInterception = installEmailInterception; module.exports.installCoreMailCapture = installCoreMailCapture; module.exports.routeCoreMailToProviderTemplate = routeCoreMailToProviderTemplate; +module.exports.adminForgotPasswordMail = adminForgotPasswordMail; +module.exports.sendAdminForgotPassword = sendAdminForgotPassword; +module.exports.emitProviderTemplateEvent = emitProviderTemplateEvent; +module.exports.checkCoreDesignsAtStart = checkCoreDesignsAtStart; module.exports.uninstallEmailInterception = uninstallEmailInterception; module.exports.purgeSensitiveLinkMappings = purgeSensitiveLinkMappings; module.exports.WRAPPED = WRAPPED; diff --git a/server/src/controllers/provider-templates.js b/server/src/controllers/provider-templates.js index 558c792..ac7d145 100644 --- a/server/src/controllers/provider-templates.js +++ b/server/src/controllers/provider-templates.js @@ -215,16 +215,18 @@ module.exports = ({ strapi }) => { }, /** - * Design choice of both core mails (designer or provider template). + * Design choice of the core mails (designer or provider template). * * @route GET /magic-mail/designer/core-designs * @auth Admin JWT + plugin::magic-mail.read + plugin::users-permissions.email-templates.read * @param {import('koa').Context} ctx - * @returns {Promise} 200 `{ data: { 'reset-password': {...}, 'email-confirmation': {...} } }` + * @returns {Promise} 200 `{ data: { 'reset-password': {...}, 'email-confirmation': {...}, + * 'admin-forgot-password': {...} } }`; each entry has `usable`, `problem` (error code or + * null), `lastSyncedAt`, `checkedAt` (startup check) and `editable` for the signed-in admin */ async coreDesigns(ctx) { try { - ctx.body = { data: await service().coreDesigns() }; + ctx.body = { data: await service().coreDesigns(ctx.state?.user ?? null) }; } catch (error) { handleControllerError(ctx, error, '[magic-mail] Core email designs could not be read'); } @@ -236,7 +238,8 @@ module.exports = ({ strapi }) => { * @route PUT /magic-mail/designer/core/:coreEmailType/design * @auth Admin JWT + plugin::magic-mail.manage + plugin::users-permissions.email-templates.update * @param {import('koa').Context} ctx - body `{ providerTemplate: key|null, fallbackToDesigner?: boolean }` - * @returns {Promise} 200 `{ data }` (the new design); 400 invalid type or template + * @returns {Promise} 200 `{ data }` (the new design); 400 invalid type or template; + * 403 admin-forgot-password for an admin who is not a super admin * @sideeffect Writes the plugin store; logs the change and emits * `magic-mail.core-email.design.update` on the event hub. */ diff --git a/server/src/services/email-router.js b/server/src/services/email-router.js index 2f82ee6..1258f33 100644 --- a/server/src/services/email-router.js +++ b/server/src/services/email-router.js @@ -12,6 +12,8 @@ const coordination = require('../utils/coordination'); const { checkRecipientDomains } = require('../utils/recipient-domains'); const { toPlainJson } = require('../utils/plain-json'); const { canonicalLocale } = require('../utils/locale'); +const { emitProviderTemplateEvent } = require('../utils/provider-template-events'); +const { CORE_EMAIL_TYPES } = require('../utils/core-mail-payload'); const { getAdapter, TEMPLATE_PROVIDERS } = require('../providers'); const { checkMailgunTemplate } = require('../utils/provider-api'); const { @@ -1220,6 +1222,24 @@ function providerTemplateFor(account, emailData) { return { ...row, variables: prepared.variables }; } +/** + * SendGrid dynamic template data with the mail subject as `subject` when a + * subject is passed and the data has no own `subject` key (the data wins). + * SendGrid ignores the top-level subject for dynamic templates; a template + * whose subject line is `{{subject}}` (or `{{{subject}}}`) renders this value. + * + * @param {object} variables - Plain template data + * @param {unknown} subject - Caller subject + * @returns {object} The data (a copy when the subject was added) + */ +function withTemplateSubject(variables, subject) { + const data = variables && typeof variables === 'object' ? variables : {}; + if (typeof subject !== 'string' || subject.trim() === '' || Object.hasOwn(data, 'subject')) { + return data; + } + return { ...data, subject: stripHeaderInjection(subject) }; +} + /** * Message-ID for the account's domain. Queue sends pass a stable local part, * so every attempt of one queued message uses the same Message-ID. @@ -1840,10 +1860,12 @@ module.exports = ({ strapi }) => ({ `Provider template "${key}" is not synced. Sync the provider templates in Magic Mail first`, 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN' ); + await this.emitProviderTemplateEvent('failed', key, error.code, options); if (prepared.fallbackTemplateReferenceId && options.providerTemplateFallback !== false) { strapi.log.warn( `[magic-mail] Provider template ${key} is not usable; sending the configured Magic Mail fallback template` ); + await this.emitProviderTemplateEvent('fallback', key, error.code, options); return { ...prepared, useFallback: true, reason: error.code }; } throw error; @@ -1852,6 +1874,27 @@ module.exports = ({ strapi }) => ({ return prepared; }, + /** + * Emits `magic-mail.provider-template.failed` or `.fallback` (template key, + * error code and, for core emails, the core email type; no personal data). + * + * @param {'failed'|'fallback'} name + * @param {string} key - Provider template key + * @param {string|null} code - Error code + * @param {object} [options] - send() options (`coreEmailType` for core emails) + * @returns {Promise} + */ + async emitProviderTemplateEvent(name, key, code, options = {}) { + await emitProviderTemplateEvent(strapi, name, { + key, + code: typeof code === 'string' ? code : null, + coreEmailType: CORE_EMAIL_TYPES.includes(options.coreEmailType) + ? options.coreEmailType + : null, + ...(name === 'fallback' ? { fallback: 'magic-mail-template' } : {}), + }); + }, + /** * Stored locale of the (single) recipient: the users-permissions user with * this email, when the host added a string or enumeration `locale` @@ -1938,6 +1981,8 @@ module.exports = ({ strapi }) => ({ } catch { // frozen error } + const code = sanitizeErrorCode(error); + await this.emitProviderTemplateEvent('failed', prepared.key, code, options); if ( safe && prepared.fallbackTemplateReferenceId && @@ -1946,6 +1991,7 @@ module.exports = ({ strapi }) => ({ strapi.log.warn( `[magic-mail] Provider template ${prepared.key} failed; sending the configured Magic Mail fallback template` ); + await this.emitProviderTemplateEvent('fallback', prepared.key, code, options); return this.sendProviderTemplateFallback(input, options, prepared); } strapi.log.error( @@ -3205,7 +3251,13 @@ module.exports = ({ strapi }) => ({ if (template) { // Dynamic template: the provider renders subject and body from the // same data a local template gets (Handlebars, top-level keys). - personalization.dynamic_template_data = template.variables; + // SendGrid takes the subject from the template version, never from + // the top-level `subject`; a template that uses {{subject}} gets the + // caller's subject when the data does not set one itself. + personalization.dynamic_template_data = withTemplateSubject( + template.variables, + emailData.subject + ); } const magicmailId = magicmailIdOf(emailData); const msg = { diff --git a/server/src/services/provider-templates.js b/server/src/services/provider-templates.js index 1fdd439..00b538f 100644 --- a/server/src/services/provider-templates.js +++ b/server/src/services/provider-templates.js @@ -52,6 +52,52 @@ const MAX_LOCALES_PER_TEMPLATE = 50; /** Sample values for test sends; the same values local template tests use. */ const SAMPLE_DATA = Object.freeze({ name: 'Test User' }); +/** Codes for a core email whose provider template can not be used. */ +const CORE_PROBLEM = Object.freeze({ + UNKNOWN: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN', + UNAVAILABLE: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE', + NO_SUBJECT: 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT', +}); + +/** The admin forgot-password mail resets admin accounts: super admins only. */ +const SUPER_ADMIN_ONLY_CORE_TYPES = Object.freeze(['admin-forgot-password']); + +/** + * Whether an admin user holds the Super Admin role (`strapi-super-admin`). + * + * @param {unknown} adminUser - ctx.state.user (roles populated by Strapi) + * @returns {boolean} + */ +const isSuperAdmin = (adminUser) => + Array.isArray(adminUser?.roles) && + adminUser.roles.some((role) => role?.code === 'strapi-super-admin'); + +/** + * Synthetic input for a core-mail sample payload (test sends, preview). + * + * @param {string} coreEmailType + * @param {string} to - Test recipient + * @returns {object} + */ +function coreSampleInput(coreEmailType, to) { + if (coreEmailType === 'admin-forgot-password') { + return { + url: 'https://api.example.test/admin/auth/reset-password?code=sample-token', + user: { id: 1, email: to, firstname: 'Test', lastname: 'User', username: 'test.user' }, + adminUrl: 'https://api.example.test/admin', + serverUrl: 'https://api.example.test', + }; + } + return { + URL: 'https://app.example.test/auth', + SERVER_URL: 'https://api.example.test', + ADMIN_URL: 'https://api.example.test/admin', + USER: { id: 1, email: to, username: 'test.user' }, + TOKEN: 'sample-token', + CODE: 'sample-code', + }; +} + /** * Turns a provider template name into the key slug: lower case ASCII letters, * digits and single dashes, at most 80 characters ('template' when empty). @@ -136,7 +182,7 @@ module.exports = ({ strapi }) => ({ /** * The plugin-store state (fallbacks, core-mail designs, sync bookkeeping). * - * @returns {Promise<{fallbacks: object, locales: object, coreMails: object, accounts: object, lastSyncedAt: string|null}>} + * @returns {Promise<{fallbacks: object, locales: object, coreMails: object, accounts: object, lastSyncedAt: string|null, coreCheck: object|null}>} */ async getState() { const store = await strapi.store({ type: STORE.type, name: STORE.name }); @@ -147,6 +193,10 @@ module.exports = ({ strapi }) => ({ coreMails: value.coreMails && typeof value.coreMails === 'object' ? value.coreMails : {}, accounts: value.accounts && typeof value.accounts === 'object' ? value.accounts : {}, lastSyncedAt: typeof value.lastSyncedAt === 'string' ? value.lastSyncedAt : null, + coreCheck: + value.coreCheck && typeof value.coreCheck === 'object' && !Array.isArray(value.coreCheck) + ? value.coreCheck + : null, }; }, @@ -166,6 +216,7 @@ module.exports = ({ strapi }) => ({ coreMails: { ...(current.coreMails || {}) }, accounts: { ...(current.accounts || {}) }, lastSyncedAt: current.lastSyncedAt || null, + coreCheck: current.coreCheck || null, }); }); }, @@ -539,9 +590,9 @@ module.exports = ({ strapi }) => ({ })), variablesTruncated: best?.variables?.truncated === true, sampleData: sample, - coreMailVariables: group.usedByCoreMails.length - ? coreMailVariableNames(group.usedByCoreMails[0]) - : [], + coreMailVariables: [ + ...new Set(group.usedByCoreMails.flatMap((type) => coreMailVariableNames(type))), + ], copyWarnings: toMustacheWarnings.slice(0, 50), usage: `await strapi.plugin('magic-mail').service('email-router').send({\n to: 'user@example.com',\n providerTemplate: '${key}',\n data: { name: 'Ada' },\n});`, }; @@ -549,7 +600,9 @@ module.exports = ({ strapi }) => ({ /** * Sample template data for test sends: the local-template sample values, - * plus core-mail sample data when a core mail uses the template. + * plus core-mail sample data for every core mail that uses the template + * (merged in order, so each core mail's variables are present; for names + * two core mails share, such as `url` or `meta`, the first core mail wins). * * @param {{key: string, usedByCoreMails: string[]}} group * @param {string} to - Test recipient @@ -557,23 +610,14 @@ module.exports = ({ strapi }) => ({ */ sampleData(group, to) { const base = { ...SAMPLE_DATA, email: to }; - const coreType = group.usedByCoreMails?.[0]; - if (!coreType) return base; - return { - ...base, - ...buildCoreMailPayload( - coreType, - { - URL: 'https://app.example.test/auth', - SERVER_URL: 'https://api.example.test', - ADMIN_URL: 'https://api.example.test/admin', - USER: { id: 1, email: to, username: 'test.user' }, - TOKEN: 'sample-token', - CODE: 'sample-code', - }, - { templateKey: group.key } - ), - }; + const coreTypes = (group.usedByCoreMails || []).filter((type) => + CORE_EMAIL_TYPES.includes(type) + ); + if (coreTypes.length === 0) return base; + const samples = coreTypes.map((type) => + buildCoreMailPayload(type, coreSampleInput(type, to), { templateKey: group.key }) + ); + return Object.assign({}, base, ...samples.reverse()); }, /** @@ -817,25 +861,47 @@ module.exports = ({ strapi }) => ({ /** * Core-mail design choices with the state of the chosen template. * + * @param {object} [adminUser] - With an admin user, each entry gets + * `editable` (the admin forgot-password design is for super admins only) * @returns {Promise>} */ - async coreDesigns() { + async coreDesigns(adminUser) { const [state, overview] = await Promise.all([this.getState(), this.overview()]); const out = {}; for (const type of CORE_EMAIL_TYPES) { const choice = state.coreMails?.[type] || {}; const key = isProviderTemplateKey(choice.providerTemplate) ? choice.providerTemplate : null; const group = key ? overview.templates.find((t) => t.key === key) : null; + // A Mailgun template without a Subject header can not send a core + // email: Magic Mail does not pass the Strapi subject on (it would + // override the template), and Mailgun requires a subject. + const noSubject = + Boolean(group?.usable) && group.provider === 'mailgun' && !String(group.subject || ''); + const usable = key ? Boolean(group?.usable) && !noSubject : true; out[type] = { mode: key ? 'provider' : 'designer', providerTemplate: key, templateName: group?.name || null, provider: group?.provider || (key ? key.split(':')[0] : null), status: key ? (group ? group.status : 'missing') : null, - usable: key ? Boolean(group?.usable) : true, + usable, + // Why the template can not be used: not synced at all, or synced + // but deleted/unpublished at the provider or only on inactive accounts. + problem: usable + ? null + : noSubject + ? CORE_PROBLEM.NO_SUBJECT + : group + ? CORE_PROBLEM.UNAVAILABLE + : CORE_PROBLEM.UNKNOWN, fallbackToDesigner: choice.fallbackToDesigner === true, updatedAt: choice.updatedAt || null, + lastSyncedAt: key ? overview.lastSyncedAt || null : null, + checkedAt: key ? state.coreCheck?.checkedAt || null : null, variables: coreMailVariableNames(type), + ...(adminUser !== undefined + ? { editable: !SUPER_ADMIN_ONLY_CORE_TYPES.includes(type) || isSuperAdmin(adminUser) } + : {}), }; } return out; @@ -845,17 +911,24 @@ module.exports = ({ strapi }) => ({ * Sets the design of a core mail: the Magic Mail designer (providerTemplate * null) or a synced provider template. * - * @param {'reset-password'|'email-confirmation'} coreEmailType + * @param {'reset-password'|'email-confirmation'|'admin-forgot-password'} coreEmailType * @param {{providerTemplate: string|null, fallbackToDesigner?: boolean}} input * @param {{id?: number|string}|undefined} adminUser - The admin making the change * @returns {Promise} The new design entry (see coreDesigns()) * @throws {errors.ValidationError} Unknown core type or template + * @throws {errors.ForbiddenError} admin-forgot-password by an admin who is + * not a super admin * @sideeffect Writes the plugin store; logs the change (without personal data). */ async setCoreDesign(coreEmailType, input, adminUser) { if (!CORE_EMAIL_TYPES.includes(coreEmailType)) { throw new errors.ValidationError('Invalid core email type'); } + if (SUPER_ADMIN_ONLY_CORE_TYPES.includes(coreEmailType) && !isSuperAdmin(adminUser)) { + throw new errors.ForbiddenError( + 'Only super admins can change the design of the admin password reset email' + ); + } const key = input.providerTemplate ?? null; if (key !== null) { const overview = await this.overview(); @@ -894,7 +967,7 @@ module.exports = ({ strapi }) => ({ } catch { // Listeners must not break the save. } - return (await this.coreDesigns())[coreEmailType]; + return (await this.coreDesigns(adminUser))[coreEmailType]; }, /** @@ -912,6 +985,63 @@ module.exports = ({ strapi }) => ({ fallbackToDesigner: choice.fallbackToDesigner === true, }; }, + + /** + * Checks every core email that uses a provider template (run once after + * start, see bootstrap). With `syncIfStale`, a template list older than + * 10 minutes (or never synced) is synced first, read-only at the provider. + * Each core email whose template is not synced or not usable is logged at + * warn level with its type, key and code (never values). The result is + * stored for the admin (`coreCheck`). + * + * @param {{syncIfStale?: boolean}} [options] + * @returns {Promise<{checkedAt: string|null, synced: boolean, syncError: string|null, problems: Array<{coreEmailType: string, key: string, code: string}>}>} + * @sideeffect May call the provider APIs (sync); writes the plugin store. + */ + async checkCoreDesigns({ syncIfStale = true } = {}) { + const state = await this.getState(); + const configured = CORE_EMAIL_TYPES.filter((type) => + isProviderTemplateKey(state.coreMails?.[type]?.providerTemplate) + ); + if (configured.length === 0) { + return { checkedAt: null, synced: false, syncError: null, problems: [] }; + } + let synced = false; + let syncError = null; + const last = state.lastSyncedAt ? Date.parse(state.lastSyncedAt) : 0; + if (syncIfStale && (!last || Date.now() - last > STALE_AFTER_MS)) { + try { + await this.sync(); + synced = true; + } catch (error) { + syncError = typeof error?.code === 'string' ? error.code : 'SYNC_FAILED'; + strapi.log.warn( + `[magic-mail] Provider templates could not be synced at start (${syncError}); core emails are checked against the last sync` + ); + } + } + const designs = await this.coreDesigns(); + const problems = []; + for (const type of configured) { + const design = designs[type]; + if (!design || design.usable) continue; + problems.push({ coreEmailType: type, key: design.providerTemplate, code: design.problem }); + strapi.log.warn( + `[magic-mail] Core email ${type} uses provider template ${design.providerTemplate}, which is not usable (${design.problem}). These emails fail until the template is available and synced, or the core email uses the Magic Mail designer again` + ); + } + const checkedAt = new Date().toISOString(); + await this.updateState((current) => ({ + ...current, + coreCheck: { checkedAt, problems: problems.slice(0, CORE_EMAIL_TYPES.length) }, + })); + if (problems.length === 0) { + strapi.log.info( + `[magic-mail] Core email provider templates checked: ${configured.length} usable` + ); + } + return { checkedAt, synced, syncError, problems }; + }, }); module.exports.isProviderTemplateKey = isProviderTemplateKey; @@ -919,3 +1049,4 @@ module.exports.slugify = slugify; module.exports.templateError = templateError; module.exports.STALE_AFTER_MS = STALE_AFTER_MS; module.exports.SAMPLE_DATA = SAMPLE_DATA; +module.exports.CORE_PROBLEM = CORE_PROBLEM; diff --git a/server/src/utils/core-mail-payload.js b/server/src/utils/core-mail-payload.js index a3a62c3..e2f82f6 100644 --- a/server/src/utils/core-mail-payload.js +++ b/server/src/utils/core-mail-payload.js @@ -9,19 +9,33 @@ * moment users-permissions renders (see `createCoreMailCapture`) and, when a * core mail is set to use a provider template, sends them as template data. * + * The admin panel's forgot-password mail is rendered by + * `sendTemplatedEmail(options, template, { url, user })`; Magic Mail + * recognises that call (see bootstrap.js) and builds its payload directly. + * * Contract v1 (keys may be added later, never removed): - * - the familiar users-permissions names: URL, SERVER_URL, ADMIN_URL, USER, - * TOKEN (password reset) or CODE (email confirmation); - * - camelCase aliases: url (fully built link), baseUrl, serverUrl, adminUrl, - * user, token or code; - * - meta: { templateKey, payloadVersion: 1, coreEmailType, locale? }. + * - users-permissions mails (reset-password, email-confirmation): + * - the familiar users-permissions names: URL, SERVER_URL, ADMIN_URL, USER, + * TOKEN (password reset) or CODE (email confirmation); + * - camelCase aliases: url (fully built link), baseUrl, serverUrl, adminUrl, + * user, token or code; + * - admin forgot password (admin-forgot-password): user, url (the finished + * reset link Strapi built), token, adminUrl, serverUrl; + * - meta: { templateKey, payloadVersion: 1, coreEmailType, locale?, + * strapiVersion? }. * USER/user carry only id, email, username and, when present, firstname and * lastname. The full user entity is never forwarded. */ const crypto = require('crypto'); -const CORE_EMAIL_TYPES = Object.freeze(['reset-password', 'email-confirmation']); +const CORE_EMAIL_TYPES = Object.freeze([ + 'reset-password', + 'email-confirmation', + 'admin-forgot-password', +]); +/** Core mails rendered by users-permissions (captured through template()). */ +const UP_CORE_EMAIL_TYPES = Object.freeze(['reset-password', 'email-confirmation']); const CORE_PAYLOAD_VERSION = 1; const USER_FIELDS = Object.freeze(['id', 'email', 'username', 'firstname', 'lastname']); const CAPTURE_TTL_MS = 5 * 60 * 1000; @@ -74,18 +88,83 @@ function buildCoreLink(coreEmailType, baseUrl, secret) { return url.toString(); } +/** + * Returns the value when it is an absolute http(s) URL, else ''. + * + * @param {unknown} value + * @returns {string} + */ +function absoluteHttpUrl(value) { + if (typeof value !== 'string' || value.length === 0 || value.length > MAX_FIELD_LENGTH) return ''; + try { + const url = new URL(value); + return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : ''; + } catch { + return ''; + } +} + +/** + * The reset token of an admin forgot-password link (`?code=`), else ''. + * + * @param {string} url - Absolute link built by @strapi/admin + * @returns {string} + */ +function adminResetToken(url) { + if (!url) return ''; + try { + return asText(new URL(url).searchParams.get('code') || ''); + } catch { + return ''; + } +} + +/** + * The common `meta` envelope of payload v1. `locale` and `strapiVersion` are + * only present when known. + * + * @param {string} coreEmailType + * @param {{templateKey?: string, locale?: string, strapiVersion?: string}} meta + * @returns {object} + */ +function buildMeta(coreEmailType, meta) { + return { + templateKey: String(meta.templateKey || ''), + payloadVersion: CORE_PAYLOAD_VERSION, + coreEmailType, + ...(typeof meta.locale === 'string' && meta.locale ? { locale: meta.locale } : {}), + ...(typeof meta.strapiVersion === 'string' && meta.strapiVersion + ? { strapiVersion: meta.strapiVersion.slice(0, 64) } + : {}), + }; +} + /** * Builds the v1 template data for a core mail. * - * @param {'reset-password'|'email-confirmation'} coreEmailType + * @param {'reset-password'|'email-confirmation'|'admin-forgot-password'} coreEmailType * @param {object} captured - Variables users-permissions rendered with - * ({ URL, SERVER_URL, ADMIN_URL, USER, TOKEN | CODE }) - * @param {{templateKey: string, locale?: string}} meta - * @returns {object} Plain template data + * ({ URL, SERVER_URL, ADMIN_URL, USER, TOKEN | CODE }); for + * admin-forgot-password `{ url, user, adminUrl, serverUrl }` (the data + * @strapi/admin passes to sendTemplatedEmail plus the configured URLs) + * @param {{templateKey: string, locale?: string, strapiVersion?: string}} meta + * @returns {object} Plain template data; `url` is '' when no absolute + * http(s) link can be built * @throws {TypeError} For an unknown core email type */ function buildCoreMailPayload(coreEmailType, captured = {}, meta = {}) { if (!CORE_EMAIL_TYPES.includes(coreEmailType)) throw new TypeError('Unknown core email type'); + if (coreEmailType === 'admin-forgot-password') { + const url = absoluteHttpUrl(captured.url); + return { + user: allowlistUser(captured.user), + url, + token: adminResetToken(url), + adminUrl: asText(captured.adminUrl), + serverUrl: asText(captured.serverUrl), + meta: buildMeta(coreEmailType, meta), + }; + } const user = allowlistUser(captured.USER); const baseUrl = asText(captured.URL); const serverUrl = asText(captured.SERVER_URL); @@ -106,23 +185,38 @@ function buildCoreMailPayload(coreEmailType, captured = {}, meta = {}) { adminUrl, user: { ...user }, ...(isReset ? { token: secret } : { code: secret }), - meta: { - templateKey: String(meta.templateKey || ''), - payloadVersion: CORE_PAYLOAD_VERSION, - coreEmailType, - ...(typeof meta.locale === 'string' && meta.locale ? { locale: meta.locale } : {}), - }, + meta: buildMeta(coreEmailType, meta), }; return payload; } +const META_VARIABLES = Object.freeze([ + 'meta', + 'meta.templateKey', + 'meta.payloadVersion', + 'meta.coreEmailType', + 'meta.locale', + 'meta.strapiVersion', +]); + /** * Variable names Magic Mail sends for a core mail (for the admin screen). * - * @param {'reset-password'|'email-confirmation'} coreEmailType + * @param {'reset-password'|'email-confirmation'|'admin-forgot-password'} coreEmailType * @returns {string[]} */ function coreMailVariableNames(coreEmailType) { + if (coreEmailType === 'admin-forgot-password') { + return [ + 'user', + ...USER_FIELDS.map((field) => `user.${field}`), + 'url', + 'token', + 'adminUrl', + 'serverUrl', + ...META_VARIABLES, + ]; + } const isReset = coreEmailType === 'reset-password'; return [ 'URL', @@ -138,11 +232,7 @@ function coreMailVariableNames(coreEmailType) { 'user', ...USER_FIELDS.map((field) => `user.${field}`), isReset ? 'token' : 'code', - 'meta', - 'meta.templateKey', - 'meta.payloadVersion', - 'meta.coreEmailType', - 'meta.locale', + ...META_VARIABLES, ]; } @@ -234,8 +324,10 @@ function createCoreMailCapture({ now = () => Date.now() } = {}) { module.exports = { CORE_EMAIL_TYPES, + UP_CORE_EMAIL_TYPES, CORE_PAYLOAD_VERSION, USER_FIELDS, + absoluteHttpUrl, allowlistUser, buildCoreLink, buildCoreMailPayload, diff --git a/server/src/utils/provider-template-events.js b/server/src/utils/provider-template-events.js new file mode 100644 index 0000000..11e4373 --- /dev/null +++ b/server/src/utils/provider-template-events.js @@ -0,0 +1,41 @@ +'use strict'; + +/** + * Event hub events for provider-template sends: + * - `magic-mail.provider-template.failed`: a provider-template send failed + * (template not synced or unusable, provider refused it, no account took it); + * - `magic-mail.provider-template.fallback`: another body was sent instead + * (the configured local fallback template, or the designer version of a + * core email). + * + * Payload: `{ key, code, coreEmailType, fallback? }`. Template key, error + * code and labels only; never addresses, subjects or template data. + */ + +/** + * Emits `magic-mail.provider-template.` on the event hub (best effort). + * The payload carries the template key, an error code and non-personal + * labels only: never addresses, subjects or template data. + * + * @param {object} strapi + * @param {'failed'|'fallback'} name + * @param {{key: string, code: string|null, coreEmailType?: string|null, fallback?: string}} payload + * @returns {Promise} + */ +async function emitProviderTemplateEvent(strapi, name, payload) { + try { + if (!strapi.eventHub || typeof strapi.eventHub.emit !== 'function') return; + await strapi.eventHub.emit(`magic-mail.provider-template.${name}`, { + key: payload.key, + code: payload.code ?? null, + coreEmailType: payload.coreEmailType ?? null, + ...(payload.fallback ? { fallback: payload.fallback } : {}), + }); + } catch (error) { + strapi.log?.warn?.( + `[magic-mail] Provider template event listener failed: ${error?.name || 'Error'}` + ); + } +} + +module.exports = { emitProviderTemplateEvent }; diff --git a/tests/admin/strict-mode.test.jsx b/tests/admin/strict-mode.test.jsx index 233d9cc..edbf160 100644 --- a/tests/admin/strict-mode.test.jsx +++ b/tests/admin/strict-mode.test.jsx @@ -606,3 +606,75 @@ test('plugin settings page: the provider-tracking switch appears only with a tem assert.equal(live(result.mountCalls, '/magic-mail/settings').length, 1); assert.equal(mutations(result.calls).length, 0, 'no mutation'); }); + +/** Core designs with the admin forgot-password row (RFC #27752). */ +const coreDesignsWithAdmin = ({ editable, broken = false }) => ({ + ...Object.fromEntries( + Object.entries(CORE_DESIGNS).map(([type, design]) => [type, { ...design, editable: true }]) + ), + 'admin-forgot-password': broken + ? { + ...CORE_DESIGNS['reset-password'], + mode: 'provider', + providerTemplate: 'sendgrid:admin-reset', + templateName: null, + provider: 'sendgrid', + status: 'missing', + usable: false, + problem: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE', + checkedAt: '2026-11-19T08:00:00.000Z', + editable, + } + : { ...CORE_DESIGNS['reset-password'], editable }, +}); + +test('core emails: the admin password reset row offers the design choice to super admins only', async () => { + for (const editable of [true, false]) { + providerRoutes(); + network.on('GET', '/magic-mail/designer/core-designs', { + data: coreDesignsWithAdmin({ editable }), + }); + const result = await checkStrictEntry(, { + path: '/plugins/magic-mail/designer', + permissions: ALL, + async whileMounted() { + await clickLabel('Core emails'); + await wait(50); + assert.match(document.body.textContent, /Admin password reset/); + assert.match(document.body.textContent, /subject and body from Users & Permissions/); + assert.equal(button('Edit Admin password reset'), undefined, 'no local editor'); + assert.ok(button('Edit Reset password')); + if (editable) { + await clickLabel('Choose design of Admin password reset'); + assert.match(document.body.textContent, /Design of Admin password reset/); + await clickLabel('Close'); + await wait(50); + } else { + assert.equal(button('Choose design of Admin password reset'), undefined); + assert.ok(button('Choose design of Reset password')); + } + }, + }); + assert.equal(mutations(result.calls).length, 0, 'no mutation'); + } +}); + +test('dashboard: the core email alert names the admin mail with its reason and check time', async () => { + pluginRoutes(); + network.on('GET', '/magic-mail/accounts', { data: [ACCOUNT, BREVO_ACCOUNT] }); + network.on('GET', '/magic-mail/designer/core-designs', { + data: coreDesignsWithAdmin({ editable: true, broken: true }), + }); + const result = await checkStrictEntry(, { + path: '/plugins/magic-mail', + permissions: ALL, + async whileMounted() { + await wait(50); + const alert = document.querySelector('[role="alert"]'); + assert.ok(alert, 'alert is shown'); + assert.match(alert.textContent, /Admin password reset \(deleted or unpublished/); + assert.match(alert.textContent, /Last checked:/); + }, + }); + assert.equal(mutations(result.calls).length, 0, 'no mutation'); +}); diff --git a/tests/core-mails-integration.test.js b/tests/core-mails-integration.test.js new file mode 100644 index 0000000..e6d043a --- /dev/null +++ b/tests/core-mails-integration.test.js @@ -0,0 +1,638 @@ +'use strict'; + +// Core emails through provider templates (Strapi RFC #27752 gaps) against the +// fake SendGrid and Mailgun servers: email confirmation end to end through +// both providers, password reset and admin forgot password through Mailgun +// and SendGrid, the SendGrid subject injection, the provider-template events +// and the startup check. Synthetic data only; no request leaves 127.0.0.1. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { + createState, + redirectProviderFetch, + startFakeProviders, +} = require('./helpers/fake-template-providers'); +const { createStrapi, quietLog } = require('./helpers/provider-template-strapi'); +const { encryptCredentials } = require('../server/src/utils/encryption'); +const bootstrap = require('../server/src/bootstrap'); + +const { installEmailInterception, uninstallEmailInterception } = bootstrap; + +let fake; +let state; +let restoreFetch; +let previousKey; + +test.before(async () => { + previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = 'q'.repeat(32); + state = createState(); + fake = await startFakeProviders(state); + restoreFetch = redirectProviderFetch(fake.port); +}); + +test.after(async () => { + restoreFetch(); + await fake.close(); + if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey; +}); + +function reset() { + const fresh = createState(); + for (const key of Object.keys(fresh)) state[key] = fresh[key]; +} + +const sendgridAccount = (documentId) => ({ + documentId, + name: documentId, + provider: 'sendgrid', + fromEmail: `noreply@${documentId}.example.test`, + fromName: 'Synthetic', + isActive: true, + priority: 5, + config: encryptCredentials({ apiKey: `SG.${documentId}` }), +}); + +const mailgunAccount = (documentId) => ({ + documentId, + name: documentId, + provider: 'mailgun', + fromEmail: 'noreply@mg.example.test', + isActive: true, + priority: 4, + config: encryptCredentials({ + apiKey: `key-${documentId}`, + domain: 'mg.example.test', + region: 'us', + }), +}); + +const sgTemplate = (id, name, subject = '{{subject}}') => ({ + id, + name, + updated_at: '2026-11-10 08:30:00', + versions: [ + { + id: `${id}-v1`, + template_id: id, + active: 1, + name: 'v1', + subject, + html_content: '

{{url}}

', + plain_content: '{{url}}', + updated_at: '2026-11-11 09:00:00', + }, + ], +}); + +const mgTemplate = (name) => ({ + name, + id: `mg-${name}`, + createdAt: 'Mon, 10 Nov 2026 08:30:00 UTC', + version: { + tag: 'v1', + template: '

{{url}}

', + engine: 'handlebars', + createdAt: 'Tue, 11 Nov 2026 09:00:00 UTC', + active: true, + id: `mg-${name}-v1`, + headers: { Subject: 'Synthetic subject' }, + }, +}); + +const sends = (host) => + state.requests.filter( + (r) => r.host === host && r.method === 'POST' && /\/(mail\/send|messages)$/.test(r.path) + ); + +const interpolate = (layout, data) => + layout.replace(/<%=\s*([\w.]+)\s*%>/g, (_, path) => + String(path.split('.').reduce((value, part) => value?.[part], data) ?? '') + ); + +/** users-permissions template(): lodash-style <%= KEY %> interpolation. */ +function fakeUsersPermissions() { + const service = { template: (layout, data) => interpolate(layout, data) }; + return { service: (name) => (name === 'users-permissions' ? service : null), _service: service }; +} + +/** + * @strapi/email 5.63 double: send() and sendTemplatedEmail() both end in + * provider.send(); sendTemplatedEmail renders subject/text/html first. + */ +function emailPluginDouble() { + const nativeSends = []; + const provider = { + send: async (options) => { + nativeSends.push(options); + return { messageId: 'native' }; + }, + }; + const service = { + send: (options) => provider.send(options), + sendTemplatedEmail: (options, template, data) => { + const rendered = {}; + for (const field of ['subject', 'text', 'html']) { + if (template[field]) rendered[field] = interpolate(template[field], data); + } + return provider.send({ ...options, ...rendered }); + }, + }; + return { plugin: { provider, service: () => service }, service, nativeSends }; +} + +const ADMIN_URL = 'https://cms.example.test/admin'; +const SERVER_URL = 'https://cms.example.test'; +const ADMIN_TEMPLATE = Object.freeze({ + subject: 'Reset password', + text: 'Reset your password: <%= url %>', + html: '

Reset your password: <%= url %>

', +}); +const CONFIG = { + 'admin.absoluteUrl': ADMIN_URL, + 'server.absoluteUrl': SERVER_URL, + 'admin.forgotPassword.emailTemplate': ADMIN_TEMPLATE, + 'info.strapi': '5.63.0', +}; +const SUPER_ADMIN = { id: 1, roles: [{ code: 'strapi-super-admin' }] }; + +/** Mirrors @strapi/admin 5.63 services/auth.js forgotPassword(). */ +function adminForgotPassword(email, template = ADMIN_TEMPLATE) { + return email.service.sendTemplatedEmail( + { to: 'admin@example.test', from: undefined, replyTo: undefined }, + template, + { + url: `${ADMIN_URL}/auth/reset-password?code=admintok42`, + user: { email: 'admin@example.test', firstname: 'Grace', lastname: 'Hopper', username: null }, + } + ); +} + +/** Mirrors users-permissions 5.63 sendConfirmationEmail(). */ +function sendConfirmation(up, email) { + const data = { + URL: `${SERVER_URL}/api/auth/email-confirmation`, + SERVER_URL, + ADMIN_URL, + USER: { + id: 9, + documentId: 'user9', + email: 'new@example.test', + username: 'new.user', + confirmed: false, + }, + CODE: 'conf123', + }; + const message = up._service.template('

Confirm: <%= URL %>?confirmation=<%= CODE %>

', data); + const subject = up._service.template('Account confirmation', { USER: data.USER }); + return email.service.send({ + to: 'new@example.test', + from: undefined, + replyTo: 'support@example.test', + subject, + text: message, + html: message, + }); +} + +/** Mirrors users-permissions 5.63 forgotPassword(). */ +function sendReset(up, email, baseUrl = 'https://app.example.test/reset') { + const data = { + URL: baseUrl, + SERVER_URL, + ADMIN_URL, + USER: { id: 7, email: 'user@example.test', username: 'user.seven' }, + TOKEN: 'tok123', + }; + const message = up._service.template('

Reset: <%= URL %>?code=<%= TOKEN %>

', data); + return email.service.send({ + to: 'user@example.test', + subject: 'Reset password', + text: message, + html: message, + }); +} + +/** A harness with interception installed for one provider account. */ +async function setup({ accounts, adminUser = { id: 3, preferedLanguage: 'de-AT' }, log } = {}) { + const up = fakeUsersPermissions(); + const email = emailPluginDouble(); + const db = { + query: (uid) => ({ + findOne: async () => (uid === 'admin::user' ? adminUser : null), + }), + }; + const h = createStrapi({ + accounts, + emailPlugin: email.plugin, + usersPermissions: up, + config: CONFIG, + db, + ...(log ? { log } : {}), + }); + installEmailInterception(h.strapi, log || quietLog); + await h.service('provider-templates').sync({ force: true }); + return { h, up, email, service: h.service('provider-templates') }; +} + +// ─── Email confirmation end to end ──────────────────────────────────────── + +test('email confirmation through a SendGrid template: v1 payload, no designer body', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-confirm', 'Confirm email')]; + const { h, up, email, service } = await setup({ accounts: [sendgridAccount('sg1')] }); + try { + await service.setCoreDesign( + 'email-confirmation', + { providerTemplate: 'sendgrid:confirm-email' }, + { id: 1 } + ); + await sendConfirmation(up, email); + assert.equal(email.nativeSends.length, 0); + const json = sends('api.sendgrid.com')[0].json; + assert.equal(json.template_id, 'd-confirm'); + assert.equal(json.content, undefined, 'no designer body'); + assert.equal(json.subject, undefined, 'the users-permissions subject is not sent'); + const data = json.personalizations[0].dynamic_template_data; + assert.equal(data.CODE, 'conf123'); + assert.equal(data.code, 'conf123'); + assert.equal(data.url, `${SERVER_URL}/api/auth/email-confirmation?confirmation=conf123`); + assert.deepEqual(data.user, { id: 9, email: 'new@example.test', username: 'new.user' }); + assert.equal(data.subject, undefined, 'no subject is injected for core mails'); + assert.deepEqual(data.meta, { + templateKey: 'sendgrid:confirm-email', + payloadVersion: 1, + coreEmailType: 'email-confirmation', + strapiVersion: '5.63.0', + }); + assert.equal(json.reply_to.email, 'support@example.test', 'Reply-To from Strapi is kept'); + assert.equal(json.from.email, 'noreply@sg1.example.test'); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +test('email confirmation through a Mailgun template: template, t:variables, template subject', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('confirm-email')]; + const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')] }); + try { + await service.setCoreDesign( + 'email-confirmation', + { providerTemplate: 'mailgun:confirm-email' }, + { id: 1 } + ); + await sendConfirmation(up, email); + assert.equal(email.nativeSends.length, 0); + const form = Object.fromEntries(sends('api.mailgun.net')[0].form); + assert.equal(form.template, 'confirm-email'); + assert.equal(form.subject, undefined, 'the Mailgun template Subject header is used'); + assert.equal(form.html, undefined); + const vars = JSON.parse(form['t:variables']); + assert.equal(vars.url, `${SERVER_URL}/api/auth/email-confirmation?confirmation=conf123`); + assert.equal(vars.meta.coreEmailType, 'email-confirmation'); + assert.equal(form['h:Reply-To'], 'support@example.test'); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +// ─── Mailgun core path: password reset and admin forgot password ──────────── + +test('Mailgun: password reset through the chosen template with the v1 payload', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('reset-password')]; + const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')] }); + try { + await service.setCoreDesign( + 'reset-password', + { providerTemplate: 'mailgun:reset-password' }, + { id: 1 } + ); + await sendReset(up, email); + const form = Object.fromEntries(sends('api.mailgun.net')[0].form); + assert.equal(form.template, 'reset-password'); + const vars = JSON.parse(form['t:variables']); + assert.equal(vars.TOKEN, 'tok123'); + assert.equal(vars.url, 'https://app.example.test/reset?code=tok123'); + assert.deepEqual(vars.USER, { id: 7, email: 'user@example.test', username: 'user.seven' }); + assert.equal(vars.meta.strapiVersion, '5.63.0'); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +test('Mailgun: admin forgot password through the chosen template with payload v1', async () => { + reset(); + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('admin-reset')]; + const { h, email, service } = await setup({ accounts: [mailgunAccount('mg1')] }); + try { + await assert.rejects( + service.setCoreDesign( + 'admin-forgot-password', + { providerTemplate: 'mailgun:admin-reset' }, + { id: 2, roles: [{ code: 'strapi-editor' }] } + ), + (error) => error.name === 'ForbiddenError' + ); + await service.setCoreDesign( + 'admin-forgot-password', + { providerTemplate: 'mailgun:admin-reset' }, + SUPER_ADMIN + ); + await adminForgotPassword(email); + assert.equal(email.nativeSends.length, 0, 'Strapi did not render or send its own body'); + const form = Object.fromEntries(sends('api.mailgun.net')[0].form); + assert.equal(form.template, 'admin-reset'); + assert.equal(form.to, 'admin@example.test'); + assert.equal(form.subject, undefined); + assert.deepEqual(JSON.parse(form['t:variables']), { + user: { + id: 3, + email: 'admin@example.test', + firstname: 'Grace', + lastname: 'Hopper', + }, + url: `${ADMIN_URL}/auth/reset-password?code=admintok42`, + token: 'admintok42', + adminUrl: ADMIN_URL, + serverUrl: SERVER_URL, + meta: { + templateKey: 'mailgun:admin-reset', + payloadVersion: 1, + coreEmailType: 'admin-forgot-password', + locale: 'de-AT', + strapiVersion: '5.63.0', + }, + }); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +test('admin forgot password without a provider template: Strapi renders the local body as before', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-admin', 'Admin reset')]; + const { h, email } = await setup({ accounts: [sendgridAccount('sg1')] }); + try { + await adminForgotPassword(email); + const json = sends('api.sendgrid.com')[0].json; + assert.equal(json.template_id, undefined); + assert.equal(json.subject, 'Reset password'); + assert.match(json.content[1].value, /admintok42/); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +test('SendGrid: admin forgot password via template, strict error, opt-in Strapi fallback, events', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-admin', 'Admin reset')]; + const { h, email, service } = await setup({ accounts: [sendgridAccount('sg1')] }); + try { + await service.setCoreDesign( + 'admin-forgot-password', + { providerTemplate: 'sendgrid:admin-reset' }, + SUPER_ADMIN + ); + await adminForgotPassword(email); + const data = sends('api.sendgrid.com')[0].json.personalizations[0].dynamic_template_data; + assert.equal(data.token, 'admintok42'); + assert.equal(data.meta.coreEmailType, 'admin-forgot-password'); + + // The template disappears: strict by default, nothing else is sent. + state.sendgrid.us = []; + await service.sync({ force: true }); + h.events.length = 0; + await assert.rejects( + adminForgotPassword(email), + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + assert.equal(sends('api.sendgrid.com').length, 1); + assert.deepEqual(h.events, [ + { + name: 'magic-mail.provider-template.failed', + payload: { + key: 'sendgrid:admin-reset', + code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE', + coreEmailType: 'admin-forgot-password', + }, + }, + ]); + + // Opt-in fallback: the Strapi admin email is rendered and sent instead. + await service.setCoreDesign( + 'admin-forgot-password', + { providerTemplate: 'sendgrid:admin-reset', fallbackToDesigner: true }, + SUPER_ADMIN + ); + h.events.length = 0; + await adminForgotPassword(email); + const local = sends('api.sendgrid.com')[1].json; + assert.equal(local.template_id, undefined); + assert.equal(local.subject, 'Reset password'); + assert.match(local.content[1].value, /admintok42/); + assert.deepEqual( + h.events.map((event) => event.name), + ['magic-mail.provider-template.failed', 'magic-mail.provider-template.fallback'] + ); + assert.deepEqual(h.events[1].payload, { + key: 'sendgrid:admin-reset', + code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE', + coreEmailType: 'admin-forgot-password', + fallback: 'designer', + }); + const serialized = JSON.stringify(h.events); + assert.equal(serialized.includes('admin@example.test'), false, 'no addresses in events'); + assert.equal(serialized.includes('admintok42'), false, 'no tokens in events'); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +// ─── Missing url warning ───────────────────────────────────────────────── + +test('a core mail whose base URL is not absolute warns once and sends url ""', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-reset', 'Reset password')]; + const warnings = []; + const log = { ...quietLog, warn: (message) => warnings.push(String(message)) }; + const { h, up, email, service } = await setup({ accounts: [sendgridAccount('sg1')], log }); + try { + await service.setCoreDesign( + 'reset-password', + { providerTemplate: 'sendgrid:reset-password' }, + { id: 1 } + ); + await sendReset(up, email, 'null'); + await sendReset(up, email, '/relative/reset'); + const first = sends('api.sendgrid.com')[0].json.personalizations[0].dynamic_template_data; + assert.equal(first.url, ''); + const urlWarnings = warnings.filter((message) => message.includes('"url" can not be built')); + assert.equal(urlWarnings.length, 1, 'warned once per process and core mail'); + assert.match(urlWarnings[0], /reset-password/); + assert.equal(urlWarnings[0].includes('tok123'), false); + } finally { + uninstallEmailInterception(h.strapi); + } +}); + +// ─── SendGrid subject injection ──────────────────────────────────────────── + +test('SendGrid: a passed subject becomes dynamic_template_data.subject unless data sets one', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-news', 'News')]; + const h = createStrapi({ accounts: [sendgridAccount('sg1')] }); + await h.service('provider-templates').sync({ force: true }); + const router = h.service('email-router'); + + await router.send({ + to: 'a@example.test', + providerTemplate: 'sendgrid:news', + subject: 'Per-mail subject\r\nBcc: x@example.test', + data: { name: 'Ada' }, + }); + let json = sends('api.sendgrid.com')[0].json; + assert.deepEqual(json.personalizations[0].dynamic_template_data, { + name: 'Ada', + subject: 'Per-mail subjectBcc: x@example.test', + }); + + await router.send({ + to: 'a@example.test', + providerTemplate: 'sendgrid:news', + subject: 'Ignored', + data: { subject: 'From data' }, + }); + json = sends('api.sendgrid.com')[1].json; + assert.equal(json.personalizations[0].dynamic_template_data.subject, 'From data'); + + await router.send({ to: 'a@example.test', providerTemplate: 'sendgrid:news', data: {} }); + json = sends('api.sendgrid.com')[2].json; + assert.deepEqual(json.personalizations[0].dynamic_template_data, {}); +}); + +// ─── Startup check ───────────────────────────────────────────────────────── + +test('startup check: syncs a stale list, warns with key and code, stores the result', async () => { + reset(); + state.sendgrid.us = [sgTemplate('d-reset', 'Reset password')]; + state.mailgun.us.domains['mg.example.test'] = [mgTemplate('admin-reset')]; + const warnings = []; + const log = { ...quietLog, warn: (message) => warnings.push(String(message)) }; + const h = createStrapi({ accounts: [sendgridAccount('sg1'), mailgunAccount('mg1')], log }); + const service = h.service('provider-templates'); + await service.sync({ force: true }); + await service.setCoreDesign( + 'reset-password', + { providerTemplate: 'sendgrid:reset-password' }, + { id: 1 } + ); + await service.setCoreDesign( + 'admin-forgot-password', + { providerTemplate: 'mailgun:admin-reset' }, + SUPER_ADMIN + ); + // A key that was never synced (for example typed into a restored database). + await service.updateState((current) => ({ + ...current, + coreMails: { + ...current.coreMails, + 'email-confirmation': { providerTemplate: 'sendgrid:never-synced' }, + }, + })); + + // The Mailgun template is deleted at the provider; the last sync is stale. + state.mailgun.us.domains['mg.example.test'] = []; + await service.updateState((current) => ({ + ...current, + lastSyncedAt: new Date(Date.now() - 60 * 60 * 1000).toISOString(), + })); + const syncRequestsBefore = state.requests.filter((r) => r.method === 'GET').length; + + await bootstrap.checkCoreDesignsAtStart(h.strapi, log); + + assert.ok( + state.requests.filter((r) => r.method === 'GET').length > syncRequestsBefore, + 'the stale list was synced' + ); + const problems = warnings.filter((message) => message.includes('Core email')); + assert.equal(problems.length, 2); + assert.ok( + problems.some( + (m) => + m.includes('admin-forgot-password') && + m.includes('mailgun:admin-reset') && + m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE') + ) + ); + assert.ok( + problems.some( + (m) => + m.includes('email-confirmation') && + m.includes('sendgrid:never-synced') && + m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN') + ) + ); + const designs = await service.coreDesigns(SUPER_ADMIN); + assert.equal(designs['reset-password'].usable, true); + assert.equal(designs['reset-password'].problem, null); + assert.equal( + designs['admin-forgot-password'].problem, + 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNAVAILABLE' + ); + assert.equal(designs['email-confirmation'].problem, 'MAGIC_MAIL_PROVIDER_TEMPLATE_UNKNOWN'); + assert.ok(Date.parse(designs['admin-forgot-password'].checkedAt) > 0); + assert.equal(designs['admin-forgot-password'].editable, true); + const stored = (await service.getState()).coreCheck; + assert.equal(stored.problems.length, 2); + + // A fresh list is not synced again. + const before = state.requests.length; + const fresh = await service.checkCoreDesigns({ syncIfStale: true }); + assert.equal(fresh.synced, false); + assert.equal(state.requests.length, before); +}); + +test('startup check without provider-template core emails does nothing', async () => { + reset(); + const h = createStrapi({ accounts: [sendgridAccount('sg1')] }); + const result = await h.service('provider-templates').checkCoreDesigns(); + assert.deepEqual(result, { checkedAt: null, synced: false, syncError: null, problems: [] }); + assert.equal(state.requests.length, 0); +}); + +test('a Mailgun template without Subject header is reported as unusable for core emails', async () => { + reset(); + const noSubject = mgTemplate('plain'); + noSubject.version.headers = {}; + state.mailgun.us.domains['mg.example.test'] = [noSubject]; + const warnings = []; + const log = { ...quietLog, warn: (message) => warnings.push(String(message)) }; + const { h, up, email, service } = await setup({ accounts: [mailgunAccount('mg1')], log }); + try { + await service.setCoreDesign('reset-password', { providerTemplate: 'mailgun:plain' }, { id: 1 }); + const designs = await service.coreDesigns(); + assert.equal(designs['reset-password'].usable, false); + assert.equal(designs['reset-password'].problem, 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT'); + const result = await service.checkCoreDesigns({ syncIfStale: false }); + assert.deepEqual(result.problems, [ + { + coreEmailType: 'reset-password', + key: 'mailgun:plain', + code: 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT', + }, + ]); + assert.ok(warnings.some((m) => m.includes('MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT'))); + // The send fails before anything reaches Mailgun (strict default). + await assert.rejects( + sendReset(up, email), + (error) => error.code === 'MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT' + ); + assert.equal(sends('api.mailgun.net').length, 0); + } finally { + uninstallEmailInterception(h.strapi); + } +}); diff --git a/tests/core-mails-units.test.js b/tests/core-mails-units.test.js new file mode 100644 index 0000000..cb57dc3 --- /dev/null +++ b/tests/core-mails-units.test.js @@ -0,0 +1,236 @@ +'use strict'; + +// Units for the core-mail additions of Strapi RFC #27752: the +// admin-forgot-password payload v1, meta.strapiVersion, the admin +// sendTemplatedEmail recognition, sample data for every core type and the +// provider-template event payload. Synthetic data only. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const { + CORE_EMAIL_TYPES, + buildCoreMailPayload, + coreMailVariableNames, +} = require('../server/src/utils/core-mail-payload'); +const { adminForgotPasswordMail } = require('../server/src/bootstrap'); +const { emitProviderTemplateEvent } = require('../server/src/utils/provider-template-events'); +const { createStrapi } = require('./helpers/provider-template-strapi'); + +const ADMIN_URL = 'https://cms.example.test/admin'; +const TEMPLATE = { subject: 's', text: 't' }; +const strapiWith = (config) => ({ + config: { get: (key) => config[key] }, +}); + +test('core email types include the admin forgot-password mail', () => { + assert.deepEqual(CORE_EMAIL_TYPES, [ + 'reset-password', + 'email-confirmation', + 'admin-forgot-password', + ]); +}); + +test('admin forgot-password payload v1: user allowlist, built url, token, URLs, meta', () => { + const payload = buildCoreMailPayload( + 'admin-forgot-password', + { + url: `${ADMIN_URL}/auth/reset-password?code=abc123`, + user: { + id: 4, + email: 'a@example.test', + firstname: 'Ada', + lastname: 'Lovelace', + username: 'ada', + password: 'never', + resetPasswordToken: 'never', + }, + adminUrl: ADMIN_URL, + serverUrl: 'https://cms.example.test', + }, + { templateKey: 'sendgrid:admin-reset', locale: 'fr', strapiVersion: '5.63.0' } + ); + assert.deepEqual(payload, { + user: { + id: 4, + email: 'a@example.test', + username: 'ada', + firstname: 'Ada', + lastname: 'Lovelace', + }, + url: `${ADMIN_URL}/auth/reset-password?code=abc123`, + token: 'abc123', + adminUrl: ADMIN_URL, + serverUrl: 'https://cms.example.test', + meta: { + templateKey: 'sendgrid:admin-reset', + payloadVersion: 1, + coreEmailType: 'admin-forgot-password', + locale: 'fr', + strapiVersion: '5.63.0', + }, + }); +}); + +test('admin forgot-password: a relative or invalid link gives url "" and no token', () => { + for (const url of ['/admin/auth/reset-password?code=x', 'javascript:alert(1)', '', null]) { + const payload = buildCoreMailPayload('admin-forgot-password', { url, user: {} }, {}); + assert.equal(payload.url, ''); + assert.equal(payload.token, ''); + } +}); + +test('meta.strapiVersion is additive: omitted when unknown, existing keys unchanged', () => { + const captured = { + URL: 'https://app.example.test/reset', + USER: { id: 1, email: 'u@example.test' }, + TOKEN: 't', + }; + const without = buildCoreMailPayload('reset-password', captured, { templateKey: 'k' }); + assert.deepEqual(Object.keys(without.meta), ['templateKey', 'payloadVersion', 'coreEmailType']); + const withVersion = buildCoreMailPayload('reset-password', captured, { + templateKey: 'k', + strapiVersion: '5.63.0', + }); + assert.equal(withVersion.meta.strapiVersion, '5.63.0'); + const { meta: a, ...restA } = without; + const { meta: b, ...restB } = withVersion; + assert.deepEqual(restA, restB); + assert.equal(a.payloadVersion, b.payloadVersion); +}); + +test('variable names for the admin mail list the v1 keys only', () => { + const names = coreMailVariableNames('admin-forgot-password'); + for (const name of ['user', 'user.email', 'url', 'token', 'adminUrl', 'serverUrl', 'meta']) { + assert.ok(names.includes(name), name); + } + assert.ok(names.includes('meta.strapiVersion')); + assert.equal(names.includes('TOKEN'), false); + assert.ok(coreMailVariableNames('reset-password').includes('meta.strapiVersion')); +}); + +test('admin sendTemplatedEmail call is recognised by template identity or reset link', () => { + const strapi = strapiWith({ + 'admin.absoluteUrl': ADMIN_URL, + 'server.absoluteUrl': 'https://cms.example.test', + 'admin.forgotPassword.emailTemplate': TEMPLATE, + }); + const data = { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: { email: 'a@x.test' } }; + const options = { to: 'a@x.test' }; + + assert.deepEqual(adminForgotPasswordMail(strapi, [options, TEMPLATE, data]), { + url: data.url, + user: data.user, + adminUrl: ADMIN_URL, + serverUrl: 'https://cms.example.test', + }); + // A custom template object configured elsewhere: the reset link decides. + assert.ok(adminForgotPasswordMail(strapi, [options, { subject: 'x', text: 'y' }, data])); + // Same template, but the host overrode admin.url between calls: identity decides. + assert.ok( + adminForgotPasswordMail(strapi, [ + options, + TEMPLATE, + { url: 'https://other.example.test/x?code=1', user: {} }, + ]) + ); +}); + +test('other sendTemplatedEmail calls are not treated as the admin mail', () => { + const strapi = strapiWith({ + 'admin.absoluteUrl': ADMIN_URL, + 'admin.forgotPassword.emailTemplate': TEMPLATE, + }); + const other = { subject: 'Welcome', text: 'Hi' }; + const cases = [ + [{ to: 'a@x.test' }, other, { url: 'https://app.example.test/welcome', user: {} }], + [{ to: 'a@x.test' }, other, { url: `${ADMIN_URL}/auth/login`, user: {} }], + [ + { to: 'a@x.test' }, + TEMPLATE, + { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: {}, extra: 1 }, + ], + [{ to: 'a@x.test' }, TEMPLATE, { url: `${ADMIN_URL}/auth/reset-password?code=x` }], + [{ to: 'a@x.test' }, TEMPLATE, { url: 42, user: {} }], + [{ to: 'a@x.test' }, TEMPLATE, null], + [null, TEMPLATE, { url: `${ADMIN_URL}/auth/reset-password?code=x`, user: {} }], + ]; + for (const args of cases) assert.equal(adminForgotPasswordMail(strapi, args), null); +}); + +test('test-send sample data covers every core mail that uses the template', () => { + const h = createStrapi(); + const service = h.service('provider-templates'); + const sample = service.sampleData( + { key: 'sendgrid:shared', usedByCoreMails: ['reset-password', 'admin-forgot-password'] }, + 'me@example.test' + ); + assert.equal(sample.TOKEN, 'sample-token', 'reset-password variables'); + assert.equal(sample.adminUrl, 'https://api.example.test/admin'); + assert.equal(sample.user.email, 'me@example.test'); + assert.equal( + sample.meta.coreEmailType, + 'reset-password', + 'the first core mail wins shared names' + ); + assert.equal(sample.name, 'Test User'); + + const confirmAndAdmin = service.sampleData( + { key: 'sendgrid:shared', usedByCoreMails: ['email-confirmation', 'admin-forgot-password'] }, + 'me@example.test' + ); + assert.equal(confirmAndAdmin.CODE, 'sample-code'); + assert.equal(confirmAndAdmin.token, 'sample-token', 'admin token present as well'); + assert.match(confirmAndAdmin.url, /confirmation=sample-code/); + + const plain = service.sampleData({ key: 'sendgrid:x', usedByCoreMails: [] }, 'me@example.test'); + assert.deepEqual(plain, { name: 'Test User', email: 'me@example.test' }); +}); + +test('provider-template events carry key, code and labels only', async () => { + const events = []; + const strapi = { eventHub: { emit: async (name, payload) => events.push({ name, payload }) } }; + await emitProviderTemplateEvent(strapi, 'failed', { + key: 'mailgun:x', + code: 'HTTP_404', + coreEmailType: null, + to: 'leak@example.test', + data: { token: 'leak' }, + }); + assert.deepEqual(events, [ + { + name: 'magic-mail.provider-template.failed', + payload: { key: 'mailgun:x', code: 'HTTP_404', coreEmailType: null }, + }, + ]); + + const warnings = []; + await emitProviderTemplateEvent( + { + log: { warn: (message) => warnings.push(message) }, + eventHub: { + emit: async () => { + throw new Error('listener'); + }, + }, + }, + 'fallback', + { key: 'k', code: null } + ); + assert.equal(warnings.length, 1, 'a failing listener is logged, never thrown'); + await emitProviderTemplateEvent({}, 'failed', { key: 'k', code: null }); +}); + +test('the admin forgot-password design is editable by super admins only', async () => { + const h = createStrapi(); + const service = h.service('provider-templates'); + const editor = { id: 2, roles: [{ code: 'strapi-editor' }] }; + const designs = await service.coreDesigns(editor); + assert.equal(designs['admin-forgot-password'].editable, false); + assert.equal(designs['reset-password'].editable, true); + assert.equal(designs['admin-forgot-password'].mode, 'designer'); + assert.equal((await service.coreDesigns())['reset-password'].editable, undefined); + await assert.rejects( + service.setCoreDesign('admin-forgot-password', { providerTemplate: null }, editor), + (error) => error.name === 'ForbiddenError' + ); +}); diff --git a/tests/helpers/provider-template-strapi.js b/tests/helpers/provider-template-strapi.js index 21cb50e..d6aaca3 100644 --- a/tests/helpers/provider-template-strapi.js +++ b/tests/helpers/provider-template-strapi.js @@ -39,7 +39,9 @@ function matches(row, filters = {}) { } /** - * @param {{accounts?: object[], localTemplates?: object[], log?: object, upTemplate?: Function}} [options] + * @param {{accounts?: object[], localTemplates?: object[], log?: object, emailPlugin?: object, + * usersPermissions?: object, config?: Record, db?: object}} [options] + * `config` answers strapi.config.get(key); `db` becomes strapi.db * @returns {{strapi: object, tables: object, logs: object[], store: Map, service: Function}} */ function createStrapi({ @@ -48,6 +50,8 @@ function createStrapi({ log = quietLog, emailPlugin = null, usersPermissions = null, + config = {}, + db = null, } = {}) { let counter = 0; const nextId = () => `doc${(counter += 1)}`; @@ -67,7 +71,10 @@ function createStrapi({ const strapi = { log, magicMail: {}, - config: { get: (key, fallback) => fallback }, + config: { + get: (key, fallback) => (Object.hasOwn(config, key) ? config[key] : fallback), + }, + ...(db ? { db } : {}), eventHub: { emit: (name, payload) => events.push({ name, payload }) }, store: async ({ type, name }) => ({ get: async ({ key }) => { diff --git a/tests/live/core-mails.live.test.js b/tests/live/core-mails.live.test.js new file mode 100644 index 0000000..3217873 --- /dev/null +++ b/tests/live/core-mails.live.test.js @@ -0,0 +1,382 @@ +'use strict'; + +// Opt-in live suite for the core emails (Strapi RFC #27752) against the REAL +// SendGrid and Mailgun APIs: email confirmation, password reset and the admin +// password reset routed through provider templates, the SendGrid subject +// injection and the startup check. +// +// Run: npm run test:live (with the other live suites) +// LIVE_PROVIDERS=sendgrid,mailgun node --test tests/live/core-mails.live.test.js +// Needs the same ~/.config/magic-mail-live/.env as provider-templates.live.test.js +// (SENDGRID_API_KEY, SENDGRID_FROM, SENDGRID_TEMPLATE_ID, MAILGUN_API_KEY, +// MAILGUN_DOMAIN, MAILGUN_REGION, MAILGUN_TEMPLATE, LIVE_TEST_RECIPIENT). The +// SendGrid key needs Template Engine write access and the Mailgun key template +// write access: this suite creates two synthetic templates +// (`magic-mail-live-core-`) and deletes them again in `after`. +// +// Nothing is delivered: SendGrid sends run in sandbox mode and Mailgun sends +// with o:testmode=yes (forced by installLiveFetch). Values are never printed. + +const test = require('node:test'); +const assert = require('node:assert/strict'); +const crypto = require('node:crypto'); +const { PROVIDERS, installLiveFetch, loadLiveConfig } = require('../helpers/live-env'); + +const { env, skipReason } = loadLiveConfig({ + sendgrid: ['SENDGRID_API_KEY', 'SENDGRID_FROM', 'SENDGRID_TEMPLATE_ID', 'LIVE_TEST_RECIPIENT'], + mailgun: [ + 'MAILGUN_API_KEY', + 'MAILGUN_DOMAIN', + 'MAILGUN_REGION', + 'MAILGUN_TEMPLATE', + 'LIVE_TEST_RECIPIENT', + ], +}); + +const ready = PROVIDERS.filter((provider) => !skipReason(provider)); +for (const provider of PROVIDERS) { + const reason = skipReason(provider); + if (reason) console.log(`live core-mail suite: ${provider} tests skipped: ${reason}`); +} +const liveFor = (provider) => (name, fn) => test(name, { skip: skipReason(provider) || false }, fn); +const liveSendGrid = liveFor('sendgrid'); +const liveMailgun = liveFor('mailgun'); + +const SUBJECT = 'Magic Mail live test (can be deleted)'; +const SYNTHETIC = `magic-mail-live-core-${crypto.randomBytes(4).toString('hex')}`; +const ADMIN_URL = 'https://cms.example.test/admin'; +const SERVER_URL = 'https://cms.example.test'; +const ADMIN_TEMPLATE = Object.freeze({ subject: 'Reset password', text: 'Reset: <%= url %>' }); +const SUPER_ADMIN = { id: 1, roles: [{ code: 'strapi-super-admin' }] }; + +const sgHost = () => (env.SENDGRID_REGION === 'eu' ? 'api.eu.sendgrid.com' : 'api.sendgrid.com'); +const mgHost = () => (env.MAILGUN_REGION === 'eu' ? 'api.eu.mailgun.net' : 'api.mailgun.net'); +const sgAuth = () => ({ Authorization: `Bearer ${env.SENDGRID_API_KEY}` }); +const mgAuth = () => ({ + Authorization: `Basic ${Buffer.from(`api:${env.MAILGUN_API_KEY}`).toString('base64')}`, +}); + +let live; +let previousKey; +const created = { sendgridId: null, mailgunName: null }; +const cleanup = { sendgrid: null, mailgun: null }; + +/** Creates the synthetic SendGrid dynamic template whose subject is {{subject}}. */ +async function createSendGridTemplate() { + const response = await fetch(`https://${sgHost()}/v3/templates`, { + method: 'POST', + headers: { ...sgAuth(), 'content-type': 'application/json' }, + body: JSON.stringify({ name: SYNTHETIC, generation: 'dynamic' }), + }); + assert.equal(response.status, 201, 'SendGrid template created (Template Engine write access)'); + const { id } = await response.json(); + created.sendgridId = id; + const version = await fetch(`https://${sgHost()}/v3/templates/${id}/versions`, { + method: 'POST', + headers: { ...sgAuth(), 'content-type': 'application/json' }, + body: JSON.stringify({ + template_id: id, + active: 1, + name: 'v1', + subject: '{{subject}}', + html_content: '

{{name}} {{url}}

', + plain_content: '{{name}} {{url}}', + }), + }); + assert.equal(version.status, 201, 'SendGrid template version created'); +} + +/** Creates the synthetic Mailgun domain template with a Subject header. */ +async function createMailgunTemplate() { + const form = new FormData(); + form.set('name', SYNTHETIC); + form.set('description', SUBJECT); + form.set('template', '

{{url}} {{user.email}} {{meta.coreEmailType}}

'); + form.set('engine', 'handlebars'); + form.set('tag', 'v1'); + form.set('headers', JSON.stringify({ Subject: SUBJECT })); + const response = await fetch( + `https://${mgHost()}/v3/${encodeURIComponent(env.MAILGUN_DOMAIN)}/templates`, + { method: 'POST', headers: mgAuth(), body: form } + ); + assert.equal(response.status, 200, 'Mailgun template created (template write access)'); + created.mailgunName = SYNTHETIC; +} + +test.before(async () => { + if (ready.length === 0) return; + previousKey = process.env.MAGIC_MAIL_ENCRYPTION_KEY; + process.env.MAGIC_MAIL_ENCRYPTION_KEY = crypto.randomBytes(32).toString('hex'); + live = installLiveFetch(); + if (ready.includes('sendgrid')) await createSendGridTemplate(); + if (ready.includes('mailgun')) await createMailgunTemplate(); +}); + +test.after(async () => { + if (ready.length === 0) return; + // Restore the accounts: delete both synthetic templates and confirm. + if (created.sendgridId) { + const response = await fetch(`https://${sgHost()}/v3/templates/${created.sendgridId}`, { + method: 'DELETE', + headers: sgAuth(), + }); + const check = await fetch(`https://${sgHost()}/v3/templates/${created.sendgridId}`, { + headers: sgAuth(), + }); + cleanup.sendgrid = { deleteStatus: response.status, afterStatus: check.status }; + } + if (created.mailgunName) { + const path = `/v3/${encodeURIComponent(env.MAILGUN_DOMAIN)}/templates/${created.mailgunName}`; + const response = await fetch(`https://${mgHost()}${path}`, { + method: 'DELETE', + headers: mgAuth(), + }); + const check = await fetch(`https://${mgHost()}${path}`, { headers: mgAuth() }); + cleanup.mailgun = { deleteStatus: response.status, afterStatus: check.status }; + } + live.restore(); + if (previousKey === undefined) delete process.env.MAGIC_MAIL_ENCRYPTION_KEY; + else process.env.MAGIC_MAIL_ENCRYPTION_KEY = previousKey; + console.log(JSON.stringify({ cleanup, liveRequests: live.results }, null, 1)); + if (cleanup.sendgrid) assert.equal(cleanup.sendgrid.afterStatus, 404, 'SendGrid cleanup'); + if (cleanup.mailgun) assert.equal(cleanup.mailgun.afterStatus, 404, 'Mailgun cleanup'); +}); + +const interpolate = (layout, data) => + layout.replace(/<%=\s*([\w.]+)\s*%>/g, (_, path) => + String(path.split('.').reduce((value, part) => value?.[part], data) ?? '') + ); + +let h; +let email; +let up; +/** Strapi harness with interception, one live account per ready provider. */ +function harness() { + if (h) return h; + const { createStrapi, quietLog } = require('../helpers/provider-template-strapi'); + const { encryptCredentials } = require('../../server/src/utils/encryption'); + const { installEmailInterception } = require('../../server/src/bootstrap'); + const accounts = []; + if (ready.includes('sendgrid')) { + accounts.push({ + documentId: 'live-sendgrid', + name: 'live-sendgrid', + provider: 'sendgrid', + fromEmail: env.SENDGRID_FROM, + isActive: true, + priority: 5, + config: encryptCredentials({ + apiKey: env.SENDGRID_API_KEY, + region: env.SENDGRID_REGION === 'eu' ? 'eu' : 'us', + }), + }); + } + if (ready.includes('mailgun')) { + accounts.push({ + documentId: 'live-mailgun', + 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: env.MAILGUN_REGION === 'eu' ? 'eu' : 'us', + }), + }); + } + const nativeSends = []; + const provider = { + send: async (options) => { + nativeSends.push(options); + return { messageId: 'native' }; + }, + }; + const service = { + send: (options) => provider.send(options), + sendTemplatedEmail: (options, template, data) => + provider.send({ + ...options, + subject: interpolate(template.subject, data), + text: interpolate(template.text, data), + }), + }; + email = { service, nativeSends }; + const upService = { template: (layout, data) => interpolate(layout, data) }; + up = upService; + h = createStrapi({ + accounts, + emailPlugin: { provider, service: () => service }, + usersPermissions: { service: (name) => (name === 'users-permissions' ? upService : null) }, + config: { + 'admin.absoluteUrl': ADMIN_URL, + 'server.absoluteUrl': SERVER_URL, + 'admin.forgotPassword.emailTemplate': ADMIN_TEMPLATE, + 'info.strapi': '5.63.0', + }, + db: { query: () => ({ findOne: async () => ({ id: 1, preferedLanguage: 'en' }) }) }, + }); + installEmailInterception(h.strapi, quietLog); + return h; +} + +let syncPromise; +const syncOnce = () => { + syncPromise ??= harness().service('provider-templates').sync({ force: true }); + return syncPromise; +}; +const rowKey = (predicate) => + harness().tables['plugin::magic-mail.provider-template'].find(predicate)?.key; + +/** users-permissions sendConfirmationEmail(), live recipient, synthetic user. */ +function confirmEmail() { + const data = { + URL: `${SERVER_URL}/api/auth/email-confirmation`, + SERVER_URL, + ADMIN_URL, + USER: { id: 9, email: env.LIVE_TEST_RECIPIENT, username: 'live.user' }, + CODE: crypto.randomBytes(8).toString('hex'), + }; + const body = up.template('

<%= URL %>?confirmation=<%= CODE %>

', data); + return email.service.send({ + to: env.LIVE_TEST_RECIPIENT, + subject: 'Account confirmation', + text: body, + html: body, + }); +} + +/** users-permissions forgotPassword(). */ +function resetPassword() { + const data = { + URL: 'https://app.example.test/reset', + SERVER_URL, + ADMIN_URL, + USER: { id: 9, email: env.LIVE_TEST_RECIPIENT, username: 'live.user' }, + TOKEN: crypto.randomBytes(8).toString('hex'), + }; + const body = up.template('

<%= URL %>?code=<%= TOKEN %>

', data); + return email.service.send({ + to: env.LIVE_TEST_RECIPIENT, + subject: 'Reset password', + text: body, + html: body, + }); +} + +/** @strapi/admin forgotPassword(). */ +function adminForgotPassword() { + return email.service.sendTemplatedEmail( + { to: env.LIVE_TEST_RECIPIENT, from: undefined, replyTo: undefined }, + ADMIN_TEMPLATE, + { + url: `${ADMIN_URL}/auth/reset-password?code=${crypto.randomBytes(8).toString('hex')}`, + user: { email: env.LIVE_TEST_RECIPIENT, firstname: 'Live', lastname: 'Test' }, + } + ); +} + +const CORE_SENDS = [ + ['email-confirmation', confirmEmail], + ['reset-password', resetPassword], + ['admin-forgot-password', adminForgotPassword], +]; + +// ── SendGrid ────────────────────────────────────────────────────────────── + +liveSendGrid('SendGrid: core emails go through the real dynamic template (sandbox)', async () => { + await syncOnce(); + const key = rowKey((r) => r.provider === 'sendgrid' && r.remoteId === env.SENDGRID_TEMPLATE_ID); + assert.ok(key, 'SENDGRID_TEMPLATE_ID synced'); + const service = harness().service('provider-templates'); + for (const [type, send] of CORE_SENDS) { + await service.setCoreDesign(type, { providerTemplate: key }, SUPER_ADMIN); + const result = await send(); + assert.equal(result.success, true, `${type} accepted by SendGrid`); + const body = live.sent.sendgrid.at(-1); + assert.equal(body.template_id, env.SENDGRID_TEMPLATE_ID); + assert.equal(body.mail_settings.sandbox_mode.enable, true); + const data = body.personalizations[0].dynamic_template_data; + assert.equal(data.meta.coreEmailType, type); + assert.equal(data.meta.payloadVersion, 1); + assert.equal(data.meta.strapiVersion, '5.63.0'); + assert.match(data.url, /^https:\/\//); + assert.equal(body.content, undefined, `${type}: no designer body`); + await service.setCoreDesign(type, { providerTemplate: null }, SUPER_ADMIN); + } + assert.equal(email.nativeSends.length, 0); +}); + +liveSendGrid('SendGrid: a passed subject reaches a {{subject}} template (sandbox)', async () => { + await syncOnce(); + const key = rowKey((r) => r.provider === 'sendgrid' && r.remoteId === created.sendgridId); + assert.ok(key, 'synthetic SendGrid template synced'); + const detail = await harness().service('provider-templates').detail(key); + assert.ok( + detail.variables.some((v) => v.path === 'subject'), + 'variable detection finds {{subject}} in the real template' + ); + const result = await harness() + .service('email-router') + .send({ + to: env.LIVE_TEST_RECIPIENT, + providerTemplate: key, + subject: SUBJECT, + data: { name: 'Live Test', url: 'https://example.test' }, + }); + assert.equal(result.success, true); + const body = live.sent.sendgrid.at(-1); + assert.equal(body.template_id, created.sendgridId); + assert.equal(body.personalizations[0].dynamic_template_data.subject, SUBJECT); +}); + +// ── Mailgun ─────────────────────────────────────────────────────────────── + +liveMailgun( + 'Mailgun: core emails go through a real template with Subject header (test mode)', + async () => { + await syncOnce(); + const key = rowKey((r) => r.provider === 'mailgun' && r.name === created.mailgunName); + assert.ok(key, 'synthetic Mailgun template synced'); + const service = harness().service('provider-templates'); + assert.equal( + (await service.overview()).templates.find((t) => t.key === key).subject, + SUBJECT, + 'the Subject header was synced' + ); + for (const [type, send] of CORE_SENDS) { + await service.setCoreDesign(type, { providerTemplate: key }, SUPER_ADMIN); + const result = await send(); + assert.equal(result.success, true, `${type} accepted by Mailgun`); + const form = Object.fromEntries(live.sent.mailgun.at(-1)); + assert.equal(form.template, created.mailgunName); + assert.equal(form['o:testmode'], 'yes'); + assert.equal(form.subject, undefined, 'the template Subject header is used'); + const vars = JSON.parse(form['t:variables']); + assert.equal(vars.meta.coreEmailType, type); + assert.match(vars.url, /^https:\/\//); + await service.setCoreDesign(type, { providerTemplate: null }, SUPER_ADMIN); + } + assert.equal(email.nativeSends.length, 0); + } +); + +liveMailgun('Mailgun: the startup check flags a real template without Subject header', async () => { + await syncOnce(); + const service = harness().service('provider-templates'); + const plain = rowKey((r) => r.provider === 'mailgun' && r.name === env.MAILGUN_TEMPLATE); + const synthetic = rowKey((r) => r.provider === 'mailgun' && r.name === created.mailgunName); + const plainRow = (await service.overview()).templates.find((t) => t.key === plain); + await service.setCoreDesign('reset-password', { providerTemplate: synthetic }, SUPER_ADMIN); + await service.setCoreDesign('admin-forgot-password', { providerTemplate: plain }, SUPER_ADMIN); + const result = await service.checkCoreDesigns({ syncIfStale: false }); + const flagged = result.problems.map((p) => `${p.coreEmailType}:${p.code}`); + if (plainRow.subject) { + assert.deepEqual(flagged, [], 'MAILGUN_TEMPLATE has a Subject header: nothing to flag'); + } else { + assert.deepEqual(flagged, ['admin-forgot-password:MAGIC_MAIL_PROVIDER_TEMPLATE_NO_SUBJECT']); + } + await service.setCoreDesign('reset-password', { providerTemplate: null }, SUPER_ADMIN); + await service.setCoreDesign('admin-forgot-password', { providerTemplate: null }, SUPER_ADMIN); +});