Branded email template + footer pages: help center, token unsubscribe, settings deep links
release gate / check (push) Failing after 6m56s

Transactional mail now goes out as the Superbrain HTML design
(internal/mailer/template.html, embedded verbatim) with a plain-text
alternative: multipart/alternative (plain first per RFC 2046), random
boundary, CRLF normalization and SMTP dot-stuffing. Render() fills the
{{placeholders}} with HTML-escaped values and removes optional sections
(CTA + fallback link, note block, footer links, address) when empty;
anchor drift fails the unit tests and degrades to plain text at send
time, never blocking delivery. Password reset gets the headline,
first-name greeting, "Choose a new password" button (Outlook VML
fallback) and expiry/single-use note; notification and agent emails
render title-as-headline with body paragraphs.

The template's footer links are now real pages:
- /help: public help center (10 topic sections + FAQ accordion), linked
  from the login page.
- /unsubscribe?token=...: public confirmation page; the HMAC-signed user
  id (notify.UnsubscribeToken, domain-separated, stable, no stored row)
  IS the credential. POST /api/notifications/unsubscribe accepts the
  RFC 8058 one-click shape (token in query, form body ignored) and the
  browser JSON shape; it disables the user's enabled email channels and
  pauses enabled agent email tasks addressed to their own email
  (idempotent, re-enableable, per-client rate limited, audit logged).
- Email preferences deep-links to /settings?tab=notifications; Settings
  now honors ?tab=<section> (unknown values fall back to profile).

notify.FooterLinks is the single eligibility point: preferences + help
whenever NEXTAUTH_URL is set; unsubscribe ONLY when the recipient is the
owner's own account email — third-party channel addresses and agent
recipients never receive a link that changes someone else's settings,
and transactional mail (password reset) never carries unsubscribe.
Owner-addressed mail also carries List-Unsubscribe +
List-Unsubscribe-Post headers.

Verified: Go build/vet/unit green; new TestUnsubscribeFlow integration
test pins footer + headers, blast radius (slack channel and third-party
task survive), one-click + JSON paths, idempotence, tampered tokens and
the third-party/transactional exclusions; notifications, phase-2,
password-reset and agent suites green; web lint/SSR-lint/build 0 errors;
full browser regressions pass; live smoke of /help, /unsubscribe states,
the settings deep-link auth gate and bad-token 400 through the proxy.
This commit is contained in:
Andrew S Erwin
2026-11-20 10:00:03 -06:00
parent ef69be6320
commit 7a7e77e039
20 changed files with 1589 additions and 21 deletions
+94 -14
View File
@@ -1,5 +1,7 @@
// Package mailer sends transactional email (password-reset links) through a
// configured SMTP relay.
// Package mailer sends transactional email (password-reset links,
// notification and agent deliveries) through a configured SMTP relay.
// Messages go out as the branded HTML design (template.html, see Render)
// with a plain-text alternative; Send remains available for plain-only mail.
//
// Like every server-initiated dial, sending is bounded by internal/outbound
// and guarded by internal/netguard: private/link-local relay hosts (the
@@ -18,7 +20,9 @@ package mailer
import (
"context"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"net"
@@ -74,6 +78,22 @@ func (c Config) Configured() bool { return c.Host != "" && c.From != "" }
// Send delivers one plain-text message. It is synchronous: the caller owns
// the request context and any retry policy.
func Send(ctx context.Context, to, subject, body string) error {
return send(ctx, to, subject, body, "", "")
}
// SendTemplate delivers one branded message as multipart/alternative: text
// is the plain-text alternative, c describes the HTML rendering. A render
// failure (template drift) degrades to plain text — delivery never blocks
// on cosmetics.
func SendTemplate(ctx context.Context, to, subject, text string, c Content) error {
html, err := Render(subject, c)
if err != nil {
html = ""
}
return send(ctx, to, subject, text, html, c.UnsubscribePostURL)
}
func send(ctx context.Context, to, subject, body, html, listUnsub string) error {
cfg := LoadConfig()
if !cfg.Configured() {
return ErrNotConfigured
@@ -139,18 +159,7 @@ func Send(ctx context.Context, to, subject, body string) error {
if err != nil {
return fmt.Errorf("mailer: DATA: %w", err)
}
msg := strings.Join([]string{
"From: " + cfg.From,
"To: " + to,
"Subject: " + sanitizeHeader(subject),
"Date: " + time.Now().UTC().Format(time.RFC1123Z),
"MIME-Version: 1.0",
"Content-Type: text/plain; charset=UTF-8",
"Content-Transfer-Encoding: 8BIT",
"",
body,
"",
}, "\r\n")
msg := buildMessage(cfg.From, to, subject, body, html, listUnsub)
if _, err := data.Write([]byte(msg)); err != nil {
return fmt.Errorf("mailer: write: %w", err)
}
@@ -168,6 +177,77 @@ func sanitizeHeader(s string) string {
return strings.NewReplacer("\r", " ", "\n", " ").Replace(strings.TrimSpace(s))
}
// buildMessage assembles the RFC 5322 payload: plain-only when html is
// empty, otherwise multipart/alternative with the plain part first (RFC
// 2046: least-preferred alternative first, HTML last). A non-empty
// listUnsub adds the RFC 8058 one-click unsubscribe headers.
func buildMessage(from, to, subject, text, html, listUnsub string) string {
var b strings.Builder
b.WriteString("From: " + sanitizeHeader(from) + "\r\n")
b.WriteString("To: " + sanitizeHeader(to) + "\r\n")
b.WriteString("Subject: " + sanitizeHeader(subject) + "\r\n")
b.WriteString("Date: " + time.Now().UTC().Format(time.RFC1123Z) + "\r\n")
b.WriteString("MIME-Version: 1.0\r\n")
if listUnsub != "" {
b.WriteString("List-Unsubscribe: <" + sanitizeHeader(listUnsub) + ">\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.