// 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: password resets are rare and an unreachable or // blackholed relay must not pile up goroutines (same shape as the IMAP // and CardDAV callers). release, _, ok := outbound.Reserve("smtp", 5, 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) }