The module path claimed a nonexistent GitHub repo. Point it (and the agent User-Agent contact URL, README/RUNNING clone URLs) at the real Gitea repository. Pure identifier rename: no runtime behavior change. Verified: build, vet, unit + full DB integration (-race), db-converge, web lint/SSR/build, browser regressions, e2e against rebuilt stack.
261 lines
9.0 KiB
Go
261 lines
9.0 KiB
Go
// 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
|
|
// 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/rand"
|
|
"crypto/tls"
|
|
"encoding/hex"
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/smtp"
|
|
"os"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"gitea.federated.computer/Federated_Computer/brain/internal/netguard"
|
|
"gitea.federated.computer/Federated_Computer/brain/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 {
|
|
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
|
|
}
|
|
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 := buildMessage(cfg.From, to, subject, body, html, listUnsub)
|
|
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))
|
|
}
|
|
|
|
// 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.
|
|
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)
|
|
}
|