Lightweight server monitoring with historical data, docker stats, and alerts.
feat(alerts): send alert emails as styled HTML (#2697)
Sven van Ginkelf6e4ad4a79eb
diff --git a/internal/alerts/alerts.go b/internal/alerts/alerts.goindex f0ad7bec0..c60746ba4 100644--- a/internal/alerts/alerts.go+++ b/internal/alerts/alerts.go@@ -8,6 +8,7 @@ import ("sync""time"+ "github.com/henrygd/beszel/internal/email""github.com/nicholas-fedor/shoutrrr""github.com/pocketbase/dbx""github.com/pocketbase/pocketbase/core"@@ -261,8 +262,8 @@ func (am *AlertManager) SendAlert(data AlertMessageData) error {return nil}addresses := []mail.Address{}- for _, email := range userAlertSettings.Emails {- addresses = append(addresses, mail.Address{Address: email})+ for _, address := range userAlertSettings.Emails {+ addresses = append(addresses, mail.Address{Address: address})}message := mailer.Message{To: addresses,@@ -273,6 +274,17 @@ func (am *AlertManager) SendAlert(data AlertMessageData) error {Name: am.hub.Settings().Meta.SenderName,},}+ if html, err := email.RenderAlert(email.Alert{+ Title: data.Title,+ Message: data.Message,+ Link: data.Link,+ LinkText: data.LinkText,+ SettingsLink: am.hub.MakeLink("settings", "notifications"),+ }); err != nil {+ am.hub.Logger().Error("Failed to render email alert HTML", "err", err)+ } else {+ message.HTML = html+ }err = am.hub.NewMailClient().Send(&message)if err != nil {return errdiff --git a/internal/alerts/alerts_zfs_test.go b/internal/alerts/alerts_zfs_test.goindex 3208f7a62..5c2af0af1 100644--- a/internal/alerts/alerts_zfs_test.go+++ b/internal/alerts/alerts_zfs_test.go@@ -45,6 +45,7 @@ func TestZfsPoolAlertOnlineToDegraded(t *testing.T) {assert.Contains(t, lastMessage.Subject, "Storage pool DEGRADED on test-system")assert.Contains(t, lastMessage.Subject, "tank")assert.Contains(t, lastMessage.Text, "ONLINE to DEGRADED")+ assert.Contains(t, lastMessage.HTML, "ONLINE to DEGRADED", "email should include an HTML part")}func TestZfsPoolAlertDegradedToFaulted(t *testing.T) {diff --git a/internal/email/alert.html b/internal/email/alert.htmlnew file mode 100644index 000000000..2d10e883c--- /dev/null+++ b/internal/email/alert.html@@ -0,0 +1,27 @@+{{define "content"}}+{{- range .Blocks}}+{{- if .Code}}+<pre class="code" style="margin:0 0 16px;padding:12px 14px;background-color:#f4f4f5;border:1px solid #e4e4e7;border-radius:6px;font-family:ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;font-size:12px;line-height:1.5;color:#27272a;white-space:pre-wrap;word-break:break-word;">{{range $i, $l := .Lines}}{{if $i}}+{{end}}{{$l}}{{end}}</pre>+{{- else}}+<p class="text" style="margin:0 0 16px;font-size:15px;line-height:1.6;color:#3f3f46;">{{range $i, $l := .Lines}}{{if $i}}<br>{{end}}{{$l}}{{end}}</p>+{{- end}}+{{- end}}+{{- if .Link}}+<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-top:8px;">+<tr>+<td class="btn" style="border-radius:6px;background-color:#18181b;">+<a href="{{.Link}}" style="display:inline-block;padding:10px 18px;font-size:14px;font-weight:600;color:#ffffff;text-decoration:none;border-radius:6px;">{{.LinkText}}</a>+</td>+</tr>+</table>+{{- end}}+{{end}}++{{define "footer"}}+<tr>+<td class="footer" style="padding:16px 4px 0;font-size:12px;line-height:1.5;color:#71717a;">+You're receiving this because email notifications are enabled in Beszel.{{if .SettingsLink}} <a href="{{.SettingsLink}}" style="color:#71717a;text-decoration:underline;">Manage notifications</a>{{end}}+</td>+</tr>+{{end}}diff --git a/internal/email/auth_email_test.go b/internal/email/auth_email_test.gonew file mode 100644index 000000000..e12005148--- /dev/null+++ b/internal/email/auth_email_test.go@@ -0,0 +1,30 @@+//go:build testing++package email_test++import (+ "os"+ "testing"++ beszelTests "github.com/henrygd/beszel/internal/tests"+ "github.com/pocketbase/pocketbase/mails"+ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestAuthEmailsUseBeszelLayout(t *testing.T) {+ hub, user := beszelTests.GetHubWithUser(t)+ defer hub.Cleanup()++ require.NoError(t, mails.SendRecordPasswordReset(hub, user))++ message := hub.TestMailer.LastMessage()+ assert.Contains(t, message.HTML, `class="card content"`, "should use the Beszel layout")+ assert.Contains(t, message.HTML, "<title>"+message.Subject+"</title>")+ assert.Contains(t, message.HTML, "/_/#/auth/confirm-password-reset/", "should keep the template content")+ assert.NotContains(t, message.HTML, "Source Sans Pro", "should drop the PocketBase layout")++ if dir := os.Getenv("BESZEL_EMAIL_PREVIEW_DIR"); dir != "" {+ require.NoError(t, os.WriteFile(dir+"/password_reset_email.html", []byte(message.HTML), 0o644))+ }+}diff --git a/internal/email/email.go b/internal/email/email.gonew file mode 100644index 000000000..737074caf--- /dev/null+++ b/internal/email/email.go@@ -0,0 +1,118 @@+// Package email renders Beszel's HTML emails.+package email++import (+ _ "embed"+ "html/template"+ "strings"++ "github.com/pocketbase/pocketbase/core"+)++var (+ //go:embed layout.html+ layoutSource string+ //go:embed alert.html+ alertSource string+)++var (+ layoutTemplate = template.Must(template.New("layout").Parse(layoutSource))+ alertTemplate = template.Must(template.Must(layoutTemplate.Clone()).Parse(alertSource))+ contentTemplate = template.Must(template.Must(layoutTemplate.Clone()).Parse(`{{define "content"}}{{.Content}}{{end}}`))+)++// Alert is the content of an alert email.+type Alert struct {+ Title string+ Message string+ Link string+ LinkText string+ SettingsLink string+}++// block is a paragraph or a fenced code block of an alert message.+type block struct {+ Code bool+ Lines []string+}++// RenderAlert renders the HTML body of an alert email.+func RenderAlert(a Alert) (string, error) {+ if a.LinkText == "" {+ a.LinkText = "Open Beszel"+ }+ var sb strings.Builder+ err := alertTemplate.Execute(&sb, struct {+ Alert+ Blocks []block+ }{a, messageBlocks(a.Message)})+ return sb.String(), err+}++// messageBlocks splits a message into code blocks (``` fences) and+// paragraphs (separated by blank lines).+func messageBlocks(message string) []block {+ var blocks []block+ var lines []string+ inCode := false+ flush := func() {+ if len(lines) > 0 {+ blocks = append(blocks, block{Code: inCode, Lines: lines})+ }+ lines = nil+ }+ for line := range strings.SplitSeq(strings.ReplaceAll(message, "\r\n", "\n"), "\n") {+ switch {+ case strings.HasPrefix(strings.TrimSpace(line), "```"):+ flush()+ inCode = !inCode+ case !inCode && strings.TrimSpace(line) == "":+ flush()+ default:+ lines = append(lines, line)+ }+ }+ flush()+ return blocks+}++// BindAuthEmails restyles PocketBase's auth emails (verification, password+// reset, email change, OTP and login alert) with the Beszel layout.+func BindAuthEmails(app core.App) {+ app.OnMailerRecordVerificationSend().BindFunc(restyleAuthEmail)+ app.OnMailerRecordPasswordResetSend().BindFunc(restyleAuthEmail)+ app.OnMailerRecordEmailChangeSend().BindFunc(restyleAuthEmail)+ app.OnMailerRecordOTPSend().BindFunc(restyleAuthEmail)+ app.OnMailerRecordAuthAlertSend().BindFunc(restyleAuthEmail)+}++func restyleAuthEmail(e *core.MailerRecordEvent) error {+ if html, ok := wrapPocketBaseHTML(e.Message.Subject, e.Message.HTML); ok {+ e.Message.HTML = html+ } else {+ e.App.Logger().Warn("Could not restyle auth email, sending PocketBase layout", "subject", e.Message.Subject)+ }+ return e.Next()+}++// wrapPocketBaseHTML replaces PocketBase's mail layout with the Beszel layout,+// keeping the (possibly admin-customized) template content inside <body>.+func wrapPocketBaseHTML(title, pbHTML string) (string, bool) {+ start := strings.Index(pbHTML, "<body>")+ end := strings.LastIndex(pbHTML, "</body>")+ if start == -1 || end < start {+ return "", false+ }+ // The content comes from the collection's email template, which PocketBase+ // already renders as trusted HTML with escaped placeholder values.+ content := template.HTML(strings.TrimSpace(pbHTML[start+len("<body>") : end]))+ var sb strings.Builder+ if err := contentTemplate.Execute(&sb, struct {+ Title string+ Content template.HTML+ }{title, content}); err != nil {+ return "", false+ }+ return sb.String(), true+}diff --git a/internal/email/email_test.go b/internal/email/email_test.gonew file mode 100644index 000000000..17717bdc0--- /dev/null+++ b/internal/email/email_test.go@@ -0,0 +1,81 @@+//go:build testing++package email++import (+ "os"+ "testing"++ "github.com/stretchr/testify/assert"+ "github.com/stretchr/testify/require"+)++func TestRenderAlert(t *testing.T) {+ html, err := RenderAlert(Alert{+ Title: "CPU above threshold on web-1",+ Message: "CPU averaged 91.00% for the previous 10 minutes.",+ Link: "https://beszel.example.com/system/abc",+ LinkText: "View web-1",+ SettingsLink: "https://beszel.example.com/settings/notifications",+ })+ require.NoError(t, err)++ assert.Contains(t, html, "<title>CPU above threshold on web-1</title>")+ assert.Contains(t, html, "CPU averaged 91.00% for the previous 10 minutes.")+ assert.Contains(t, html, `href="https://beszel.example.com/system/abc"`)+ assert.Contains(t, html, ">View web-1</a>")+ assert.Contains(t, html, `href="https://beszel.example.com/settings/notifications"`)++ if dir := os.Getenv("BESZEL_EMAIL_PREVIEW_DIR"); dir != "" {+ preview, _ := RenderAlert(Alert{+ Title: "Container api is unhealthy on web-1",+ Message: "Container api became unhealthy.\nPrevious state: healthy\n\napi logs:\n```\nERROR connection refused\nretrying in 5s\n```",+ Link: "https://beszel.example.com/system/abc",+ LinkText: "View web-1",+ SettingsLink: "https://beszel.example.com/settings/notifications",+ })+ require.NoError(t, os.WriteFile(dir+"/alert_email.html", []byte(preview), 0o644))+ }+}++func TestRenderAlertEscapesContent(t *testing.T) {+ html, err := RenderAlert(Alert{+ Title: "<b>title</b>",+ Message: "```\n<script>alert(1)</script>\n```",+ Link: "javascript:alert(1)",+ })+ require.NoError(t, err)++ assert.NotContains(t, html, "<script>")+ assert.NotContains(t, html, "<b>title</b>")+ assert.Contains(t, html, "<script>")+ assert.NotContains(t, html, `href="javascript:`)+ assert.Contains(t, html, ">Open Beszel</a>", "empty link text falls back")+ assert.NotContains(t, html, "Manage notifications", "no settings link when empty")+}++func TestMessageBlocks(t *testing.T) {+ assert.Equal(t, []block{+ {Lines: []string{"first line", "second line"}},+ {Lines: []string{"next paragraph"}},+ {Lines: []string{"logs:"}},+ {Code: true, Lines: []string{"line 1", "", "line 3"}},+ {Lines: []string{"(+1 more)"}},+ }, messageBlocks("first line\nsecond line\n\nnext paragraph\n\nlogs:\n```\nline 1\n\nline 3\n```\n\n(+1 more)"))++ assert.Empty(t, messageBlocks(""))+ // an unterminated fence still renders its content as code+ assert.Equal(t, []block{{Code: true, Lines: []string{"x"}}}, messageBlocks("```\nx"))+ assert.Equal(t, []block{{Lines: []string{"a", "b"}}}, messageBlocks("a\r\nb"))+}++func TestWrapPocketBaseHTML(t *testing.T) {+ html, ok := wrapPocketBaseHTML("Reset your Beszel password", "<html><head><style>x</style></head><body>\n<p>Hello,</p><a class=\"btn\" href=\"https://x/reset\">Reset password</a>\n</body></html>")+ require.True(t, ok)+ assert.Contains(t, html, "<title>Reset your Beszel password</title>")+ assert.Contains(t, html, `<p>Hello,</p><a class="btn" href="https://x/reset">Reset password</a>`)+ assert.NotContains(t, html, "<style>x</style>")++ _, ok = wrapPocketBaseHTML("subject", "<p>no body tag</p>")+ assert.False(t, ok)+}diff --git a/internal/email/layout.html b/internal/email/layout.htmlnew file mode 100644index 000000000..bd16c6e22--- /dev/null+++ b/internal/email/layout.html@@ -0,0 +1,49 @@+<!doctype html>+<html lang="en">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width, initial-scale=1">+<meta name="color-scheme" content="light dark">+<meta name="supported-color-schemes" content="light dark">+<title>{{.Title}}</title>+<style>+:root { color-scheme: light dark; supported-color-schemes: light dark; }+.content p { margin: 0 0 16px; font-size: 15px; line-height: 1.6; color: #3f3f46; }+.content a { color: #18181b; }+.content a.btn { display: inline-block; padding: 10px 18px; font-size: 14px; font-weight: 600; color: #ffffff !important; background-color: #18181b !important; text-decoration: none !important; border-radius: 6px; }+.content .hidden { display: none !important; }+@media (prefers-color-scheme: dark) {+ .bg { background-color: #09090b !important; }+ .brand, .title { color: #fafafa !important; }+ .card { background-color: #18181b !important; border-color: #27272a !important; }+ .text, .content p { color: #d4d4d8 !important; }+ .content a { color: #fafafa !important; }+ .code { background-color: #09090b !important; border-color: #27272a !important; color: #e4e4e7 !important; }+ .btn { background-color: #fafafa !important; }+ .btn a, .content a.btn { color: #18181b !important; }+ .content a.btn { background-color: #fafafa !important; }+ .footer, .footer a { color: #a1a1aa !important; }+}+</style>+</head>+<body class="bg" style="margin:0;padding:0;background-color:#f4f4f5;">+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="bg" style="background-color:#f4f4f5;">+<tr>+<td align="center" style="padding:32px 16px;">+<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="max-width:560px;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;">+<tr>+<td class="brand" style="padding:0 4px 16px;font-size:18px;font-weight:700;letter-spacing:-0.01em;color:#18181b;">Beszel</td>+</tr>+<tr>+<td class="card content" style="background-color:#ffffff;border:1px solid #e4e4e7;border-radius:10px;padding:28px 28px 32px;">+<h1 class="title" style="margin:0 0 16px;font-size:20px;line-height:1.35;font-weight:600;color:#18181b;">{{.Title}}</h1>+{{block "content" .}}{{end}}+</td>+</tr>+{{- block "footer" .}}{{end}}+</table>+</td>+</tr>+</table>+</body>+</html>diff --git a/internal/hub/hub.go b/internal/hub/hub.goindex daf5168c0..ce13aaa73 100644--- a/internal/hub/hub.go+++ b/internal/hub/hub.go@@ -12,6 +12,7 @@ import ("strings""github.com/henrygd/beszel/internal/alerts"+ "github.com/henrygd/beszel/internal/email""github.com/henrygd/beszel/internal/hub/config""github.com/henrygd/beszel/internal/hub/heartbeat""github.com/henrygd/beszel/internal/hub/systems"@@ -111,6 +112,7 @@ func (h *Hub) StartHub() error {h.App.OnRecordCreate("user_settings").BindFunc(h.um.InitializeUserSettings)bindNetworkMonitorsEvents(h)+ email.BindAuthEmails(h.App)pb, ok := h.App.(*pocketbase.PocketBase)if !ok {