diff --git a/docs/services/mail.md b/docs/services/mail.md index 83156f06..0fd98e2b 100644 --- a/docs/services/mail.md +++ b/docs/services/mail.md @@ -16,6 +16,12 @@ The file format is WinterCMS's: an INI header with the `subject`, the `layout` a Each message gets an HTML part, rendered from the Markdown, and a plain-text part. `mail.css` and the brand CSS go into the layout's style block; see [Branding](#branding). +### CSS inlining + +Many mail clients drop a style block, so postcard also copies the CSS onto the elements it styles, as WinterCMS does: after the layout has rendered, every rule of the HTML's style elements is written into the `style` attribute of the elements it matches (with go-premailer), and CSS widths and heights also become `width` and `height` attributes. Classes stay on the elements. Rules that cannot be inlined, such as media queries and `:hover`, stay in a style element in the head; the style block holds only those afterwards. The preview, the test send and real mail are inlined the same way, and the plain-text part is never touched. + +A layout keeps its CSS in the style block only when it opts out: a layout file with `disable_auto_inline_css = true` in its header (`1` and `yes` also work), or a layout edited in the admin with **Do not inline CSS** switched on (its CSS tab). The built-in layouts all inline. If the inliner fails on a message, that message is sent with its style block only and a warning is logged; mail is never stopped by it. + ## Partials A partial is a block that several templates and layouts share, such as a button or a footer note. A plugin implements `pact.HasMailPartials`: it returns its embedded `views/mail` files and the partial names it ships. A partial named `acme.blog::mail.partials.note` lives in `views/mail/partials/note.htm`, and its file has the layout format, with a text section and an HTML section: diff --git a/go.mod b/go.mod index b5457434..f1dd3e8d 100644 --- a/go.mod +++ b/go.mod @@ -40,14 +40,15 @@ require ( github.com/spf13/pflag v1.0.9 github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 + github.com/vanng822/go-premailer v1.38.0 github.com/wneessen/go-mail v0.8.1 github.com/yuin/goldmark v1.8.6 gocloud.dev v0.46.0 - golang.org/x/crypto v0.57.0 + golang.org/x/crypto v0.58.0 golang.org/x/image v0.46.0 - golang.org/x/net v0.58.0 - golang.org/x/term v0.46.0 - golang.org/x/text v0.42.0 + golang.org/x/net v0.62.0 + golang.org/x/term v0.47.0 + golang.org/x/text v0.43.0 gorm.io/driver/postgres v1.6.3 gorm.io/gorm v1.31.2 ) @@ -56,6 +57,8 @@ require ( dario.cat/mergo v1.0.2 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/Microsoft/go-winio v0.6.2 // indirect + github.com/PuerkitoBio/goquery v1.13.0 // indirect + github.com/andybalholm/cascadia v1.3.4 // indirect github.com/atotto/clipboard v0.1.4 // indirect github.com/aws/aws-sdk-go-v2 v1.41.9 // indirect github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.11 // indirect @@ -100,6 +103,7 @@ require ( github.com/docker/go-units v0.5.0 // indirect github.com/dustin/go-humanize v1.0.1 // indirect github.com/ebitengine/purego v0.10.1 // indirect + github.com/fatih/color v1.18.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect github.com/gabriel-vasile/mimetype v1.4.15 // indirect github.com/go-logr/logr v1.4.3 // indirect @@ -112,6 +116,7 @@ require ( github.com/google/wire v0.7.0 // indirect github.com/googleapis/gax-go/v2 v2.19.0 // indirect github.com/gorilla/css v1.0.1 // indirect + github.com/inbucket/html2text v1.0.0 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/jackc/pgpassfile v1.0.0 // indirect github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect @@ -125,6 +130,8 @@ require ( github.com/lucasb-eyer/go-colorful v1.4.1 // indirect github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e // indirect github.com/magiconair/properties v1.8.10 // indirect + github.com/mattn/go-colorable v0.1.14 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect github.com/mattn/go-runewidth v0.0.30 // indirect github.com/mitchellh/copystructure v1.2.0 // indirect github.com/mitchellh/hashstructure/v2 v2.0.2 // indirect @@ -139,6 +146,9 @@ require ( github.com/moby/sys/userns v0.1.0 // indirect github.com/moby/term v0.5.2 // indirect github.com/muesli/cancelreader v0.2.2 // indirect + github.com/olekukonko/errors v1.1.0 // indirect + github.com/olekukonko/ll v0.0.9 // indirect + github.com/olekukonko/tablewriter v1.0.7 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect @@ -150,6 +160,7 @@ require ( github.com/segmentio/encoding v0.5.4 // indirect github.com/shirou/gopsutil/v4 v4.26.6 // indirect github.com/sirupsen/logrus v1.9.4 // indirect + github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf // indirect github.com/stretchr/testify v1.12.1 // indirect github.com/tidwall/gjson v1.19.0 // indirect github.com/tidwall/match v1.2.0 // indirect @@ -157,6 +168,7 @@ require ( github.com/tidwall/sjson v1.2.5 // indirect github.com/tklauser/go-sysconf v0.4.0 // indirect github.com/tklauser/numcpus v0.12.0 // indirect + github.com/vanng822/css v1.0.1 // indirect github.com/xo/terminfo v1.0.0 // indirect github.com/yosida95/uritemplate/v3 v3.0.2 // indirect github.com/yuin/gopher-lua v1.1.1 // indirect @@ -171,8 +183,8 @@ require ( go.uber.org/atomic v1.12.0 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/oauth2 v0.36.0 // indirect - golang.org/x/sync v0.23.0 // indirect - golang.org/x/sys v0.48.0 // indirect + golang.org/x/sync v0.24.0 // indirect + golang.org/x/sys v0.49.0 // indirect golang.org/x/time v0.15.0 // indirect golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da // indirect google.golang.org/api v0.272.0 // indirect diff --git a/go.sum b/go.sum index 20ac4e5b..b30d1bc0 100644 --- a/go.sum +++ b/go.sum @@ -40,6 +40,8 @@ github.com/MakeNowJust/heredoc v1.0.0 h1:cXCdzVdstXyiTqTvfqk9SDHpKNjxuom+DOlyEeQ github.com/MakeNowJust/heredoc v1.0.0/go.mod h1:mG5amYoWBHf8vpLOuehzbGGw0EHxpZZ6lCpQ4fNJ8LE= github.com/Microsoft/go-winio v0.6.2 h1:F2VQgta7ecxGYO8k3ZZz3RS8fVIXVxONVUPlNERoyfY= github.com/Microsoft/go-winio v0.6.2/go.mod h1:yd8OoFMLzJbo9gZq8j5qaps8bJ9aShtEA8Ipt1oGCvU= +github.com/PuerkitoBio/goquery v1.13.0 h1:mqHbjD7Jmnul4DTR24LKTjo1uUmHUh072kteGV+xpFM= +github.com/PuerkitoBio/goquery v1.13.0/go.mod h1:Hip5mdBL8K2wEGKJdr27sRaNwIdDajmCwB/ExUPwW+g= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= @@ -48,6 +50,8 @@ github.com/alecthomas/repr v0.5.2 h1:SU73FTI9D1P5UNtvseffFSGmdNci/O6RsqzeXJtP0Qs github.com/alecthomas/repr v0.5.2/go.mod h1:Fr0507jx4eOXV7AlPV6AVZLYrLIuIeSOWtW57eE/O/4= github.com/alicebob/miniredis/v2 v2.40.0 h1:6IgTQbvm2JiMYZ8yur/acNJzVjtSOWCelxXbk/LUBXc= github.com/alicebob/miniredis/v2 v2.40.0/go.mod h1:TcL7YfarKPGDAthEtl5NBeHZfeUQj6OXMm/+iu5cLMM= +github.com/andybalholm/cascadia v1.3.4 h1:vM2lgh0Vru9Vwyfm4cQqWP2HHMW0u0+2PAW7Q38Qufg= +github.com/andybalholm/cascadia v1.3.4/go.mod h1:BLRmbRjpEtNKieZOCCvYj4RqN+KRA41GBe/5O+G93kM= github.com/atotto/clipboard v0.1.4 h1:EH0zSVneZPSuFR11BlR9YppQTVDbh5+16AmcJi4g1z4= github.com/atotto/clipboard v0.1.4/go.mod h1:ZY9tmq7sm5xIbd9bOK4onWV4S6X0u6GY7Vn0Yu86PYI= github.com/aws/aws-sdk-go-v2 v1.41.9 h1:/rYeyO2+HrMztAmxAq9++XJtFMqSIpSsNA0yDGALYq4= @@ -167,6 +171,8 @@ github.com/envoyproxy/go-control-plane/envoy v1.37.0 h1:u3riX6BoYRfF4Dr7dwSOroNf github.com/envoyproxy/go-control-plane/envoy v1.37.0/go.mod h1:DReE9MMrmecPy+YvQOAOHNYMALuowAnbjjEMkkWOi6A= github.com/envoyproxy/protoc-gen-validate v1.3.3 h1:MVQghNeW+LZcmXe7SY1V36Z+WFMDjpqGAGacLe2T0ds= github.com/envoyproxy/protoc-gen-validate v1.3.3/go.mod h1:TsndJ/ngyIdQRhMcVVGDDHINPLWB7C82oDArY51KfB0= +github.com/fatih/color v1.18.0 h1:S8gINlzdQ840/4pfAwic/ZE0djQEH3wM94VfqLTZcOM= +github.com/fatih/color v1.18.0/go.mod h1:4FelSpRwEGDpQ12mAdzqdOukCy4u8WUtOY6lkT/6HfU= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx59Ho= @@ -227,6 +233,8 @@ github.com/gorilla/css v1.0.1 h1:ntNaBIghp6JmvWnxbZKANoLyuXTPZ4cAMlo6RyhlbO8= github.com/gorilla/css v1.0.1/go.mod h1:BvnYkspnSzMmwRK+b8/xgNPLiIuNZr6vbZBTPQ2A3b0= github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUqJM= github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= +github.com/inbucket/html2text v1.0.0 h1:N5kza++4uBBDJ2Z3KUnTRyPNoBcW+YfOgNiNmNB+sgs= +github.com/inbucket/html2text v1.0.0/go.mod h1:5TrhXQKGU+LXurODaSm55Y9eXoPBRnYiOz4x2XfUoJU= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= github.com/jackc/pgerrcode v0.0.0-20240316143900-6e2875d9b438 h1:Dj0L5fhJ9F82ZJyVOmBx6msDp/kfd1t9GRfny/mfJA0= @@ -269,6 +277,10 @@ github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e h1:Q6MvJtQK/iRcRt github.com/lufia/plan9stats v0.0.0-20260330125221-c963978e514e/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg= github.com/magiconair/properties v1.8.10 h1:s31yESBquKXCV9a/ScB3ESkOjUYYv+X0rg8SYxI99mE= github.com/magiconair/properties v1.8.10/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0= +github.com/mattn/go-colorable v0.1.14 h1:9A9LHSqF/7dyVVX6g0U9cwm9pG3kP9gSzcuIPHPsaIE= +github.com/mattn/go-colorable v0.1.14/go.mod h1:6LmQG8QLFO4G5z1gPvYEzlUgJ2wF+stgPZH1UqBm1s8= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/mattn/go-runewidth v0.0.30 h1:+KUuiDA4fF0R1p5FeueHefjDm+GIM+kWfFnDjybOPgk= github.com/mattn/go-runewidth v0.0.30/go.mod h1:3qAiGCV4Koz/yuveO58qUefmUTRm8r0IGEXZ9jeHp/8= github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU= @@ -309,6 +321,12 @@ github.com/muesli/cancelreader v0.2.2 h1:3I4Kt4BQjOR54NavqnDogx/MIoWBFa0StPA8ELU github.com/muesli/cancelreader v0.2.2/go.mod h1:3XuTXfFS2VjM+HTLZY9Ak0l6eUKfijIfMUZ4EgX0QYo= github.com/nicksnyder/go-i18n/v2 v2.6.1 h1:JDEJraFsQE17Dut9HFDHzCoAWGEQJom5s0TRd17NIEQ= github.com/nicksnyder/go-i18n/v2 v2.6.1/go.mod h1:Vee0/9RD3Quc/NmwEjzzD7VTZ+Ir7QbXocrkhOzmUKA= +github.com/olekukonko/errors v1.1.0 h1:RNuGIh15QdDenh+hNvKrJkmxxjV4hcS50Db478Ou5sM= +github.com/olekukonko/errors v1.1.0/go.mod h1:ppzxA5jBKcO1vIpCXQ9ZqgDh8iwODz6OXIGKU8r5m4Y= +github.com/olekukonko/ll v0.0.9 h1:Y+1YqDfVkqMWuEQMclsF9HUR5+a82+dxJuL1HHSRpxI= +github.com/olekukonko/ll v0.0.9/go.mod h1:En+sEW0JNETl26+K8eZ6/W4UQ7CYSrrgg/EdIYT2H8g= +github.com/olekukonko/tablewriter v1.0.7 h1:HCC2e3MM+2g72M81ZcJU11uciw6z/p82aEnm4/ySDGw= +github.com/olekukonko/tablewriter v1.0.7/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= @@ -351,6 +369,8 @@ github.com/spf13/pflag v1.0.9 h1:9exaQaMOCwffKiiiYk6/BndUBv+iRViNW+4lEMi0PvY= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spiffe/go-spiffe/v2 v2.6.0 h1:l+DolpxNWYgruGQVV0xsfeya3CsC7m8iBzDnMpsbLuo= github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xIx7lEzqblHEs= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf h1:pvbZ0lM0XWPBqUKqFU8cmavspvIl9nulOYwdy6IFRRo= +github.com/ssor/bom v0.0.0-20170718123548-6386211fdfcf/go.mod h1:RJID2RhlZKId02nZ62WenDCkgHFerpIOmW0iT7GKmXM= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= github.com/stretchr/objx v0.5.3/go.mod h1:rDQraq+vQZU7Fde9LOZLr8Tax6zZvy4kuNKF+QYS+U0= @@ -377,6 +397,10 @@ github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRU github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= github.com/tklauser/numcpus v0.12.0/go.mod h1:ABHeXzJnr/qqwguhClkZKT1/8VABcYrsyUiUGobwWJg= +github.com/vanng822/css v1.0.1 h1:10yiXc4e8NI8ldU6mSrWmSWMuyWgPr9DZ63RSlsgDw8= +github.com/vanng822/css v1.0.1/go.mod h1:tcnB1voG49QhCrwq1W0w5hhGasvOg+VQp9i9H1rCM1w= +github.com/vanng822/go-premailer v1.38.0 h1:nYXopG+L6lcRV6dEAemLLE71bihun3gxgfNJZ9iYm1Q= +github.com/vanng822/go-premailer v1.38.0/go.mod h1:6Jcm7sYO8ON3J/IIlox2fWq+YPgGopwx7VbETlZRZtY= github.com/wneessen/go-mail v0.8.1 h1:tVcncj02/QySVFw3zr/kXOzZcuFQqBNT6K+Rbgm/pcM= github.com/wneessen/go-mail v0.8.1/go.mod h1:dWZ61zadzCIyvB4y1/YzC5O7MrbbzBfPkARmbosdf8w= github.com/xo/terminfo v1.0.0 h1:2ZpYzqWzyyytjk3TP6aJVDhkMAkc99/1xKQdA3TDTBY= @@ -420,34 +444,35 @@ go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw= go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg= gocloud.dev v0.46.0 h1:niIuZwSjMtBx8K+ITB2s5kZullB13PGOS2ZoQPZxQ4Q= gocloud.dev v0.46.0/go.mod h1:ACQe+2qO+hEO+pdcvvsM+RB63r8TyGD1W3ESCLFyzvM= -golang.org/x/crypto v0.57.0 h1:3ZVCjf8Ggz7zneR/EHRVx68Ctf+2pmIMP2UFhh9cC6M= -golang.org/x/crypto v0.57.0/go.mod h1:Fdz0i5U6CoizGwLda9DttjSk6qlZo25zYNtR+ycvuZA= +golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= +golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20231006140011-7918f672742d h1:jtJma62tbqLibJ5sFQz8bKtEM8rJBtfilJ2qTU199MI= golang.org/x/exp v0.0.0-20231006140011-7918f672742d/go.mod h1:ldy0pHrwJyGW56pPQzzkH36rKxoZW1tw7ZJpeKx+hdo= golang.org/x/image v0.0.0-20191009234506-e7c1f5e7dbb8/go.mod h1:FeLwcggjj3mMvU+oOTbSwawSJRM1uh48EjtB4UJZlP0= golang.org/x/image v0.46.0 h1:b1+oYj0Jbp6K5MDT4i4/eZpYlk3V8SJhhDKh6LBHAyQ= golang.org/x/image v0.46.0/go.mod h1:3B3W05VGVQyuXucLINLjXKrqISASfi4Xj+iCVkLMwew= -golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To= -golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= -golang.org/x/sync v0.23.0 h1:KameEIfc1IkluZyXWLn39Wd4tURc6GbCiISGiZm2bQk= -golang.org/x/sync v0.23.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= +golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= +golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.0.0-20190916202348-b4ddaad3f8a3/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20201204225414-ed752295db88/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs= golang.org/x/sys v0.0.0-20210616094352-59db8d763f22/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= -golang.org/x/sys v0.48.0 h1:bbX/i/6MgT9BVLM9RT1thmxL04yeTAhbEz4SyadbXoo= -golang.org/x/sys v0.48.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= -golang.org/x/term v0.46.0 h1:3+OXuTbaKDgwk8jTi3aSLHRlmWqHEUDUtxnbFigO4YE= -golang.org/x/term v0.46.0/go.mod h1:+K02xbkittuwc0Am4abfA3Fc+XRGXkvBXNO88NCXPoc= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= +golang.org/x/sys v0.49.0/go.mod h1:hNLxWAXmnKAxqDtdwIYC4bM9oQPEecfsnNMuSxOs3og= +golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= +golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= -golang.org/x/text v0.42.0 h1:JbOZXgfeCPU9gacVtYliJqOhD+zhrEqK4LfdpmlUZqI= -golang.org/x/text v0.42.0/go.mod h1:ojzP1Z+2QtioaF8DTtO8K5q7JWVVYwZKenzujK0Zd0E= +golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= +golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= -golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI= -golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo= +golang.org/x/tools v0.51.0 h1:k4Xc/1Om9jwkBJBo4NVLMSARBoWtK10mx+W5BnXCeAI= +golang.org/x/tools v0.51.0/go.mod h1:9eEncMayCV6zRMGhR5eZEC2iBx98qWcF1HZ9Z7wJOoA= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da h1:noIWHXmPHxILtqtCOPIhSt0ABwskkZKjD3bXGnZGpNY= golang.org/x/xerrors v0.0.0-20240903120638-7835f813f4da/go.mod h1:NDW/Ps6MPRej6fsCIbMTohpP40sJ/P/vI1MoTEGwX90= gonum.org/v1/gonum v0.16.0 h1:5+ul4Swaf3ESvrOnidPp4GZbzf0mxVQpDCYUQE7OJfk= diff --git a/modules/cabana/README.md b/modules/cabana/README.md index d0bedeea..04a3a2d7 100644 --- a/modules/cabana/README.md +++ b/modules/cabana/README.md @@ -59,7 +59,7 @@ Use cases: - Form fields on another plugin's controller: a `pact.AdminActionExtension` with `Form` set to a `pact.AdminFormExtension` places fields and tabs in any admin controller's form by its ID. Its fields document is the `fields.yaml` format plus `before:`/`after:` anchors, `zone:` (only the tab zone for now) and a `tabs:` list, compiled at boot with every `fields.yaml` check; extensions apply in plugin activation order and the form is sent in the compiled order, so the SPA adds no ordering. `Hide` removes owner fields, `Permissions` and `Visible` decide per request who sees the fields (schema, show and save alike), widget fields run the extension's `Actions` and partial fields render from its `Dir` through `PartialData`. Extension values leave the save body before any owner path reads them; `Save` runs in the record's save transaction after the owner row is written (`pact.AdminFormErrors` answers 422, its notices join `meta.notices`) and `Load` serves the values on show. A form no extension lays out compiles unchanged. Unknown anchors, duplicate names, anchor cycles, anchors outside `Requires()`, other zones, `fileupload` fields and clashing widget action or partial names stop the boot naming the plugin, the controller and the name. - Plugins screen: Settings → System → Plugins opens the admin SPA route `/system/plugins` (the settings entry carries `path` instead of a controller) for administrators holding `cabana.PermissionViewPlugins` (`backend.view_plugins`, granted to no role in code; superusers always pass). GET `/plugins` lists the plugins the application was built with from the `party.Installed` metadata `summer build` bakes (name, description, version, source, module and package), or only the IDs of `party.Activated` for an application built before that metadata existed, with the framework version and the state of the plugin registry (`plugins.registry_url`, read through `kiosk.RegistryURL`). With the registry configured, cabana (never the SPA) looks up each versioned plugin's releases through `kiosk.Client` and marks an update when `kiosk.NewestCompatible` finds a release newer than the installed version by `kiosk.Newer` (a `git describe` string or a pseudo-version compares by the tag it builds on), with the `summer plugin:update ` command; GET `/plugins/marketplace` searches the registry and adds installed and compatibility markers (compatible when `summer plugin:install` can install some release with the built framework, looking up the releases of a plugin whose newest one needs a newer framework; always compatible when the built framework version is not a release) and the `summer plugin:install ` command. Registry calls have a 4 second timeout, at most four run at once, and answers are cached in process (searches 5 minutes, at most 256 distinct searches with expired and then the oldest dropped first, releases 15 minutes, failures 1 minute); a failing registry gives `status` unavailable and never a non-200 answer. - Administrators screen: when some plugin registers admin controllers, `cabana.Activate` also compiles the admin's own screens, an internal plugin with ID `summercms.cabana`. Settings → System → Administrators (controller `cabana.AdministratorsControllerID`, permission `cabana.PermissionManageUsers`) lists backend administrators with their role and last sign-in, opens a preview of each, where record actions (the admin's own and contributed ones) are offered, and creates and edits administrators: login, email, names, a password (hashed at `admin.password.bcrypt_cost`, at least 4 characters and at most 72 bytes), the role and per-administrator permission overrides. The server enforces the privilege rules in the save transaction: only a superuser sees superusers or sends the superuser switch, an administrator can neither grant permissions or roles above their own grants nor change an administrator who holds more than they do, their own role, superuser flag, permissions and password are not changed here, and the last active superuser cannot be demoted. A password set for another administrator ends their sessions (personal API tokens stay valid, as with `admin:reset-password`). Administrators are activated, deactivated and restored by record and bulk actions and deleted softly through `deleted_at` (never hard-deleted); the list shows deleted and deactivated rows with their row states and filters deleted ones, and the preview shows a status hint. Deactivating or deleting an administrator ends their sessions and stops their personal API tokens; the last active superuser cannot be demoted, deactivated or deleted on any of these paths (a transaction-scoped advisory lock serializes the check). The permission codes `cabana.PermissionManageUsers` and `cabana.PermissionManageRoles` are registered with no role grant, so after an upgrade only superusers see the screens until an administrator grants them. An application without admin controllers still activates no admin. -- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists one row per template of this process's catalog (rows of uninstalled plugins are hidden; the row is the template's own, or the lowest locale variant when only variants ship) with code, subject, description, customized locales (`cabana.MailTemplate.CustomizedLocales`: Default and the locale codes of the customized versions, at most three then +N) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` and `postcard.EnsureLocaleRows` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process, and a list request syncs again when the mail locales changed. The mail locales are the locales the translator's catalog holds plus, when a `cabana.TranslationWriter` is published, its enabled locales; the default locale is the writer's default locale, else the translator's. A template is one record per locale version: its own row (Default), a row per locale variant file (`welcome-en`) and a row per other mail locale that ships no file (`welcome-de`, created by `postcard.EnsureLocaleRows`, showing and sending the default version until it is customized). The update form's locale switcher lists them (`meta.localeVariants`); the record title is the template's base code, and the show response first ensures the template's missing locale rows, so a newly enabled locale can be opened without a restart. A save of a locale without a file stamps `base_hash` with the base file's hash; until it is customized, its form shows the base template's current version (its customization when there is one), and reset returns it to the base file. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated); on the templates list both apply to the whole template, any of its locale versions. The forms carry the `info` and `file_version` partials: the file (the base template's for a locale without a file), the status, on a template with locale versions the Default line or the line of a locale without a file (`backend::lang.mail.info_locale_default`, `info_locale_fallback`), the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, a `mailimage` logo, the `site_name` text field shown by the built-in layouts' header and footer (trimmed, at most 255 characters, empty falls back to the display name of `mail.from`) and 13 `colorpicker` colours; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. POST `/mail/preview` renders an unsaved draft (`cabana.AdminMailPreviewRequest`: `mode`, `id`, `values`) through `postcard.Editor.Preview` and answers `cabana.AdminMailPreviewResult` (subject, html, text); mode `template` needs `system.manage_mail_templates`, modes `layout`, `partial` and `branding` need `system.manage_mail_layouts`. POST `/mail/test-send` (interactive sessions only) sends a template, layout or partial draft to the signed-in administrator's own email (`cabana.AdminMailTestSendResult`), refuses recipient keys in the body, and is limited to five sends per administrator per ten minutes through a published `cooler.Attempter` when `serve` has one, otherwise an in-process fixed window (429 with `Retry-After`). Forms carry `mailpreview` fields (`mode` matching the screen). +- Mail screens (Settings → Mail): when the application publishes postcard's Mailer (`postcard.EditorFrom` succeeds; `party.Activate` runs `postcard.Activate`), the internal plugin also registers the mail screens over postcard's tables, the permission codes `cabana.PermissionManageMailTemplates` (`system.manage_mail_templates`) and `cabana.PermissionManageMailLayouts` (`system.manage_mail_layouts`), both granted to no role in code, and their Settings entries in category `backend::lang.settings.category_mail`. Mail templates (controller `cabana.MailTemplatesControllerID`, model `cabana.MailTemplate`) lists one row per template of this process's catalog (rows of uninstalled plugins are hidden; the row is the template's own, or the lowest locale variant when only variants ship) with code, subject, description, customized locales (`cabana.MailTemplate.CustomizedLocales`: Default and the locale codes of the customized versions, at most three then +N) and layout, and edits the subject, the Markdown body and the layout (a `relation` over `cabana.MailLayout` rows: every database-only layout and the catalog's file layouts). There is no create and no delete. A save marks the row customized, stamps `base_hash` with the file's current hash and `customized_at`, and validates the result through `postcard.Editor.Validate` inside the save's transaction; a `postcard.DraftError` is a 422 on its field with `backend::lang.mail.invalid_` (`:message`, `:name`). The index rows are written by `postcard.SyncIndex` and `postcard.EnsureLocaleRows` through `lagoon.OnDatabase` at activation; a failed sync is logged and retried on the first mail list request of the process, and a list request syncs again when the mail locales changed. The mail locales are the locales the translator's catalog holds plus, when a `cabana.TranslationWriter` is published, its enabled locales; the default locale is the writer's default locale, else the translator's. A template is one record per locale version: its own row (Default), a row per locale variant file (`welcome-en`) and a row per other mail locale that ships no file (`welcome-de`, created by `postcard.EnsureLocaleRows`, showing and sending the default version until it is customized). The update form's locale switcher lists them (`meta.localeVariants`); the record title is the template's base code, and the show response first ensures the template's missing locale rows, so a newly enabled locale can be opened without a restart. A save of a locale without a file stamps `base_hash` with the base file's hash; until it is customized, its form shows the base template's current version (its customization when there is one), and reset returns it to the base file. Mail layouts (`cabana.MailLayoutsControllerID`, model `cabana.MailLayout`) lists postcard's default layout first, then the file layouts and the custom (database-only, `source` NULL, shown as Custom) layouts by name; it creates custom layouts (code `^[a-z0-9-]+$`, free, create-only) and deletes them, refusing one that template rows still reference with a `cabana.ForbiddenError` whose message names the layout and the count (CLDR plural). Mail partials (`cabana.MailPartialsControllerID`, model `cabana.MailPartial`) edits the partials' HTML and text sections. Both need `cabana.PermissionManageMailLayouts`; saves are stamped and validated as templates are. On all three, the record action `reset` (danger, offered on a customized file-backed row) calls `postcard.ResetOverride` in the action's transaction; rows from files are never deleted. The list row states are `customized` (an override) and `outdated` (an override whose `base_hash` differs from the file's `file_hash`), the lists have a status filter (customized, not customized, outdated); on the templates list both apply to the whole template, any of its locale versions. The forms carry the `info` and `file_version` partials: the file (the base template's for a locale without a file), the status, on a template with locale versions the Default line or the line of a locale without a file (`backend::lang.mail.info_locale_default`, `info_locale_fallback`), the sample variables or the partial's call, the drift callout, and a 3-line-context LCS line diff of the serialized override (`postcard.FormatTemplate`, `FormatLayout`, `FormatPartial`) against the file, skipped above 2000 lines per side. The mail controllers declare `recordActions` without a preview block: the admin offers them in the update form's footer, a boot rule only these internal controllers are exempt from. The layout form's CSS tab has the `disable_auto_inline_css` switch (`cabana.MailLayout.DisableAutoInlineCSS`, off for a new custom layout): on, postcard keeps the layout's CSS in its style block instead of also copying it onto the elements; the preview and the save validation render with the switch's value. Layout and partial content fields use the built-in `codeeditor` type (`language: html|css|text`, optional `mailImages`); Branding is the settings form `mail_brand` on `cabana.MailBrandSetting` (postcard's brand row, a `mailimage` logo, the `site_name` text field shown by the built-in layouts' header and footer (trimmed, at most 255 characters, empty falls back to the display name of `mail.from`) and 13 `colorpicker` colours; the first save switches mail from `mail.brandCss` to the compiled colours). Mail images is the singleton controller `cabana.MailImagesControllerID` (`cabana.MailImageLibrary`) with a public attachMany `images` fileupload; GET/POST `/mail/images` and GET `/mail/images/{id}` return absolute public URLs (`attach.AbsolutePublicURL`) and refuse with `mail.images.no_public_url` when neither `storage.uploads.public_url` nor `app.url` is set. Listing answers either mail permission; upload and the singleton form need `system.manage_mail_layouts`. POST `/mail/preview` renders an unsaved draft (`cabana.AdminMailPreviewRequest`: `mode`, `id`, `values`) through `postcard.Editor.Preview` and answers `cabana.AdminMailPreviewResult` (subject, html, text); mode `template` needs `system.manage_mail_templates`, modes `layout`, `partial` and `branding` need `system.manage_mail_layouts`. POST `/mail/test-send` (interactive sessions only) sends a template, layout or partial draft to the signed-in administrator's own email (`cabana.AdminMailTestSendResult`), refuses recipient keys in the body, and is limited to five sends per administrator per ten minutes through a published `cooler.Attempter` when `serve` has one, otherwise an in-process fixed window (429 with `Retry-After`). Forms carry `mailpreview` fields (`mode` matching the screen). - Danger record actions: `pact.AdminRecordAction.Danger` is served as `danger` on the record response's `cabana.RecordAction` (absent when false, so existing payloads are unchanged); the admin's confirm dialog then uses its danger variant. - Prompted record actions: a `pact.AdminRecordAction` with a `Prompt` (`pact.AdminActionPrompt`) asks the administrator for one text value in its confirm dialog. The record response serves it as `prompt` on the action's `cabana.RecordAction` (absent for every other action, so existing payloads are unchanged), and the action route accepts the body key `payload`, a JSON string, only for such an action: trimmed, not empty and at most `max_length` runes (422 on `payload` with `backend::lang.form.action_prompt_required` or `action_prompt_too_long`, `backend::lang.form.action_prompt_invalid` for another JSON type), then handed to `Run` as `pact.AdminRecordActionInput.Value`. Every other record action keeps refusing `record_id`, `values` and `payload`. A prompt without a label fails boot, owned or contributed. - My account contributions: a plugin implementing `pact.HasAccountContributions` adds sections (`pact.AccountContribution`) to the administrator's own account page, each with a status line and buttons (`pact.AccountAction`). GET `/account/contributions` lists them for the signed-in administrator and POST `/account/contributions/{name}/actions/{action}` runs one for that administrator only, behind the interactive-only guard, the action's permissions and its `Applies` rule, inside a transaction; the answer may carry a URL the admin opens in a new tab. That URL is kept only when it is an absolute `http`/`https` URL with a host or a same-origin path (one leading `/`); anything else, `javascript:` and `data:` included, is dropped and logged without the URL. A section whose `Status` fails is listed with an empty status and `error: true`, and an action whose `Applies` fails is left out and marks its section `error: true` as well; both are logged and the other sections are answered as usual. A status is translated only when it is a phrase key. Names are generic: cabana never names the contributing plugin. The existing `/account*` and `/auth/me` payloads are unchanged. A non-identifier or duplicate section name, an empty label, a duplicate or non-identifier action name, a nil `Run` or an empty action label stops the boot. diff --git a/modules/cabana/backendscreens/models/maillayout/fields.yaml b/modules/cabana/backendscreens/models/maillayout/fields.yaml index 0b453ec6..df3fe660 100644 --- a/modules/cabana/backendscreens/models/maillayout/fields.yaml +++ b/modules/cabana/backendscreens/models/maillayout/fields.yaml @@ -51,6 +51,12 @@ fields: mode: layout span: full tab: backend::lang.mail.layout.tab_text + disable_auto_inline_css: + label: backend::lang.mail.layout.disable_inline_css + comment: backend::lang.mail.layout.disable_inline_css_comment + type: switch + span: full + tab: backend::lang.mail.layout.tab_css content_css: label: backend::lang.mail.layout.css comment: backend::lang.mail.layout.css_comment diff --git a/modules/cabana/mail_admin.go b/modules/cabana/mail_admin.go index fe029c4d..f0ece523 100644 --- a/modules/cabana/mail_admin.go +++ b/modules/cabana/mail_admin.go @@ -410,9 +410,13 @@ type MailLayout struct { ContentHTML string `gorm:"column:content_html"` ContentText string `gorm:"column:content_text"` ContentCSS string `gorm:"column:content_css"` - IsCustom bool `gorm:"column:is_custom"` - FileHash *string `gorm:"column:file_hash"` - BaseHash *string `gorm:"column:base_hash"` + // DisableAutoInlineCSS keeps the layout's CSS in its style block only + // (postcard copies it onto the elements otherwise). A new custom layout + // starts with it off. + DisableAutoInlineCSS bool `gorm:"column:disable_auto_inline_css"` + IsCustom bool `gorm:"column:is_custom"` + FileHash *string `gorm:"column:file_hash"` + BaseHash *string `gorm:"column:base_hash"` // CustomizedAt is when the layout was last saved from the admin. CustomizedAt *time.Time `gorm:"column:customized_at"` CreatedAt time.Time `gorm:"column:created_at"` @@ -1036,7 +1040,7 @@ func stamp(custom *bool, base, file **string, at **time.Time, hash string) { // Fillable lists the columns the layout form writes. code is written only // when a custom layout is created (its field's context is create). func (MailLayout) Fillable() []string { - return []string{"name", "code", "content_html", "content_text", "content_css"} + return []string{"name", "code", "content_html", "content_text", "content_css", "disable_auto_inline_css"} } // Rules require a name and a code. @@ -1249,7 +1253,7 @@ func (c mailLayoutsAdmin) validate(ctx context.Context, model any) error { if err != nil { return err } - draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS} + draft := postcard.Draft{Kind: postcard.KindLayout, Name: l.Code, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.DisableAutoInlineCSS} if de := c.mail.editor.Validate(ctx, draft); de != nil { return c.mail.draftFailure(ctx, de) } diff --git a/modules/cabana/mail_routes.go b/modules/cabana/mail_routes.go index 5da5c0d4..b4d4533e 100644 --- a/modules/cabana/mail_routes.go +++ b/modules/cabana/mail_routes.go @@ -546,11 +546,12 @@ func (s *service) mailLayoutDraft(ctx context.Context, id uint64, values map[str name = code } return postcard.Draft{ - Kind: postcard.KindLayout, - Name: name, - HTML: stringValue(values["content_html"]), - Text: stringValue(values["content_text"]), - CSS: stringValue(values["content_css"]), + Kind: postcard.KindLayout, + Name: name, + HTML: stringValue(values["content_html"]), + Text: stringValue(values["content_text"]), + CSS: stringValue(values["content_css"]), + DisableAutoInlineCSS: boolValue(values["disable_auto_inline_css"]), }, nil } @@ -653,6 +654,25 @@ func (s *service) mailLayoutCodeByID(ctx context.Context, id uint) (string, erro return codes[0], nil } +// boolValue reads a switch value from a form payload: a JSON boolean, a +// number, or a string such as "1", "true" or "on". +func boolValue(v any) bool { + switch b := v.(type) { + case bool: + return b + case float64: + return b != 0 + case int: + return b != 0 + case string: + switch strings.ToLower(strings.TrimSpace(b)) { + case "1", "true", "on", "yes": + return true + } + } + return false +} + func stringValue(v any) string { if v == nil { return "" diff --git a/modules/cabana/mail_screens_smoke_test.go b/modules/cabana/mail_screens_smoke_test.go index 161119d9..59e12ad5 100644 --- a/modules/cabana/mail_screens_smoke_test.go +++ b/modules/cabana/mail_screens_smoke_test.go @@ -13,6 +13,7 @@ import ( "net/http/httptest" "os" "path/filepath" + "regexp" "strings" "sync" "sync/atomic" @@ -671,7 +672,7 @@ func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) { if err := env.gdb.First(&custom, customID).Error; err != nil { t.Fatal(err) } - if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" { + if !custom.IsCustom || custom.Source != nil || custom.Code != "promo-2026" || custom.DisableAutoInlineCSS { t.Fatalf("custom layout = %+v", custom) } env.expectFieldRefusal(t, http.StatusUnprocessableEntity, http.MethodPost, mailLayoutsPath, rootToken, map[string]any{ @@ -714,6 +715,30 @@ func mailLayoutsAndPartials(t *testing.T, env *mailEnv, rootToken string) { if msgs := env.driver.messages(); !strings.Contains(msgs[len(msgs)-1].HTML, "customized-layout") { t.Fatalf("send did not use the customized layout: %s", msgs[len(msgs)-1].HTML) } + + // The CSS tab's switch keeps the layout's CSS in its style block: + // the next send has no inlined style on the button. + withButton := `
{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Go" }}
` + for _, optOut := range []bool{true, false} { + env.expect(t, http.StatusOK, http.MethodPut, blogPath, rootToken, map[string]any{ + "name": "Blog", "content_html": withButton, "content_text": blogFile.Text, "content_css": ".button { color: #123456; }", "disable_auto_inline_css": optOut, + }) + if err := env.gdb.First(&blog, blogID).Error; err != nil || blog.DisableAutoInlineCSS != optOut { + t.Fatalf("saved switch = %v, want %v (err %v)", blog.DisableAutoInlineCSS, optOut, err) + } + if err := env.mailer.Send(context.Background(), postcard.Message{Template: blogWelcomeEn, To: []string{"reader@example.test"}, Vars: map[string]any{"name": "Grace"}}); err != nil { + t.Fatal(err) + } + msgs := env.driver.messages() + html := msgs[len(msgs)-1].HTML + button := regexp.MustCompile(`]*button-primary[^>]*>`).FindString(html) + if inlined := strings.Contains(button, `style="color:#123456"`); button == "" || inlined == optOut { + t.Fatalf("opt-out %v: button %q in %s", optOut, button, html) + } + if optOut && !strings.Contains(html, "{{ .Content }}`, Text: "{{ .logoUrl }}\n{{ .Content }}"}}, }) + ed.m.inline = noInline got, err = ed.Preview(ctx, Draft{Kind: KindBrand, Brand: &Brand{LinkColor: "#112233", LogoURL: "https://cdn.example.com/u/logo.png"}}) if err != nil { t.Fatal(err) @@ -263,9 +279,13 @@ func TestMailBrandSmoke(t *testing.T) { // A logo and a site name: the logo in the header, the name as its // alternative text, the card, the styled button and the footer. got := send("blog@example.com", &Brand{LogoURL: logo, SiteName: " Acme Mail "}) + if style := buttonStyle(t, got.HTML); !strings.Contains(style, "background-color:#d66829") { + t.Errorf("logo and name: the button is not styled: %q", style) + } + got.HTML = unstyled(got.HTML) for _, want := range []string{ `class="wrapper layout-default"`, - "\n\"Acme", + "\n\"Acme", `class="inner-body"`, "\n

Hi Ada

", `class="button button-primary"`, @@ -285,29 +305,34 @@ func TestMailBrandSmoke(t *testing.T) { // A site name without a logo: the name in the header. got = send("blog@example.com", &Brand{SiteName: "Acme Mail"}) + got.HTML = unstyled(got.HTML) if !strings.Contains(got.HTML, "\nAcme Mail") || strings.Contains(got.HTML, "Co`}) + got.HTML = unstyled(got.HTML) if !strings.Contains(got.HTML, `alt="Bob "&" <b>Co</b>"`) || strings.Contains(got.HTML, "Co") { t.Errorf("the site name is not escaped:\n%s", got.HTML) } // No Branding row: the display name of mail.from. got = send("Acme ", nil) + got.HTML = unstyled(got.HTML) if !strings.Contains(got.HTML, "\nAcme") || !strings.Contains(got.HTML, "

"+copyright()+" Acme

") { t.Errorf("mail.from name: HTML = %s", got.HTML) } // A Branding row with an empty name falls back to mail.from too. got = send("Acme ", &Brand{SiteName: " "}) + got.HTML = unstyled(got.HTML) if !strings.Contains(got.HTML, "Acme") { t.Errorf("empty site name: HTML = %s", got.HTML) } // Neither a name nor a logo: no header row, the year alone. got = send("no-reply@acme.test", nil) + got.HTML = unstyled(got.HTML) if strings.Contains(got.HTML, `class="header"`) || !strings.Contains(got.HTML, "

"+copyright()+"

") { t.Errorf("no name, no logo: HTML = %s", got.HTML) } @@ -330,6 +355,9 @@ func TestMailBrandSmoke(t *testing.T) { gdb := mailPostgres(t) cfg := brandCfg(t, map[string]string{"mail.yaml": "driver: memory\ncss: \"p{margin:1px}\"\nbrandCss: \".cfg{color:blue}\"\n"}) m, drv, logs := bootMailAppCfg(t, gdb, cfg) + // The style block shows which CSS fills the slots; inlining would + // move it onto the elements. + m.inline = noInline // No Branding row: the configured brand CSS, as before. sendFixture(t, m, acmeNotice, "") diff --git a/modules/postcard/brand_test.go b/modules/postcard/brand_test.go index 76c92d75..22fdea10 100644 --- a/modules/postcard/brand_test.go +++ b/modules/postcard/brand_test.go @@ -71,6 +71,8 @@ func TestBrand(t *testing.T) { CSS: ".mail-css{margin:0}", Overrides: fakeOverrides{ov: ov}, }) + // Which CSS fills the slots, not how it is inlined. + m.(*mailer).inline = noInline sendFixture(t, m, acmeNotice, "") got := lastMessage(t, drv) if !strings.Contains(got.HTML, "#112233") { @@ -92,6 +94,7 @@ func TestBrand(t *testing.T) { } drv := NewMemoryDriver() m := NewMailer(cat, drv, Options{BrandCSS: ".from-config{color:red}", CSS: ".mail-css{margin:0}"}) + m.(*mailer).inline = noInline sendFixture(t, m, acmeNotice, "") got := lastMessage(t, drv) if !strings.Contains(got.HTML, ".from-config") || !strings.Contains(got.HTML, ".mail-css") { diff --git a/modules/postcard/editor.go b/modules/postcard/editor.go index c7ae390f..7a3ce6d6 100644 --- a/modules/postcard/editor.go +++ b/modules/postcard/editor.go @@ -44,6 +44,8 @@ type Draft struct { HTML string Text string CSS string + // DisableAutoInlineCSS is a layout draft's opt-out of CSS inlining. + DisableAutoInlineCSS bool // Brand is a branding draft. Nil is the default brand. Brand *Brand @@ -261,7 +263,7 @@ func (e *Editor) renderLayout(d Draft, ov Overrides, opts renderOptions) (Render for k, v := range ov.Layouts { layouts[k] = v } - layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS} + layouts[code] = LayoutOverride{Name: code, HTML: d.HTML, Text: d.Text, CSS: d.CSS, DisableAutoInlineCSS: d.DisableAutoInlineCSS} ov.Layouts = layouts opts.overrides = ov sample := sampleMessage() diff --git a/modules/postcard/editor_smoke_test.go b/modules/postcard/editor_smoke_test.go index 85e806fa..e8882147 100644 --- a/modules/postcard/editor_smoke_test.go +++ b/modules/postcard/editor_smoke_test.go @@ -301,8 +301,9 @@ func TestMailEditorSmoke(t *testing.T) { t.Errorf("draft layout not applied: %q / %q", got.Subject, got.HTML) } - // A layout draft wraps the sample message. - got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `
{{ .Content }}
`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}"}) + // A layout draft wraps the sample message; this one keeps its style + // block. + got, err = ed.Preview(ctx, Draft{Kind: KindLayout, Name: "promo", HTML: `
{{ .Content }}
`, Text: "PROMO\n{{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true}) if err != nil { t.Fatalf("layout preview: %v", err) } @@ -756,6 +757,73 @@ FROM `+TemplatesTable+` t LEFT JOIN `+LayoutsTable+` l ON l.id = t.layout_id WHE } } }) + + t.Run("inline_flag", func(t *testing.T) { + gdb := mailPostgres(t) + const plain = "acme.shop::mail.layouts.plain" + cat := NewCatalog() + fsys := fstest.MapFS{ + "views/mail/x.htm": {Data: []byte("subject = \"X\"\nlayout = \"plain\"\n==\nx\n")}, + "views/mail/layouts/plain.htm": {Data: []byte("name = \"Plain\"\ndisable_auto_inline_css = true\n==\n{{ .Content }}\n==\n
{{ .Content }}
\n")}, + } + if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.x"}, map[string]string{"plain": plain}); err != nil { + t.Fatal(err) + } + flag := func(code string) bool { + t.Helper() + var v []bool + if err := gdb.Raw(`SELECT disable_auto_inline_css FROM `+LayoutsTable+` WHERE code = ?`, code).Scan(&v).Error; err != nil || len(v) != 1 { + t.Fatalf("flag of %s: %v %v", code, v, err) + } + return v[0] + } + sync := func() { + t.Helper() + if err := SyncIndex(ctx, gdb, cat, nil); err != nil { + t.Fatal(err) + } + } + // The index row mirrors the file's header key while not customized. + sync() + if !flag(plain) || flag(defaultLayoutName) { + t.Fatalf("after sync: plain %v, default %v", flag(plain), flag(defaultLayoutName)) + } + if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil { + t.Fatal(err) + } + sync() + if !flag(plain) { + t.Error("sync did not restore the file's value on a row that is not customized") + } + // A customized row keeps its own value, and the source reports it. + if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE, is_custom = TRUE, base_hash = file_hash WHERE code = '` + plain + `'`).Error; err != nil { + t.Fatal(err) + } + sync() + if flag(plain) { + t.Error("sync overwrote the value of a customized row") + } + ov, err := NewDBSource(appWith(t, gdb)).MailOverrides(ctx, "") + if err != nil || ov.Layouts[plain].DisableAutoInlineCSS { + t.Errorf("overrides = %+v, %v", ov.Layouts, err) + } + if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = TRUE WHERE code = '` + plain + `'`).Error; err != nil { + t.Fatal(err) + } + if ov, err = NewDBSource(appWith(t, gdb)).MailOverrides(ctx, ""); err != nil || !ov.Layouts[plain].DisableAutoInlineCSS { + t.Errorf("overrides = %+v, %v", ov.Layouts, err) + } + // Reset writes the file's value back. + if err := gdb.Exec(`UPDATE ` + LayoutsTable + ` SET disable_auto_inline_css = FALSE WHERE code = '` + plain + `'`).Error; err != nil { + t.Fatal(err) + } + if err := ResetOverride(ctx, gdb, cat, KindLayout, plain); err != nil { + t.Fatal(err) + } + if !flag(plain) { + t.Error("reset did not write the file's value back") + } + }) } func with(d Draft, edit func(*Draft)) Draft { edit(&d); return d } diff --git a/modules/postcard/inline.go b/modules/postcard/inline.go new file mode 100644 index 00000000..53f32549 --- /dev/null +++ b/modules/postcard/inline.go @@ -0,0 +1,31 @@ +package postcard + +import ( + "fmt" + + "github.com/vanng822/go-premailer/premailer" +) + +// inlineCSS copies the rules of html's style elements onto the elements they +// match, as WinterCMS does with CssToInlineStyles, so that mail clients that +// drop the style block still show the design. Rules that cannot be inlined, +// such as media queries and pseudo-classes, are kept in a style element. +// Classes are kept, and CSS widths and heights are mirrored to the width +// and height attributes (go-premailer's default options). A panic in the +// inliner is returned as an error. +func inlineCSS(html string) (out string, err error) { + defer func() { + if r := recover(); r != nil { + out, err = "", fmt.Errorf("postcard: inline CSS: %v", r) + } + }() + p, err := premailer.NewPremailerFromString(html, premailer.NewOptions()) + if err != nil { + return "", fmt.Errorf("postcard: inline CSS: %w", err) + } + out, err = p.Transform() + if err != nil { + return "", fmt.Errorf("postcard: inline CSS: %w", err) + } + return out, nil +} diff --git a/modules/postcard/mailer.go b/modules/postcard/mailer.go index e9c37df1..0033068d 100644 --- a/modules/postcard/mailer.go +++ b/modules/postcard/mailer.go @@ -54,6 +54,9 @@ type mailer struct { // log receives override warnings and failures; nil means moduleLog. log *slog.Logger warned warnGate + // inline inlines a message's CSS; nil means inlineCSS. Tests set it to + // force an inliner error. + inline func(html string) (string, error) } // NewMailer returns a mailer that renders from cat and delivers through @@ -149,7 +152,10 @@ func (m *mailer) render(ctx context.Context, msg Message) (RenderedMessage, erro // keeps mail.brandCss. The site name is the Branding's, else the display // name of mail.from. func (m *mailer) options(brand *Brand) renderOptions { - opts := renderOptions{css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year()} + opts := renderOptions{ + css: m.opts.CSS, brandCSS: m.opts.BrandCSS, siteName: siteName(brand, m.opts.From), year: time.Now().Year(), + inline: m.inline, warn: m.warn, + } if brand == nil { return opts } diff --git a/modules/postcard/mailer_test.go b/modules/postcard/mailer_test.go index ca85e7ef..c4fcac87 100644 --- a/modules/postcard/mailer_test.go +++ b/modules/postcard/mailer_test.go @@ -136,7 +136,7 @@ Body **{{ .Name }}**. t.Fatalf("Register: %v", err) } drv := NewMemoryDriver() - mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"}) + mail := NewMailer(cat, drv, Options{CSS: "p{color:red}", BrandCSS: ".layout-hello{color:blue}"}) if err := mail.Send(context.Background(), Message{ Template: "golem15.hello::mail.note", To: []string{"ada@example.test"}, @@ -154,7 +154,8 @@ Body **{{ .Name }}**. if !strings.Contains(got[0].HTML, `class="layout-hello"`) || !strings.Contains(got[0].HTML, "Ada") { t.Fatalf("HTML wrapper = %q", got[0].HTML) } - if !strings.Contains(got[0].HTML, "p{color:red}") || !strings.Contains(got[0].HTML, ".brand{color:blue}") { + // mail.css and the brand CSS are inlined onto the elements they match. + if !strings.Contains(got[0].HTML, `

`) || !strings.Contains(got[0].HTML, `

`) { t.Fatalf("shared css missing: %q", got[0].HTML) } diff --git a/modules/postcard/override_smoke_test.go b/modules/postcard/override_smoke_test.go index fad8dbe0..c25cab8d 100644 --- a/modules/postcard/override_smoke_test.go +++ b/modules/postcard/override_smoke_test.go @@ -343,12 +343,13 @@ func TestMailOverrideSmoke(t *testing.T) { gdb := mailPostgres(t) m, drv, logs := bootMailApp(t, gdb) stmts := []string{ - // A customized file layout, a database-only layout and an index - // row that is not customized. - `INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom) VALUES - ('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '
{{ .Content }}
', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE), - ('promo', NULL, 'Promo', '
{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}
', 'PROMO {{ .Content }}', '', TRUE), - ('` + defaultLayoutName + `', 'postcard', 'Default', '
{{ .Content }}
', 'MIRROR {{ .Content }}', '', FALSE)`, + // A customized file layout that keeps its style block (no + // inlining), a database-only layout and an index row that is not + // customized. + `INSERT INTO ` + LayoutsTable + ` (code, source, name, content_html, content_text, content_css, is_custom, disable_auto_inline_css) VALUES + ('acme.blog::mail.layouts.blog', 'acme.blog', 'Blog', '
{{ .Content }}
', '[custom] {{ .Content }}', '.custom{margin:0}', TRUE, TRUE), + ('promo', NULL, 'Promo', '
{{ .Content }}{{ partial "button" "url" "https://example.com" "body" "Shop" }}
', 'PROMO {{ .Content }}', '', TRUE, FALSE), + ('` + defaultLayoutName + `', 'postcard', 'Default', '
{{ .Content }}
', 'MIRROR {{ .Content }}', '', FALSE, FALSE)`, // A customized built-in partial. `INSERT INTO ` + PartialsTable + ` (code, source, name, content_html, content_text, is_custom) VALUES ('postcard::mail.partials.button', 'postcard', 'Button', '
{{ .body }}', '{{ .body }}: {{ .url }}', TRUE), @@ -387,9 +388,12 @@ func TestMailOverrideSmoke(t *testing.T) { if all.Template != nil || len(all.Layouts) != 2 || len(all.Partials) != 1 { t.Errorf("overrides without a template name = %+v", all) } - if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") { + if l := all.Layouts["promo"]; l.Name != "Promo" || !strings.HasPrefix(l.Text, "PROMO") || l.DisableAutoInlineCSS { t.Errorf("promo layout = %+v", l) } + if l := all.Layouts["acme.blog::mail.layouts.blog"]; !l.DisableAutoInlineCSS { + t.Errorf("blog layout = %+v, want the inlining opt-out", l) + } if logs.Len() != 0 { t.Errorf("unexpected log output:\n%s", logs) } diff --git a/modules/postcard/partials_smoke_test.go b/modules/postcard/partials_smoke_test.go index e6790cd7..76df08ad 100644 --- a/modules/postcard/partials_smoke_test.go +++ b/modules/postcard/partials_smoke_test.go @@ -1,8 +1,12 @@ package postcard import ( + "bytes" "context" + "errors" "io/fs" + "log/slog" + "regexp" "strconv" "strings" "testing" @@ -51,6 +55,25 @@ var ( _ pact.HasMailTemplates = templatesOnly{} ) +// buttonTag finds the opening tag of the button partial's link. +var buttonTag = regexp.MustCompile(`]*button-primary[^>]*>`) + +// buttonStyle returns the style attribute of the button partial's link, or +// empty when it has none. +func buttonStyle(t *testing.T, html string) string { + t.Helper() + tag := buttonTag.FindString(html) + if tag == "" { + t.Fatalf("no button in %s", html) + } + _, style, ok := strings.Cut(tag, ` style="`) + if !ok { + return "" + } + style, _, _ = strings.Cut(style, `"`) + return style +} + // copyright is the footer line of the built-in layouts without a site name. func copyright() string { return "© " + strconv.Itoa(time.Now().Year()) } @@ -219,7 +242,7 @@ func TestMailPartialsSmoke(t *testing.T) { } for _, want := range []string{ "

Hi Ada

\nGo`, + `Go`, "
\n

Bye

", } { if !strings.Contains(msg.HTML, want) { @@ -340,9 +363,9 @@ func TestMailPartialsSmoke(t *testing.T) { m, drv := partialsMailer(t, Options{CSS: "p{color:red}", BrandCSS: ".brand{color:blue}"}, nil) msg := sendTemplate(t, m, drv, "acme.blog::mail.auto", nil) for _, want := range []string{ - `class="wrapper layout-system"`, "

Done.

", + // mail.css is inlined onto the paragraph. + `class="wrapper layout-system"`, `

Done.

`, `This is an automatic message. Please do not reply to it.", - ".brand{color:blue}", "p{color:red}", } { if !strings.Contains(msg.HTML, want) { t.Errorf("system layout: HTML lacks %q:\n%s", want, msg.HTML) @@ -353,11 +376,12 @@ func TestMailPartialsSmoke(t *testing.T) { } msg = sendTemplate(t, m, drv, "acme.blog::mail.bare", nil) - if !strings.Contains(msg.HTML, "\n

Done.

\n\n") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") { + if !strings.Contains(msg.HTML, "\n

Done.

\n\n\n") || strings.Contains(msg.HTML, "content-body") || strings.Contains(msg.HTML, "layout-system") { t.Errorf("minimal layout: HTML = %q", msg.HTML) } - if !strings.Contains(msg.HTML, "") { - t.Errorf("minimal layout: style block = %q", msg.HTML) + // Every rule was inlined or matched nothing: no style block is left. + if strings.Contains(msg.HTML, "{{ .Content }}\n")}, + } + cat := NewCatalog() + if err := cat.Register("acme.shop", fsys, []string{"acme.shop::mail.plain"}, map[string]string{"plain": "acme.shop::mail.layouts.plain"}); err != nil { + t.Fatal(err) + } + if f, ok := cat.Layout("acme.shop::mail.layouts.plain"); !ok || !f.DisableAutoInlineCSS { + t.Errorf("header value %q: LayoutFile = %+v", value, f) + } + drv := NewMemoryDriver() + optedOut("file layout "+value, sendTemplate(t, NewMailer(cat, drv, Options{Overrides: fakeOverrides{ov: Overrides{Brand: brand}}}), drv, "acme.shop::mail.plain", nil)) + } + if f, _ := NewCatalog().Layout(defaultLayoutName); f.DisableAutoInlineCSS { + t.Error("the built-in default layout opts out") + } + + // A database layout with the column set opts out; without it, it inlines. + def, _ := NewCatalog().Layout(defaultLayoutName) + ov := &Overrides{Brand: brand, Layouts: map[string]LayoutOverride{defaultLayoutName: {HTML: def.HTML, Text: def.Text, DisableAutoInlineCSS: true}}} + m, drv = partialsMailer(t, Options{}, ov) + dbOptedOut := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome) + optedOut("database layout", dbOptedOut) + if dbOptedOut.Text != inlined.Text { + t.Errorf("the text part changed with the opt-out: %q, want %q", dbOptedOut.Text, inlined.Text) + } + ov.Layouts[defaultLayoutName] = LayoutOverride{HTML: def.HTML, Text: def.Text} + m, drv = partialsMailer(t, Options{}, ov) + if style := buttonStyle(t, sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome).HTML); !strings.Contains(style, "#445566") { + t.Errorf("a database layout without the column did not inline: %q", style) + } + + // A layout draft with the flag previews the same way. + ed, _ := newEditor(t, &Overrides{Brand: brand}) + draft := Draft{Kind: KindLayout, HTML: `{{ .Content }}`, Text: "{{ .Content }}"} + prev, err := ed.Preview(context.Background(), draft) + if err != nil { + t.Fatal(err) + } + if style := buttonStyle(t, prev.HTML); !strings.Contains(style, "#445566") { + t.Errorf("a layout draft without the flag did not inline: %q", style) + } + draft.DisableAutoInlineCSS = true + if prev, err = ed.Preview(context.Background(), draft); err != nil { + t.Fatal(err) + } + optedOut("layout draft", RenderedMessage{HTML: prev.HTML}) + + // An inliner error sends the un-inlined HTML and warns once. + m, drv = partialsMailer(t, Options{CSS: media}, &Overrides{Brand: brand}) + mm := m.(*mailer) + var logs bytes.Buffer + mm.log = slog.New(slog.NewTextHandler(&logs, nil)) + mm.inline = func(string) (string, error) { return "", errors.New("inliner broke") } + failed := sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome) + sendTemplate(t, m, drv, "acme.blog::mail.welcome", welcome) + optedOut("inliner error", failed) + if n := strings.Count(logs.String(), "level=WARN"); n != 1 || !strings.Contains(logs.String(), "inliner broke") { + t.Errorf("log = %q, want one warning naming the error", logs.String()) + } + if failed.Text != inlined.Text { + t.Errorf("the text part changed with inlining: %q, want %q", failed.Text, inlined.Text) + } + }) + t.Run("layout_partials", func(t *testing.T) { m, drv := partialsMailer(t, Options{}, nil) msg := sendTemplate(t, m, drv, "acme.blog::mail.note", map[string]any{"Text": "hi"}) @@ -399,11 +528,13 @@ func TestMailPartialsSmoke(t *testing.T) { t.Run("overrides", func(t *testing.T) { ov := Overrides{ - // A customized file layout, by its full name. + // A customized file layout, by its full name. Both layouts keep + // their style block (no inlining), so the order of the CSS slots + // shows in it. Layouts: map[string]LayoutOverride{ - "acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `
{{ .Content }}
`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}"}, + "acme.blog::mail.layouts.blog": {Name: "Blog", HTML: `
{{ .Content }}
`, Text: "[custom] {{ .Content }}", CSS: ".custom{margin:0}", DisableAutoInlineCSS: true}, // A database-only layout, by its code. - "promo": {Name: "Promo", HTML: `
{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}
`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}"}, + "promo": {Name: "Promo", HTML: `
{{ .Content }}{{ partial "acme.blog::mail.partials.note" "text" "promo" }}
`, Text: "PROMO {{ .Content }}", CSS: ".promo{margin:0}", DisableAutoInlineCSS: true}, }, Partials: map[string]PartialOverride{ "acme.blog::mail.partials.note": {HTML: ``, Text: "* {{ .text }}"}, diff --git a/modules/postcard/store.go b/modules/postcard/store.go index 7d51cefa..5e33f506 100644 --- a/modules/postcard/store.go +++ b/modules/postcard/store.go @@ -166,6 +166,18 @@ var Migrations = []*gormigrate.Migration{ return tx.Exec(`ALTER TABLE ` + BrandTable + ` DROP COLUMN IF EXISTS site_name`).Error }, }, + { + // disable_auto_inline_css keeps a layout's CSS in its style block + // only (LayoutOverride.DisableAutoInlineCSS); file-backed rows that + // are not customized mirror the file's header key. + ID: "202611130003_mail_layout_disable_auto_inline_css", + Migrate: func(tx *gorm.DB) error { + return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` ADD COLUMN disable_auto_inline_css BOOLEAN NOT NULL DEFAULT FALSE`).Error + }, + Rollback: func(tx *gorm.DB) error { + return tx.Exec(`ALTER TABLE ` + LayoutsTable + ` DROP COLUMN IF EXISTS disable_auto_inline_css`).Error + }, + }, } // OverrideSource supplies the database overrides one render needs. @@ -218,6 +230,9 @@ type LayoutOverride struct { HTML string Text string CSS string + // DisableAutoInlineCSS keeps the CSS in the style block only: it is not + // copied onto the elements (the disable_auto_inline_css column). + DisableAutoInlineCSS bool } // PartialOverride replaces a partial's HTML and text sections. @@ -283,15 +298,16 @@ WHERE t.code = ? AND t.is_custom`, name).Scan(&rows).Error ContentHTML string `gorm:"column:content_html"` ContentText string `gorm:"column:content_text"` ContentCSS string `gorm:"column:content_css"` + NoInline bool `gorm:"column:disable_auto_inline_css"` } - if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil { + if err := tx.Raw(`SELECT code, name, content_html, content_text, content_css, disable_auto_inline_css FROM ` + LayoutsTable + ` WHERE is_custom`).Scan(&layouts).Error; err != nil { return err } for _, l := range layouts { if out.Layouts == nil { out.Layouts = make(map[string]LayoutOverride, len(layouts)) } - out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS} + out.Layouts[l.Code] = LayoutOverride{Name: l.Name, HTML: l.ContentHTML, Text: l.ContentText, CSS: l.ContentCSS, DisableAutoInlineCSS: l.NoInline} } var partials []struct { Code string @@ -386,11 +402,11 @@ const syncLockKey = "summercms.postcard.sync" // It runs layouts first, then templates (whose layout_id points at the // layout row of the file's layout), then partials. // -// For a row that is not customized the content columns mirror the file. For -// a customized row they are left alone: only source, description, locale, -// base_code, name and file_hash follow the file, which is what makes a -// changed file show as a difference between base_hash and file_hash. No row -// is deleted, database-only layouts are not touched, and a row that already +// For a row that is not customized the content columns (and a layout's +// disable_auto_inline_css) mirror the file. For a customized row they are +// left alone: only source, description, locale, base_code, name and +// file_hash follow the file, which is what makes a changed file show as a +// difference between base_hash and file_hash. No row is deleted, database-only layouts are not touched, and a row that already // matches is not written. locales are the application's locales, for // TemplateLocale and TemplateBase. // @@ -409,8 +425,8 @@ func SyncIndex(ctx context.Context, db *gorm.DB, cat *Catalog, locales []string) return err } for _, l := range layouts { - if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, file_hash) -VALUES (?, ?, ?, ?, ?, '', ?) + if err := tx.Exec(`INSERT INTO `+LayoutsTable+` AS t (code, source, name, content_html, content_text, content_css, disable_auto_inline_css, file_hash) +VALUES (?, ?, ?, ?, ?, '', ?, ?) ON CONFLICT (code) DO UPDATE SET source = EXCLUDED.source, name = EXCLUDED.name, @@ -418,13 +434,14 @@ ON CONFLICT (code) DO UPDATE SET content_html = CASE WHEN t.is_custom THEN t.content_html ELSE EXCLUDED.content_html END, content_text = CASE WHEN t.is_custom THEN t.content_text ELSE EXCLUDED.content_text END, content_css = CASE WHEN t.is_custom THEN t.content_css ELSE EXCLUDED.content_css END, + disable_auto_inline_css = CASE WHEN t.is_custom THEN t.disable_auto_inline_css ELSE EXCLUDED.disable_auto_inline_css END, updated_at = NOW() WHERE t.source IS DISTINCT FROM EXCLUDED.source OR t.name IS DISTINCT FROM EXCLUDED.name OR t.file_hash IS DISTINCT FROM EXCLUDED.file_hash - OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css) - IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css))`, - l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.Hash).Error; err != nil { + OR (NOT t.is_custom AND (t.content_html, t.content_text, t.content_css, t.disable_auto_inline_css) + IS DISTINCT FROM (EXCLUDED.content_html, EXCLUDED.content_text, EXCLUDED.content_css, EXCLUDED.disable_auto_inline_css))`, + l.Name, l.PluginID, rowName(l.Title, l.Name), l.HTML, l.Text, l.DisableAutoInlineCSS, l.Hash).Error; err != nil { return err } } @@ -607,8 +624,8 @@ WHERE code = ? AND source IS NOT NULL`, f.Subject, f.Body, f.Layout, f.Hash, cod return fmt.Errorf("postcard: reset %s: no file version", code) } res = db.Exec(`UPDATE `+LayoutsTable+` SET name = ?, content_html = ?, content_text = ?, content_css = '', - file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW() -WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.Hash, code) + disable_auto_inline_css = ?, file_hash = ?, is_custom = FALSE, base_hash = NULL, customized_at = NULL, updated_at = NOW() +WHERE code = ? AND source IS NOT NULL`, rowName(f.Title, f.Name), f.HTML, f.Text, f.DisableAutoInlineCSS, f.Hash, code) case KindPartial: f, ok := cat.Partial(code) if !ok { diff --git a/modules/postcard/templates.go b/modules/postcard/templates.go index 490a60bb..048a2262 100644 --- a/modules/postcard/templates.go +++ b/modules/postcard/templates.go @@ -86,6 +86,8 @@ type parsedLayout struct { htmlWrap string source string hash string + // disableInline is the disable_auto_inline_css header key. + disableInline bool } // parsedPartial is a partial file: the layout file format, a header, a text @@ -387,16 +389,31 @@ func parseLayout(name, pluginID, src string) (*parsedLayout, error) { return nil, fmt.Errorf("postcard: parse %s: %w", name, err) } return &parsedLayout{ - name: name, - pluginID: pluginID, - headerName: fields["name"], - textWrap: strings.TrimSuffix(textWrap, "\n"), - htmlWrap: strings.TrimSuffix(htmlWrap, "\n"), - source: src, - hash: fileHash(src), + name: name, + pluginID: pluginID, + headerName: fields["name"], + textWrap: strings.TrimSuffix(textWrap, "\n"), + htmlWrap: strings.TrimSuffix(htmlWrap, "\n"), + source: src, + hash: fileHash(src), + disableInline: headerBool(fields[disableInlineKey]), }, nil } +// disableInlineKey is the layout header key (and the layouts table column) +// that keeps a layout's CSS in its style block only, WinterCMS's option of +// the same name. +const disableInlineKey = "disable_auto_inline_css" + +// headerBool reads a header value as a switch: true, 1 or yes, in any case. +func headerBool(v string) bool { + switch strings.ToLower(strings.TrimSpace(v)) { + case "true", "1", "yes": + return true + } + return false +} + func normalizeNewlines(src string) string { return strings.ReplaceAll(src, "\r\n", "\n") } @@ -506,6 +523,8 @@ type renderOptions struct { siteName string // year is the year of the copyright line; zero is the current year. year int + // inline copies the CSS onto the elements; nil is inlineCSS. + inline func(html string) (string, error) // overrides are the database overrides to apply; the zero value renders // the file version. overrides Overrides @@ -682,6 +701,12 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions) if err := validateHTML(html); err != nil { return out, partLayoutHTML, err } + if !layout.disableInline { + html, err = inlineHTML(html, layout.name, opts) + if err != nil { + return out, partLayoutHTML, err + } + } out = RenderedMessage{ To: append([]string(nil), msg.To...), Cc: append([]string(nil), msg.Cc...), @@ -694,6 +719,37 @@ func (c *Catalog) renderParts(msg Message, src renderSource, opts renderOptions) return out, "", nil } +// styleElement finds a style element, the only place inlining reads CSS from. +var styleElement = regexp.MustCompile(`(?i)]`) + +// inlineHTML copies the CSS of a rendered message onto its elements. HTML +// without a style element has nothing to inline and is returned as it is. +// An inliner error keeps html as it is, with its style block, and is +// reported through opts.warn; mail is never stopped by it. The inlined HTML +// passes the safety checks again, since CSS values now sit in style +// attributes. +func inlineHTML(html, layout string, opts renderOptions) (string, error) { + if !styleElement.MatchString(html) { + return html, nil + } + inline := opts.inline + if inline == nil { + inline = inlineCSS + } + inlined, err := inline(html) + if err != nil { + if opts.warn != nil { + opts.warn("inline:"+layout, "postcard: CSS could not be inlined, sending the style block only", + "layout", layout, "error", err.Error()) + } + return html, nil + } + if err := validateHTML(inlined); err != nil { + return "", err + } + return inlined, nil +} + // renderLayout is the layout one render uses: a file layout, a file layout // with its override applied, or a database-only layout. type renderLayout struct { @@ -701,6 +757,8 @@ type renderLayout struct { textWrap string htmlWrap string css string + // disableInline keeps the CSS in the style block only. + disableInline bool } // layoutFor returns the layout src renders in. An override of that layout, @@ -733,7 +791,7 @@ func (c *Catalog) layoutFor(src renderSource, opts renderOptions) (renderLayout, func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride) (renderLayout, bool, error) { if ov, ok := overrides[code]; ok { - return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS}, true, nil + return renderLayout{name: code, textWrap: ov.Text, htmlWrap: ov.HTML, css: ov.CSS, disableInline: ov.DisableAutoInlineCSS}, true, nil } c.mu.RLock() l, ok := c.layouts[code] @@ -741,7 +799,7 @@ func (c *Catalog) layoutByCode(code string, overrides map[string]LayoutOverride) if !ok { return renderLayout{}, false, nil } - return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap}, true, nil + return renderLayout{name: l.name, textWrap: l.textWrap, htmlWrap: l.htmlWrap, disableInline: l.disableInline}, true, nil } func markdownHTML(src string) (string, error) { @@ -830,6 +888,9 @@ type LayoutFile struct { HTML string Source string Hash string + // DisableAutoInlineCSS is the file's disable_auto_inline_css header + // key: the layout keeps its CSS in the style block only. + DisableAutoInlineCSS bool } // PartialFile is a registered partial as its plugin (or postcard) ships it. @@ -860,7 +921,7 @@ func (t *parsedTemplate) file() TemplateFile { } func (l *parsedLayout) file() LayoutFile { - return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash} + return LayoutFile{Name: l.name, PluginID: l.pluginID, Title: l.headerName, Text: l.textWrap, HTML: l.htmlWrap, Source: l.source, Hash: l.hash, DisableAutoInlineCSS: l.disableInline} } func (p *parsedPartial) file() PartialFile {