diff --git a/API.md b/API.md index a7ed192..165ec9b 100644 --- a/API.md +++ b/API.md @@ -446,6 +446,18 @@ recipient's tenant plan gates the send. History and delivery rows carry carry the footer "Managed by David's Superbrain."; paying plans and core do not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`). +Branded email (multipart/alternative, `internal/mailer/template.html`) +carries footer links when `NEXTAUTH_URL` is set: Email preferences +(`/settings?tab=notifications`), Help center (`/help`) and — ONLY when the +recipient is the owner's own account email — Unsubscribe +(`/unsubscribe?token=…`). The token is a stable HMAC-signed user id +(`notify.UnsubscribeToken`, no stored row); owner-addressed mail also +carries `List-Unsubscribe` + `List-Unsubscribe-Post` (RFC 8058 one-click). +Unsubscribe disables the user's enabled email channels and pauses enabled +agent email tasks addressed to the user's own email; it is idempotent and +never touches transactional mail (password reset) or third-party +recipients. + | Method | Path | Body / Returns | |---|---|---| | GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` | @@ -458,6 +470,7 @@ not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`). | PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version | | DELETE | `/api/notifications/rules/{id}` | `{ok:true}` | | GET | `/api/notifications` | Last 100 deliveries for rows you own OR were targeted on: `[{id,title,body,status,attempts,ruleName,channelKind,recipientId,sentAt,createdAt}]`; status ∈ pending/sent/failed/suppressed | +| POST | `/api/notifications/unsubscribe` | Token-credentialed, NO session: `?token=…` (RFC 8058 one-click; body ignored) or JSON `{token}` → `{ok:true,channels,tasks}`; 400 for invalid/tampered tokens; per-client rate limited | ### Agent automations ("hey superbrain") diff --git a/internal/agent/engine.go b/internal/agent/engine.go index 64669b3..3946a48 100644 --- a/internal/agent/engine.go +++ b/internal/agent/engine.go @@ -370,7 +370,9 @@ func fire(ctx context.Context, d *db.DB, t Task, summary string) (string, string defer release() sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second) defer cancel() - if err := mailer.Send(sendCtx, t.Spec.Action.To, title, body); err != nil { + c := notify.FooterLinks(sendCtx, d, t.OwnerID, t.Spec.Action.To) + c.Headline, c.Body = title, body + if err := mailer.SendTemplate(sendCtx, t.Spec.Action.To, title, body, c); err != nil { return "failed", "email: " + err.Error() } case "bookmark": diff --git a/internal/auth/password_reset.go b/internal/auth/password_reset.go index 03ac7b1..a47cc22 100644 --- a/internal/auth/password_reset.go +++ b/internal/auth/password_reset.go @@ -25,6 +25,7 @@ import ( "encoding/base64" "encoding/hex" "errors" + "fmt" "log" "net/http" "net/mail" @@ -161,7 +162,29 @@ func HandleForgotPassword(w http.ResponseWriter, r *http.Request) { link + "\n\n" + "If you did not request a reset, you can ignore this email; the link is\n" + "single-use and your password stays unchanged.\n" - if e := mailer.Send(r.Context(), email, "Reset your Superbrain password", body); e != nil { + minutes := int(resetTokenTTL.Minutes()) + firstName := "" + if u.Name != nil { + if fields := strings.Fields(*u.Name); len(fields) > 0 { + firstName = fields[0] + } + } + content := mailer.Content{ + Preheader: fmt.Sprintf("Choose a new password — the link expires in %d minutes.", minutes), + Headline: "Reset your password", + FirstName: firstName, + Body: "We received a request to reset your Superbrain password.\nClick the button below to choose a new one.", + CTAURL: link, + CTALabel: "Choose a new password", + Note: fmt.Sprintf("This link expires in %d minutes and can only be used once. "+ + "If you didn't request a reset, you can ignore this email — your password stays unchanged.", minutes), + // Transactional mail: preferences and help, but deliberately NO + // unsubscribe — a reset link must never depend on notification + // preferences (base is non-empty here; checked above). + PreferencesURL: base + "/settings?tab=notifications", + HelpURL: base + "/help", + } + if e := mailer.SendTemplate(r.Context(), email, "Reset your Superbrain password", body, content); e != nil { log.Printf("password reset: delivery to %s failed: %v", email, e) } okResponse() diff --git a/internal/handlers/notifications.go b/internal/handlers/notifications.go index c24dc38..dea5978 100644 --- a/internal/handlers/notifications.go +++ b/internal/handlers/notifications.go @@ -11,6 +11,7 @@ import ( "encoding/json" "errors" "fmt" + "log" "math" "net/http" "sort" @@ -652,3 +653,75 @@ func ruleProjection(row object, channelKind, channelName string) object { "lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"], } } + +// HandleNotificationUnsubscribe consumes a signed unsubscribe token. There +// is no session: the HMAC token IS the credential (it ships only in mail to +// the owner's own address, see notify.FooterLinks), which also makes the +// endpoint RFC 8058 one-click compatible — mail clients POST to the +// List-Unsubscribe URL with the token in the query and a form body we +// ignore. The browser confirmation page POSTs JSON {"token": ...} instead. +// +// Effect: disable the user's enabled email channels and pause enabled agent +// tasks whose email action addresses the user's own email. Idempotent, and +// deliberately NOT a delete — preferences are re-enableable in Settings. +// Transactional mail (password reset) never consults this state. +// +// POST /api/notifications/unsubscribe?token=... +func HandleNotificationUnsubscribe(w http.ResponseWriter, r *http.Request) { + token := strings.TrimSpace(r.URL.Query().Get("token")) + if token == "" { + b, ok := read(w, r) + if !ok { + return + } + token = strings.TrimSpace(str(b, "token")) + } + // token = 32-hex id + "." + 64-hex MAC; anything longer is junk. + if token == "" || len(token) > 128 { + respond(w, 0, nil, bad("Invalid unsubscribe link")) + return + } + userID, ok := notify.ParseUnsubscribeToken(token) + if !ok { + respond(w, 0, nil, bad("Invalid unsubscribe link")) + return + } + d := database(r) + var email *string + if e := d.QueryRowContext(r.Context(), `SELECT email FROM "User" WHERE id=$1`, userID).Scan(&email); e != nil { + if errors.Is(e, db.ErrNotFound) { + // A valid MAC for a deleted account is still a dead link; the + // answer is identical to a tampered token (no oracle). + respond(w, 0, nil, bad("Invalid unsubscribe link")) + return + } + respond(w, 0, nil, e) + return + } + chRes, e := d.ExecContext(r.Context(), ` + UPDATE "NotificationChannel" + SET enabled=false, version=version+1, "updatedAt"=now() + WHERE "ownerId"=$1 AND kind='email' AND enabled=true`, userID) + if e != nil { + respond(w, 0, nil, e) + return + } + channels, _ := chRes.RowsAffected() + var tasks int64 + if email != nil && *email != "" { + taskRes, e := d.ExecContext(r.Context(), ` + UPDATE "AgentTask" + SET enabled=false, status='paused', version=version+1, "updatedAt"=now() + WHERE "ownerId"=$1 AND enabled=true + AND spec->'action'->>'type'='email' + AND lower(spec->'action'->>'to')=lower($2)`, userID, *email) + if e != nil { + respond(w, 0, nil, e) + return + } + tasks, _ = taskRes.RowsAffected() + } + // Audited like other preference changes: ids and counts, no secrets. + log.Printf("audit: email unsubscribe for user %s (channels=%d tasks=%d)", userID, channels, tasks) + respond(w, 200, object{"ok": true, "channels": channels, "tasks": tasks}, nil) +} diff --git a/internal/http/server.go b/internal/http/server.go index 64b74e2..822b0c4 100644 --- a/internal/http/server.go +++ b/internal/http/server.go @@ -128,6 +128,12 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server { mux.HandleFunc("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate)) mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete)) mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList)) + // Unsubscribe is token-authenticated (no session — the HMAC token in the + // mail IS the credential), so it gets the public-endpoint treatment: a + // per-effective-client rate limit, never the shared Next container bucket. + unsubscribeLimiter := auth.NewLimiterStore() + mux.HandleFunc("POST /api/notifications/unsubscribe", + auth.Limiter(unsubscribeLimiter, 10, time.Minute)(handlers.HandleNotificationUnsubscribe)) // 4.7c Agent automations ("hey superbrain"): compile NL into a validated // proposal (never writes), then owner-confirmed task CRUD + runs. diff --git a/internal/http/unsubscribe_test.go b/internal/http/unsubscribe_test.go new file mode 100644 index 0000000..601a88a --- /dev/null +++ b/internal/http/unsubscribe_test.go @@ -0,0 +1,220 @@ +package http + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "net/http/cookiejar" + "regexp" + "strings" + "testing" + "time" + + "github.com/andrew/superbrain/internal/notify" +) + +var unsubTokenRx = regexp.MustCompile(`/unsubscribe\?token=([0-9a-f.]+)`) + +// The unsubscribe surface end to end: footer links + RFC 8058 headers on +// owner-addressed mail, the token-credentialed one-click endpoint (no +// session), the exact blast radius (email channels + self-addressed agent +// email tasks, nothing else), idempotence, and the third-party/transactional +// exclusions. +func TestUnsubscribeFlow(t *testing.T) { + srv, d := testServerDB(t) + smtp := newFakeSMTP(t) + host, port, _ := net.SplitHostPort(smtp.ln.Addr().String()) + t.Setenv("SMTP_HOST", host) + t.Setenv("SMTP_PORT", port) + t.Setenv("SMTP_FROM", "superbrain@superbrain.test") + t.Setenv("NEXTAUTH_URL", "https://superbrain.test") + + jar, _ := cookiejar.New(nil) + alice := apiClient{t, &http.Client{Jar: jar}, srv.URL} + alice.request("POST", "/api/signup", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 201) + alice.request("POST", "/api/auth/login", map[string]any{"email": "alice@superbrain.test", "password": "a-long-test-password"}, 200) + aliceID := meID(alice) + + hook := newFakeWebhook(t) + selfCh := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "email", "name": "My inbox", "config": map[string]any{"address": ""}, + }, 201) + thirdCh := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "email", "name": "Bob's inbox", "config": map[string]any{"address": "bob@superbrain.test"}, + }, 201) + slackCh := alice.request("POST", "/api/notifications/channels", map[string]any{ + "kind": "slack", "name": "Team", "config": map[string]any{"webhookUrl": hook.url()}, + }, 201) + + // Signal-condition email tasks need no AI. One addresses the owner, + // one a third party: unsubscribe must pause only the former. + selfTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Self mail", "spec": map[string]any{ + "condition": map[string]any{"type": "signal"}, + "action": map[string]any{"type": "email", "to": "alice@superbrain.test"}, + }}, 201) + thirdTask := alice.request("POST", "/api/agent/tasks", map[string]any{"name": "Bob mail", "spec": map[string]any{ + "condition": map[string]any{"type": "signal"}, + "action": map[string]any{"type": "email", "to": "bob@superbrain.test"}, + }}, 201) + + // --- owner-addressed delivery carries footer links + one-click headers --- + due := time.Now().UTC().Add(6 * time.Hour).Format(time.RFC3339) + alice.request("POST", "/api/bookmarks", map[string]any{ + "url": "https://example.org/unsub-due", "title": "Unsub due", "dueDate": due, + }, 201) + alice.request("POST", "/api/notifications/rules", map[string]any{ + "name": "Due reminders", "trigger": "bookmark_due", "channelId": selfCh["id"], + "config": map[string]any{"leadHours": 24}, "cooldownMinutes": 60, + }, 201) + if e := notify.RunOnce(context.Background(), d); e != nil { + t.Fatal(e) + } + msg := smtp.waitForMessage(t, 1) + if msg[0] != "alice@superbrain.test" { + t.Fatalf("envelope recipient = %q", msg[0]) + } + for _, want := range []string{ + "List-Unsubscribe: \r\n") + b.WriteString("List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n") + } + if html == "" { + b.WriteString("Content-Type: text/plain; charset=UTF-8\r\n") + b.WriteString("Content-Transfer-Encoding: 8BIT\r\n") + b.WriteString("\r\n") + b.WriteString(smtpBody(text)) + b.WriteString("\r\n") + return b.String() + } + boundary := newBoundary(text, html) + b.WriteString("Content-Type: multipart/alternative; boundary=\"" + boundary + "\"\r\n") + b.WriteString("\r\n") + b.WriteString("--" + boundary + "\r\n") + b.WriteString("Content-Type: text/plain; charset=UTF-8\r\n") + b.WriteString("Content-Transfer-Encoding: 8BIT\r\n") + b.WriteString("\r\n") + b.WriteString(smtpBody(text)) + b.WriteString("\r\n--" + boundary + "\r\n") + b.WriteString("Content-Type: text/html; charset=UTF-8\r\n") + b.WriteString("Content-Transfer-Encoding: 8BIT\r\n") + b.WriteString("\r\n") + b.WriteString(smtpBody(html)) + b.WriteString("\r\n--" + boundary + "--\r\n") + return b.String() +} + +// newBoundary picks a random multipart boundary that does not occur in +// either part (a collision would truncate the message at the relay). +func newBoundary(text, html string) string { + for { + raw := make([]byte, 16) + if _, err := rand.Read(raw); err != nil { + // crypto/rand never fails on the supported platforms; a fixed + // fallback still beats an empty boundary. + return "superbrain-boundary-0000000000000000" + } + b := "sb-" + hex.EncodeToString(raw) + if !strings.Contains(text, b) && !strings.Contains(html, b) { + return b + } + } +} + +// smtpBody normalizes line endings to CRLF and dot-stuffs (RFC 5321 +// §4.5.2): a line consisting of or starting with "." must be doubled so +// the DATA terminator can never appear inside a part. +func smtpBody(s string) string { + s = strings.ReplaceAll(s, "\r\n", "\n") + s = strings.ReplaceAll(s, "\r", "\n") + s = strings.ReplaceAll(s, "\n", "\r\n") + s = strings.ReplaceAll(s, "\r\n.", "\r\n..") + if strings.HasPrefix(s, ".") { + s = "." + s + } + return s +} + // dial resolves and connects through netguard: range checks apply unless // INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and // only the standard SMTP ports are reachable from public ranges. diff --git a/internal/mailer/render.go b/internal/mailer/render.go new file mode 100644 index 0000000..51cf505 --- /dev/null +++ b/internal/mailer/render.go @@ -0,0 +1,243 @@ +// Branded HTML rendering for transactional email. template.html is the +// Superbrain email design (table layout, Outlook VML button fallback, +// dark-mode overrides); it is embedded verbatim and filled here. +// +// The template uses {{placeholder}} markers rather than text/template so +// the design file stays editable as plain HTML (and Outlook conditional +// comments survive untouched). Every substituted value is HTML-escaped, +// and optional sections (CTA button + fallback link, note block, footer +// links, address line) are removed when their values are empty. + +package mailer + +import ( + _ "embed" + "errors" + "fmt" + "html" + "strings" +) + +//go:embed template.html +var emailTemplate string + +// Content describes one branded rendering. Headline falls back to the +// subject, SignOff to "Thanks,", CTALabel to "Open Superbrain", and the +// preheader to the first body paragraph. Empty optional fields remove +// their section instead of rendering a stub. +type Content struct { + Preheader string // inbox preview line (kept under ~90 characters) + Headline string + FirstName string // optional; the greeting degrades to "Hi," + Body string // newline-separated paragraphs + CTAURL string // optional button + fallback link + CTALabel string + Note string // optional highlighted note block + SignOff string + + // Optional footer links; unset ones are omitted. + PreferencesURL string + UnsubscribeURL string + HelpURL string + CompanyAddress string + + // UnsubscribePostURL is the RFC 8058 one-click endpoint (POST, token in + // the query). When set, the message carries List-Unsubscribe + + // List-Unsubscribe-Post headers so mail clients can offer native + // unsubscribe. It is independent of UnsubscribeURL (the human page). + UnsubscribePostURL string +} + +// Template markers. The CTA cut spans the button row AND the fallback-link +// row (both are meaningless without a URL); the note cut spans the optional +// note block. Anchors must stay in sync with template.html — Render errors +// (and the unit tests fail) if the design drifts away from them. +const ( + ctaStartMarker = "" + noteStartMarker = "" + bodyStartAnchor = `

{{body_paragraph_1}}

` + bodyEndAnchor = `

{{body_paragraph_2}}

` + addressParagraph = `

Superbrain, {{company_address}}

` + footerLinkAnchor = "{{preferences_url}}" +) + +// Render fills the embedded template for one message. An error means the +// template no longer matches the renderer's anchors (a programming error, +// caught by tests); callers degrade to plain text rather than block mail. +func Render(subject string, c Content) (string, error) { + s := emailTemplate + var err error + + headline := c.Headline + if headline == "" { + headline = subject + } + paras := paragraphs(c.Body) + preheader := c.Preheader + if preheader == "" && len(paras) > 0 { + preheader = paras[0] + } + if preheader == "" { + preheader = headline + } + preheader = truncateRunes(preheader, 90) + + // Optional CTA: without a URL, drop the button and fallback-link rows. + if c.CTAURL == "" { + s, err = cutSpan(s, ctaStartMarker, noteStartMarker) + if err != nil { + return "", err + } + } else { + label := c.CTALabel + if label == "" { + label = "Open Superbrain" + } + s = strings.ReplaceAll(s, "{{cta_url}}", html.EscapeString(c.CTAURL)) + s = strings.ReplaceAll(s, "{{cta_label}}", html.EscapeString(label)) + } + + // Optional note block. + if c.Note == "" { + s, err = cutSpan(s, noteStartMarker, signOffMarker) + if err != nil { + return "", err + } + } else { + s = strings.ReplaceAll(s, "{{note_text}}", html.EscapeString(c.Note)) + } + + // Greeting: a missing name must not render "Hi ,". + greeting := "Hi," + if c.FirstName != "" { + greeting = "Hi " + html.EscapeString(c.FirstName) + "," + } + s = strings.Replace(s, "Hi {{first_name}},", greeting, 1) + + // Body: replace the two placeholder paragraphs with one

per line. + var b strings.Builder + for i, p := range paras { + style := "margin:0 0 16px 0;" + if i == len(paras)-1 { + style = "margin:0;" + } + if i > 0 { + b.WriteString("\n ") + } + b.WriteString(`

` + html.EscapeString(p) + `

`) + } + s, err = replaceSpan(s, bodyStartAnchor, bodyEndAnchor, b.String()) + if err != nil { + return "", err + } + + signOff := c.SignOff + if signOff == "" { + signOff = "Thanks," + } + s = strings.ReplaceAll(s, "{{sign_off}}", html.EscapeString(signOff)) + s = strings.ReplaceAll(s, "{{subject}}", html.EscapeString(subject)) + s = strings.ReplaceAll(s, "{{preheader_text}}", html.EscapeString(preheader)) + s = strings.ReplaceAll(s, "{{headline}}", html.EscapeString(headline)) + + // Footer links: keep only the ones with a URL; drop the whole paragraph + // when none are configured (the product has no preference/help pages yet). + s, err = renderFooterLinks(s, c) + if err != nil { + return "", err + } + if c.CompanyAddress == "" { + s = strings.Replace(s, addressParagraph, "", 1) + } else { + s = strings.ReplaceAll(s, "{{company_address}}", html.EscapeString(c.CompanyAddress)) + } + + if strings.Contains(s, "{{") { + return "", errors.New("mailer: template has unfilled placeholders") + } + return s, nil +} + +func renderFooterLinks(s string, c Content) (string, error) { + var links []string + for _, l := range []struct{ url, label string }{ + {c.PreferencesURL, "Email preferences"}, + {c.UnsubscribeURL, "Unsubscribe"}, + {c.HelpURL, "Help center"}, + } { + if l.url == "" { + continue + } + links = append(links, ``+l.label+``) + } + start, end, err := paragraphSpan(s, footerLinkAnchor) + if err != nil { + return "", err + } + if len(links) == 0 { + return s[:start] + s[end:], nil + } + repl := `

` + strings.Join(links, "  |  ") + `

` + return s[:start] + repl + s[end:], nil +} + +// paragraphs splits body text into trimmed, non-empty lines. +func paragraphs(body string) []string { + var out []string + for _, line := range strings.Split(body, "\n") { + if line = strings.TrimSpace(line); line != "" { + out = append(out, line) + } + } + return out +} + +func truncateRunes(s string, n int) string { + r := []rune(s) + if len(r) <= n { + return s + } + return string(r[:n]) +} + +// cutSpan removes [startMarker, endMarker) — the end marker stays for the +// next cut. Both markers must exist. +func cutSpan(s, startMarker, endMarker string) (string, error) { + i := strings.Index(s, startMarker) + if i < 0 { + return "", fmt.Errorf("mailer: template marker %q not found", startMarker) + } + j := strings.Index(s[i:], endMarker) + if j < 0 { + return "", fmt.Errorf("mailer: template marker %q not found", endMarker) + } + return s[:i] + s[i+j:], nil +} + +// replaceSpan swaps [startAnchor, endAnchor] (inclusive) for repl. +func replaceSpan(s, startAnchor, endAnchor, repl string) (string, error) { + i := strings.Index(s, startAnchor) + if i < 0 { + return "", fmt.Errorf("mailer: template anchor %q not found", startAnchor) + } + j := strings.Index(s[i:], endAnchor) + if j < 0 { + return "", fmt.Errorf("mailer: template anchor %q not found", endAnchor) + } + return s[:i] + repl + s[i+j+len(endAnchor):], nil +} + +// paragraphSpan locates the

…

enclosing anchor. +func paragraphSpan(s, anchor string) (start, end int, err error) { + i := strings.Index(s, anchor) + if i < 0 { + return 0, 0, fmt.Errorf("mailer: template anchor %q not found", anchor) + } + start = strings.LastIndex(s[:i], "") + if start < 0 || j < 0 { + return 0, 0, errors.New("mailer: template paragraph around anchor not found") + } + return start, i + j + len("

"), nil +} diff --git a/internal/mailer/render_test.go b/internal/mailer/render_test.go new file mode 100644 index 0000000..b0948a6 --- /dev/null +++ b/internal/mailer/render_test.go @@ -0,0 +1,219 @@ +package mailer + +import ( + "strings" + "testing" +) + +// The renderer and the embedded design file are one unit: these tests pin +// the anchors so a template edit that drops a marker fails loudly instead +// of silently shipping unfilled placeholders. + +func TestRenderFull(t *testing.T) { + html, err := Render("Reset your Superbrain password", Content{ + Preheader: "Choose a new password.", + Headline: "Reset your password", + FirstName: "Alice", + Body: "First paragraph.\nSecond paragraph.", + CTAURL: "https://superbrain.test/reset-password?token=abc", + CTALabel: "Choose a new password", + Note: "The link expires in 30 minutes.", + SignOff: "Cheers,", + PreferencesURL: "https://superbrain.test/settings", + UnsubscribeURL: "https://superbrain.test/unsubscribe", + HelpURL: "https://superbrain.test/help", + CompanyAddress: "1 Example Way, Testville", + }) + if err != nil { + t.Fatal(err) + } + for _, want := range []string{ + "Reset your password", "Hi Alice,", "First paragraph.", "Second paragraph.", + "Choose a new password", "https://superbrain.test/reset-password?token=abc", + "v:roundrect", "If the button doesn't work", // Outlook fallback + plain link + "The link expires in 30 minutes.", "Cheers,", "The Superbrain team", + "Email preferences", "Unsubscribe", "Help center", "1 Example Way, Testville", + "Choose a new password.", // preheader + } { + if !strings.Contains(html, want) { + t.Errorf("rendered mail missing %q", want) + } + } + if strings.Contains(html, "{{") { + t.Errorf("unfilled placeholder remains:\n%s", html) + } +} + +func TestRenderMinimal(t *testing.T) { + html, err := Render("Bookmark due: Due soon", Content{ + Headline: "Bookmark due: Due soon", + Body: "Due soon is due in 6 hours.", + }) + if err != nil { + t.Fatal(err) + } + if strings.Contains(html, "{{") { + t.Errorf("unfilled placeholder remains:\n%s", html) + } + // Optional sections are removed, not stubbed. + for _, absent := range []string{ + "v:roundrect", "If the button doesn't work", // CTA + fallback rows + `"`, Content{ + Headline: ``, + FirstName: `Ann", "Ann