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
+13
View File
@@ -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 carry the footer "Managed by David's Superbrain."; paying plans and core do
not (`entitlements.ManagedFooter`, per-tenant override `managed_footer`). 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 | | Method | Path | Body / Returns |
|---|---|---| |---|---|---|
| GET | `/api/notifications/channels` | `[{id,kind,name,enabled,version,config(masked),createdAt}]` | | 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 | | PATCH | `/api/notifications/rules/{id}` | `{version, name?,enabled?,cooldownMinutes?,channelId?,config?}` → 200; 409 on stale version |
| DELETE | `/api/notifications/rules/{id}` | `{ok:true}` | | 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 | | 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") ### Agent automations ("hey superbrain")
+3 -1
View File
@@ -370,7 +370,9 @@ func fire(ctx context.Context, d *db.DB, t Task, summary string) (string, string
defer release() defer release()
sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second) sendCtx, cancel := context.WithTimeout(ctx, 30*time.Second)
defer cancel() 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() return "failed", "email: " + err.Error()
} }
case "bookmark": case "bookmark":
+24 -1
View File
@@ -25,6 +25,7 @@ import (
"encoding/base64" "encoding/base64"
"encoding/hex" "encoding/hex"
"errors" "errors"
"fmt"
"log" "log"
"net/http" "net/http"
"net/mail" "net/mail"
@@ -161,7 +162,29 @@ func HandleForgotPassword(w http.ResponseWriter, r *http.Request) {
link + "\n\n" + link + "\n\n" +
"If you did not request a reset, you can ignore this email; the link is\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" "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) log.Printf("password reset: delivery to %s failed: %v", email, e)
} }
okResponse() okResponse()
+73
View File
@@ -11,6 +11,7 @@ import (
"encoding/json" "encoding/json"
"errors" "errors"
"fmt" "fmt"
"log"
"math" "math"
"net/http" "net/http"
"sort" "sort"
@@ -652,3 +653,75 @@ func ruleProjection(row object, channelKind, channelName string) object {
"lastFiredAt": row["lastFiredAt"], "version": row["version"], "createdAt": row["createdAt"], "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)
}
+6
View File
@@ -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("PATCH /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesUpdate))
mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete)) mux.HandleFunc("DELETE /api/notifications/rules/{id}", authed(handlers.HandleNotificationRulesDelete))
mux.HandleFunc("GET /api/notifications", authed(handlers.HandleNotificationsList)) 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 // 4.7c Agent automations ("hey superbrain"): compile NL into a validated
// proposal (never writes), then owner-confirmed task CRUD + runs. // proposal (never writes), then owner-confirmed task CRUD + runs.
+220
View File
@@ -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: <https://superbrain.test/api/notifications/unsubscribe?token=",
"List-Unsubscribe-Post: List-Unsubscribe=One-Click",
"https://superbrain.test/unsubscribe?token=",
"https://superbrain.test/settings?tab=notifications",
"https://superbrain.test/help",
} {
if !strings.Contains(msg[1], want) {
t.Fatalf("owner-addressed mail missing %q:\n%s", want, msg[1])
}
}
m := unsubTokenRx.FindStringSubmatch(msg[1])
if m == nil {
t.Fatalf("no unsubscribe token in mail:\n%s", msg[1])
}
token := m[1]
if id, ok := notify.ParseUnsubscribeToken(token); !ok || id != aliceID {
t.Fatalf("token resolves to %q (%v), want the channel owner %q", id, ok, aliceID)
}
// --- RFC 8058 one-click: no session, token in the query, form body ---
oneClick := func(tok string) map[string]any {
t.Helper()
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+tok,
strings.NewReader("List-Unsubscribe=One-Click"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, e := (&http.Client{}).Do(req)
if e != nil {
t.Fatal(e)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
if res.StatusCode != 200 {
t.Fatalf("one-click unsubscribe: wanted 200, got %d: %s", res.StatusCode, raw)
}
var v map[string]any
if e := json.Unmarshal(raw, &v); e != nil {
t.Fatal(e)
}
return v
}
got := oneClick(token)
if got["ok"] != true || got["channels"].(float64) != 2 || got["tasks"].(float64) != 1 {
t.Fatalf("unsubscribe result = %v, want ok with 2 email channels + 1 self-addressed task", got)
}
// Blast radius: BOTH of alice's email channels disabled (the preference
// is account-wide), slack untouched; only the self-addressed task paused.
channels := map[string]map[string]any{}
for _, row := range listGET(alice, "/api/notifications/channels") {
r := row.(map[string]any)
channels[r["id"].(string)] = r
}
if channels[selfCh["id"].(string)]["enabled"] != false || channels[thirdCh["id"].(string)]["enabled"] != false {
t.Fatalf("email channels not disabled: %v", channels)
}
if channels[slackCh["id"].(string)]["enabled"] != true {
t.Fatalf("slack channel must survive unsubscribe: %v", channels[slackCh["id"].(string)])
}
tasks := map[string]map[string]any{}
for _, row := range listGET(alice, "/api/agent/tasks") {
r := row.(map[string]any)
tasks[r["id"].(string)] = r
}
if tasks[selfTask["id"].(string)]["enabled"] != false || tasks[selfTask["id"].(string)]["status"] != "paused" {
t.Fatalf("self-addressed task not paused: %v", tasks[selfTask["id"].(string)])
}
if tasks[thirdTask["id"].(string)]["enabled"] != true {
t.Fatalf("third-party task must survive unsubscribe: %v", tasks[thirdTask["id"].(string)])
}
// Idempotent: a second click changes nothing.
got = oneClick(token)
if got["channels"].(float64) != 0 || got["tasks"].(float64) != 0 {
t.Fatalf("second unsubscribe = %v, want zero counts", got)
}
// Tampered and junk tokens are dead links (400, identical answers).
for _, bad := range []string{
token[:len(token)-1] + "0",
strings.Repeat("f", 32) + "." + strings.Repeat("0", 64),
"not-a-token",
} {
req, _ := http.NewRequest("POST", srv.URL+"/api/notifications/unsubscribe?token="+bad, nil)
res, e := (&http.Client{}).Do(req)
if e != nil {
t.Fatal(e)
}
res.Body.Close()
if res.StatusCode != 400 {
t.Fatalf("bad token %q: wanted 400, got %d", bad, res.StatusCode)
}
}
// --- browser confirmation path: JSON body, no query token ---
alice.request("PATCH", "/api/notifications/channels/"+selfCh["id"].(string), map[string]any{
"enabled": true, "version": int(channels[selfCh["id"].(string)]["version"].(float64)),
}, 200)
anon := apiClient{t, &http.Client{}, srv.URL}
got = anon.request("POST", "/api/notifications/unsubscribe", map[string]any{"token": token}, 200)
if got["channels"].(float64) != 1 {
t.Fatalf("JSON-body unsubscribe = %v, want the re-enabled channel disabled again", got)
}
// --- third-party recipient: footer help/preferences, NO unsubscribe ---
// Unsubscribe is account-wide, so re-enable the third-party channel
// first (an owner may keep mailing other people after unsubscribing
// themselves).
alice.request("PATCH", "/api/notifications/channels/"+thirdCh["id"].(string), map[string]any{
"enabled": true, "version": int(channels[thirdCh["id"].(string)]["version"].(float64)),
}, 200)
alice.request("POST", "/api/bookmarks", map[string]any{
"url": "https://example.org/unsub-due-2", "title": "Unsub due 2", "dueDate": due,
}, 201)
alice.request("POST", "/api/notifications/rules", map[string]any{
"name": "Bob reminders", "trigger": "bookmark_due", "channelId": thirdCh["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, 2)
if msg[0] != "bob@superbrain.test" {
t.Fatalf("third-party envelope recipient = %q", msg[0])
}
if !strings.Contains(msg[1], "https://superbrain.test/help") {
t.Fatalf("third-party mail lost the help footer:\n%s", msg[1])
}
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
t.Fatalf("third-party recipient must never receive an unsubscribe link:\n%s", msg[1])
}
// --- transactional mail: preferences + help, never unsubscribe ---
alice.request("POST", "/api/password/forgot", map[string]any{"email": "alice@superbrain.test"}, 200)
msg = smtp.waitForMessage(t, 3)
if !strings.Contains(msg[1], "https://superbrain.test/settings?tab=notifications") ||
!strings.Contains(msg[1], "https://superbrain.test/help") {
t.Fatalf("reset mail missing footer links:\n%s", msg[1])
}
if strings.Contains(msg[1], "List-Unsubscribe") || strings.Contains(msg[1], "/unsubscribe?token=") {
t.Fatalf("transactional mail must not carry unsubscribe:\n%s", msg[1])
}
}
+94 -14
View File
@@ -1,5 +1,7 @@
// Package mailer sends transactional email (password-reset links) through a // Package mailer sends transactional email (password-reset links,
// configured SMTP relay. // 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 // Like every server-initiated dial, sending is bounded by internal/outbound
// and guarded by internal/netguard: private/link-local relay hosts (the // and guarded by internal/netguard: private/link-local relay hosts (the
@@ -18,7 +20,9 @@ package mailer
import ( import (
"context" "context"
"crypto/rand"
"crypto/tls" "crypto/tls"
"encoding/hex"
"errors" "errors"
"fmt" "fmt"
"net" "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 // Send delivers one plain-text message. It is synchronous: the caller owns
// the request context and any retry policy. // the request context and any retry policy.
func Send(ctx context.Context, to, subject, body string) error { 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() cfg := LoadConfig()
if !cfg.Configured() { if !cfg.Configured() {
return ErrNotConfigured return ErrNotConfigured
@@ -139,18 +159,7 @@ func Send(ctx context.Context, to, subject, body string) error {
if err != nil { if err != nil {
return fmt.Errorf("mailer: DATA: %w", err) return fmt.Errorf("mailer: DATA: %w", err)
} }
msg := strings.Join([]string{ msg := buildMessage(cfg.From, to, subject, body, html, listUnsub)
"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")
if _, err := data.Write([]byte(msg)); err != nil { if _, err := data.Write([]byte(msg)); err != nil {
return fmt.Errorf("mailer: write: %w", err) 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)) 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 // dial resolves and connects through netguard: range checks apply unless
// INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and // INTEGRATIONS_ALLOW_PRIVATE=1 (house relays live on private networks), and
// only the standard SMTP ports are reachable from public ranges. // only the standard SMTP ports are reachable from public ranges.
+243
View File
@@ -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 = "<!-- Button (bulletproof, with Outlook fallback) -->"
noteStartMarker = "<!-- Note block"
signOffMarker = "<!-- Sign-off -->"
bodyStartAnchor = `<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>`
bodyEndAnchor = `<p style="margin:0;">{{body_paragraph_2}}</p>`
addressParagraph = `<p style="margin:0;">Superbrain, {{company_address}}</p>`
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 <p> 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(`<p style="` + style + `">` + html.EscapeString(p) + `</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, `<a href="`+html.EscapeString(l.url)+`" class="t-accent" style="color:#3646E8; text-decoration:underline;">`+l.label+`</a>`)
}
start, end, err := paragraphSpan(s, footerLinkAnchor)
if err != nil {
return "", err
}
if len(links) == 0 {
return s[:start] + s[end:], nil
}
repl := `<p style="margin:0 0 8px 0;">` + strings.Join(links, "&nbsp;&nbsp;|&nbsp;&nbsp;") + `</p>`
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 <p>…</p> 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], "<p")
j := strings.Index(s[i:], "</p>")
if start < 0 || j < 0 {
return 0, 0, errors.New("mailer: template paragraph around anchor not found")
}
return start, i + j + len("</p>"), nil
}
+219
View File
@@ -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
`<td class="bg-note`, // note block
"Email preferences", // footer links paragraph
"Superbrain, ", // address line
"Hi ,", // broken greeting
} {
if strings.Contains(html, absent) {
t.Errorf("minimal render still contains %q", absent)
}
}
for _, want := range []string{"Hi,", "Bookmark due: Due soon", "Due soon is due in 6 hours.", "Thanks,"} {
if !strings.Contains(html, want) {
t.Errorf("minimal render missing %q", want)
}
}
}
func TestRenderEscaping(t *testing.T) {
html, err := Render(`Subject "<x>"`, Content{
Headline: `<script>alert(1)</script>`,
FirstName: `Ann<script>`,
Body: `<img src=x onerror=alert(1)> & "quotes"`,
CTAURL: `https://x.test/"onmouseover="alert(1)`,
Note: `<b>note</b>`,
})
if err != nil {
t.Fatal(err)
}
for _, absent := range []string{
"<script>alert(1)</script>", "Ann<script>", "<img src=x", `"onmouseover="`, "<b>note</b>",
} {
if strings.Contains(html, absent) {
t.Errorf("unescaped value %q survived rendering", absent)
}
}
for _, want := range []string{"&lt;script&gt;", "&amp;", "&#34;"} {
if !strings.Contains(html, want) {
t.Errorf("expected escaped form %q", want)
}
}
}
func TestRenderBodyParagraphs(t *testing.T) {
html, err := Render("s", Content{Headline: "h", Body: "one\n\n two \nthree\n"})
if err != nil {
t.Fatal(err)
}
for _, want := range []string{
`<p style="margin:0 0 16px 0;">one</p>`,
`<p style="margin:0 0 16px 0;">two</p>`,
`<p style="margin:0;">three</p>`, // last paragraph loses the bottom margin
} {
if !strings.Contains(html, want) {
t.Errorf("missing paragraph %q", want)
}
}
// Empty body: greeting survives, no placeholder paragraphs remain.
html, err = Render("s", Content{Headline: "h"})
if err != nil {
t.Fatal(err)
}
if strings.Contains(html, "{{") || !strings.Contains(html, "Hi,") {
t.Errorf("empty-body render broken:\n%s", html)
}
}
func TestRenderDefaults(t *testing.T) {
html, err := Render("Fallback subject", Content{
Body: strings.Repeat("x", 120),
CTAURL: "https://superbrain.test/",
})
if err != nil {
t.Fatal(err)
}
if !strings.Contains(html, "<h1") || !strings.Contains(html, "Fallback subject") {
t.Error("headline must fall back to the subject")
}
if !strings.Contains(html, "Open Superbrain") {
t.Error("CTA label must default to Open Superbrain")
}
// Preheader defaults to the first paragraph, truncated to 90 runes.
pre := html[strings.Index(html, `opacity:0;">`)+len(`opacity:0;">`):]
pre = strings.TrimSpace(pre[:strings.Index(pre, "&#847;")])
if pre != strings.Repeat("x", 90) {
t.Errorf("preheader = %q, want 90 x's", pre)
}
}
func TestRenderTemplateDrift(t *testing.T) {
saved := emailTemplate
defer func() { emailTemplate = saved }()
emailTemplate = "<html>{{headline}} only</html>"
if _, err := Render("s", Content{Headline: "h"}); err == nil {
t.Fatal("Render must error when the template loses its anchors")
}
}
func TestBuildMessagePlain(t *testing.T) {
msg := buildMessage("from@x.test", "to@x.test", "hi\r\nBcc: evil@x.test", "body", "", "")
if strings.Contains(msg, "\r\nBcc:") {
t.Fatal("header injection via subject survived")
}
if !strings.Contains(msg, "Content-Type: text/plain; charset=UTF-8") {
t.Fatal("plain message lost its content type")
}
if strings.Contains(msg, "multipart") {
t.Fatal("plain message must not be multipart")
}
if strings.Contains(msg, "List-Unsubscribe") {
t.Fatal("plain message without an unsubscribe URL must not carry the headers")
}
}
func TestBuildMessageMultipart(t *testing.T) {
text := "plain alternative\nwith a link https://x.test/"
html := "<html>\n.dot line\n</html>"
msg := buildMessage("from@x.test", "to@x.test", "s", text, html, "")
if !strings.Contains(msg, "Content-Type: multipart/alternative; boundary=\"sb-") {
t.Fatalf("missing multipart header:\n%s", msg)
}
boundary := msg[strings.Index(msg, `boundary="`)+len(`boundary="`):]
boundary = boundary[:strings.Index(boundary, `"`)]
if n := strings.Count(msg, "--"+boundary); n != 3 {
t.Fatalf("boundary appears %d times, want 3 (two parts + close)", n)
}
if !strings.HasSuffix(msg, "--"+boundary+"--\r\n") {
t.Fatal("multipart close delimiter missing")
}
if strings.Index(msg, "text/plain") > strings.Index(msg, "text/html") {
t.Fatal("RFC 2046: the plain alternative must come first")
}
if !strings.Contains(msg, "\r\n..dot line") {
t.Fatal("HTML part must be dot-stuffed")
}
if !strings.Contains(msg, smtpBody(text)) {
t.Fatal("plain alternative missing")
}
}
func TestSMTPBody(t *testing.T) {
got := smtpBody(".start\nmid\r\n.dot\n")
want := "..start\r\nmid\r\n..dot\r\n"
if got != want {
t.Fatalf("smtpBody = %q, want %q", got, want)
}
}
func TestBuildMessageListUnsubscribe(t *testing.T) {
msg := buildMessage("from@x.test", "to@x.test", "s", "text", "<html></html>",
"https://x.test/api/notifications/unsubscribe?token=abc\r\nBcc: evil@x.test")
if !strings.Contains(msg, "List-Unsubscribe: <https://x.test/api/notifications/unsubscribe?token=abc") {
t.Fatalf("List-Unsubscribe header missing:\n%s", msg)
}
if !strings.Contains(msg, "List-Unsubscribe-Post: List-Unsubscribe=One-Click\r\n") {
t.Fatal("RFC 8058 one-click header missing")
}
if strings.Contains(msg, "\r\nBcc:") {
t.Fatal("header injection via the unsubscribe URL survived")
}
}
+170
View File
@@ -0,0 +1,170 @@
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="x-apple-disable-message-reformatting">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<title>{{subject}}</title>
<!--[if mso]>
<noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript>
<style>td,th,div,p,a,h1,span{font-family:Arial,Helvetica,sans-serif !important;}</style>
<![endif]-->
<link href="https://fonts.googleapis.com/css2?family=Bricolage+Grotesque:wght@500;700&display=swap" rel="stylesheet">
<style>
body, table, td, a { -webkit-text-size-adjust: 100%; -ms-text-size-adjust: 100%; }
table, td { mso-table-lspace: 0pt; mso-table-rspace: 0pt; }
img { border: 0; outline: none; text-decoration: none; -ms-interpolation-mode: bicubic; }
body { margin: 0 !important; padding: 0 !important; width: 100% !important; }
a[x-apple-data-detectors] { color: inherit !important; text-decoration: none !important; }
@media screen and (max-width: 620px) {
.container { width: 100% !important; }
.px { padding-left: 24px !important; padding-right: 24px !important; }
.headline { font-size: 28px !important; line-height: 34px !important; }
.btn a { display: block !important; }
}
/* Dark mode (Apple Mail, iOS Mail, Outlook for Mac/iOS, some Android clients) */
@media (prefers-color-scheme: dark) {
.bg-outer { background-color: #0E1024 !important; }
.bg-card { background-color: #181B36 !important; }
.bg-note { background-color: #22264A !important; }
.t-ink { color: #ECEDF8 !important; }
.t-muted { color: #A3A7C9 !important; }
.t-accent { color: #9AA4FF !important; }
.rule { border-color: #2C3060 !important; }
}
[data-ogsc] .bg-outer { background-color: #0E1024 !important; }
[data-ogsc] .bg-card { background-color: #181B36 !important; }
[data-ogsc] .bg-note { background-color: #22264A !important; }
[data-ogsc] .t-ink { color: #ECEDF8 !important; }
[data-ogsc] .t-muted { color: #A3A7C9 !important; }
[data-ogsc] .t-accent { color: #9AA4FF !important; }
</style>
</head>
<body class="bg-outer" style="margin:0; padding:0; background-color:#ECEEF6;">
<!-- Preheader: the preview line shown in the inbox. Keep it under ~90 characters. -->
<div style="display:none; max-height:0; overflow:hidden; mso-hide:all; font-size:1px; line-height:1px; color:#ECEEF6; opacity:0;">
{{preheader_text}}&#847;&zwnj;&nbsp;&#847;&zwnj;&nbsp;&#847;&zwnj;&nbsp;&#847;&zwnj;&nbsp;&#847;&zwnj;&nbsp;
</div>
<table role="presentation" class="bg-outer" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#ECEEF6;">
<tr>
<td align="center" style="padding:40px 12px;">
<table role="presentation" class="container" width="600" cellpadding="0" cellspacing="0" border="0" style="width:600px; max-width:600px;">
<!-- Wordmark -->
<tr>
<td class="px" style="padding:0 40px 20px 40px;">
<table role="presentation" cellpadding="0" cellspacing="0" border="0">
<tr>
<td width="14" height="14" style="width:14px; height:14px; background-color:#3646E8; border-radius:7px; font-size:0; line-height:0;">&nbsp;</td>
<td width="6" style="font-size:0;">&nbsp;</td>
<td width="8" height="8" style="width:8px; height:8px; background-color:#9AA4FF; border-radius:4px; font-size:0; line-height:0;">&nbsp;</td>
<td style="padding-left:10px; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:20px; font-weight:700; letter-spacing:-0.3px; color:#1A1D3A;" class="t-ink">
superbrain
</td>
</tr>
</table>
</td>
</tr>
<!-- Card -->
<tr>
<td class="bg-card" style="background-color:#FFFFFF; border-radius:16px; border-top:6px solid #3646E8;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
<!-- Headline -->
<tr>
<td class="px" style="padding:44px 48px 12px 48px;">
<h1 class="headline t-ink" style="margin:0; font-family:'Bricolage Grotesque', Arial, Helvetica, sans-serif; font-size:34px; line-height:40px; font-weight:700; letter-spacing:-0.8px; color:#1A1D3A;">
{{headline}}
</h1>
</td>
</tr>
<!-- Body -->
<tr>
<td class="px t-ink" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
<p style="margin:0 0 16px 0;">Hi {{first_name}},</p>
<p style="margin:0 0 16px 0;">{{body_paragraph_1}}</p>
<p style="margin:0;">{{body_paragraph_2}}</p>
</td>
</tr>
<!-- Button (bulletproof, with Outlook fallback) -->
<tr>
<td class="px btn" style="padding:32px 48px 8px 48px;">
<!--[if mso]>
<v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{{cta_url}}" style="height:50px; v-text-anchor:middle; width:240px;" arcsize="20%" stroke="f" fillcolor="#3646E8">
<w:anchorlock/>
<center style="color:#ffffff; font-family:Arial,sans-serif; font-size:16px; font-weight:bold;">{{cta_label}}</center>
</v:roundrect>
<![endif]-->
<!--[if !mso]><!-->
<a href="{{cta_url}}" style="display:inline-block; background-color:#3646E8; color:#FFFFFF; font-family:Arial, Helvetica, sans-serif; font-size:16px; font-weight:700; line-height:50px; text-align:center; text-decoration:none; padding:0 32px; border-radius:10px;">
{{cta_label}}
</a>
<!--<![endif]-->
</td>
</tr>
<!-- Fallback link -->
<tr>
<td class="px t-muted" style="padding:12px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:13px; line-height:20px; color:#6A6F92;">
If the button doesn't work, paste this link into your browser:<br>
<a href="{{cta_url}}" class="t-accent" style="color:#3646E8; word-break:break-all;">{{cta_url}}</a>
</td>
</tr>
<!-- Note block (optional — delete this row if not needed) -->
<tr>
<td class="px" style="padding:32px 48px 0 48px;">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
<tr>
<td class="bg-note t-ink" style="background-color:#EEF0FF; border-radius:10px; padding:18px 20px; font-family:Arial, Helvetica, sans-serif; font-size:14px; line-height:22px; color:#2E3254;">
{{note_text}}
</td>
</tr>
</table>
</td>
</tr>
<!-- Sign-off -->
<tr>
<td class="px t-ink" style="padding:32px 48px 44px 48px; font-family:Arial, Helvetica, sans-serif; font-size:16px; line-height:26px; color:#2E3254;">
{{sign_off}}<br>
The Superbrain team
</td>
</tr>
</table>
</td>
</tr>
<!-- Footer -->
<tr>
<td class="px t-muted" style="padding:28px 48px 0 48px; font-family:Arial, Helvetica, sans-serif; font-size:12px; line-height:19px; color:#6A6F92;">
<p style="margin:0 0 8px 0;">You're receiving this email because you have a Superbrain account.</p>
<p style="margin:0 0 8px 0;">
<a href="{{preferences_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Email preferences</a>
&nbsp;&nbsp;|&nbsp;&nbsp;
<a href="{{unsubscribe_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Unsubscribe</a>
&nbsp;&nbsp;|&nbsp;&nbsp;
<a href="{{help_url}}" class="t-accent" style="color:#3646E8; text-decoration:underline;">Help center</a>
</p>
<p style="margin:0;">Superbrain, {{company_address}}</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
+3 -1
View File
@@ -255,7 +255,9 @@ func Send(ctx context.Context, d *db.DB, ch Channel, title, body string) error {
} }
to = *email to = *email
} }
return mailer.Send(ctx, to, title, text) c := FooterLinks(ctx, d, ch.OwnerID, to)
c.Headline, c.Body = title, body
return mailer.SendTemplate(ctx, to, title, text, c)
case "slack": case "slack":
return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200}) return postJSON(ctx, ch.Config["webhookUrl"], nil, map[string]any{"text": text}, []int{200})
case "matrix": case "matrix":
+76
View File
@@ -0,0 +1,76 @@
package notify
// Email footer links and the unsubscribe token. The token is a stable,
// HMAC-signed user id (no stored row, no expiry): every notification mail
// carries the same link, and rotating AUTH_SECRET invalidates outstanding
// links exactly like sessions. Unsubscribe is a NOTIFICATION preference —
// transactional mail (password reset) is never gated by it.
import (
"context"
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"strings"
"github.com/andrew/superbrain/internal/config"
"github.com/andrew/superbrain/internal/db"
"github.com/andrew/superbrain/internal/mailer"
)
// unsubscribeDomain separates these MACs from every other use of the
// signing secret (assertions, forwarded-IP attestation, ...).
const unsubscribeDomain = "superbrain-unsubscribe:"
// UnsubscribeToken returns the signed unsubscribe token for a user. IDs
// are 32-char hex (db.NewID), so the single "." separator is unambiguous.
func UnsubscribeToken(userID string) string {
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
mac.Write([]byte(unsubscribeDomain + userID))
return userID + "." + hex.EncodeToString(mac.Sum(nil))
}
// ParseUnsubscribeToken validates a token and returns the user id it
// carries. The comparison is constant-time; a tampered or foreign-secret
// token never resolves an identity.
func ParseUnsubscribeToken(token string) (string, bool) {
userID, sig, ok := strings.Cut(token, ".")
if !ok || userID == "" || sig == "" {
return "", false
}
mac := hmac.New(sha256.New, []byte(config.Load().Secret()))
mac.Write([]byte(unsubscribeDomain + userID))
want := hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(want), []byte(sig)) {
return "", false
}
return userID, true
}
// FooterLinks builds the branded email footer for a message to recipient.
// Preferences and Help are offered whenever the deployment has a public
// origin (NEXTAUTH_URL). Unsubscribe is offered ONLY when recipient is the
// owner's own account email: a third-party recipient (a channel address or
// an agent task's To) must never receive a link that changes the owner's
// settings. With no origin configured every link stays empty and the
// renderer omits the footer sections.
func FooterLinks(ctx context.Context, d *db.DB, ownerID, recipient string) mailer.Content {
var c mailer.Content
base := strings.TrimRight(strings.TrimSpace(config.Load().NextAuthURL), "/")
if base == "" {
return c
}
c.PreferencesURL = base + "/settings?tab=notifications"
c.HelpURL = base + "/help"
var email *string
if err := d.QueryRowContext(ctx, `SELECT email FROM "User" WHERE id=$1`, ownerID).Scan(&email); err != nil {
return c
}
if email == nil || *email == "" || !strings.EqualFold(strings.TrimSpace(recipient), *email) {
return c
}
token := UnsubscribeToken(ownerID)
c.UnsubscribeURL = base + "/unsubscribe?token=" + token
c.UnsubscribePostURL = base + "/api/notifications/unsubscribe?token=" + token
return c
}
+47
View File
@@ -0,0 +1,47 @@
package notify
import (
"strings"
"testing"
)
func TestUnsubscribeTokenRoundtrip(t *testing.T) {
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
tok := UnsubscribeToken("0123456789abcdef0123456789abcdef")
id, ok := ParseUnsubscribeToken(tok)
if !ok || id != "0123456789abcdef0123456789abcdef" {
t.Fatalf("roundtrip = %q, %v", id, ok)
}
// Stable: every mail to the same user carries the same link.
if UnsubscribeToken("0123456789abcdef0123456789abcdef") != tok {
t.Fatal("token must be stable across issuances")
}
}
func TestUnsubscribeTokenRejectsTampering(t *testing.T) {
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
const id = "0123456789abcdef0123456789abcdef"
tok := UnsubscribeToken(id)
_, mac, _ := strings.Cut(tok, ".")
// A token minted under a different secret must not verify here.
t.Setenv("AUTH_SECRET", "a-different-secret")
foreign := UnsubscribeToken(id)
t.Setenv("AUTH_SECRET", "unsubscribe-test-secret")
cases := []struct{ name, token string }{
{"swapped id", "ffffffffffffffffffffffffffffffff." + mac},
{"flipped mac", id + "." + strings.Repeat("0", 63) + "1"},
{"truncated mac", tok[:len(tok)-1]},
{"no separator", strings.ReplaceAll(tok, ".", "")},
{"empty id", "." + mac},
{"empty mac", id + "."},
{"empty token", ""},
{"foreign secret", foreign},
}
for _, c := range cases {
if _, ok := ParseUnsubscribeToken(c.token); ok {
t.Errorf("%s accepted", c.name)
}
}
}
+12 -3
View File
@@ -2,6 +2,7 @@
import { useState, useEffect, useCallback, Fragment } from 'react' import { useState, useEffect, useCallback, Fragment } from 'react'
import { useSession } from 'next-auth/react' import { useSession } from 'next-auth/react'
import { useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button' import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input' import { Input } from '@/components/ui/input'
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs' import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs'
@@ -50,17 +51,25 @@ const NAV_GROUPS = [
export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) { export function SettingsClient({ oidc, callbackUrl }: { oidc: OidcStatus; callbackUrl: string }) {
const { data: session } = useSession() const { data: session } = useSession()
// ?tab=<value> deep links (email footer "Email preferences" lands on
// notifications). Unknown values fall back to profile; the Radix tab
// values stay the canonical section ids.
const requestedTab = useSearchParams().get('tab') ?? ''
const initialSection = NAV_GROUPS.some(g => g.items.some(i => i.value === requestedTab))
? requestedTab
: 'profile'
const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' }) const [imapConfig, setImapConfig] = useState({ host: '', port: 993, tls: true, username: '', password: '', folder: 'INBOX' })
const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' }) const [ncConfig, setNcConfig] = useState({ nextcloudUrl: '', cardDavPath: '', username: '', password: '' })
const [savingImap, setSavingImap] = useState(false) const [savingImap, setSavingImap] = useState(false)
const [testingImap, setTestingImap] = useState(false) const [testingImap, setTestingImap] = useState(false)
const [syncingContacts, setSyncingContacts] = useState(false) const [syncingContacts, setSyncingContacts] = useState(false)
const [section, setSection] = useState('profile') const [section, setSection] = useState(initialSection)
// Below md the grouped nav becomes a list -> detail flow (same // Below md the grouped nav becomes a list -> detail flow (same
// master-detail pattern as collections/tags/contacts); at md+ the // master-detail pattern as collections/tags/contacts); at md+ the
// nav and the selected panel sit side by side. // nav and the selected panel sit side by side. A deep link opens the
// detail pane directly on narrow screens.
const isNarrow = useMediaQuery('(max-width: 767px)') const isNarrow = useMediaQuery('(max-width: 767px)')
const [mobileDetail, setMobileDetail] = useState(false) const [mobileDetail, setMobileDetail] = useState(initialSection !== 'profile')
useEffect(() => { useEffect(() => {
fetch('/api/settings/imap').then(r => r.json()).then(data => { fetch('/api/settings/imap').then(r => r.json()).then(data => {
+8 -1
View File
@@ -1,6 +1,7 @@
import { SettingsClient } from './client' import { SettingsClient } from './client'
import { getOidcStatus } from '@/lib/oidc-config' import { getOidcStatus } from '@/lib/oidc-config'
import { headers } from 'next/headers' import { headers } from 'next/headers'
import { Suspense } from 'react'
export const dynamic = 'force-dynamic' export const dynamic = 'force-dynamic'
@@ -20,5 +21,11 @@ export default async function SettingsPage() {
const proto = h.get('x-forwarded-proto') ?? 'http' const proto = h.get('x-forwarded-proto') ?? 'http'
if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia` if (host) callbackUrl = `${proto}://${host}/api/auth/callback/authelia`
} }
return <SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} /> // useSearchParams in the client (?tab= deep links, e.g. from email
// footers) needs a Suspense boundary for prerender.
return (
<Suspense>
<SettingsClient oidc={getOidcStatus()} callbackUrl={callbackUrl} />
</Suspense>
)
} }
+45
View File
@@ -0,0 +1,45 @@
'use client'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
const FAQ = [
{
q: 'How do I stop notification emails?',
a: 'Use the unsubscribe link in any notification email — it turns off your email channels and any automations that email you, without signing in. You can also toggle channels and rules in Settings → Notifications. Password resets and other account emails are not affected by unsubscribing.',
},
{
q: 'Why didn\u2019t my notification arrive?',
a: 'Check Settings → Notifications: the channel and the rule must both be enabled, and your plan must include the channel kind. History lists every delivery attempt, including suppressed ones (for example a recipient without a channel of that kind, or a plan downgrade). Email delivery also needs the operator to have configured an SMTP relay.',
},
{
q: 'Who can see a public bookmark link?',
a: 'Anyone with the link. It publishes the title, description, notes, due date, tags and preview — and deliberately no owner attribution. Treat public links as published content; revoking the public toggle stops access immediately.',
},
{
q: 'Can I use my own AI provider and key?',
a: 'Yes. Settings → AI stores your own OpenAI-compatible, Anthropic or Gemini key (encrypted, write-only). Your key is used before any server key, and the server key itself depends on your plan. Without any AI configured, AI features point you to Settings instead of failing silently.',
},
{
q: 'What happens when I delete a page or bookmark?',
a: 'Deletions are recoverable from Trash. Deleting a parent page promotes its children instead of deleting them, and page revisions let you restore earlier content. Note that restoring from Trash does not restore access grants — re-share if needed.',
},
{
q: 'How do I connect Nextcloud?',
a: 'Settings → WebDAV, CalDAV or CardDAV. On Core deployments the forms offer a prefill for your account\u2019s Nextcloud URL. Each connected share, calendar or address book becomes its own collection, synced on a schedule; files, events and contacts appear as bookmarks.',
},
]
export function HelpFaq() {
return (
<Accordion type="single" collapsible className="mt-4">
{FAQ.map((item, i) => (
<AccordionItem key={i} value={`faq-${i}`}>
<AccordionTrigger className="text-sm font-medium">{item.q}</AccordionTrigger>
<AccordionContent className="text-sm leading-relaxed text-muted-foreground">
{item.a}
</AccordionContent>
</AccordionItem>
))}
</Accordion>
)
}
+190
View File
@@ -0,0 +1,190 @@
import Link from 'next/link'
import { Button } from '@/components/ui/button'
import { Badge } from '@/components/ui/badge'
import { HelpFaq } from './faq'
import {
Bookmark, FolderOpen, FileText, Kanban, Radar, Bell, Bot,
FolderSync, KeyRound, ArrowRight,
} from 'lucide-react'
export const dynamic = 'force-dynamic'
const SECTIONS = [
{
id: 'getting-started',
icon: ArrowRight,
title: 'Getting started',
body: [
'Sign in with your email and password, or with Authelia single sign-on if your deployment uses it. On first run, create your account from the sign-up page — then start by saving a bookmark, writing a page, or connecting a service in Settings.',
'Forgot your password? Use the "Forgot password?" link on the sign-in page; a single-use reset link is emailed to you. On single-sign-on deployments, recovery is handled by your identity provider instead.',
],
where: 'Sign in → /login · Reset → /forgot-password',
},
{
id: 'bookmarks',
icon: Bookmark,
title: 'Bookmarks & tags',
body: [
'Every URL you save becomes a bookmark with a title, description, notes, tags and an optional due date. Open a bookmark to edit its details, attach it to pages and collections, or place it on the board.',
'Sharing a tag shares every bookmark under it with the recipients — group-wide, including bookmarks other recipients add later. A public bookmark link publishes the title, description, notes, due date, tags and preview to anyone with the link, and deliberately carries no owner attribution.',
],
where: 'Sidebar → Bookmarks · Tags',
},
{
id: 'collections',
icon: FolderOpen,
title: 'Collections',
body: [
'Collections group bookmarks manually or by smart filters, and render as a table or a board grouped by any select property. Shared collections are read-only for recipients.',
'Connected services materialize as collections automatically: each WebDAV share, CalDAV calendar and CardDAV address book becomes its own collection whose files, events or contacts are bookmarks. Syncing mirrors the server — removed items detach, and your own removals stay removed.',
],
where: 'Sidebar → Collections · Settings → WebDAV / CalDAV / CardDAV',
},
{
id: 'pages',
icon: FileText,
title: 'Pages',
body: [
'Pages are WYSIWYG documents stored as Markdown. Every URL you add — via the Link button, the links popover, or a bare-URL paste — is also saved as a bookmark linked to the page, reusing an existing bookmark for the same URL instead of duplicating it.',
'Pages can nest under a parent; deleting a parent promotes its children. Every save keeps a revision you can restore, and deleted pages are recoverable from Trash. Autosave pauses on a version conflict so you never clobber newer content.',
],
where: 'Sidebar → Pages · Trash',
},
{
id: 'board',
icon: Kanban,
title: 'Kanban board',
body: [
'The board places bookmarks in columns you define. Drag cards between columns or reorder within a column; moves are saved immediately. Shared cards are read-only.',
],
where: 'Sidebar → Board',
},
{
id: 'signals',
icon: Radar,
title: 'Signals & mailbox watches',
body: [
'Signals are events attached to bookmarks — notes, arrivals, reminders. Connect an IMAP mailbox in Settings and add a watch from a bookmark\'s Signals panel: matching emails become signals on that bookmark.',
],
where: 'Settings → IMAP · Bookmark → Signals',
},
{
id: 'notifications',
icon: Bell,
title: 'Notifications',
body: [
'Notification rules fire on signals created, bookmarks coming due, or shares received, and deliver through your channels: email, Slack, Matrix, Telegram or Signal. Rules can target other people in your organization; each recipient gets the delivery through their own channel. History shows every delivery, including suppressed ones.',
'Email preferences live in Settings → Notifications. Every notification email also carries an unsubscribe link that turns off your email channels and any automations that email you — password resets and other account emails are not affected.',
],
where: 'Settings → Notifications',
},
{
id: 'assistant',
icon: Bot,
title: 'Assistant & automations',
body: [
'The assistant answers questions about your data and can propose automations: stored tasks that periodically check a page and then notify you, send an email, or save a bookmark. Proposals are compiled into a validated spec and only run after you confirm them — the assistant never acts on its own.',
'AI features use your own provider key (Settings → AI) or the server key when your plan includes it. Without any AI configured, the app tells you where to add one instead of failing silently.',
],
where: 'Assistant panel · Settings → AI / Automations',
},
{
id: 'connections',
icon: FolderSync,
title: 'Connections',
body: [
'Settings connects Superbrain to your services: WebDAV shares, CalDAV calendars, CardDAV address books, Nextcloud contacts sync, and IMAP mailboxes. Credentials are stored encrypted and are write-only — the app never shows them back to you.',
'On Core deployments with Nextcloud, the connection forms offer a one-click prefill for your account.',
],
where: 'Settings → Connections',
},
{
id: 'developer',
icon: KeyRound,
title: 'API keys & MCP',
body: [
'Personal API keys (sb_…) authenticate machine clients against the Go API directly; the plaintext key is shown once at creation and stored hashed. The superbrain-mcp server exposes your data to MCP clients through the federated gateway.',
'You can also register external MCP servers (Settings → MCP) for Superbrain to dial as a client.',
],
where: 'Settings → API Keys / MCP',
},
]
export default function HelpPage() {
return (
<div className="min-h-screen bg-background">
<header className="border-b border-border">
<div className="mx-auto flex max-w-4xl items-center justify-between px-6 py-4">
<Link href="/login" className="font-display text-lg font-bold tracking-tight">
superbrain
</Link>
<Button asChild size="sm">
<Link href="/login">Open Superbrain</Link>
</Button>
</div>
</header>
<main className="mx-auto max-w-4xl px-6 pb-24">
<div className="pt-16 pb-10">
<Badge variant="secondary" className="mb-4">Help center</Badge>
<h1 className="font-display text-4xl font-bold tracking-tight">
How Superbrain works
</h1>
<p className="mt-3 max-w-2xl text-base text-muted-foreground">
Bookmarks, pages, collections and automations — a quick guide to every
surface of the app. Jump to a topic below, or browse the FAQ at the end.
</p>
<nav className="mt-6 flex flex-wrap gap-2">
{SECTIONS.map(s => (
<a
key={s.id}
href={`#${s.id}`}
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
>
{s.title}
</a>
))}
<a
href="#faq"
className="rounded-full border border-border px-3 py-1 text-xs text-muted-foreground transition-colors hover:bg-accent hover:text-accent-foreground"
>
FAQ
</a>
</nav>
</div>
<div className="space-y-12">
{SECTIONS.map(s => (
<section key={s.id} id={s.id} className="scroll-mt-8">
<div className="flex items-center gap-3">
<div className="flex h-9 w-9 items-center justify-center rounded-lg bg-primary/10 text-primary">
<s.icon className="h-5 w-5" />
</div>
<h2 className="font-display text-2xl font-bold tracking-tight">{s.title}</h2>
</div>
<div className="mt-4 space-y-3 text-sm leading-relaxed text-foreground/90">
{s.body.map((p, i) => <p key={i}>{p}</p>)}
</div>
<p className="mt-3 font-mono text-xs text-muted-foreground">{s.where}</p>
</section>
))}
<section id="faq" className="scroll-mt-8">
<h2 className="font-display text-2xl font-bold tracking-tight">Frequently asked questions</h2>
<HelpFaq />
</section>
</div>
</main>
<footer className="border-t border-border">
<div className="mx-auto flex max-w-4xl flex-wrap items-center justify-between gap-2 px-6 py-6 text-xs text-muted-foreground">
<span>Superbrain — your second brain, federated.</span>
<span className="flex gap-4">
<Link href="/login" className="hover:text-primary hover:underline">Sign in</Link>
<Link href="/forgot-password" className="hover:text-primary hover:underline">Reset password</Link>
</span>
</div>
</footer>
</div>
)
}
+3
View File
@@ -117,6 +117,9 @@ export function LoginClient({ oidcEnabled, passwordEnabled }: { oidcEnabled: boo
</p> </p>
</> </>
)} )}
<p className="text-center text-xs text-muted-foreground">
<Link href="/help" className="hover:text-primary hover:underline">Help center</Link>
</p>
</div> </div>
</div> </div>
</div> </div>
+127
View File
@@ -0,0 +1,127 @@
'use client'
import { useState } from 'react'
import { useSearchParams } from 'next/navigation'
import { Button } from '@/components/ui/button'
import { BellOff, Check, Link2 } from 'lucide-react'
import Link from 'next/link'
import { toast } from 'sonner'
// The token in the link IS the credential (HMAC-signed user id, issued only
// in mail to the owner's own address). The page never needs a session; the
// Go endpoint validates the token and disables email notification channels
// plus self-addressed agent email tasks. Transactional mail (password
// resets) keeps flowing — the copy must say so.
export function UnsubscribeClient() {
const params = useSearchParams()
const token = params.get('token') ?? ''
const [loading, setLoading] = useState(false)
const [done, setDone] = useState(false)
const [invalid, setInvalid] = useState(false)
const handleUnsubscribe = async () => {
setLoading(true)
try {
const res = await fetch('/api/notifications/unsubscribe', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
})
const data = await res.json().catch(() => null)
if (res.ok && data?.ok) {
setDone(true)
} else if (res.status === 400) {
setInvalid(true)
} else {
toast.error(data?.error ?? 'Could not unsubscribe right now')
}
} catch {
toast.error('Could not unsubscribe right now')
}
setLoading(false)
}
if (!token || invalid) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8 text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Link2 className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Invalid Link</h1>
<p className="text-sm text-muted-foreground mt-2">
This unsubscribe link is invalid or has expired. Open Settings → Notifications
in the app to manage your email preferences directly.
</p>
<p className="text-center text-xs text-muted-foreground">
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
{' · '}
<Link href="/help" className="text-primary hover:underline">Help center</Link>
{' · '}
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
</p>
</div>
</div>
)
}
if (done) {
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8 text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<Check className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">You&apos;re Unsubscribed</h1>
<p className="text-sm text-muted-foreground mt-2">
Notification emails and automations that email you have been turned off.
You can re-enable them anytime in Settings → Notifications. Account emails
such as password resets are not affected.
</p>
<p className="text-center text-xs text-muted-foreground">
<Link href="/settings?tab=notifications" className="text-primary hover:underline">Email preferences</Link>
{' · '}
<Link href="/help" className="text-primary hover:underline">Help center</Link>
{' · '}
<Link href="/login" className="text-primary hover:underline">Back to sign in</Link>
</p>
</div>
</div>
)
}
return (
<div className="min-h-screen flex items-center justify-center bg-background p-4">
<div className="w-full max-w-sm space-y-8">
<div className="text-center">
<div className="flex justify-center mb-4">
<div className="flex h-14 w-14 items-center justify-center rounded-2xl bg-primary text-primary-foreground">
<BellOff className="h-7 w-7" />
</div>
</div>
<h1 className="font-display text-3xl font-bold tracking-tight">Unsubscribe</h1>
<p className="text-sm text-muted-foreground mt-2">
Stop notification emails and automations that email you. Password resets and
other account emails keep working, and you can re-enable notifications anytime
in Settings.
</p>
</div>
<div className="space-y-3">
<Button className="w-full" onClick={handleUnsubscribe} loading={loading}>
Unsubscribe from notification emails
</Button>
<Button variant="outline" className="w-full" asChild>
<Link href="/settings?tab=notifications">Keep my current preferences</Link>
</Button>
</div>
<p className="text-center text-xs text-muted-foreground">
<Link href="/help" className="text-primary hover:underline">Help center</Link>
</p>
</div>
</div>
)
}
+13
View File
@@ -0,0 +1,13 @@
import { UnsubscribeClient } from './client'
import { Suspense } from 'react'
export const dynamic = 'force-dynamic'
export default function UnsubscribePage() {
// useSearchParams in the client needs a Suspense boundary for prerender.
return (
<Suspense>
<UnsubscribeClient />
</Suspense>
)
}