Files
superbrain/internal/mailer/mailer.go
T
Andrew S Erwin 451312c3cf
release gate / check (push) Failing after 6m54s
Add notification engine phase 1: channels, rules, plan-gated delivery
When something happens in the brain, tell the user (PLAN_PRICING_TIERS
step 3). The engine is a SCANNER, not a hook system: producers are never
instrumented; exactly-once comes solely from UNIQUE(ruleId,dedupeKey) +
ON CONFLICT DO NOTHING, so rescans are free and restarts are safe.

Schema (migration 013 + schema.sql, converge-verified):
NotificationChannel (secrets encrypted at rest via internal/crypto, the
IMAP-password format), NotificationRule (one channel per rule in phase 1,
cooldown, version column), Notification (dedupe ledger + delivery state:
pending/sent/failed/suppressed, attempts, backoff timestamp).

internal/notify: two triggers — signal_created (fires only for signals
newer than the rule, never retro-notifying history) and bookmark_due
(lead-hours window, dedupe key carries the UTC due date so moving a
dueDate re-notifies and same-day rescans do not). Delivery claims rows in
one short transaction (FOR UPDATE SKIP LOCKED, batch 10) so multiple app
instances never double-send; exponential backoff to 5 attempts; per-rule
cooldown; per-owner pending cap. Channels: email (internal/mailer,
falls back to the account email), Slack webhook, Matrix room, Telegram
bot — webhooks dial through netguard inside outbound.Reserve budgets.
The plan gate re-checks at delivery: a downgraded tenant's rows become
'suppressed' instead of sending. Signal-app delivery deliberately absent
(needs a daemon; see plan doc hard truths).

API: channel/rule CRUD with the house version contract (409 on stale
base), write-only secrets (masked in every response; a PATCH echoing the
mask keeps the stored value), test-send endpoint with its own budget,
owner-scoped delivery history. Channel kinds gate on the ENTITLEMENT
CATALOG (403 'Not available on your plan') — never on TIER, per the
tenancy invariant.

Web: Settings -> Notifications tab (channels with per-kind forms and
Test button, rule builder, recent-delivery strip). Data loading uses the
house promise-chain shape; setState only in async callbacks (SSR lint).

Fixes along the way: mailer send budget raised 5->20/min (shared by
resets and notifications; 5/min would throttle a hosted instance) and
outbound gains ResetBudget() wired into the test harness — the global
'smtp' window made password-reset and notification tests collide when
the package ran as a whole.

Tests: full channel/rule/engine integration pass (masking + encryption
round-trip, masked-PATCH preservation, version contract, plan gating via
a forced 'free' tenant, dedupe across rescans, cooldown, real SMTP and
webhook delivery via loopback fakes, backoff recording, downgrade
suppression, history). Full suite green with -race; web lint/SSR-eslint/
build clean. Docs: API.md endpoint table, RUNNING.md, AGENTS.md
invariants, DESIGN_NOTIFICATIONS.md (local).
2026-10-26 14:43:15 -05:00

181 lines
5.8 KiB
Go

// Package mailer sends transactional email (password-reset links) through a
// configured SMTP relay.
//
// Like every server-initiated dial, sending is bounded by internal/outbound
// and guarded by internal/netguard: private/link-local relay hosts (the
// normal in-cluster case, e.g. a docker-mailserver on the compose network)
// require INTEGRATIONS_ALLOW_PRIVATE=1, exactly like IMAP and CardDAV.
//
// Configuration (env):
//
// SMTP_HOST relay host (required; empty disables sending entirely)
// SMTP_PORT default 587; 465 selects implicit TLS, otherwise STARTTLS
// is used when the server advertises it
// SMTP_USERNAME optional; enables AUTH PLAIN when non-empty
// SMTP_PASSWORD optional
// SMTP_FROM envelope+header sender (required, e.g. superbrain@host)
package mailer
import (
"context"
"crypto/tls"
"errors"
"fmt"
"net"
"net/smtp"
"os"
"strconv"
"strings"
"time"
"github.com/andrew/superbrain/internal/netguard"
"github.com/andrew/superbrain/internal/outbound"
)
// ErrNotConfigured means SMTP_HOST/SMTP_FROM are unset; callers surface a
// 503 rather than pretending the message was queued.
var ErrNotConfigured = errors.New("mailer: SMTP is not configured")
// sendTimeout bounds one full SMTP conversation (dial + TLS + transfer).
const sendTimeout = 30 * time.Second
// Config is the SMTP_* environment snapshot.
type Config struct {
Host string
Port int
Username string
Password string
From string
}
// LoadConfig reads the SMTP_* variables. An unset or unparsable SMTP_PORT
// falls back to 587 (submission).
func LoadConfig() Config {
port := 587
if v := strings.TrimSpace(os.Getenv("SMTP_PORT")); v != "" {
if p, err := strconv.Atoi(v); err == nil && p > 0 && p < 65536 {
port = p
}
}
return Config{
Host: strings.TrimSpace(os.Getenv("SMTP_HOST")),
Port: port,
Username: strings.TrimSpace(os.Getenv("SMTP_USERNAME")),
Password: os.Getenv("SMTP_PASSWORD"),
From: strings.TrimSpace(os.Getenv("SMTP_FROM")),
}
}
// Configured reports whether Send can possibly work. This is a global
// deployment property, so surfacing it to unauthenticated callers leaks
// nothing per-account.
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 {
cfg := LoadConfig()
if !cfg.Configured() {
return ErrNotConfigured
}
if to == "" {
return errors.New("mailer: missing recipient")
}
// Global send budget: transactional mail is rare per user but a hosted
// (multi-tenant) instance can legitimately send bursts — password resets
// and notification deliveries share this one key. The bound exists so an
// unreachable or blackholed relay cannot pile up goroutines (same shape
// as the IMAP and CardDAV callers), not to ration legitimate mail.
release, _, ok := outbound.Reserve("smtp", 20, time.Minute)
if !ok {
return errors.New("mailer: send budget exhausted")
}
defer release()
ctx, cancel := context.WithTimeout(ctx, sendTimeout)
defer cancel()
conn, err := dial(ctx, cfg.Host, cfg.Port)
if err != nil {
return fmt.Errorf("mailer: dial: %w", err)
}
if cfg.Port == 465 {
// Implicit TLS: handshake before the SMTP greeting is read.
tlsConn := tls.Client(conn, &tls.Config{ServerName: cfg.Host})
if err := tlsConn.HandshakeContext(ctx); err != nil {
conn.Close()
return fmt.Errorf("mailer: tls: %w", err)
}
conn = tlsConn
}
client, err := smtp.NewClient(conn, cfg.Host)
if err != nil {
conn.Close()
return fmt.Errorf("mailer: smtp handshake: %w", err)
}
defer client.Close()
if cfg.Port != 465 {
if ok, _ := client.Extension("STARTTLS"); ok {
if err := client.StartTLS(&tls.Config{ServerName: cfg.Host}); err != nil {
return fmt.Errorf("mailer: starttls: %w", err)
}
}
}
if cfg.Username != "" {
if ok, _ := client.Extension("AUTH"); !ok {
return errors.New("mailer: relay requires credentials but does not advertise AUTH")
}
if err := client.Auth(smtp.PlainAuth("", cfg.Username, cfg.Password, cfg.Host)); err != nil {
return fmt.Errorf("mailer: auth: %w", err)
}
}
if err := client.Mail(cfg.From); err != nil {
return fmt.Errorf("mailer: MAIL FROM: %w", err)
}
if err := client.Rcpt(to); err != nil {
return fmt.Errorf("mailer: RCPT TO: %w", err)
}
data, err := client.Data()
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")
if _, err := data.Write([]byte(msg)); err != nil {
return fmt.Errorf("mailer: write: %w", err)
}
if err := data.Close(); err != nil {
return fmt.Errorf("mailer: data close: %w", err)
}
// Best effort; Close() above already released the connection on error.
_ = client.Quit()
return nil
}
// sanitizeHeader strips CR/LF so a caller-controlled subject can never
// inject additional headers (or a second message).
func sanitizeHeader(s string) string {
return strings.NewReplacer("\r", " ", "\n", " ").Replace(strings.TrimSpace(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.
func dial(ctx context.Context, host string, port int) (net.Conn, error) {
address := net.JoinHostPort(host, strconv.Itoa(port))
if netguard.AllowPrivate() {
return netguard.DialContext(ctx, "tcp", address)
}
return netguard.DialContextPorts(ctx, "tcp", address, 25, 465, 587)
}