diff --git a/internal/api/admin_smtp.go b/internal/api/admin_smtp.go index 7a04b17b..2b364f9d 100644 --- a/internal/api/admin_smtp.go +++ b/internal/api/admin_smtp.go @@ -120,9 +120,12 @@ func (h *handlers) handleTestSMTPConfig(w http.ResponseWriter, r *http.Request) defer cancel() sender := mailer.NewSMTPSender(h.pool, h.logger) - textBody := "This is a test message from your Minstrel server.\n\nIf you got this, your SMTP config is working.\n\n— Minstrel" - htmlBody := "

This is a test message from your Minstrel server.

If you got this, your SMTP config is working.

— Minstrel

" - if err := sender.Send(ctx, *caller.Email, "Minstrel SMTP test", textBody, htmlBody); err != nil { + textBody, htmlBody, err := mailer.RenderSMTPTestEmail(h.netSettings.PublicURL()) + if err != nil { + writeErrWithLog(w, h.logger, "admin smtp: render test email failed", apierror.Internal(err)) + return + } + if err := sender.Send(ctx, *caller.Email, mailer.SMTPTestSubject, textBody, htmlBody); err != nil { if errors.Is(err, mailer.ErrNotConfigured) { writeErr(w, apierror.BadRequest("not_configured", "SMTP is not enabled or required fields are empty")) diff --git a/internal/api/auth_forgot.go b/internal/api/auth_forgot.go index 1fdcfa10..cf2002f1 100644 --- a/internal/api/auth_forgot.go +++ b/internal/api/auth_forgot.go @@ -117,6 +117,7 @@ func (h *handlers) sendResetEmail(ctx context.Context, user dbq.User) error { Username: user.Username, ResetURL: resetURL, ExpiryHours: int(resetTokenTTL.Hours()), + Server: h.netSettings.PublicURL(), }) if err != nil { return err diff --git a/internal/mailer/layout.go b/internal/mailer/layout.go new file mode 100644 index 00000000..bcc18e49 --- /dev/null +++ b/internal/mailer/layout.go @@ -0,0 +1,147 @@ +package mailer + +import ( + "bytes" + "embed" + "fmt" + htmltemplate "html/template" + "io/fs" + "strings" + texttemplate "text/template" +) + +// Every email Minstrel sends is drawn by one layout: the Minstrel name at the +// top, the email's heading and message on a card, and a footer saying which +// server sent it and why. An email supplies only its content, as a text +// template and an HTML template, plus a Frame; Render puts the content in the +// frame. A plain-text body goes out beside the HTML for clients that won't +// show HTML. Colours and type come from the Minstrel +// design system's dark theme, the app's own look, so an email reads as part +// of the same product on every client. + +//go:embed templates/layout.html templates/layout.txt +var layoutFS embed.FS + +var ( + layoutText = texttemplate.Must(texttemplate.ParseFS(layoutFS, "templates/layout.txt")) + layoutHTML = htmltemplate.Must(htmltemplate.New("layout.html").Funcs(htmltemplate.FuncMap{"style": style}). + ParseFS(layoutFS, "templates/layout.html")) +) + +// The Minstrel design system's values, as an email client needs them: inline, +// and with web fonts named first but never required. +const ( + colourPage = "#14171A" // --fs-surface-page + colourCard = "#1E2228" // --fs-surface-raised + colourBorder = "#3F4651" // --fs-border-color + colourText = "#E8E4D8" // --fs-text-primary + colourSecondary = "#C2BFB4" // --fs-text-secondary + colourTertiary = "#9C9A92" // --fs-text-tertiary + colourLink = "#A1AEA0" // --fs-accent-fg: the accent, readable as text on a dark card + colourAction = "#4A5D3F" // --fs-action-primary + colourOnAction = "#E8E4D8" // --fs-text-on-action + fontBody = "'Inter', system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif" + fontDisplay = "'Fraunces', Georgia, 'Times New Roman', serif" + fontMono = "'JetBrains Mono', ui-monospace, Menlo, Consolas, monospace" +) + +// styles are the named inline styles an email's HTML content uses, written +// `style="{{style "link"}}"`, so every email's links, buttons and quiet text +// look alike and change in one place. +var styles = map[string]string{ + "page": "margin:0; padding:0; background:" + colourPage + ";", + "wrap": "background:" + colourPage + ";", + "brand": "padding:0 4px 16px; font-family:" + fontDisplay + "; font-size:22px; font-weight:500; color:" + colourText + ";", + "heading": "margin:0 0 20px; font-family:" + fontDisplay + "; font-size:20px; font-weight:500; line-height:1.3; color:" + colourText + ";", + "card": "background:" + colourCard + "; border:1px solid " + colourBorder + "; border-radius:12px; padding:28px; font-family:" + fontBody + "; font-size:15px; line-height:1.55; color:" + colourText + ";", + "footer": "padding:16px 4px 0; font-family:" + fontBody + "; font-size:12px; line-height:1.5; color:" + colourTertiary + ";", + "p": "margin:0 0 16px;", + "link": "color:" + colourLink + "; text-decoration:underline;", + "quiet": "color:" + colourSecondary + "; font-size:14px;", + "faint": "color:" + colourTertiary + ";", + "group": "margin:20px 0 4px; font-weight:600; color:" + colourText + ";", + "list": "margin:0 0 8px; padding-left:20px;", + "item": "margin:2px 0;", + "button": "display:inline-block; padding:12px 24px; background:" + colourAction + "; color:" + colourOnAction + "; text-decoration:none; border-radius:8px; font-weight:500;", + "code": "font-family:" + fontMono + "; font-size:13px; word-break:break-all; color:" + colourSecondary + ";", +} + +// style returns a named style for an inline style attribute. An unknown name +// fails the render, so a typo shows in the email's test, not in an inbox. +func style(name string) (htmltemplate.CSS, error) { + s, ok := styles[name] + if !ok { + return "", fmt.Errorf("mailer: no email style %q", name) + } + return htmltemplate.CSS(s), nil //nolint:gosec // fixed strings from the table above, never user input +} + +// Frame is what the layout says around an email's content. +type Frame struct { + // Heading is the line at the top of the card, saying what the email is. + Heading string + // Server is the server's public address, named in the footer as the + // sender; empty when none is set, and the footer says "your Minstrel + // server" instead. + Server string + // Reason finishes the footer's "…because": why this person got this + // email, in a clause ("you asked to reset your password"). + Reason string + // NotificationSettings adds where to choose which notifications are + // emailed: a link under Server when it is set, else where to find it in + // the app. + NotificationSettings bool +} + +// SettingsURL is the notification settings page under Server, or "". +func (f Frame) SettingsURL() string { + if f.Server == "" { + return "" + } + return strings.TrimRight(f.Server, "/") + "/settings/notifications" +} + +// ServerName is how the footer names the sender. +func (f Frame) ServerName() string { + if f.Server == "" { + return "your Minstrel server" + } + return "the Minstrel server at " + strings.TrimRight(f.Server, "/") +} + +type layoutVars struct { + Content any + Frame Frame +} + +// Render returns an email's text and HTML bodies: the content templates +// textName and htmlName from content, executed with vars, inside the shared +// layout, framed by frame. HTML content styles its elements with +// {{style "name"}}. +func Render(content fs.FS, textName, htmlName string, vars any, frame Frame) (string, string, error) { + textSrc, err := fs.ReadFile(content, textName) + if err != nil { + return "", "", fmt.Errorf("mailer: read %s: %w", textName, err) + } + htmlSrc, err := fs.ReadFile(content, htmlName) + if err != nil { + return "", "", fmt.Errorf("mailer: read %s: %w", htmlName, err) + } + textTpl := texttemplate.Must(layoutText.Clone()) + if _, err := textTpl.New("content").Parse(string(textSrc)); err != nil { + return "", "", fmt.Errorf("mailer: parse %s: %w", textName, err) + } + htmlTpl := htmltemplate.Must(layoutHTML.Clone()) + if _, err := htmlTpl.New("content").Parse(string(htmlSrc)); err != nil { + return "", "", fmt.Errorf("mailer: parse %s: %w", htmlName, err) + } + lv := layoutVars{Content: vars, Frame: frame} + var textBuf, htmlBuf bytes.Buffer + if err := textTpl.ExecuteTemplate(&textBuf, "layout.txt", lv); err != nil { + return "", "", fmt.Errorf("mailer: render %s: %w", textName, err) + } + if err := htmlTpl.ExecuteTemplate(&htmlBuf, "layout.html", lv); err != nil { + return "", "", fmt.Errorf("mailer: render %s: %w", htmlName, err) + } + return textBuf.String(), htmlBuf.String(), nil +} diff --git a/internal/mailer/layout_test.go b/internal/mailer/layout_test.go new file mode 100644 index 00000000..df327b17 --- /dev/null +++ b/internal/mailer/layout_test.go @@ -0,0 +1,65 @@ +package mailer + +import ( + "strings" + "testing" + "testing/fstest" +) + +// Every email Minstrel sends goes out in the one layout: the Minstrel name, +// its heading on the card, and a footer naming the sending server and why. +func TestEveryEmailIsFramedByTheLayout(t *testing.T) { + reset := func() (string, string, error) { + return RenderResetEmail(ResetEmailVars{ + Username: "alice", ResetURL: "https://music.example/reset/abc", ExpiryHours: 1, Server: "https://music.example", + }) + } + smtpTest := func() (string, string, error) { return RenderSMTPTestEmail("https://music.example/") } + + for name, render := range map[string]func() (string, string, error){"reset": reset, "smtp test": smtpTest} { + text, html, err := render() + if err != nil { + t.Fatalf("%s: %v", name, err) + } + for _, want := range []string{ + `">Minstrel`, + "

Hi.

")}} + text, html, err := Render(content, "c.txt", "c.html", nil, Frame{ + Heading: "Hello", Reason: "you asked", NotificationSettings: true, + }) + if err != nil { + t.Fatal(err) + } + for _, body := range []string{text, html} { + if !strings.Contains(body, "Sent by your Minstrel server because you asked.") { + t.Errorf("footer should name the server generically:\n%s", body) + } + if !strings.Contains(body, "under Settings → Notifications") || strings.Contains(body, "http") { + t.Errorf("with no address, the settings line says where to look, without a link:\n%s", body) + } + } +} + +// A misspelt style name fails the render rather than shipping an unstyled email. +func TestUnknownStyleFailsTheRender(t *testing.T) { + content := fstest.MapFS{"c.txt": {Data: []byte("x")}, "c.html": {Data: []byte(`

x

`)}} + if _, _, err := Render(content, "c.txt", "c.html", nil, Frame{Heading: "h", Reason: "r"}); err == nil { + t.Fatal("want an error for an unknown style") + } +} diff --git a/internal/mailer/templates.go b/internal/mailer/templates.go index 9c526973..6413be09 100644 --- a/internal/mailer/templates.go +++ b/internal/mailer/templates.go @@ -1,45 +1,44 @@ package mailer -import ( - "bytes" - "embed" - "fmt" - htmltemplate "html/template" - texttemplate "text/template" -) +import "embed" -//go:embed templates/password_reset.txt templates/password_reset.html -var resetEmailFS embed.FS +//go:embed templates/password_reset.txt templates/password_reset.html templates/smtp_test.txt templates/smtp_test.html +var emailsFS embed.FS // ResetEmailVars is the data passed to the password reset templates. type ResetEmailVars struct { Username string ResetURL string ExpiryHours int -} - -// RenderResetEmail returns (textBody, htmlBody) for the password -// reset email, parameterized with the given vars. -func RenderResetEmail(vars ResetEmailVars) (string, string, error) { - textTpl, err := texttemplate.ParseFS(resetEmailFS, "templates/password_reset.txt") - if err != nil { - return "", "", fmt.Errorf("mailer: parse text template: %w", err) - } - htmlTpl, err := htmltemplate.ParseFS(resetEmailFS, "templates/password_reset.html") - if err != nil { - return "", "", fmt.Errorf("mailer: parse html template: %w", err) - } - - var textBuf, htmlBuf bytes.Buffer - if err := textTpl.Execute(&textBuf, vars); err != nil { - return "", "", fmt.Errorf("mailer: render text: %w", err) - } - if err := htmlTpl.Execute(&htmlBuf, vars); err != nil { - return "", "", fmt.Errorf("mailer: render html: %w", err) - } - return textBuf.String(), htmlBuf.String(), nil + // Server is the server's public address, named in the footer as the + // sender. + Server string } // ResetEmailSubject is the subject line used by the forgot-password // flow. Exported so callers don't string-literal it independently. const ResetEmailSubject = "Minstrel password reset" + +// RenderResetEmail returns (textBody, htmlBody) for the password reset +// email. +func RenderResetEmail(vars ResetEmailVars) (string, string, error) { + return Render(emailsFS, "templates/password_reset.txt", "templates/password_reset.html", vars, Frame{ + Heading: "Reset your password", + Server: vars.Server, + Reason: "a password reset was requested for your account", + }) +} + +// SMTPTestSubject is the subject of the message an admin sends to check +// the server's email settings. +const SMTPTestSubject = "Minstrel email test" + +// RenderSMTPTestEmail returns (textBody, htmlBody) for the email settings +// test message. server is the server's public address, or "". +func RenderSMTPTestEmail(server string) (string, string, error) { + return Render(emailsFS, "templates/smtp_test.txt", "templates/smtp_test.html", struct{}{}, Frame{ + Heading: "Email is working", + Server: server, + Reason: "an admin sent a test from the email settings", + }) +} diff --git a/internal/mailer/templates/layout.html b/internal/mailer/templates/layout.html new file mode 100644 index 00000000..603d55b3 --- /dev/null +++ b/internal/mailer/templates/layout.html @@ -0,0 +1,29 @@ + + + + + + + + + + + +
+ + + + +
Minstrel
+

{{.Frame.Heading}}

+{{template "content" .Content}} +
+Sent by {{.Frame.ServerName}} because {{.Frame.Reason}}.
+{{- if .Frame.NotificationSettings}} +{{with .Frame.SettingsURL}}Choose which notifications are emailed to you{{else}}Choose which notifications are emailed to you in Minstrel, under Settings → Notifications.{{end}}
+{{- end}} +— Minstrel +
+
+ + diff --git a/internal/mailer/templates/layout.txt b/internal/mailer/templates/layout.txt new file mode 100644 index 00000000..bf3bf477 --- /dev/null +++ b/internal/mailer/templates/layout.txt @@ -0,0 +1,9 @@ +{{.Frame.Heading}} + +{{template "content" .Content}} +-- +Sent by {{.Frame.ServerName}} because {{.Frame.Reason}}. +{{- if .Frame.NotificationSettings}} +{{with .Frame.SettingsURL}}Choose which notifications are emailed to you: {{.}}{{else}}Choose which notifications are emailed to you in Minstrel, under Settings → Notifications.{{end}} +{{- end}} +— Minstrel diff --git a/internal/mailer/templates/password_reset.html b/internal/mailer/templates/password_reset.html index c5d52527..e48e3a4c 100644 --- a/internal/mailer/templates/password_reset.html +++ b/internal/mailer/templates/password_reset.html @@ -1,29 +1,7 @@ - - - -

Hello {{.Username}},

- -

A password reset was requested for your Minstrel account. To set a new - password, click the button below within {{.ExpiryHours}} hours:

- -

- Reset password -

- -

- Or copy this URL into your browser:
- {{.ResetURL}} -

- -

- If you didn't request this, you can safely ignore this email — your - password won't change. -

- -

- — Minstrel -

- - +

Hello {{.Username}},

+

A password reset was requested for your Minstrel account. To set a new +password, use the button below within {{.ExpiryHours}} hours.

+

Reset password

+

Or copy this address into your browser:
+{{.ResetURL}}

+

If you didn't ask for this, you can ignore this email. Your password won't change.

diff --git a/internal/mailer/templates/password_reset.txt b/internal/mailer/templates/password_reset.txt index ac1f3618..0cefb6db 100644 --- a/internal/mailer/templates/password_reset.txt +++ b/internal/mailer/templates/password_reset.txt @@ -5,7 +5,5 @@ password, follow this link within {{.ExpiryHours}} hours: {{.ResetURL}} -If you didn't request this, you can safely ignore this email — your -password won't change. - -— Minstrel +If you didn't ask for this, you can ignore this email. Your password +won't change. diff --git a/internal/mailer/templates/smtp_test.html b/internal/mailer/templates/smtp_test.html new file mode 100644 index 00000000..745384d7 --- /dev/null +++ b/internal/mailer/templates/smtp_test.html @@ -0,0 +1,2 @@ +

This is a test message from your Minstrel server.

+

It arrived, so the server's email settings work: password resets and the notification emails people choose will reach their inboxes.

diff --git a/internal/mailer/templates/smtp_test.txt b/internal/mailer/templates/smtp_test.txt new file mode 100644 index 00000000..61e68240 --- /dev/null +++ b/internal/mailer/templates/smtp_test.txt @@ -0,0 +1,4 @@ +This is a test message from your Minstrel server. + +It arrived, so the server's email settings work: password resets and the +notification emails people choose will reach their inboxes. diff --git a/internal/notifications/digest_render.go b/internal/notifications/digest_render.go index 12949603..d8f495fb 100644 --- a/internal/notifications/digest_render.go +++ b/internal/notifications/digest_render.go @@ -1,23 +1,17 @@ package notifications import ( - "bytes" "embed" "encoding/json" "fmt" - htmltemplate "html/template" "strings" - texttemplate "text/template" + + "git.fabledsword.com/bvandeusen/minstrel/internal/mailer" ) //go:embed templates/digest.txt templates/digest.html var digestFS embed.FS -var ( - digestText = texttemplate.Must(texttemplate.ParseFS(digestFS, "templates/digest.txt")) - digestHTML = htmltemplate.Must(htmltemplate.ParseFS(digestFS, "templates/digest.html")) -) - // digestEmail is one rendered email. type digestEmail struct { Subject string @@ -38,22 +32,24 @@ type digestArtist struct { } type digestVars struct { - Name string - Intro string - Items []digestLine - Artists []digestArtist - SettingsURL string + Name string + Intro string + Items []digestLine + Artists []digestArtist } // renderDigest renders one group's email. base is the public address; with // none set, the email still goes out, without links. func renderDigest(group EmailGroup, name string, items []pendingItem, base string) (digestEmail, error) { - vars := digestVars{Name: name, SettingsURL: joinURL(base, "/settings/notifications")} + vars := digestVars{Name: name} + frame := mailer.Frame{Server: base, NotificationSettings: true} var subject string if group == EmailSummary { vars.Artists = summaryArtists(items, base) vars.Intro = "New in your library since the last summary:" subject = "Minstrel: new music in your library" + frame.Heading = "New music in your library" + frame.Reason = "you chose to get new-music summaries by email" } else { for _, it := range items { r := Render(it.Kind, it.Payload) @@ -61,19 +57,19 @@ func renderDigest(group EmailGroup, name string, items []pendingItem, base strin } vars.Intro = "Here's what happened on Minstrel:" subject = fmt.Sprintf("Minstrel: %d updates", len(items)) + frame.Heading = fmt.Sprintf("%d updates", len(items)) if len(items) == 1 { subject = "Minstrel: " + vars.Items[0].Title + frame.Heading = vars.Items[0].Title } + frame.Reason = "you chose to get these notifications by email" } - var text, html bytes.Buffer - if err := digestText.Execute(&text, vars); err != nil { - return digestEmail{}, fmt.Errorf("render text: %w", err) + text, html, err := mailer.Render(digestFS, "templates/digest.txt", "templates/digest.html", vars, frame) + if err != nil { + return digestEmail{}, fmt.Errorf("render digest: %w", err) } - if err := digestHTML.Execute(&html, vars); err != nil { - return digestEmail{}, fmt.Errorf("render html: %w", err) - } - return digestEmail{Subject: subject, Text: text.String(), HTML: html.String()}, nil + return digestEmail{Subject: subject, Text: text, HTML: html}, nil } // summaryArtists groups new-music arrivals by artist, in the order each diff --git a/internal/notifications/templates/digest.html b/internal/notifications/templates/digest.html index e4f43e54..ff6e0290 100644 --- a/internal/notifications/templates/digest.html +++ b/internal/notifications/templates/digest.html @@ -1,25 +1,15 @@ - - - -

Hello {{.Name}},

- -

{{.Intro}}

+

Hello {{.Name}},

+

{{.Intro}}

{{range .Artists}} -

{{if .URL}}{{.Name}}{{else}}{{.Name}}{{end}}

- {{if .Titles}}{{end}} +

{{if .URL}}{{.Name}}{{else}}{{.Name}}{{end}}

+{{if .Titles}}{{end}} {{end}}{{if .Items}} - + {{end}} -

- {{if .SettingsURL}}Choose which notifications are emailed to you{{else}}Choose which notifications are emailed to you in Minstrel, under Settings → Notifications.{{end}}
- — Minstrel -

- - diff --git a/internal/notifications/templates/digest.txt b/internal/notifications/templates/digest.txt index 01b0b178..26ec9d43 100644 --- a/internal/notifications/templates/digest.txt +++ b/internal/notifications/templates/digest.txt @@ -11,6 +11,3 @@ Hello {{.Name}}, {{.Body}}{{end}}{{if .URL}} {{.URL}}{{end}} {{end}} -{{if .SettingsURL}}Choose which notifications are emailed to you: {{.SettingsURL}}{{else}}Choose which notifications are emailed to you in Minstrel, under Settings → Notifications.{{end}} - -— Minstrel