Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (email): Send instance mail and channel mail through one SMTP transport, so a stripped STARTTLS offer no longer leaks credentials

Rostislav Dugin777078ff40eb
diff --git a/.env.example b/.env.example
index 07fcd489..3f728afc 100644
--- a/.env.example
+++ b/.env.example
@@ -52,6 +52,7 @@ SMTP_PORT=1025
SMTP_PASSWORD=password
+SMTP_SECURITY=none
SMTP_INSECURE_SKIP_VERIFY=false
# domain (used in email links)
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index be735be1..335c7ceb 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -17,6 +17,7 @@ import (
env_utils "databasus-backend/internal/util/env"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/smtp_transport"
"databasus-backend/internal/util/tools"
)
@@ -93,12 +94,14 @@ type EnvVariables struct {
CloudflareTurnstileSiteKey string `env:"CLOUDFLARE_TURNSTILE_SITE_KEY"`
// SMTP configuration (optional)
- SMTPHost string `env:"SMTP_HOST"`
- SMTPPort int `env:"SMTP_PORT"`
- SMTPUser string `env:"SMTP_USER"`
- SMTPPassword string `env:"SMTP_PASSWORD"`
- SMTPFrom string `env:"SMTP_FROM"`
- SMTPInsecureSkipVerify bool `env:"SMTP_INSECURE_SKIP_VERIFY"`
+ SMTPHost string `env:"SMTP_HOST"`
+ SMTPPort int `env:"SMTP_PORT"`
+ SMTPUser string `env:"SMTP_USER"`
+ SMTPPassword string `env:"SMTP_PASSWORD"`
+ SMTPFrom string `env:"SMTP_FROM"`
+ SMTPSecurity smtp_transport.Security `env:"SMTP_SECURITY"`
+ SMTPHeloName string `env:"SMTP_HELO_NAME"`
+ SMTPInsecureSkipVerify bool `env:"SMTP_INSECURE_SKIP_VERIFY"`
// Application URL (optional) - used for email links
DatabasusURL string `env:"DATABASUS_URL"`
@@ -155,8 +158,8 @@ func loadEnvVariables() {
logger.ExitAfterFlush(1)
}
- if env.SMTPHost != "" && env.SMTPPort <= 0 {
- log.Error("SMTP_PORT must be a positive integer when SMTP_HOST is set", "value", env.SMTPPort)
+ if err := validateSMTPSettings(&env); err != nil {
+ log.Error("invalid SMTP configuration", "error", err)
logger.ExitAfterFlush(1)
}
@@ -235,6 +238,30 @@ func loadEnvVariables() {
log.Info("environment variables loaded successfully")
}
+func validateSMTPSettings(env *EnvVariables) error {
+ if env.SMTPHost != "" && env.SMTPPort <= 0 {
+ return fmt.Errorf("SMTP_PORT must be a positive integer when SMTP_HOST is set, got %d", env.SMTPPort)
+ }
+
+ if env.SMTPSecurity != "" && !env.SMTPSecurity.IsValid() {
+ return fmt.Errorf("SMTP_SECURITY %q: %w", env.SMTPSecurity, smtp_transport.ErrUnknownSecurity)
+ }
+
+ if env.SMTPHeloName != "" {
+ if err := smtp_transport.ValidateHeloName(env.SMTPHeloName); err != nil {
+ return fmt.Errorf("SMTP_HELO_NAME %q: %w", env.SMTPHeloName, err)
+ }
+ }
+
+ if env.SMTPFrom != "" {
+ if _, err := smtp_transport.ParseSender(env.SMTPFrom); err != nil {
+ return fmt.Errorf("SMTP_FROM %q: %w", env.SMTPFrom, err)
+ }
+ }
+
+ return nil
+}
+
// An operator-supplied connection string wins, then the one startup published, then
// whatever the baked defaults still carry.
func adoptPublishedDatabaseDsnIfUnset(publishedDsnPath string) {
diff --git a/backend/internal/config/config_test.go b/backend/internal/config/config_test.go
index 2e42b33e..eb85ac83 100644
--- a/backend/internal/config/config_test.go
+++ b/backend/internal/config/config_test.go
@@ -160,3 +160,70 @@ func Test_IsStorageProbeProcess_RecognisesOnlyTheStorageProbeFlag(t *testing.T)
})
}
}
+
+func Test_ValidateSMTPSettings_RejectsUnusableValuesAndNamesTheVariable(t *testing.T) {
+ testCases := []struct {
+ name string
+ env EnvVariables
+ expectedVariable string
+ }{
+ {
+ name: "host without a port",
+ env: EnvVariables{SMTPHost: "smtp.example.com"},
+ expectedVariable: "SMTP_PORT",
+ },
+ {
+ name: "unknown security mode",
+ env: EnvVariables{SMTPHost: "smtp.example.com", SMTPPort: 587, SMTPSecurity: "ssl"},
+ expectedVariable: "SMTP_SECURITY",
+ },
+ {
+ name: "greeting name with a space",
+ env: EnvVariables{SMTPHost: "smtp.example.com", SMTPPort: 587, SMTPHeloName: "my relay"},
+ expectedVariable: "SMTP_HELO_NAME",
+ },
+ {
+ name: "unreadable sender",
+ env: EnvVariables{
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 587,
+ SMTPFrom: "noreply at example.com",
+ },
+ expectedVariable: "SMTP_FROM",
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ err := validateSMTPSettings(&testCase.env)
+
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), testCase.expectedVariable)
+ })
+ }
+}
+
+func Test_ValidateSMTPSettings_AcceptsUsableValues(t *testing.T) {
+ testCases := []struct {
+ name string
+ env EnvVariables
+ }{
+ {name: "no mail server", env: EnvVariables{}},
+ {
+ name: "sender with a display name",
+ env: EnvVariables{
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 587,
+ SMTPFrom: "Acme Backups <[email protected]>",
+ SMTPSecurity: "none",
+ SMTPHeloName: "[IPv6:2001:db8::1]",
+ },
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ assert.NoError(t, validateSMTPSettings(&testCase.env))
+ })
+ }
+}
diff --git a/backend/internal/features/email/di.go b/backend/internal/features/email/di.go
index e0c0505a..d047967f 100644
--- a/backend/internal/features/email/di.go
+++ b/backend/internal/features/email/di.go
@@ -3,24 +3,39 @@ package email
import (
"databasus-backend/internal/config"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/smtp_transport"
)
-var (
- env = config.GetEnv()
- log = logger.GetLogger()
-)
-
-var emailSMTPSender = &EmailSMTPSender{
- log,
- env.SMTPHost,
- env.SMTPPort,
- env.SMTPUser,
- env.SMTPPassword,
- env.SMTPFrom,
- env.SMTPInsecureSkipVerify,
- env.SMTPHost != "" && env.SMTPPort != 0,
-}
+var emailSMTPSender = newEmailSMTPSenderFromEnv(config.GetEnv())
func GetEmailSMTPSender() *EmailSMTPSender {
return emailSMTPSender
}
+
+func newEmailSMTPSenderFromEnv(env *config.EnvVariables) *EmailSMTPSender {
+ if env.SMTPHost == "" {
+ return &EmailSMTPSender{logger.GetLogger(), smtp_transport.Connection{}, "", false}
+ }
+
+ security := env.SMTPSecurity
+ if security == "" {
+ security = smtp_transport.GetDefaultSecurityForPort(env.SMTPPort)
+ }
+
+ heloName := env.SMTPHeloName
+ if heloName == "" {
+ heloName = smtp_transport.GetDefaultHeloName(env.DatabasusURL)
+ }
+
+ connection := smtp_transport.Connection{
+ Host: env.SMTPHost,
+ Port: env.SMTPPort,
+ Security: security,
+ Username: env.SMTPUser,
+ Password: env.SMTPPassword,
+ HeloName: heloName,
+ IsInsecureSkipVerify: env.SMTPInsecureSkipVerify,
+ }
+
+ return &EmailSMTPSender{logger.GetLogger(), connection, env.SMTPFrom, true}
+}
diff --git a/backend/internal/features/email/email.go b/backend/internal/features/email/email.go
index 7c7c1a21..d82d4aa8 100644
--- a/backend/internal/features/email/email.go
+++ b/backend/internal/features/email/email.go
@@ -2,257 +2,37 @@ package email
import (
"context"
- "crypto/tls"
- "fmt"
"log/slog"
- "mime"
- "net"
- "net/smtp"
- "time"
-)
-const (
- ImplicitTLSPort = 465
- DefaultTimeout = 5 * time.Second
- DefaultHelloName = "localhost"
- MIMETypeHTML = "text/html"
- MIMECharsetUTF8 = "UTF-8"
+ "databasus-backend/internal/util/smtp_transport"
)
type EmailSMTPSender struct {
- logger *slog.Logger
- smtpHost string
- smtpPort int
- smtpUser string
- smtpPassword string
- smtpFrom string
- isInsecureSkipVerify bool
- isConfigured bool
+ logger *slog.Logger
+ connection smtp_transport.Connection
+ from string
+ isConfigured bool
}
func (s *EmailSMTPSender) IsConfigured() bool {
return s.isConfigured
}
-func (s *EmailSMTPSender) SendEmail(to, subject, body string) error {
+func (s *EmailSMTPSender) SendEmail(ctx context.Context, to, subject, body string) error {
if !s.isConfigured {
- s.logger.Warn("Skipping email send, SMTP not initialized", "to", to, "subject", subject)
+ s.logger.WarnContext(ctx, "skipping email send, SMTP is not configured", "to_email", to, "subject", subject)
return nil
}
- from := s.smtpFrom
- if from == "" {
- from = s.smtpUser
- }
- if from == "" {
- from = "noreply@" + s.smtpHost
- }
-
- emailContent := s.buildEmailContent(to, subject, body, from)
- isAuthRequired := s.smtpUser != "" && s.smtpPassword != ""
-
- if s.smtpPort == ImplicitTLSPort {
- return s.sendImplicitTLS(to, from, emailContent, isAuthRequired)
- }
-
- return s.sendStartTLS(to, from, emailContent, isAuthRequired)
-}
-
-func (s *EmailSMTPSender) buildEmailContent(to, subject, body, from string) []byte {
- // Encode Subject header using RFC 2047 to avoid SMTPUTF8 requirement
- encodedSubject := encodeRFC2047(subject)
- subjectHeader := fmt.Sprintf("Subject: %s\r\n", encodedSubject)
- dateHeader := fmt.Sprintf("Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
-
- mimeHeaders := fmt.Sprintf(
- "MIME-version: 1.0;\nContent-Type: %s; charset=\"%s\";\n\n",
- MIMETypeHTML,
- MIMECharsetUTF8,
- )
-
- // Encode From header display name if it contains non-ASCII
- encodedFrom := encodeRFC2047(from)
- fromHeader := fmt.Sprintf("From: %s\r\n", encodedFrom)
-
- toHeader := fmt.Sprintf("To: %s\r\n", to)
-
- return []byte(fromHeader + toHeader + subjectHeader + dateHeader + mimeHeaders + body)
-}
-
-func (s *EmailSMTPSender) sendImplicitTLS(
- to, from string,
- emailContent []byte,
- isAuthRequired bool,
-) error {
- createClient := func() (*smtp.Client, func(), error) {
- return s.createImplicitTLSClient()
- }
-
- client, cleanup, err := s.authenticateWithRetry(createClient, isAuthRequired)
- if err != nil {
- return err
- }
- defer cleanup()
-
- return s.sendEmail(client, to, from, emailContent)
-}
-
-func (s *EmailSMTPSender) sendStartTLS(
- to, from string,
- emailContent []byte,
- isAuthRequired bool,
-) error {
- createClient := func() (*smtp.Client, func(), error) {
- return s.createStartTLSClient()
- }
-
- client, cleanup, err := s.authenticateWithRetry(createClient, isAuthRequired)
+ sender, err := smtp_transport.ResolveSender(s.from, s.connection.Username, s.connection.Host)
if err != nil {
return err
}
- defer cleanup()
-
- return s.sendEmail(client, to, from, emailContent)
-}
-
-func (s *EmailSMTPSender) createImplicitTLSClient() (*smtp.Client, func(), error) {
- addr := net.JoinHostPort(s.smtpHost, fmt.Sprintf("%d", s.smtpPort))
- tlsConfig := &tls.Config{ServerName: s.smtpHost, InsecureSkipVerify: s.isInsecureSkipVerify}
- dialer := &net.Dialer{Timeout: DefaultTimeout}
-
- conn, err := (&tls.Dialer{NetDialer: dialer, Config: tlsConfig}).DialContext(context.Background(), "tcp", addr)
- if err != nil {
- return nil, nil, fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
-
- client, err := smtp.NewClient(conn, s.smtpHost)
- if err != nil {
- _ = conn.Close()
- return nil, nil, fmt.Errorf("failed to create SMTP client: %w", err)
- }
-
- return client, func() { _ = client.Quit() }, nil
-}
-
-func (s *EmailSMTPSender) createStartTLSClient() (*smtp.Client, func(), error) {
- addr := net.JoinHostPort(s.smtpHost, fmt.Sprintf("%d", s.smtpPort))
- dialer := &net.Dialer{Timeout: DefaultTimeout}
-
- conn, err := dialer.Dial("tcp", addr)
- if err != nil {
- return nil, nil, fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
-
- client, err := smtp.NewClient(conn, s.smtpHost)
- if err != nil {
- _ = conn.Close()
- return nil, nil, fmt.Errorf("failed to create SMTP client: %w", err)
- }
-
- if err := client.Hello(DefaultHelloName); err != nil {
- _ = client.Quit()
- _ = conn.Close()
- return nil, nil, fmt.Errorf("SMTP hello failed: %w", err)
- }
-
- if ok, _ := client.Extension("STARTTLS"); ok {
- if err := client.StartTLS(&tls.Config{
- ServerName: s.smtpHost,
- InsecureSkipVerify: s.isInsecureSkipVerify,
- }); err != nil {
- _ = client.Quit()
- _ = conn.Close()
- return nil, nil, fmt.Errorf("STARTTLS failed: %w", err)
- }
- }
-
- return client, func() { _ = client.Quit() }, nil
-}
-
-func (s *EmailSMTPSender) authenticateWithRetry(
- createClient func() (*smtp.Client, func(), error),
- isAuthRequired bool,
-) (*smtp.Client, func(), error) {
- client, cleanup, err := createClient()
- if err != nil {
- return nil, nil, err
- }
-
- if !isAuthRequired {
- return client, cleanup, nil
- }
-
- // Try PLAIN auth first
- plainAuth := smtp.PlainAuth("", s.smtpUser, s.smtpPassword, s.smtpHost)
- if err := client.Auth(plainAuth); err == nil {
- return client, cleanup, nil
- }
-
- // PLAIN auth failed, connection may be closed - recreate and try LOGIN auth
- cleanup()
-
- client, cleanup, err = createClient()
- if err != nil {
- return nil, nil, err
- }
-
- loginAuth := &loginAuth{username: s.smtpUser, password: s.smtpPassword}
- if err := client.Auth(loginAuth); err != nil {
- cleanup()
- return nil, nil, fmt.Errorf("SMTP authentication failed: %w", err)
- }
-
- return client, cleanup, nil
-}
-
-func (s *EmailSMTPSender) sendEmail(client *smtp.Client, to, from string, content []byte) error {
- if err := client.Mail(from); err != nil {
- return fmt.Errorf("failed to set sender: %w", err)
- }
- if err := client.Rcpt(to); err != nil {
- return fmt.Errorf("failed to set recipient: %w", err)
- }
-
- writer, err := client.Data()
- if err != nil {
- return fmt.Errorf("failed to get data writer: %w", err)
- }
-
- if _, err = writer.Write(content); err != nil {
- return fmt.Errorf("failed to write email content: %w", err)
- }
-
- if err = writer.Close(); err != nil {
- return fmt.Errorf("failed to close data writer: %w", err)
- }
-
- return nil
-}
-
-func encodeRFC2047(s string) string {
- return mime.QEncoding.Encode("UTF-8", s)
-}
-
-type loginAuth struct {
- username string
- password string
-}
-
-func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
- return "LOGIN", []byte{}, nil
-}
-
-func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
- if more {
- switch string(fromServer) {
- case "Username:", "User Name\x00":
- return []byte(a.username), nil
- case "Password:", "Password\x00":
- return []byte(a.password), nil
- default:
- return []byte(a.username), nil
- }
- }
- return nil, nil
+ return smtp_transport.Send(ctx, s.connection, smtp_transport.Message{
+ Sender: sender,
+ Recipient: to,
+ Subject: subject,
+ HTMLBody: body,
+ })
}
diff --git a/backend/internal/features/email/email_test.go b/backend/internal/features/email/email_test.go
index 857efb9b..cdf891f5 100644
--- a/backend/internal/features/email/email_test.go
+++ b/backend/internal/features/email/email_test.go
@@ -1,43 +1,32 @@
package email
import (
- "bufio"
- "crypto/ecdsa"
- "crypto/elliptic"
- "crypto/rand"
- "crypto/tls"
- "crypto/x509"
- "crypto/x509/pkix"
"fmt"
- "math/big"
- "net"
- "strings"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
- "databasus-backend/internal/util/logger"
+ "databasus-backend/internal/config"
"databasus-backend/internal/util/testing/containers"
"databasus-backend/internal/util/testing/mailpit"
)
-func Test_EmailSMTPSenderSendEmail_WhenSmtpServerAccepts_DeliversMessageToRecipient(t *testing.T) {
+func Test_SendEmail_WhenSmtpServerAccepts_DeliversMessageWithSenderNameAndMessageID(t *testing.T) {
mailpitEndpoint := containers.StartMailpit(t)
mailpitClient := mailpit.NewClient(
fmt.Sprintf("%s:%d", mailpitEndpoint.HTTP.Host, mailpitEndpoint.HTTP.Port),
)
- sender := &EmailSMTPSender{
- logger: logger.GetLogger(),
- smtpHost: mailpitEndpoint.SMTP.Host,
- smtpPort: mailpitEndpoint.SMTP.Port,
- smtpFrom: "[email protected]",
- isConfigured: true,
- }
+ sender := newEmailSMTPSenderFromEnv(&config.EnvVariables{
+ SMTPHost: mailpitEndpoint.SMTP.Host,
+ SMTPPort: mailpitEndpoint.SMTP.Port,
+ SMTPFrom: "[email protected]",
+ SMTPSecurity: "none",
+ })
- err := sender.SendEmail("[email protected]", "Password Reset Code", "<b>123456</b>")
+ err := sender.SendEmail(t.Context(), "[email protected]", "Password Reset Code", "<b>123456</b>")
require.NoError(t, err)
var delivered []mailpit.Message
@@ -53,109 +42,25 @@ func Test_EmailSMTPSenderSendEmail_WhenSmtpServerAccepts_DeliversMessageToRecipi
}, 5*time.Second, 100*time.Millisecond, "Mailpit should receive exactly one message")
assert.Equal(t, "Password Reset Code", delivered[0].Subject)
+ assert.Equal(t, "Databasus", delivered[0].From.Name)
+ assert.Equal(t, "[email protected]", delivered[0].From.Address)
+ assert.NotEmpty(t, delivered[0].MessageID)
require.Len(t, delivered[0].To, 1)
assert.Equal(t, "[email protected]", delivered[0].To[0].Address)
}
-func Test_EmailSMTPSenderImplicitTLS_WithUntrustedCert_FailsUnlessSkipVerify(t *testing.T) {
- host, port := startImplicitTLSGreetingServer(t, newSelfSignedTLSConfig(t))
-
- t.Run("verification on rejects the untrusted certificate", func(t *testing.T) {
- sender := &EmailSMTPSender{logger: logger.GetLogger(), smtpHost: host, smtpPort: port}
-
- _, _, dialErr := sender.createImplicitTLSClient()
-
- require.Error(t, dialErr)
- assert.Contains(t, dialErr.Error(), "certificate")
- })
-
- t.Run("skip verify accepts the untrusted certificate", func(t *testing.T) {
- sender := &EmailSMTPSender{
- logger: logger.GetLogger(),
- smtpHost: host,
- smtpPort: port,
- isInsecureSkipVerify: true,
- }
-
- client, cleanup, dialErr := sender.createImplicitTLSClient()
- require.NoError(t, dialErr)
- defer cleanup()
+func Test_SendEmail_WhenSmtpHostIsUnset_SkipsWithoutError(t *testing.T) {
+ sender := newEmailSMTPSenderFromEnv(&config.EnvVariables{})
- require.NotNil(t, client)
- })
+ assert.False(t, sender.IsConfigured())
+ assert.NoError(t, sender.SendEmail(t.Context(), "[email protected]", "Subject", "<p>body</p>"))
}
-// newSelfSignedTLSConfig builds a TLS config whose certificate is not signed by any trusted
-// root, so a verifying client rejects it and a skip-verify client accepts it.
-func newSelfSignedTLSConfig(t *testing.T) *tls.Config {
- t.Helper()
-
- key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
- require.NoError(t, err)
-
- template := x509.Certificate{
- SerialNumber: big.NewInt(1),
- Subject: pkix.Name{CommonName: "127.0.0.1"},
- NotBefore: time.Now().UTC().Add(-time.Hour),
- NotAfter: time.Now().UTC().Add(time.Hour),
- KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
- ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
- IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.IPv6loopback},
- IsCA: true,
- }
-
- der, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
- require.NoError(t, err)
-
- return &tls.Config{
- Certificates: []tls.Certificate{{Certificate: [][]byte{der}, PrivateKey: key}},
- }
-}
-
-// startImplicitTLSGreetingServer accepts implicit-TLS connections and speaks just enough SMTP
-// (greeting, EHLO, QUIT) for createImplicitTLSClient to connect and disconnect cleanly.
-func startImplicitTLSGreetingServer(t *testing.T, tlsConfig *tls.Config) (host string, port int) {
- t.Helper()
-
- listener, err := tls.Listen("tcp", "127.0.0.1:0", tlsConfig)
- require.NoError(t, err)
- t.Cleanup(func() { _ = listener.Close() })
-
- go func() {
- for {
- conn, acceptErr := listener.Accept()
- if acceptErr != nil {
- return
- }
-
- go serveMinimalSMTP(conn)
- }
- }()
-
- addr := listener.Addr().(*net.TCPAddr)
-
- return addr.IP.String(), addr.Port
-}
-
-func serveMinimalSMTP(conn net.Conn) {
- defer func() { _ = conn.Close() }()
-
- if _, err := conn.Write([]byte("220 test ESMTP\r\n")); err != nil {
- return
- }
-
- reader := bufio.NewReader(conn)
- for {
- line, err := reader.ReadString('\n')
- if err != nil {
- return
- }
-
- if strings.HasPrefix(strings.ToUpper(line), "QUIT") {
- _, _ = conn.Write([]byte("221 Bye\r\n"))
- return
- }
+func Test_NewEmailSMTPSenderFromEnv_WithoutSecurity_UsesPortDefault(t *testing.T) {
+ implicitTLSSender := newEmailSMTPSenderFromEnv(&config.EnvVariables{SMTPHost: "smtp.example.com", SMTPPort: 465})
+ upgradeSender := newEmailSMTPSenderFromEnv(&config.EnvVariables{SMTPHost: "smtp.example.com", SMTPPort: 587})
- _, _ = conn.Write([]byte("250 OK\r\n"))
- }
+ assert.True(t, implicitTLSSender.IsConfigured())
+ assert.Equal(t, "tls", string(implicitTLSSender.connection.Security))
+ assert.Equal(t, "starttls", string(upgradeSender.connection.Security))
}
diff --git a/backend/internal/features/notifiers/controller_test.go b/backend/internal/features/notifiers/controller_test.go
index 5697dc51..5f93f850 100644
--- a/backend/internal/features/notifiers/controller_test.go
+++ b/backend/internal/features/notifiers/controller_test.go
@@ -23,7 +23,9 @@ import (
users_testing "databasus-backend/internal/features/users/testing"
workspaces_controllers "databasus-backend/internal/features/workspaces/controllers"
workspaces_testing "databasus-backend/internal/features/workspaces/testing"
+ "databasus-backend/internal/util/smtp_transport"
test_utils "databasus-backend/internal/util/testing"
+ "databasus-backend/internal/util/testing/containers"
)
func Test_SaveNewNotifier_NotifierReturnedViaGet(t *testing.T) {
@@ -1466,3 +1468,160 @@ func decryptField(t *testing.T, encryptedValue string) string {
assert.NoError(t, err)
return decrypted
}
+
+func Test_SaveEmailNotifier_WithUnusableSettings_Refused(t *testing.T) {
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ router := createRouter()
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)
+ defer workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+
+ testCases := []struct {
+ name string
+ applyUnusableSetting func(emailNotifier *email_notifier.EmailNotifier)
+ expectedError string
+ }{
+ {
+ name: "sender without an address",
+ applyUnusableSetting: func(emailNotifier *email_notifier.EmailNotifier) { emailNotifier.From = "ops at example" },
+ expectedError: smtp_transport.ErrInvalidSender.Error(),
+ },
+ {
+ name: "unknown security mode",
+ applyUnusableSetting: func(emailNotifier *email_notifier.EmailNotifier) { emailNotifier.Security = "ssl" },
+ expectedError: smtp_transport.ErrUnknownSecurity.Error(),
+ },
+ {
+ name: "recipient without an address",
+ applyUnusableSetting: func(emailNotifier *email_notifier.EmailNotifier) {
+ emailNotifier.TargetEmail = "ops at example"
+ },
+ expectedError: smtp_transport.ErrInvalidRecipient.Error(),
+ },
+ {
+ name: "greeting name with a space",
+ applyUnusableSetting: func(emailNotifier *email_notifier.EmailNotifier) { emailNotifier.HeloName = "my relay" },
+ expectedError: smtp_transport.ErrInvalidHeloName.Error(),
+ },
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ notifier := createEmailNotifier(workspace.ID)
+ testCase.applyUnusableSetting(notifier.EmailNotifier)
+
+ response := test_utils.MakePostRequest(
+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *notifier, http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), testCase.expectedError)
+ })
+ }
+}
+
+func Test_SaveEmailNotifier_WithDisplayNameSenderAndConnectionOptions_ReturnedAsSaved(t *testing.T) {
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ router := createRouter()
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)
+
+ notifier := createEmailNotifier(workspace.ID)
+ notifier.EmailNotifier.From = "Acme Backups <[email protected]>"
+ notifier.EmailNotifier.Security = smtp_transport.SecurityNone
+ notifier.EmailNotifier.HeloName = "mail.example.com"
+
+ var savedNotifier Notifier
+ test_utils.MakePostRequestAndUnmarshal(
+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *notifier, http.StatusOK, &savedNotifier,
+ )
+
+ var retrievedNotifier Notifier
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ fmt.Sprintf("/api/v1/notifiers/%s", savedNotifier.ID.String()),
+ "Bearer "+owner.Token,
+ http.StatusOK,
+ &retrievedNotifier,
+ )
+
+ assert.Equal(t, "Acme Backups <[email protected]>", retrievedNotifier.EmailNotifier.From)
+ assert.Equal(t, smtp_transport.SecurityNone, retrievedNotifier.EmailNotifier.Security)
+ assert.Equal(t, "mail.example.com", retrievedNotifier.EmailNotifier.HeloName)
+
+ deleteNotifier(t, router, savedNotifier.ID, workspace.ID, owner.Token)
+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+}
+
+func Test_SaveEmailNotifier_WithoutSecurity_CreatesWithPortDefaultAndUpdateKeepsStoredMode(t *testing.T) {
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ router := createRouter()
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)
+
+ notifier := createEmailNotifier(workspace.ID)
+
+ var createdNotifier Notifier
+ test_utils.MakePostRequestAndUnmarshal(
+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, *notifier, http.StatusOK, &createdNotifier,
+ )
+ assert.Equal(t, smtp_transport.SecurityStartTLS, createdNotifier.EmailNotifier.Security)
+
+ createdNotifier.EmailNotifier.Security = smtp_transport.SecurityNone
+ var notifierSwitchedToNone Notifier
+ test_utils.MakePostRequestAndUnmarshal(
+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, createdNotifier, http.StatusOK, &notifierSwitchedToNone,
+ )
+
+ notifierSwitchedToNone.EmailNotifier.Security = ""
+ notifierSwitchedToNone.EmailNotifier.SMTPPort = 465
+ test_utils.MakePostRequest(
+ t, router, "/api/v1/notifiers", "Bearer "+owner.Token, notifierSwitchedToNone, http.StatusOK,
+ )
+
+ var retrievedNotifier Notifier
+ test_utils.MakeGetRequestAndUnmarshal(
+ t,
+ router,
+ fmt.Sprintf("/api/v1/notifiers/%s", createdNotifier.ID.String()),
+ "Bearer "+owner.Token,
+ http.StatusOK,
+ &retrievedNotifier,
+ )
+
+ assert.Equal(t, 465, retrievedNotifier.EmailNotifier.SMTPPort)
+ assert.Equal(t, smtp_transport.SecurityNone, retrievedNotifier.EmailNotifier.Security)
+
+ deleteNotifier(t, router, createdNotifier.ID, workspace.ID, owner.Token)
+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+}
+
+func Test_SendTestNotificationDirect_EmailWithoutSecurity_SendsWithPortDefault(t *testing.T) {
+ owner := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+ router := createRouter()
+ workspace := workspaces_testing.CreateTestWorkspace(t.Context(), "Test Workspace", owner, router)
+
+ mailpitEndpoint := containers.StartMailpit(t)
+
+ notifier := createEmailNotifier(workspace.ID)
+ notifier.EmailNotifier.SMTPHost = mailpitEndpoint.SMTP.Host
+ notifier.EmailNotifier.SMTPPort = mailpitEndpoint.SMTP.Port
+
+ response := test_utils.MakePostRequest(
+ t, router, "/api/v1/notifiers/direct-test", "Bearer "+owner.Token, *notifier, http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), smtp_transport.ErrStartTLSNotOffered.Error())
+
+ workspaces_testing.RemoveTestWorkspace(t.Context(), workspace, router)
+}
+
+func createEmailNotifier(workspaceID uuid.UUID) *Notifier {
+ return &Notifier{
+ WorkspaceID: workspaceID,
+ Name: "Test Email Notifier " + uuid.New().String(),
+ NotifierType: NotifierTypeEmail,
+ EmailNotifier: &email_notifier.EmailNotifier{
+ TargetEmail: "[email protected]",
+ SMTPHost: "smtp.example.com",
+ SMTPPort: 587,
+ },
+ }
+}
diff --git a/backend/internal/features/notifiers/model.go b/backend/internal/features/notifiers/model.go
index 7d0ca826..9a176248 100644
--- a/backend/internal/features/notifiers/model.go
+++ b/backend/internal/features/notifiers/model.go
@@ -38,6 +38,12 @@ func (n *Notifier) TableName() string {
return "notifiers"
}
+func (n *Notifier) FillDefaults() {
+ if n.NotifierType == NotifierTypeEmail && n.EmailNotifier != nil {
+ n.EmailNotifier.FillDefaults()
+ }
+}
+
func (n *Notifier) Validate(encryptor encryption.FieldEncryptor) error {
if n.Name == "" {
return errors.New("name is required")
diff --git a/backend/internal/features/notifiers/models/email_notifier/auth.go b/backend/internal/features/notifiers/models/email_notifier/auth.go
deleted file mode 100644
index d9325f77..00000000
--- a/backend/internal/features/notifiers/models/email_notifier/auth.go
+++ /dev/null
@@ -1,28 +0,0 @@
-package email_notifier
-
-import (
- "errors"
- "net/smtp"
-)
-
-type loginAuth struct {
- username, password string
-}
-
-func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
- return "LOGIN", []byte{}, nil
-}
-
-func (a *loginAuth) Next(fromServer []byte, more bool) ([]byte, error) {
- if more {
- switch string(fromServer) {
- case "Username:":
- return []byte(a.username), nil
- case "Password:":
- return []byte(a.password), nil
- default:
- return nil, errors.New("unknown LOGIN challenge: " + string(fromServer))
- }
- }
- return nil, nil
-}
diff --git a/backend/internal/features/notifiers/models/email_notifier/model.go b/backend/internal/features/notifiers/models/email_notifier/model.go
index 586d7162..8f139ebb 100644
--- a/backend/internal/features/notifiers/models/email_notifier/model.go
+++ b/backend/internal/features/notifiers/models/email_notifier/model.go
@@ -2,50 +2,50 @@ package email_notifier
import (
"context"
- "crypto/tls"
"errors"
"fmt"
"log/slog"
- "mime"
- "net"
- "net/smtp"
- "os"
- "strings"
- "time"
"github.com/google/uuid"
+ "databasus-backend/internal/config"
notifier_models "databasus-backend/internal/features/notifiers/models"
"databasus-backend/internal/util/encryption"
-)
-
-const (
- ImplicitTLSPort = 465
- DefaultTimeout = 5 * time.Second
- MIMETypeHTML = "text/html"
- MIMECharsetUTF8 = "UTF-8"
+ "databasus-backend/internal/util/smtp_transport"
)
type EmailNotifier struct {
- NotifierID uuid.UUID `json:"notifierId" gorm:"primaryKey;type:uuid;column:notifier_id"`
- TargetEmail string `json:"targetEmail" gorm:"not null;type:varchar(255);column:target_email"`
- SMTPHost string `json:"smtpHost" gorm:"not null;type:varchar(255);column:smtp_host"`
- SMTPPort int `json:"smtpPort" gorm:"not null;column:smtp_port"`
- SMTPUser string `json:"smtpUser" gorm:"type:varchar(255);column:smtp_user"`
- SMTPPassword string `json:"smtpPassword" gorm:"type:varchar(255);column:smtp_password"`
- From string `json:"from" gorm:"type:varchar(255);column:from_email"`
- IsInsecureSkipVerify bool `json:"isInsecureSkipVerify" gorm:"default:false;column:is_insecure_skip_verify"`
+ NotifierID uuid.UUID `json:"notifierId" gorm:"primaryKey;type:uuid;column:notifier_id"`
+ TargetEmail string `json:"targetEmail" gorm:"not null;type:varchar(255);column:target_email"`
+ SMTPHost string `json:"smtpHost" gorm:"not null;type:varchar(255);column:smtp_host"`
+ SMTPPort int `json:"smtpPort" gorm:"not null;column:smtp_port"`
+ SMTPUser string `json:"smtpUser" gorm:"type:varchar(255);column:smtp_user"`
+ SMTPPassword string `json:"smtpPassword" gorm:"type:varchar(255);column:smtp_password"`
+ From string `json:"from" gorm:"type:varchar(255);column:from_email"`
+ IsInsecureSkipVerify bool `json:"isInsecureSkipVerify" gorm:"default:false;column:is_insecure_skip_verify"`
+ Security smtp_transport.Security `json:"security" gorm:"not null;type:varchar(16);column:security"`
+ HeloName string `json:"heloName" gorm:"not null;type:varchar(255);column:helo_name"`
}
func (e *EmailNotifier) TableName() string {
return "email_notifiers"
}
+func (e *EmailNotifier) FillDefaults() {
+ if e.Security == "" {
+ e.Security = smtp_transport.GetDefaultSecurityForPort(e.SMTPPort)
+ }
+}
+
func (e *EmailNotifier) Validate(encryptor encryption.FieldEncryptor) error {
if e.TargetEmail == "" {
return errors.New("target email is required")
}
+ if _, err := smtp_transport.ParseRecipient(e.TargetEmail); err != nil {
+ return err
+ }
+
if e.SMTPHost == "" {
return errors.New("SMTP host is required")
}
@@ -54,11 +54,27 @@ func (e *EmailNotifier) Validate(encryptor encryption.FieldEncryptor) error {
return errors.New("SMTP port is required")
}
+ if !e.Security.IsValid() {
+ return smtp_transport.ErrUnknownSecurity
+ }
+
// Authentication is optional - both user and password must be provided together or both empty
if (e.SMTPUser == "") != (e.SMTPPassword == "") {
return errors.New("SMTP user and password must both be provided or both be empty")
}
+ if e.From != "" {
+ if _, err := smtp_transport.ParseSender(e.From); err != nil {
+ return err
+ }
+ }
+
+ if e.HeloName != "" {
+ if err := smtp_transport.ValidateHeloName(e.HeloName); err != nil {
+ return err
+ }
+ }
+
return nil
}
@@ -76,21 +92,32 @@ func (e *EmailNotifier) Send(
smtpPassword = decrypted
}
- from := e.From
- if from == "" {
- from = e.SMTPUser
- if from == "" {
- from = "noreply@" + e.SMTPHost
- }
+ sender, err := smtp_transport.ResolveSender(e.From, e.SMTPUser, e.SMTPHost)
+ if err != nil {
+ return err
}
- emailContent := e.buildEmailContent(notification.Heading, notification.Message, from)
- isAuthRequired := e.SMTPUser != "" && smtpPassword != ""
+ heloName := e.HeloName
+ if heloName == "" {
+ heloName = smtp_transport.GetDefaultHeloName(config.GetEnv().DatabasusURL)
+ }
- if e.SMTPPort == ImplicitTLSPort {
- return e.sendImplicitTLS(emailContent, from, smtpPassword, isAuthRequired)
+ connection := smtp_transport.Connection{
+ Host: e.SMTPHost,
+ Port: e.SMTPPort,
+ Security: e.Security,
+ Username: e.SMTPUser,
+ Password: smtpPassword,
+ HeloName: heloName,
+ IsInsecureSkipVerify: e.IsInsecureSkipVerify,
}
- return e.sendStartTLS(emailContent, from, smtpPassword, isAuthRequired)
+
+ return smtp_transport.Send(context.Background(), connection, smtp_transport.Message{
+ Sender: sender,
+ Recipient: e.TargetEmail,
+ Subject: notification.Heading,
+ HTMLBody: notification.Message,
+ })
}
func (e *EmailNotifier) HideSensitiveData() {
@@ -104,6 +131,11 @@ func (e *EmailNotifier) Update(incoming *EmailNotifier) {
e.SMTPUser = incoming.SMTPUser
e.From = incoming.From
e.IsInsecureSkipVerify = incoming.IsInsecureSkipVerify
+ e.HeloName = incoming.HeloName
+
+ if incoming.Security != "" {
+ e.Security = incoming.Security
+ }
if incoming.SMTPPassword != "" {
e.SMTPPassword = incoming.SMTPPassword
@@ -120,218 +152,3 @@ func (e *EmailNotifier) EncryptSensitiveData(encryptor encryption.FieldEncryptor
}
return nil
}
-
-func getHelloName() string {
- hostname, err := os.Hostname()
-
- if err != nil || hostname == "" {
- return "localhost"
- }
-
- return hostname
-}
-
-// encodeRFC2047 encodes a string using RFC 2047 MIME encoding for email headers
-// This ensures compatibility with SMTP servers that don't support SMTPUTF8
-func encodeRFC2047(s string) string {
- // mime.QEncoding handles UTF-8 → =?UTF-8?Q?...?= encoding
- // This allows non-ASCII characters (emojis, accents, etc.) in email headers
- // while maintaining compatibility with all SMTP servers
- return mime.QEncoding.Encode("UTF-8", s)
-}
-
-// sanitizeHeaderValue strips CR, LF, and NUL to prevent SMTP header injection:
-// a CRLF inside a header value would start a new header (e.g. Bcc:) or
-// terminate the header block, letting an attacker rewrite the envelope.
-func sanitizeHeaderValue(value string) string {
- value = strings.ReplaceAll(value, "\r", "")
- value = strings.ReplaceAll(value, "\n", "")
- value = strings.ReplaceAll(value, "\x00", "")
-
- return value
-}
-
-func (e *EmailNotifier) buildEmailContent(heading, message, from string) []byte {
- safeHeading := sanitizeHeaderValue(heading)
- safeFrom := sanitizeHeaderValue(from)
- safeTargetEmail := sanitizeHeaderValue(e.TargetEmail)
- safeSMTPHost := sanitizeHeaderValue(e.SMTPHost)
-
- // Encode Subject header using RFC 2047 to avoid SMTPUTF8 requirement
- // This ensures compatibility with SMTP servers that don't support SMTPUTF8
- encodedSubject := encodeRFC2047(safeHeading)
- subject := fmt.Sprintf("Subject: %s\r\n", encodedSubject)
- dateHeader := fmt.Sprintf("Date: %s\r\n", time.Now().UTC().Format(time.RFC1123Z))
- messageID := fmt.Sprintf("Message-ID: <%s@%s>\r\n", uuid.New().String(), safeSMTPHost)
-
- mimeHeaders := fmt.Sprintf(
- "MIME-version: 1.0;\nContent-Type: %s; charset=\"%s\";\n\n",
- MIMETypeHTML,
- MIMECharsetUTF8,
- )
-
- // Encode From header display name if it contains non-ASCII
- encodedFrom := encodeRFC2047(safeFrom)
- fromHeader := fmt.Sprintf("From: %s\r\n", encodedFrom)
-
- toHeader := fmt.Sprintf("To: %s\r\n", safeTargetEmail)
-
- return []byte(fromHeader + toHeader + subject + dateHeader + messageID + mimeHeaders + message)
-}
-
-func (e *EmailNotifier) sendImplicitTLS(
- emailContent []byte,
- from string,
- password string,
- isAuthRequired bool,
-) error {
- createClient := func() (*smtp.Client, func(), error) {
- return e.createImplicitTLSClient()
- }
-
- client, cleanup, err := e.authenticateWithRetry(createClient, password, isAuthRequired)
- if err != nil {
- return err
- }
- defer cleanup()
-
- return e.sendEmail(client, from, emailContent)
-}
-
-func (e *EmailNotifier) sendStartTLS(
- emailContent []byte,
- from string,
- password string,
- isAuthRequired bool,
-) error {
- createClient := func() (*smtp.Client, func(), error) {
- return e.createStartTLSClient()
- }
-
- client, cleanup, err := e.authenticateWithRetry(createClient, password, isAuthRequired)
- if err != nil {
- return err
- }
- defer cleanup()
-
- return e.sendEmail(client, from, emailContent)
-}
-
-func (e *EmailNotifier) createImplicitTLSClient() (*smtp.Client, func(), error) {
- addr := net.JoinHostPort(e.SMTPHost, fmt.Sprintf("%d", e.SMTPPort))
- tlsConfig := &tls.Config{
- ServerName: e.SMTPHost,
- InsecureSkipVerify: e.IsInsecureSkipVerify,
- }
- dialer := &net.Dialer{Timeout: DefaultTimeout}
-
- conn, err := (&tls.Dialer{NetDialer: dialer, Config: tlsConfig}).DialContext(context.Background(), "tcp", addr)
- if err != nil {
- return nil, nil, fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
-
- client, err := smtp.NewClient(conn, e.SMTPHost)
- if err != nil {
- _ = conn.Close()
- return nil, nil, fmt.Errorf("failed to create SMTP client: %w", err)
- }
-
- return client, func() { _ = client.Quit() }, nil
-}
-
-func (e *EmailNotifier) createStartTLSClient() (*smtp.Client, func(), error) {
- addr := net.JoinHostPort(e.SMTPHost, fmt.Sprintf("%d", e.SMTPPort))
- dialer := &net.Dialer{Timeout: DefaultTimeout}
-
- conn, err := dialer.Dial("tcp", addr)
- if err != nil {
- return nil, nil, fmt.Errorf("failed to connect to SMTP server: %w", err)
- }
-
- client, err := smtp.NewClient(conn, e.SMTPHost)
- if err != nil {
- _ = conn.Close()
- return nil, nil, fmt.Errorf("failed to create SMTP client: %w", err)
- }
-
- if err := client.Hello(getHelloName()); err != nil {
- _ = client.Quit()
- _ = conn.Close()
- return nil, nil, fmt.Errorf("SMTP hello failed: %w", err)
- }
-
- if ok, _ := client.Extension("STARTTLS"); ok {
- if err := client.StartTLS(&tls.Config{
- ServerName: e.SMTPHost,
- InsecureSkipVerify: e.IsInsecureSkipVerify,
- }); err != nil {
- _ = client.Quit()
- _ = conn.Close()
- return nil, nil, fmt.Errorf("STARTTLS failed: %w", err)
- }
- }
-
- return client, func() { _ = client.Quit() }, nil
-}
-
-func (e *EmailNotifier) authenticateWithRetry(
- createClient func() (*smtp.Client, func(), error),
- password string,
- isAuthRequired bool,
-) (*smtp.Client, func(), error) {
- client, cleanup, err := createClient()
- if err != nil {
- return nil, nil, err
- }
-
- if !isAuthRequired {
- return client, cleanup, nil
- }
-
- // Try PLAIN auth first
- plainAuth := smtp.PlainAuth("", e.SMTPUser, password, e.SMTPHost)
- if err := client.Auth(plainAuth); err == nil {
- return client, cleanup, nil
- }
-
- // PLAIN auth failed, connection may be closed - recreate and try LOGIN auth
- cleanup()
-
- client, cleanup, err = createClient()
- if err != nil {
- return nil, nil, err
- }
-
- loginAuth := &loginAuth{username: e.SMTPUser, password: password}
- if err := client.Auth(loginAuth); err != nil {
- cleanup()
- return nil, nil, fmt.Errorf("SMTP authentication failed: %w", err)
- }
-
- return client, cleanup, nil
-}
-
-func (e *EmailNotifier) sendEmail(client *smtp.Client, from string, content []byte) error {
- if err := client.Mail(from); err != nil {
- return fmt.Errorf("failed to set sender: %w", err)
- }
-
- if err := client.Rcpt(e.TargetEmail); err != nil {
- return fmt.Errorf("failed to set recipient: %w", err)
- }
-
- writer, err := client.Data()
- if err != nil {
- return fmt.Errorf("failed to get data writer: %w", err)
- }
-
- if _, err = writer.Write(content); err != nil {
- return fmt.Errorf("failed to write email content: %w", err)
- }
-
- if err = writer.Close(); err != nil {
- return fmt.Errorf("failed to close data writer: %w", err)
- }
-
- return nil
-}
diff --git a/backend/internal/features/notifiers/models/email_notifier/model_test.go b/backend/internal/features/notifiers/models/email_notifier/model_test.go
index 12523175..52d1e2ef 100644
--- a/backend/internal/features/notifiers/models/email_notifier/model_test.go
+++ b/backend/internal/features/notifiers/models/email_notifier/model_test.go
@@ -2,7 +2,6 @@ package email_notifier
import (
"fmt"
- "strings"
"testing"
"time"
@@ -13,73 +12,20 @@ import (
notifier_models "databasus-backend/internal/features/notifiers/models"
"databasus-backend/internal/util/encryption"
"databasus-backend/internal/util/logger"
+ "databasus-backend/internal/util/smtp_transport"
"databasus-backend/internal/util/testing/containers"
"databasus-backend/internal/util/testing/mailpit"
)
-func Test_SanitizeHeaderValue_StripsCRLFAndNUL(t *testing.T) {
- cases := []struct {
- input string
- expected string
- }{
- {"plain", "plain"},
- {"with\rcr", "withcr"},
- {"with\nlf", "withlf"},
- {"with\r\ncrlf", "withcrlf"},
- {"with\x00nul", "withnul"},
- {"a\r\nBcc: [email protected]\r\n", "aBcc: [email protected]"},
- }
-
- for _, c := range cases {
- got := sanitizeHeaderValue(c.input)
- if got != c.expected {
- t.Errorf("sanitizeHeaderValue(%q) = %q, want %q", c.input, got, c.expected)
- }
- }
-}
-
-func Test_BuildEmailContent_DropsInjectedHeadersFromTargetEmail(t *testing.T) {
- notifier := &EmailNotifier{
- NotifierID: uuid.New(),
- TargetEmail: "[email protected]\r\nBcc: [email protected]",
- SMTPHost: "smtp.example.com",
- SMTPPort: 587,
- }
-
- content := string(notifier.buildEmailContent("subject", "<p>body</p>", "[email protected]"))
-
- if strings.Contains(content, "\r\nBcc:") || strings.Contains(content, "\nBcc:") {
- t.Errorf("Bcc header line was injected via TargetEmail: %q", content)
- }
-
- if !strings.Contains(content, "To: [email protected]: [email protected]\r\n") {
- t.Errorf("expected sanitized To header without CRLF, got: %q", content)
- }
-}
-
-func Test_EmailNotifierSend_WhenSmtpServerAccepts_DeliversMessageToRecipient(t *testing.T) {
+func Test_EmailNotifierSend_WithNoneAgainstMailpit_DeliversMessageToRecipient(t *testing.T) {
mailpitEndpoint := containers.StartMailpit(t)
mailpitClient := mailpit.NewClient(
fmt.Sprintf("%s:%d", mailpitEndpoint.HTTP.Host, mailpitEndpoint.HTTP.Port),
)
- notifier := &EmailNotifier{
- NotifierID: uuid.New(),
- TargetEmail: "[email protected]",
- SMTPHost: mailpitEndpoint.SMTP.Host,
- SMTPPort: mailpitEndpoint.SMTP.Port,
- }
+ notifier := newMailpitEmailNotifier(mailpitEndpoint, smtp_transport.SecurityNone)
- err := notifier.Send(
- encryption.GetFieldEncryptor(),
- logger.GetLogger(),
- notifier_models.Notification{
- Type: notifier_models.NotificationTypeAll,
- Heading: "Backup completed",
- Message: "<b>All good</b>",
- },
- )
+ err := notifier.Send(encryption.GetFieldEncryptor(), logger.GetLogger(), newBackupNotification())
require.NoError(t, err)
var delivered []mailpit.Message
@@ -95,21 +41,39 @@ func Test_EmailNotifierSend_WhenSmtpServerAccepts_DeliversMessageToRecipient(t *
}, 5*time.Second, 100*time.Millisecond, "Mailpit should receive exactly one message")
assert.Equal(t, "Backup completed", delivered[0].Subject)
+ assert.Equal(t, "Databasus", delivered[0].From.Name)
require.Len(t, delivered[0].To, 1)
assert.Equal(t, "[email protected]", delivered[0].To[0].Address)
}
-func Test_BuildEmailContent_DropsInjectedHeadersFromSMTPHost(t *testing.T) {
- notifier := &EmailNotifier{
+func Test_EmailNotifierSend_WithStartTLSAgainstMailpit_FailsBecauseUpgradeIsNotOffered(t *testing.T) {
+ mailpitEndpoint := containers.StartMailpit(t)
+
+ notifier := newMailpitEmailNotifier(mailpitEndpoint, smtp_transport.SecurityStartTLS)
+
+ err := notifier.Send(encryption.GetFieldEncryptor(), logger.GetLogger(), newBackupNotification())
+
+ require.ErrorIs(t, err, smtp_transport.ErrStartTLSNotOffered)
+}
+
+func newMailpitEmailNotifier(
+ mailpitEndpoint containers.MailpitEndpoint,
+ security smtp_transport.Security,
+) *EmailNotifier {
+ return &EmailNotifier{
NotifierID: uuid.New(),
- TargetEmail: "[email protected]",
- SMTPHost: "smtp.example.com>\r\nX-Injected: 1",
- SMTPPort: 587,
+ TargetEmail: "[email protected]",
+ SMTPHost: mailpitEndpoint.SMTP.Host,
+ SMTPPort: mailpitEndpoint.SMTP.Port,
+ Security: security,
}
+}
- content := string(notifier.buildEmailContent("subject", "<p>body</p>", "[email protected]"))
-
- if strings.Contains(content, "\r\nX-Injected:") || strings.Contains(content, "\nX-Injected:") {
- t.Errorf("injected header line leaked via SMTPHost: %q", content)
+func newBackupNotification() notifier_models.Notification {
+ return notifier_models.Notification{
+ Type: notifier_models.NotificationTypeAll,
+ Heading: "Backup completed",
+ Message: "<b>All good</b>",
}
}
diff --git a/backend/internal/features/notifiers/service.go b/backend/internal/features/notifiers/service.go
index c19b771c..5f9e90e9 100644
--- a/backend/internal/features/notifiers/service.go
+++ b/backend/internal/features/notifiers/service.go
@@ -92,6 +92,7 @@ func (s *NotifierService) SaveNotifier(
}
} else {
notifier.WorkspaceID = workspaceID
+ notifier.FillDefaults()
if err := notifier.EncryptSensitiveData(s.fieldEncryptor); err != nil {
return err
@@ -272,6 +273,8 @@ func (s *NotifierService) SendTestNotificationToNotifier(
usingNotifier = existingNotifier
} else {
+ notifier.FillDefaults()
+
if err := notifier.EncryptSensitiveData(s.fieldEncryptor); err != nil {
return err
}
diff --git a/backend/internal/features/users/controllers/di.go b/backend/internal/features/users/controllers/di.go
index 6ed9b72d..78fb7771 100644
--- a/backend/internal/features/users/controllers/di.go
+++ b/backend/internal/features/users/controllers/di.go
@@ -14,6 +14,8 @@ var userController = &UserController{
var settingsController = &SettingsController{
users_services.GetSettingsService(),
+ ratelimiter.GetCounter(),
+ logger.GetLogger(),
}
var managementController = &ManagementController{
diff --git a/backend/internal/features/users/controllers/rate_limit.go b/backend/internal/features/users/controllers/rate_limit.go
new file mode 100644
index 00000000..956b9423
--- /dev/null
+++ b/backend/internal/features/users/controllers/rate_limit.go
@@ -0,0 +1,34 @@
+package users_controllers
+
+import (
+ "log/slog"
+ "net/http"
+
+ "github.com/gin-gonic/gin"
+
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+func checkRateLimitOrRespond(
+ ctx *gin.Context,
+ rateLimiter ratelimiter.Counter,
+ logger *slog.Logger,
+ attempt ratelimiter.Attempt,
+) bool {
+ isAllowed, err := rateLimiter.RecordAttemptAndCheckIsAllowed(ctx.Request.Context(), attempt)
+ if err != nil {
+ logger.ErrorContext(ctx.Request.Context(), "failed to evaluate a rate limit",
+ "scope", attempt.Scope, "error", err)
+ }
+
+ if err != nil || !isAllowed {
+ ctx.JSON(
+ http.StatusTooManyRequests,
+ gin.H{"error": "Rate limit exceeded. Please try again later.", "code": "rate_limit_exceeded"},
+ )
+
+ return false
+ }
+
+ return true
+}
diff --git a/backend/internal/features/users/controllers/settings_controller.go b/backend/internal/features/users/controllers/settings_controller.go
index b75a2446..9136140d 100644
--- a/backend/internal/features/users/controllers/settings_controller.go
+++ b/backend/internal/features/users/controllers/settings_controller.go
@@ -1,18 +1,31 @@
package users_controllers
import (
+ "errors"
+ "log/slog"
"net/http"
+ "time"
"github.com/gin-gonic/gin"
users_dto "databasus-backend/internal/features/users/dto"
user_enums "databasus-backend/internal/features/users/enums"
+ users_errors "databasus-backend/internal/features/users/errors"
user_middleware "databasus-backend/internal/features/users/middleware"
users_services "databasus-backend/internal/features/users/services"
+ "databasus-backend/internal/util/ratelimiter"
+)
+
+const (
+ testEmailRateLimitScope = "test-email"
+ testEmailRateLimit = 5
+ testEmailRateLimitWindow = 10 * time.Minute
)
type SettingsController struct {
settingsService *users_services.SettingsService
+ rateLimiter ratelimiter.Counter
+ logger *slog.Logger
}
func (c *SettingsController) RegisterRoutes(router *gin.RouterGroup) {
@@ -22,11 +35,16 @@ func (c *SettingsController) RegisterRoutes(router *gin.RouterGroup) {
user_middleware.RequireRole(user_enums.UserRoleAdmin),
c.UpdateUsersSettings,
)
+ router.POST(
+ "/users/settings/test-email",
+ user_middleware.RequireRole(user_enums.UserRoleAdmin),
+ c.SendTestEmail,
+ )
}
// GetUsersSettings
// @Summary Get users settings
-// @Description Get global users settings (admin only)
+// @Description Get global users settings. Every signed-in user can read them, because the main screen and the workspace dialogs depend on them
// @Tags settings
// @Produce json
// @Security BearerAuth
@@ -81,3 +99,45 @@ func (c *SettingsController) UpdateUsersSettings(ctx *gin.Context) {
ctx.JSON(http.StatusOK, settings)
}
+
+// SendTestEmail
+// @Summary Send a test email
+// @Description Send a test message through the instance mail server to the signed-in administrator's own address (admin only). A failed delivery answers 400 with the mail server's error and no code
+// @Tags settings
+// @Produce json
+// @Security BearerAuth
+// @Success 200 {object} users_dto.SendTestEmailResponseDTO
+// @Failure 400 {object} map[string]string "Mail server not configured, no usable address, or delivery failed"
+// @Failure 401 {object} map[string]string "Unauthorized"
+// @Failure 403 {object} map[string]string "Forbidden"
+// @Failure 429 {object} map[string]string "Rate limit exceeded"
+// @Router /users/settings/test-email [post]
+func (c *SettingsController) SendTestEmail(ctx *gin.Context) {
+ user, ok := user_middleware.GetUserFromContext(ctx)
+ if !ok {
+ ctx.JSON(http.StatusUnauthorized, gin.H{"error": "User not authenticated"})
+ return
+ }
+
+ if !checkRateLimitOrRespond(ctx, c.rateLimiter, c.logger, ratelimiter.Attempt{
+ Scope: testEmailRateLimitScope,
+ Identifier: user.ID.String(),
+ Limit: testEmailRateLimit,
+ Window: testEmailRateLimitWindow,
+ }) {
+ return
+ }
+
+ recipientEmail, err := c.settingsService.SendTestEmail(ctx.Request.Context(), user)
+
+ switch {
+ case errors.Is(err, users_errors.ErrEmailNotConfigured):
+ respondWithCode(ctx, http.StatusBadRequest, err, "email_not_configured")
+ case errors.Is(err, users_errors.ErrAdminEmailMissing):
+ respondWithCode(ctx, http.StatusBadRequest, err, "admin_email_missing")
+ case err != nil:
+ ctx.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
+ default:
+ ctx.JSON(http.StatusOK, users_dto.SendTestEmailResponseDTO{RecipientEmail: recipientEmail})
+ }
+}
diff --git a/backend/internal/features/users/controllers/settings_controller_test.go b/backend/internal/features/users/controllers/settings_controller_test.go
index e05c7326..61359390 100644
--- a/backend/internal/features/users/controllers/settings_controller_test.go
+++ b/backend/internal/features/users/controllers/settings_controller_test.go
@@ -457,3 +457,96 @@ func countAuditEntries(recorder *users_testing.RecordingAuditLogWriter, fragment
return count
}
+
+func Test_SendTestEmail_WhenAdminHasAddress_SendsToAdminAndAuditsDelivery(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, false)
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ var response users_dto.SendTestEmailResponseDTO
+ test_utils.MakePostRequestAndUnmarshal(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+admin.Token, nil, http.StatusOK, &response,
+ )
+
+ assert.Equal(t, admin.Email, response.RecipientEmail)
+ require.Len(t, mockEmailSender.SentEmails, 1)
+ assert.Equal(t, admin.Email, mockEmailSender.SentEmails[0].To)
+ assert.True(t, users_testing.GetAuditLogRecorder().HasEntryContaining("Test email sent to", admin.Email))
+}
+
+func Test_SendTestEmail_WhenUserIsMember_ReturnsForbiddenAndSendsNothing(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, false)
+ member := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleMember)
+
+ test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+member.Token, nil, http.StatusForbidden,
+ )
+
+ assert.Empty(t, mockEmailSender.SentEmails)
+}
+
+func Test_SendTestEmail_WhenMailServerIsMissing_RefusesWithCodeAndSendsNothing(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, true)
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ response := test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+admin.Token, nil, http.StatusBadRequest,
+ )
+
+ assert.Equal(t, "email_not_configured", readErrorCode(t, response))
+ assert.Empty(t, mockEmailSender.SentEmails)
+}
+
+func Test_SendTestEmail_WhenAdminHasBootstrapLogin_RefusesWithCodeAndSendsNothing(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, false)
+ bootstrapAdmin := users_testing.CreateTestUserWithEmail(t.Context(), users_enums.UserRoleAdmin, "admin")
+ t.Cleanup(func() { users_testing.DeleteTestUser(context.Background(), bootstrapAdmin.UserID) })
+
+ response := test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+bootstrapAdmin.Token, nil, http.StatusBadRequest,
+ )
+
+ assert.Equal(t, "admin_email_missing", readErrorCode(t, response))
+ assert.Empty(t, mockEmailSender.SentEmails)
+}
+
+func Test_SendTestEmail_SixthRequestWithinWindow_ReturnsTooManyRequests(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, false)
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ for range 5 {
+ test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+admin.Token, nil, http.StatusOK,
+ )
+ }
+
+ test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+admin.Token, nil, http.StatusTooManyRequests,
+ )
+
+ assert.Len(t, mockEmailSender.SentEmails, 5)
+}
+
+func Test_SendTestEmail_WhenDeliveryFails_ReturnsSenderErrorAndAuditsFailure(t *testing.T) {
+ router, mockEmailSender := createSettingsTestRouterWithMailSender(t, false)
+ mockEmailSender.ShouldFail = true
+ admin := users_testing.CreateTestUser(t.Context(), users_enums.UserRoleAdmin)
+
+ response := test_utils.MakePostRequest(
+ t, router, "/api/v1/users/settings/test-email", "Bearer "+admin.Token, nil, http.StatusBadRequest,
+ )
+
+ assert.Contains(t, string(response.Body), "mock email send failure")
+ assert.Empty(t, readErrorCode(t, response))
+ assert.True(t, users_testing.GetAuditLogRecorder().HasEntryContaining("Test email to", admin.Email, "failed"))
+}
+
+func readErrorCode(t *testing.T, response *test_utils.TestResponse) string {
+ t.Helper()
+
+ var errorResponse struct {
+ Code string `json:"code"`
+ }
+ require.NoError(t, json.Unmarshal(response.Body, &errorResponse))
+
+ return errorResponse.Code
+}
diff --git a/backend/internal/features/users/controllers/two_factor_controller.go b/backend/internal/features/users/controllers/two_factor_controller.go
index a4606f4b..bdf2bd0a 100644
--- a/backend/internal/features/users/controllers/two_factor_controller.go
+++ b/backend/internal/features/users/controllers/two_factor_controller.go
@@ -39,7 +39,7 @@ func (c *UserController) VerifySignInCode(ctx *gin.Context) {
return
}
- if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ if !checkRateLimitOrRespond(ctx, c.rateLimiter, c.logger, ratelimiter.Attempt{
Scope: signInCodeVerificationScope,
Identifier: request.PendingSignInID.String(),
Limit: signInCodeVerificationLimit,
diff --git a/backend/internal/features/users/controllers/user_controller.go b/backend/internal/features/users/controllers/user_controller.go
index ac5f333f..7c8aa37d 100644
--- a/backend/internal/features/users/controllers/user_controller.go
+++ b/backend/internal/features/users/controllers/user_controller.go
@@ -106,7 +106,7 @@ func (c *UserController) SignIn(ctx *gin.Context) {
return
}
- if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ if !checkRateLimitOrRespond(ctx, c.rateLimiter, c.logger, ratelimiter.Attempt{
Scope: "signin",
Identifier: request.Email,
Limit: 10,
@@ -379,7 +379,7 @@ func (c *UserController) SendResetPasswordCode(ctx *gin.Context) {
return
}
- if !c.checkRateLimitOrRespond(ctx, ratelimiter.Attempt{
+ if !checkRateLimitOrRespond(ctx, c.rateLimiter, c.logger, ratelimiter.Attempt{
Scope: "reset-password",
Identifier: request.Email,
Limit: 3,
@@ -423,25 +423,6 @@ func (c *UserController) ResetPassword(ctx *gin.Context) {
ctx.JSON(http.StatusOK, gin.H{"message": "Password reset successfully"})
}
-func (c *UserController) checkRateLimitOrRespond(ctx *gin.Context, attempt ratelimiter.Attempt) bool {
- isAllowed, err := c.rateLimiter.RecordAttemptAndCheckIsAllowed(ctx.Request.Context(), attempt)
- if err != nil {
- c.logger.ErrorContext(ctx.Request.Context(), "failed to evaluate a rate limit",
- "scope", attempt.Scope, "error", err)
- }
-
- if err != nil || !isAllowed {
- ctx.JSON(
- http.StatusTooManyRequests,
- gin.H{"error": "Rate limit exceeded. Please try again later.", "code": "rate_limit_exceeded"},
- )
-
- return false
- }
-
- return true
-}
-
// Each refusal carries a code, because the status alone does not tell the
// interface what happened: a wrong code and a failed challenge are both 400, and
// a resend inside its minute and an exhausted hourly cap are both 429.
diff --git a/backend/internal/features/users/dto/dto.go b/backend/internal/features/users/dto/dto.go
index 7782b58f..16268c5f 100644
--- a/backend/internal/features/users/dto/dto.go
+++ b/backend/internal/features/users/dto/dto.go
@@ -151,6 +151,10 @@ type SettingsResponseDTO struct {
IsEmailConfigured bool `json:"isEmailConfigured"`
}
+type SendTestEmailResponseDTO struct {
+ RecipientEmail string `json:"recipientEmail"`
+}
+
type UpdateSettingsRequestDTO struct {
IsAllowExternalRegistrations bool `json:"isAllowExternalRegistrations"`
IsAllowMemberInvitations bool `json:"isAllowMemberInvitations"`
diff --git a/backend/internal/features/users/errors/errors.go b/backend/internal/features/users/errors/errors.go
index 08d9d1ea..a7dd06a0 100644
--- a/backend/internal/features/users/errors/errors.go
+++ b/backend/internal/features/users/errors/errors.go
@@ -4,6 +4,11 @@ import "errors"
var ErrInsufficientPermissionsToInviteUsers = errors.New("insufficient permissions to invite users")
+var (
+ ErrEmailNotConfigured = errors.New("the instance has no mail server configured")
+ ErrAdminEmailMissing = errors.New("your account has no valid email address to send a test email to")
+)
+
var (
// The instance could not deliver the code, so it admits nobody through
// password sign-in while the second factor is on.
diff --git a/backend/internal/features/users/interfaces/interfaces.go b/backend/internal/features/users/interfaces/interfaces.go
index 818cdeab..cb728f9e 100644
--- a/backend/internal/features/users/interfaces/interfaces.go
+++ b/backend/internal/features/users/interfaces/interfaces.go
@@ -14,5 +14,5 @@ type EmailSender interface {
// SendEmail reports no error when the instance has no mail server, so a
// caller that must not admit a silent skip asks this first.
IsConfigured() bool
- SendEmail(to, subject, body string) error
+ SendEmail(ctx context.Context, to, subject, body string) error
}
diff --git a/backend/internal/features/users/services/settings_service.go b/backend/internal/features/users/services/settings_service.go
index 51577a02..b3cba57a 100644
--- a/backend/internal/features/users/services/settings_service.go
+++ b/backend/internal/features/users/services/settings_service.go
@@ -8,9 +8,16 @@ import (
audit_logs_models "databasus-backend/internal/features/audit_logs/models"
users_dto "databasus-backend/internal/features/users/dto"
+ users_errors "databasus-backend/internal/features/users/errors"
users_interfaces "databasus-backend/internal/features/users/interfaces"
users_models "databasus-backend/internal/features/users/models"
users_repositories "databasus-backend/internal/features/users/repositories"
+ "databasus-backend/internal/util/smtp_transport"
+)
+
+const (
+ testEmailSubject = "Databasus test email"
+ testEmailBody = `<p>This message confirms that Databasus can deliver email through its mail server.</p>`
)
// The gate and the profile form must not disagree about what counts as an
@@ -53,6 +60,31 @@ func (s *SettingsService) IsEmailConfigured() bool {
return s.emailSender != nil && s.emailSender.IsConfigured()
}
+func (s *SettingsService) SendTestEmail(ctx context.Context, admin *users_models.User) (string, error) {
+ if !s.IsEmailConfigured() {
+ return "", users_errors.ErrEmailNotConfigured
+ }
+
+ if !isDeliverableAddress(admin.Email) {
+ return "", users_errors.ErrAdminEmailMissing
+ }
+
+ sendError := s.emailSender.SendEmail(ctx, admin.Email, testEmailSubject, testEmailBody)
+
+ auditMessage := fmt.Sprintf("Test email sent to %s", admin.Email)
+ if sendError != nil {
+ auditMessage = fmt.Sprintf("Test email to %s failed", admin.Email)
+ }
+
+ s.writeAuditLog(ctx, audit_logs_models.AuditEntry{Message: auditMessage, UserID: &admin.ID})
+
+ if sendError != nil {
+ return "", sendError
+ }
+
+ return admin.Email, nil
+}
+
func (s *SettingsService) UpdateSettings(
ctx context.Context,
request users_dto.UpdateSettingsRequestDTO,
@@ -195,6 +227,18 @@ func (s *SettingsService) checkCodesCanReachEveryAdmin(ctx context.Context) erro
return nil
}
+// The validator keeps agreement with the profile form, and the transport's parser
+// keeps an address it would refuse from surfacing as a delivery failure.
+func isDeliverableAddress(address string) bool {
+ if addressValidator.Var(address, "required,email") != nil {
+ return false
+ }
+
+ _, err := smtp_transport.ParseRecipient(address)
+
+ return err == nil
+}
+
func (s *SettingsService) buildSettingsResponse(
settings *users_models.UsersSettings,
) *users_dto.SettingsResponseDTO {
diff --git a/backend/internal/features/users/services/two_factor_auth.go b/backend/internal/features/users/services/two_factor_auth.go
index 93586206..559c479d 100644
--- a/backend/internal/features/users/services/two_factor_auth.go
+++ b/backend/internal/features/users/services/two_factor_auth.go
@@ -243,7 +243,7 @@ func (s *UserService) issueTwoFactorCode(
}
}
- if err := s.emailSender.SendEmail(user.Email, twoFactorCodeSubject, twoFactorCodeBody(code)); err != nil {
+ if err := s.emailSender.SendEmail(ctx, user.Email, twoFactorCodeSubject, twoFactorCodeBody(code)); err != nil {
s.logger.ErrorContext(ctx, "failed to send the sign-in code", "user_id", user.ID, "error", err)
if markErr := s.twoFactorRepository.MarkCodeAsUsed(ctx, pendingCode.ID); markErr != nil {
diff --git a/backend/internal/features/users/services/user_services.go b/backend/internal/features/users/services/user_services.go
index d3116690..7b640d41 100644
--- a/backend/internal/features/users/services/user_services.go
+++ b/backend/internal/features/users/services/user_services.go
@@ -591,7 +591,7 @@ func (s *UserService) SendResetPasswordCode(ctx context.Context, email string) e
</html>
`, code)
- if err := s.emailSender.SendEmail(user.Email, subject, body); err != nil {
+ if err := s.emailSender.SendEmail(ctx, user.Email, subject, body); err != nil {
return fmt.Errorf("failed to send email: %w", err)
}
}
diff --git a/backend/internal/features/users/testing/mocks.go b/backend/internal/features/users/testing/mocks.go
index 450dceee..e6913cf3 100644
--- a/backend/internal/features/users/testing/mocks.go
+++ b/backend/internal/features/users/testing/mocks.go
@@ -1,6 +1,7 @@
package users_testing
import (
+ "context"
"errors"
"sync"
)
@@ -31,7 +32,7 @@ func (m *MockEmailSender) IsConfigured() bool {
return !m.IsMailServerMissing
}
-func (m *MockEmailSender) SendEmail(to, subject, body string) error {
+func (m *MockEmailSender) SendEmail(_ context.Context, to, subject, body string) error {
m.sentEmailsMutex.Lock()
defer m.sentEmailsMutex.Unlock()
diff --git a/backend/internal/features/workspaces/interfaces/interfaces.go b/backend/internal/features/workspaces/interfaces/interfaces.go
index 47fa883a..7013af48 100644
--- a/backend/internal/features/workspaces/interfaces/interfaces.go
+++ b/backend/internal/features/workspaces/interfaces/interfaces.go
@@ -1,11 +1,15 @@
package workspaces_interfaces
-import "github.com/google/uuid"
+import (
+ "context"
+
+ "github.com/google/uuid"
+)
type WorkspaceDeletionListener interface {
OnBeforeWorkspaceDeletion(workspaceID uuid.UUID) error
}
type EmailSender interface {
- SendEmail(to, subject, body string) error
+ SendEmail(ctx context.Context, to, subject, body string) error
}
diff --git a/backend/internal/features/workspaces/services/membership_service.go b/backend/internal/features/workspaces/services/membership_service.go
index dccdafaf..e5b8ebe7 100644
--- a/backend/internal/features/workspaces/services/membership_service.go
+++ b/backend/internal/features/workspaces/services/membership_service.go
@@ -107,7 +107,7 @@ func (s *MembershipService) AddMember(
subject := fmt.Sprintf("You've been invited to %s workspace", workspace.Name)
body := s.buildInvitationEmailHTML(workspace.Name, addedBy.Name, string(request.Role))
- if err := s.emailSender.SendEmail(request.Email, subject, body); err != nil {
+ if err := s.emailSender.SendEmail(ctx, request.Email, subject, body); err != nil {
s.logger.ErrorContext(ctx, "failed to send invitation email", "email", request.Email, "error", err)
}
diff --git a/backend/internal/features/workspaces/testing/mocks.go b/backend/internal/features/workspaces/testing/mocks.go
index 3c9477f5..900ac07d 100644
--- a/backend/internal/features/workspaces/testing/mocks.go
+++ b/backend/internal/features/workspaces/testing/mocks.go
@@ -1,6 +1,9 @@
package workspaces_testing
-import "errors"
+import (
+ "context"
+ "errors"
+)
type MockEmailSender struct {
SendEmailCalls []EmailCall
@@ -20,7 +23,7 @@ func NewMockEmailSender() *MockEmailSender {
}
}
-func (m *MockEmailSender) SendEmail(to, subject, body string) error {
+func (m *MockEmailSender) SendEmail(_ context.Context, to, subject, body string) error {
m.SendEmailCalls = append(m.SendEmailCalls, EmailCall{
To: to,
Subject: subject,
diff --git a/backend/internal/util/smtp_transport/address.go b/backend/internal/util/smtp_transport/address.go
new file mode 100644
index 00000000..7ec9b88e
--- /dev/null
+++ b/backend/internal/util/smtp_transport/address.go
@@ -0,0 +1,52 @@
+package smtp_transport
+
+import (
+ "fmt"
+ "net/mail"
+)
+
+const defaultSenderName = "Databasus"
+
+func ParseSender(value string) (*mail.Address, error) {
+ sender, err := mail.ParseAddress(value)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrInvalidSender, err)
+ }
+
+ if sender.Name == "" {
+ sender.Name = defaultSenderName
+ }
+
+ return sender, nil
+}
+
+func ResolveSender(from, username, host string) (*mail.Address, error) {
+ if from != "" {
+ return ParseSender(from)
+ }
+
+ if isBareAddress(username) {
+ return ParseSender(username)
+ }
+
+ return ParseSender("noreply@" + host)
+}
+
+func ParseRecipient(value string) (*mail.Address, error) {
+ recipient, err := mail.ParseAddress(value)
+ if err != nil {
+ return nil, fmt.Errorf("%w: %w", ErrInvalidRecipient, err)
+ }
+
+ if recipient.Name != "" {
+ return nil, ErrInvalidRecipient
+ }
+
+ return recipient, nil
+}
+
+func isBareAddress(value string) bool {
+ address, err := mail.ParseAddress(value)
+
+ return err == nil && address.Name == "" && address.Address == value
+}
diff --git a/backend/internal/util/smtp_transport/address_test.go b/backend/internal/util/smtp_transport/address_test.go
new file mode 100644
index 00000000..5a362769
--- /dev/null
+++ b/backend/internal/util/smtp_transport/address_test.go
@@ -0,0 +1,97 @@
+package smtp_transport
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_ParseSender_WithSupportedAndUnsupportedForms_ParsesOrRejects(t *testing.T) {
+ testCases := []struct {
+ value string
+ expectedName string
+ expectedAddress string
+ isRejected bool
+ }{
+ {"[email protected]", "Databasus", "[email protected]", false},
+ {"Acme Backups <[email protected]>", "Acme Backups", "[email protected]", false},
+ {`"Acme, Inc." <[email protected]>`, "Acme, Inc.", "[email protected]", false},
+ {"ops at example", "", "", true},
+ {"noreply at example.com", "", "", true},
+ {"", "", "", true},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.value, func(t *testing.T) {
+ sender, err := ParseSender(testCase.value)
+
+ if testCase.isRejected {
+ require.ErrorIs(t, err, ErrInvalidSender)
+ return
+ }
+
+ require.NoError(t, err)
+ assert.Equal(t, testCase.expectedName, sender.Name)
+ assert.Equal(t, testCase.expectedAddress, sender.Address)
+ })
+ }
+}
+
+func Test_ResolveSender_FallsBackFromSenderToAddressUsernameToHost(t *testing.T) {
+ testCases := []struct {
+ name string
+ from string
+ username string
+ expectedAddress string
+ }{
+ {"explicit sender wins", "Ops <[email protected]>", "[email protected]", "[email protected]"},
+ {"username that is an address", "", "[email protected]", "[email protected]"},
+ {"username apikey", "", "apikey", "[email protected]"},
+ {"access key ID username", "", "AKIAIOSFODNN7EXAMPLE", "[email protected]"},
+ {"username with a display name", "", "Mailer <[email protected]>", "[email protected]"},
+ {"no username", "", "", "[email protected]"},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ sender, err := ResolveSender(testCase.from, testCase.username, "smtp.sendgrid.net")
+
+ require.NoError(t, err)
+ assert.Equal(t, testCase.expectedAddress, sender.Address)
+ })
+ }
+}
+
+func Test_ResolveSender_WithUnreadableExplicitSender_Fails(t *testing.T) {
+ _, err := ResolveSender("ops at example", "[email protected]", "smtp.example.com")
+
+ require.ErrorIs(t, err, ErrInvalidSender)
+}
+
+func Test_ParseRecipient_AcceptsOnlyBareAddress(t *testing.T) {
+ testCases := []struct {
+ value string
+ isRejected bool
+ }{
+ {"[email protected]", false},
+ {"Admin <[email protected]>", true},
+ {"ops at example", true},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.value, func(t *testing.T) {
+ _, err := ParseRecipient(testCase.value)
+
+ if testCase.isRejected {
+ require.ErrorIs(t, err, ErrInvalidRecipient)
+ return
+ }
+
+ require.NoError(t, err)
+ })
+ }
+}
diff --git a/backend/internal/util/smtp_transport/auth.go b/backend/internal/util/smtp_transport/auth.go
new file mode 100644
index 00000000..f97b2350
--- /dev/null
+++ b/backend/internal/util/smtp_transport/auth.go
@@ -0,0 +1,97 @@
+package smtp_transport
+
+import (
+ "fmt"
+ "net/smtp"
+ "slices"
+ "strings"
+)
+
+const (
+ mechanismPlain = "PLAIN"
+ mechanismLogin = "LOGIN"
+)
+
+var (
+ loginUsernamePrompts = []string{"username:", "user name"}
+ loginPasswordPrompts = []string{"password:", "password"}
+)
+
+type credentials struct {
+ username string
+ password string
+ isUnencryptedAuthOptIn bool
+}
+
+// plainAuth replaces smtp.PlainAuth, which decides by host name whether an unencrypted
+// connection is acceptable. Here the operator's security mode decides.
+type plainAuth struct {
+ credentials
+}
+
+type loginAuth struct {
+ credentials
+}
+
+func chooseAuth(offeredMechanisms string, userCredentials credentials) (smtp.Auth, string, error) {
+ mechanisms := strings.Fields(strings.ToUpper(offeredMechanisms))
+
+ if slices.Contains(mechanisms, mechanismPlain) {
+ return &plainAuth{userCredentials}, mechanismPlain, nil
+ }
+
+ if slices.Contains(mechanisms, mechanismLogin) {
+ return &loginAuth{userCredentials}, mechanismLogin, nil
+ }
+
+ return nil, "", ErrAuthMechanismNotOffered
+}
+
+func (c credentials) checkConnectionEncryption(server *smtp.ServerInfo) error {
+ if !server.TLS && !c.isUnencryptedAuthOptIn {
+ return ErrUnencryptedAuth
+ }
+
+ return nil
+}
+
+func (a *plainAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
+ if err := a.checkConnectionEncryption(server); err != nil {
+ return "", nil, err
+ }
+
+ return mechanismPlain, []byte("\x00" + a.username + "\x00" + a.password), nil
+}
+
+func (a *plainAuth) Next(_ []byte, isMoreExpected bool) ([]byte, error) {
+ if isMoreExpected {
+ return nil, fmt.Errorf("unexpected server challenge during %s authentication", mechanismPlain)
+ }
+
+ return nil, nil
+}
+
+func (a *loginAuth) Start(server *smtp.ServerInfo) (string, []byte, error) {
+ if err := a.checkConnectionEncryption(server); err != nil {
+ return "", nil, err
+ }
+
+ return mechanismLogin, nil, nil
+}
+
+func (a *loginAuth) Next(serverPrompt []byte, isMoreExpected bool) ([]byte, error) {
+ if !isMoreExpected {
+ return nil, nil
+ }
+
+ normalizedPrompt := strings.ToLower(strings.TrimRight(string(serverPrompt), "\x00"))
+
+ switch {
+ case slices.Contains(loginUsernamePrompts, normalizedPrompt):
+ return []byte(a.username), nil
+ case slices.Contains(loginPasswordPrompts, normalizedPrompt):
+ return []byte(a.password), nil
+ default:
+ return nil, fmt.Errorf("%w: %q", ErrUnknownLoginPrompt, serverPrompt)
+ }
+}
diff --git a/backend/internal/util/smtp_transport/auth_test.go b/backend/internal/util/smtp_transport/auth_test.go
new file mode 100644
index 00000000..8359654d
--- /dev/null
+++ b/backend/internal/util/smtp_transport/auth_test.go
@@ -0,0 +1,99 @@
+package smtp_transport
+
+import (
+ "net/smtp"
+ "slices"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_Send_WhenServerOffersPlainAndLogin_UsesPlain(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismLogin, mechanismPlain}})
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ authCommandIndex := slices.Index(server.getCommandVerbs(), "AUTH")
+ require.GreaterOrEqual(t, authCommandIndex, 0)
+ assert.True(t, strings.HasPrefix(server.getCommands()[authCommandIndex], "AUTH PLAIN "))
+}
+
+func Test_Send_WhenServerOffersOnlyLogin_AnswersKnownPromptsRegardlessOfCase(t *testing.T) {
+ promptSets := [][2]string{
+ {"Username:", "Password:"},
+ {"User Name\x00", "Password\x00"},
+ {"USERNAME:", "password:"},
+ }
+
+ for _, prompts := range promptSets {
+ t.Run(prompts[0], func(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ authMechanisms: []string{mechanismLogin},
+ loginPrompts: prompts,
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ assert.Contains(t, server.getCommands(), "AUTH LOGIN")
+ assert.Len(t, server.getMessages(), 1)
+ })
+ }
+}
+
+func Test_Send_WhenLoginPromptIsUnknown_FailsWithoutGuessing(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ authMechanisms: []string{mechanismLogin},
+ loginPrompts: [2]string{"Secret:", "Password:"},
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+ require.ErrorIs(t, err, ErrUnknownLoginPrompt)
+
+ server.waitForSessionEnd(t)
+ assert.Empty(t, server.getMessages())
+}
+
+func Test_Send_WhenServerRejectsCredentials_ErrorCarriesResponseButNotPassword(t *testing.T) {
+ for _, mechanism := range []string{mechanismPlain, mechanismLogin} {
+ t.Run(mechanism, func(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanism}})
+
+ rejectedConnection := server.getConnection(SecurityNone)
+ rejectedConnection.Password = "wrong-password-value"
+
+ err := Send(t.Context(), rejectedConnection, newTestMessage(t))
+ require.Error(t, err)
+
+ assert.Contains(t, err.Error(), "535")
+ assert.Contains(t, err.Error(), "Authentication credentials invalid")
+ assert.Contains(t, err.Error(), mechanism)
+ assert.NotContains(t, err.Error(), "wrong-password-value")
+ })
+ }
+}
+
+func Test_Send_WhenServerOffersNoKnownMechanism_Fails(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{"CRAM-MD5"}})
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+
+ require.ErrorIs(t, err, ErrAuthMechanismNotOffered)
+}
+
+func Test_Auth_OnUnencryptedConnectionWithoutOptIn_Refuses(t *testing.T) {
+ unencryptedServer := &smtp.ServerInfo{Name: "relay.example.com", TLS: false}
+ userCredentials := credentials{fakeServerUsername, fakeServerPassword, false}
+
+ for _, auth := range []smtp.Auth{&plainAuth{userCredentials}, &loginAuth{userCredentials}} {
+ _, initialResponse, err := auth.Start(unencryptedServer)
+
+ require.ErrorIs(t, err, ErrUnencryptedAuth)
+ assert.Empty(t, initialResponse)
+ }
+}
diff --git a/backend/internal/util/smtp_transport/enums.go b/backend/internal/util/smtp_transport/enums.go
new file mode 100644
index 00000000..44663657
--- /dev/null
+++ b/backend/internal/util/smtp_transport/enums.go
@@ -0,0 +1,28 @@
+package smtp_transport
+
+type Security string
+
+const (
+ SecurityTLS Security = "tls"
+ SecurityStartTLS Security = "starttls"
+ SecurityNone Security = "none"
+)
+
+func (s Security) IsValid() bool {
+ switch s {
+ case SecurityTLS, SecurityStartTLS, SecurityNone:
+ return true
+ default:
+ return false
+ }
+}
+
+const implicitTLSPort = 465
+
+func GetDefaultSecurityForPort(port int) Security {
+ if port == implicitTLSPort {
+ return SecurityTLS
+ }
+
+ return SecurityStartTLS
+}
diff --git a/backend/internal/util/smtp_transport/enums_test.go b/backend/internal/util/smtp_transport/enums_test.go
new file mode 100644
index 00000000..f87c8e19
--- /dev/null
+++ b/backend/internal/util/smtp_transport/enums_test.go
@@ -0,0 +1,14 @@
+package smtp_transport
+
+import (
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func Test_GetDefaultSecurityForPort_ReturnsTLSOnlyForPort465(t *testing.T) {
+ assert.Equal(t, SecurityTLS, GetDefaultSecurityForPort(465))
+ assert.Equal(t, SecurityStartTLS, GetDefaultSecurityForPort(587))
+ assert.Equal(t, SecurityStartTLS, GetDefaultSecurityForPort(25))
+ assert.Equal(t, SecurityStartTLS, GetDefaultSecurityForPort(2525))
+}
diff --git a/backend/internal/util/smtp_transport/errors.go b/backend/internal/util/smtp_transport/errors.go
new file mode 100644
index 00000000..655b3f55
--- /dev/null
+++ b/backend/internal/util/smtp_transport/errors.go
@@ -0,0 +1,17 @@
+package smtp_transport
+
+import "errors"
+
+var (
+ ErrUnknownSecurity = errors.New("unknown SMTP security mode, expected tls, starttls or none")
+ ErrStartTLSNotOffered = errors.New("SMTP server does not offer STARTTLS")
+ ErrAuthMechanismNotOffered = errors.New("SMTP server offers neither PLAIN nor LOGIN authentication")
+ ErrUnencryptedAuth = errors.New("refusing to authenticate over an unencrypted SMTP connection")
+ ErrUnknownLoginPrompt = errors.New("unexpected LOGIN authentication prompt from SMTP server")
+ ErrSessionTimeout = errors.New("SMTP session timed out")
+ ErrInvalidSender = errors.New("sender must be an email address, optionally preceded by a display name")
+ ErrInvalidRecipient = errors.New("recipient must be a single email address")
+ ErrInvalidHeloName = errors.New(
+ "greeting name must be a host name or an address literal such as [192.0.2.1]",
+ )
+)
diff --git a/backend/internal/util/smtp_transport/fake_server_test.go b/backend/internal/util/smtp_transport/fake_server_test.go
new file mode 100644
index 00000000..9f884357
--- /dev/null
+++ b/backend/internal/util/smtp_transport/fake_server_test.go
@@ -0,0 +1,323 @@
+package smtp_transport
+
+import (
+ "bufio"
+ "crypto/ecdsa"
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/tls"
+ "crypto/x509"
+ "crypto/x509/pkix"
+ "encoding/base64"
+ "io"
+ "math/big"
+ "net"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/require"
+)
+
+const (
+ fakeServerUsername = "mailer"
+ fakeServerPassword = "correct-horse-battery-staple"
+)
+
+type fakeServerOptions struct {
+ implicitTLSConfig *tls.Config
+ startTLSConfig *tls.Config
+ authMechanisms []string
+ loginPrompts [2]string
+ isSilentAfterGreeting bool
+}
+
+type fakeServer struct {
+ host string
+ port int
+ options fakeServerOptions
+ mutex sync.Mutex
+ commands []string
+ messages []string
+ sessionsEnded chan struct{}
+}
+
+func startFakeServer(t *testing.T, options fakeServerOptions) *fakeServer {
+ t.Helper()
+
+ if options.loginPrompts == [2]string{} {
+ options.loginPrompts = [2]string{"Username:", "Password:"}
+ }
+
+ var listener net.Listener
+ var err error
+
+ if options.implicitTLSConfig != nil {
+ listener, err = tls.Listen("tcp", "127.0.0.1:0", options.implicitTLSConfig)
+ } else {
+ listener, err = net.Listen("tcp", "127.0.0.1:0")
+ }
+ require.NoError(t, err)
+ t.Cleanup(func() { _ = listener.Close() })
+
+ listenerAddress := listener.Addr().(*net.TCPAddr)
+ server := &fakeServer{
+ host: listenerAddress.IP.String(),
+ port: listenerAddress.Port,
+ options: options,
+ sessionsEnded: make(chan struct{}, 16),
+ }
+
+ go func() {
+ for {
+ conn, acceptErr := listener.Accept()
+ if acceptErr != nil {
+ return
+ }
+
+ go server.serve(conn)
+ }
+ }()
+
+ return server
+}
+
+func (s *fakeServer) getConnection(security Security) Connection {
+ return Connection{
+ Host: s.host,
+ Port: s.port,
+ Security: security,
+ Username: fakeServerUsername,
+ Password: fakeServerPassword,
+ HeloName: "backup.example.com",
+ IsInsecureSkipVerify: true,
+ }
+}
+
+func (s *fakeServer) waitForSessionEnd(t *testing.T) {
+ t.Helper()
+
+ select {
+ case <-s.sessionsEnded:
+ case <-time.After(5 * time.Second):
+ t.Fatal("fake SMTP session did not end")
+ }
+}
+
+func (s *fakeServer) getCommands() []string {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ return append([]string(nil), s.commands...)
+}
+
+func (s *fakeServer) getMessages() []string {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ return append([]string(nil), s.messages...)
+}
+
+func (s *fakeServer) getCommandVerbs() []string {
+ var verbs []string
+ for _, command := range s.getCommands() {
+ verbs = append(verbs, strings.ToUpper(strings.Fields(command)[0]))
+ }
+
+ return verbs
+}
+
+func (s *fakeServer) record(command string) {
+ s.mutex.Lock()
+ defer s.mutex.Unlock()
+
+ s.commands = append(s.commands, command)
+}
+
+func (s *fakeServer) serve(conn net.Conn) {
+ defer func() {
+ _ = conn.Close()
+ s.sessionsEnded <- struct{}{}
+ }()
+
+ if _, err := io.WriteString(conn, "220 fake ESMTP\r\n"); err != nil {
+ return
+ }
+
+ if s.options.isSilentAfterGreeting {
+ _, _ = io.Copy(io.Discard, conn)
+ return
+ }
+
+ reader := bufio.NewReader(conn)
+ isEncrypted := s.options.implicitTLSConfig != nil
+
+ for {
+ command, err := readLine(reader)
+ if err != nil {
+ return
+ }
+
+ s.record(command)
+
+ fields := strings.Fields(command)
+ if len(fields) == 0 {
+ reply(conn, "500 empty command")
+ continue
+ }
+
+ switch strings.ToUpper(fields[0]) {
+ case "EHLO":
+ s.replyToEhlo(conn, isEncrypted)
+ case "STARTTLS":
+ reply(conn, "220 ready to start TLS")
+
+ tlsConn := tls.Server(conn, s.options.startTLSConfig)
+ if err := tlsConn.Handshake(); err != nil {
+ return
+ }
+
+ conn = tlsConn
+ reader = bufio.NewReader(conn)
+ isEncrypted = true
+ case "AUTH":
+ s.handleAuth(conn, reader, fields)
+ case "DATA":
+ reply(conn, "354 end with <CR><LF>.<CR><LF>")
+
+ message, err := readMessageData(reader)
+ if err != nil {
+ return
+ }
+
+ s.mutex.Lock()
+ s.messages = append(s.messages, message)
+ s.mutex.Unlock()
+
+ reply(conn, "250 queued")
+ case "QUIT":
+ reply(conn, "221 bye")
+ return
+ default:
+ reply(conn, "250 OK")
+ }
+ }
+}
+
+func (s *fakeServer) replyToEhlo(conn net.Conn, isEncrypted bool) {
+ extensions := []string{"fake"}
+ if s.options.startTLSConfig != nil && !isEncrypted {
+ extensions = append(extensions, "STARTTLS")
+ }
+
+ if len(s.options.authMechanisms) > 0 {
+ extensions = append(extensions, "AUTH "+strings.Join(s.options.authMechanisms, " "))
+ }
+
+ for index, extension := range extensions {
+ separator := "-"
+ if index == len(extensions)-1 {
+ separator = " "
+ }
+
+ reply(conn, "250"+separator+extension)
+ }
+}
+
+func (s *fakeServer) handleAuth(conn net.Conn, reader *bufio.Reader, fields []string) {
+ var password string
+
+ switch strings.ToUpper(fields[1]) {
+ case mechanismPlain:
+ encodedPayload := ""
+ if len(fields) > 2 {
+ encodedPayload = fields[2]
+ }
+
+ payload, _ := base64.StdEncoding.DecodeString(encodedPayload)
+ payloadParts := strings.Split(string(payload), "\x00")
+ password = payloadParts[len(payloadParts)-1]
+ case mechanismLogin:
+ for index, prompt := range s.options.loginPrompts {
+ reply(conn, "334 "+base64.StdEncoding.EncodeToString([]byte(prompt)))
+
+ answer, err := readLine(reader)
+ if err != nil {
+ return
+ }
+
+ if answer == "*" {
+ reply(conn, "501 authentication cancelled")
+ return
+ }
+
+ if index == 1 {
+ decodedPassword, _ := base64.StdEncoding.DecodeString(answer)
+ password = string(decodedPassword)
+ }
+ }
+ default:
+ reply(conn, "504 unrecognized authentication type")
+ return
+ }
+
+ if password != fakeServerPassword {
+ reply(conn, "535 5.7.8 Authentication credentials invalid")
+ return
+ }
+
+ reply(conn, "235 2.7.0 Authentication successful")
+}
+
+func readLine(reader *bufio.Reader) (string, error) {
+ line, err := reader.ReadString('\n')
+
+ return strings.TrimRight(line, "\r\n"), err
+}
+
+func readMessageData(reader *bufio.Reader) (string, error) {
+ var message strings.Builder
+
+ for {
+ line, err := reader.ReadString('\n')
+ if err != nil {
+ return "", err
+ }
+
+ if line == ".\r\n" {
+ return message.String(), nil
+ }
+
+ message.WriteString(strings.TrimPrefix(line, "."))
+ }
+}
+
+func reply(conn net.Conn, line string) {
+ _, _ = io.WriteString(conn, line+"\r\n")
+}
+
+func newSelfSignedTLSConfig(t *testing.T) *tls.Config {
+ t.Helper()
+
+ key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
+ require.NoError(t, err)
+
+ template := x509.Certificate{
+ SerialNumber: big.NewInt(1),
+ Subject: pkix.Name{CommonName: "127.0.0.1"},
+ NotBefore: time.Now().UTC().Add(-time.Hour),
+ NotAfter: time.Now().UTC().Add(time.Hour),
+ KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageCertSign,
+ ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
+ IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.IPv6loopback},
+ IsCA: true,
+ }
+
+ certificate, err := x509.CreateCertificate(rand.Reader, &template, &template, &key.PublicKey, key)
+ require.NoError(t, err)
+
+ return &tls.Config{
+ Certificates: []tls.Certificate{{Certificate: [][]byte{certificate}, PrivateKey: key}},
+ }
+}
diff --git a/backend/internal/util/smtp_transport/helo.go b/backend/internal/util/smtp_transport/helo.go
new file mode 100644
index 00000000..698d5813
--- /dev/null
+++ b/backend/internal/util/smtp_transport/helo.go
@@ -0,0 +1,84 @@
+package smtp_transport
+
+import (
+ "net"
+ "net/url"
+ "os"
+ "regexp"
+ "strings"
+)
+
+const (
+ fallbackHeloName = "localhost"
+ maxHeloNameLength = 255
+ ipv6LiteralPrefix = "IPv6:"
+)
+
+var hostNamePattern = regexp.MustCompile(
+ `^[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?(\.[A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])?)*$`,
+)
+
+func ValidateHeloName(name string) error {
+ if len(name) > maxHeloNameLength {
+ return ErrInvalidHeloName
+ }
+
+ if hostNamePattern.MatchString(name) {
+ return nil
+ }
+
+ literal, isBracketed := strings.CutPrefix(name, "[")
+ literal, hasClosingBracket := strings.CutSuffix(literal, "]")
+ if !isBracketed || !hasClosingBracket {
+ return ErrInvalidHeloName
+ }
+
+ if ipv6Literal, isIPv6Literal := strings.CutPrefix(literal, ipv6LiteralPrefix); isIPv6Literal {
+ ip := net.ParseIP(ipv6Literal)
+ if ip == nil || ip.To4() != nil {
+ return ErrInvalidHeloName
+ }
+
+ return nil
+ }
+
+ ip := net.ParseIP(literal)
+ if ip == nil || ip.To4() == nil || strings.Contains(literal, ":") {
+ return ErrInvalidHeloName
+ }
+
+ return nil
+}
+
+// GetDefaultHeloName prefers the public host so that mail servers checking the greeting against
+// DNS see the name the instance is reached by, rather than a container ID.
+func GetDefaultHeloName(databasusURL string) string {
+ if databasusURL != "" {
+ if parsedURL, err := url.Parse(databasusURL); err == nil {
+ if heloName := formatHeloName(parsedURL.Hostname()); ValidateHeloName(heloName) == nil {
+ return heloName
+ }
+ }
+ }
+
+ if hostname, err := os.Hostname(); err == nil {
+ if heloName := formatHeloName(hostname); ValidateHeloName(heloName) == nil {
+ return heloName
+ }
+ }
+
+ return fallbackHeloName
+}
+
+func formatHeloName(host string) string {
+ ip := net.ParseIP(host)
+ if ip == nil {
+ return host
+ }
+
+ if ipv4 := ip.To4(); ipv4 != nil {
+ return "[" + ipv4.String() + "]"
+ }
+
+ return "[" + ipv6LiteralPrefix + ip.String() + "]"
+}
diff --git a/backend/internal/util/smtp_transport/helo_test.go b/backend/internal/util/smtp_transport/helo_test.go
new file mode 100644
index 00000000..74c7bf69
--- /dev/null
+++ b/backend/internal/util/smtp_transport/helo_test.go
@@ -0,0 +1,70 @@
+package smtp_transport
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+)
+
+func Test_ValidateHeloName_AcceptsHostNamesAndAddressLiterals(t *testing.T) {
+ testCases := []struct {
+ name string
+ isRejected bool
+ }{
+ {"mail.example.com", false},
+ {"localhost", false},
+ {"relay-01", false},
+ {"[192.0.2.1]", false},
+ {"[IPv6:2001:db8::1]", false},
+ {"my relay", true},
+ {"[::1]", true},
+ {"[IPv6:192.0.2.1]", true},
+ {"[999.0.2.1]", true},
+ {"-relay.example.com", true},
+ {"relay_01.example.com", true},
+ {"mail.example.com.", true},
+ {"mail.example.com\r\nRCPT TO:<[email protected]>", true},
+ {"", true},
+ {strings.Repeat("a.", 128) + "a", true},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ err := ValidateHeloName(testCase.name)
+
+ if testCase.isRejected {
+ assert.ErrorIs(t, err, ErrInvalidHeloName)
+ return
+ }
+
+ assert.NoError(t, err)
+ })
+ }
+}
+
+func Test_GetDefaultHeloName_UsesHostOfPublicAddress(t *testing.T) {
+ testCases := []struct {
+ databasusURL string
+ expectedHeloName string
+ }{
+ {"https://backup.example.com", "backup.example.com"},
+ {"https://backup.example.com:4005/path", "backup.example.com"},
+ {"http://192.0.2.1:4005", "[192.0.2.1]"},
+ {"http://[2001:db8::1]:4005", "[IPv6:2001:db8::1]"},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.databasusURL, func(t *testing.T) {
+ assert.Equal(t, testCase.expectedHeloName, GetDefaultHeloName(testCase.databasusURL))
+ })
+ }
+}
+
+func Test_GetDefaultHeloName_WithoutPublicAddress_ReturnsValidName(t *testing.T) {
+ for _, databasusURL := range []string{"", "not a url with spaces", "https://under_score.example.com"} {
+ t.Run(databasusURL, func(t *testing.T) {
+ assert.NoError(t, ValidateHeloName(GetDefaultHeloName(databasusURL)))
+ })
+ }
+}
diff --git a/backend/internal/util/smtp_transport/message.go b/backend/internal/util/smtp_transport/message.go
new file mode 100644
index 00000000..f5eccf28
--- /dev/null
+++ b/backend/internal/util/smtp_transport/message.go
@@ -0,0 +1,58 @@
+package smtp_transport
+
+import (
+ "bytes"
+ "fmt"
+ "mime"
+ "mime/quotedprintable"
+ "net/mail"
+ "strings"
+ "time"
+
+ "github.com/google/uuid"
+)
+
+type Message struct {
+ Sender *mail.Address
+ Recipient string
+ Subject string
+ HTMLBody string
+}
+
+var headerBreakingCharacters = strings.NewReplacer("\r", "", "\n", "", "\x00", "")
+
+func buildMessage(sender, recipient *mail.Address, subject, htmlBody string, sentAt time.Time) ([]byte, error) {
+ var content bytes.Buffer
+
+ headers := [][2]string{
+ {"From", sender.String()},
+ {"To", recipient.String()},
+ {"Subject", mime.QEncoding.Encode("UTF-8", headerBreakingCharacters.Replace(subject))},
+ {"Date", sentAt.Format(time.RFC1123Z)},
+ {"Message-ID", fmt.Sprintf("<%s@%s>", uuid.New(), getAddressDomain(sender.Address))},
+ {"MIME-Version", "1.0"},
+ {"Content-Type", `text/html; charset="UTF-8"`},
+ {"Content-Transfer-Encoding", "quoted-printable"},
+ }
+
+ for _, header := range headers {
+ content.WriteString(header[0] + ": " + header[1] + "\r\n")
+ }
+
+ content.WriteString("\r\n")
+
+ bodyWriter := quotedprintable.NewWriter(&content)
+ if _, err := bodyWriter.Write([]byte(htmlBody)); err != nil {
+ return nil, fmt.Errorf("failed to encode message body: %w", err)
+ }
+
+ if err := bodyWriter.Close(); err != nil {
+ return nil, fmt.Errorf("failed to encode message body: %w", err)
+ }
+
+ return content.Bytes(), nil
+}
+
+func getAddressDomain(address string) string {
+ return address[strings.LastIndex(address, "@")+1:]
+}
diff --git a/backend/internal/util/smtp_transport/message_test.go b/backend/internal/util/smtp_transport/message_test.go
new file mode 100644
index 00000000..54b0c28a
--- /dev/null
+++ b/backend/internal/util/smtp_transport/message_test.go
@@ -0,0 +1,112 @@
+package smtp_transport
+
+import (
+ "io"
+ "mime/quotedprintable"
+ "net/mail"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_Send_WithLineBreaksInSubject_AddsNoHeaderAndNoRecipient(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismPlain}})
+
+ message := newTestMessage(t)
+ message.Subject = "Ops\r\nBcc: [email protected]"
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), message)
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ receivedMessage := readReceivedMessage(t, server)
+
+ assert.Empty(t, receivedMessage.Header.Get("Bcc"))
+ assert.Equal(t, 1, strings.Count(strings.Join(server.getCommandVerbs(), " "), "RCPT"))
+}
+
+func Test_Send_WithNonASCIIDisplayName_RecipientDecodesOriginalName(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismPlain}})
+
+ sender, err := ParseSender("Резервные копии <[email protected]>")
+ require.NoError(t, err)
+
+ message := newTestMessage(t)
+ message.Sender = sender
+
+ err = Send(t.Context(), server.getConnection(SecurityNone), message)
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ receivedFrom, err := readReceivedMessage(t, server).Header.AddressList("From")
+ require.NoError(t, err)
+
+ assert.Equal(t, "Резервные копии", receivedFrom[0].Name)
+ assert.Equal(t, "[email protected]", receivedFrom[0].Address)
+ assert.Contains(t, server.getCommands(), "MAIL FROM:<[email protected]>")
+}
+
+func Test_Send_WithLongBodyLine_ArrivesUnchangedWithinWireLineLimit(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismPlain}})
+
+ longLine := strings.Repeat("<span>é</span>", 400)
+ require.Greater(t, len(longLine), 5000)
+
+ message := newTestMessage(t)
+ message.HTMLBody = longLine
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), message)
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ rawMessage := server.getMessages()[0]
+ for _, wireLine := range strings.Split(rawMessage, "\r\n") {
+ assert.LessOrEqual(t, len(wireLine), 998)
+ }
+
+ receivedMessage := readReceivedMessage(t, server)
+ assert.Equal(t, "quoted-printable", receivedMessage.Header.Get("Content-Transfer-Encoding"))
+
+ decodedBody, err := io.ReadAll(quotedprintable.NewReader(receivedMessage.Body))
+ require.NoError(t, err)
+ assert.Equal(t, longLine, strings.TrimSuffix(string(decodedBody), "\r\n"))
+}
+
+func Test_Send_TwoMessages_CarryDifferentMessageIDsOnSenderDomain(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismPlain}})
+
+ var messageIDs []string
+ for range 2 {
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ }
+
+ for _, rawMessage := range server.getMessages() {
+ receivedMessage, err := mail.ReadMessage(strings.NewReader(rawMessage))
+ require.NoError(t, err)
+
+ messageIDs = append(messageIDs, receivedMessage.Header.Get("Message-ID"))
+ assert.Equal(t, "1.0", receivedMessage.Header.Get("MIME-Version"))
+ assert.Equal(t, `text/html; charset="UTF-8"`, receivedMessage.Header.Get("Content-Type"))
+ }
+
+ require.Len(t, messageIDs, 2)
+ assert.NotEqual(t, messageIDs[0], messageIDs[1])
+ assert.True(t, strings.HasSuffix(messageIDs[0], "@example.com>"))
+}
+
+func readReceivedMessage(t *testing.T, server *fakeServer) *mail.Message {
+ t.Helper()
+
+ receivedMessages := server.getMessages()
+ require.Len(t, receivedMessages, 1)
+
+ receivedMessage, err := mail.ReadMessage(strings.NewReader(receivedMessages[0]))
+ require.NoError(t, err)
+
+ return receivedMessage
+}
diff --git a/backend/internal/util/smtp_transport/smtp_transport.go b/backend/internal/util/smtp_transport/smtp_transport.go
new file mode 100644
index 00000000..57b6163d
--- /dev/null
+++ b/backend/internal/util/smtp_transport/smtp_transport.go
@@ -0,0 +1,181 @@
+package smtp_transport
+
+import (
+ "context"
+ "crypto/tls"
+ "errors"
+ "fmt"
+ "net"
+ "net/smtp"
+ "os"
+ "strconv"
+ "time"
+)
+
+const sessionTimeout = 30 * time.Second
+
+type Connection struct {
+ Host string
+ Port int
+ Security Security
+ Username string
+ Password string
+ HeloName string
+ IsInsecureSkipVerify bool
+}
+
+func Send(ctx context.Context, connection Connection, message Message) error {
+ if !connection.Security.IsValid() {
+ return fmt.Errorf("%w: %q", ErrUnknownSecurity, connection.Security)
+ }
+
+ recipient, err := ParseRecipient(message.Recipient)
+ if err != nil {
+ return err
+ }
+
+ content, err := buildMessage(message.Sender, recipient, message.Subject, message.HTMLBody, time.Now().UTC())
+ if err != nil {
+ return err
+ }
+
+ sessionCtx, cancel := context.WithTimeout(ctx, sessionTimeout)
+ defer cancel()
+
+ err = runSession(sessionCtx, connection, message.Sender.Address, recipient.Address, content)
+ if err != nil && (sessionCtx.Err() != nil || errors.Is(err, os.ErrDeadlineExceeded)) {
+ return fmt.Errorf("%w: %w", ErrSessionTimeout, err)
+ }
+
+ return err
+}
+
+func runSession(
+ ctx context.Context,
+ connection Connection,
+ envelopeSender, envelopeRecipient string,
+ content []byte,
+) error {
+ conn, err := dial(ctx, connection)
+ if err != nil {
+ return fmt.Errorf("failed to connect to SMTP server: %w", err)
+ }
+
+ if deadline, hasDeadline := ctx.Deadline(); hasDeadline {
+ if err := conn.SetDeadline(deadline); err != nil {
+ _ = conn.Close()
+ return fmt.Errorf("failed to set SMTP session deadline: %w", err)
+ }
+ }
+
+ stopInterruptOnCancel := context.AfterFunc(ctx, func() { _ = conn.SetDeadline(time.Now()) })
+ defer stopInterruptOnCancel()
+
+ client, err := smtp.NewClient(conn, connection.Host)
+ if err != nil {
+ _ = conn.Close()
+ return fmt.Errorf("failed to read SMTP server greeting: %w", err)
+ }
+
+ if err := openSession(client, connection); err != nil {
+ _ = client.Close()
+ return err
+ }
+
+ if err := deliver(client, envelopeSender, envelopeRecipient, content); err != nil {
+ _ = client.Close()
+ return err
+ }
+
+ _ = client.Quit()
+
+ return nil
+}
+
+func dial(ctx context.Context, connection Connection) (net.Conn, error) {
+ address := net.JoinHostPort(connection.Host, strconv.Itoa(connection.Port))
+
+ if connection.Security == SecurityTLS {
+ tlsDialer := &tls.Dialer{Config: buildTLSConfig(connection)}
+ return tlsDialer.DialContext(ctx, "tcp", address)
+ }
+
+ var dialer net.Dialer
+
+ return dialer.DialContext(ctx, "tcp", address)
+}
+
+func openSession(client *smtp.Client, connection Connection) error {
+ heloName := connection.HeloName
+ if heloName == "" {
+ heloName = fallbackHeloName
+ }
+
+ if err := client.Hello(heloName); err != nil {
+ return fmt.Errorf("SMTP greeting failed: %w", err)
+ }
+
+ if connection.Security == SecurityStartTLS {
+ if isOffered, _ := client.Extension("STARTTLS"); !isOffered {
+ return ErrStartTLSNotOffered
+ }
+
+ if err := client.StartTLS(buildTLSConfig(connection)); err != nil {
+ return fmt.Errorf("STARTTLS failed: %w", err)
+ }
+ }
+
+ if connection.Username == "" || connection.Password == "" {
+ return nil
+ }
+
+ _, offeredMechanisms := client.Extension("AUTH")
+
+ auth, mechanism, err := chooseAuth(offeredMechanisms, credentials{
+ connection.Username,
+ connection.Password,
+ connection.Security == SecurityNone,
+ })
+ if err != nil {
+ return err
+ }
+
+ if err := client.Auth(auth); err != nil {
+ return fmt.Errorf("SMTP authentication with %s failed: %w", mechanism, err)
+ }
+
+ return nil
+}
+
+func deliver(client *smtp.Client, envelopeSender, envelopeRecipient string, content []byte) error {
+ if err := client.Mail(envelopeSender); err != nil {
+ return fmt.Errorf("SMTP server rejected the sender: %w", err)
+ }
+
+ if err := client.Rcpt(envelopeRecipient); err != nil {
+ return fmt.Errorf("SMTP server rejected the recipient: %w", err)
+ }
+
+ dataWriter, err := client.Data()
+ if err != nil {
+ return fmt.Errorf("SMTP server refused the message: %w", err)
+ }
+
+ if _, err := dataWriter.Write(content); err != nil {
+ _ = dataWriter.Close()
+ return fmt.Errorf("failed to send the message: %w", err)
+ }
+
+ if err := dataWriter.Close(); err != nil {
+ return fmt.Errorf("SMTP server rejected the message: %w", err)
+ }
+
+ return nil
+}
+
+func buildTLSConfig(connection Connection) *tls.Config {
+ return &tls.Config{
+ ServerName: connection.Host,
+ InsecureSkipVerify: connection.IsInsecureSkipVerify,
+ }
+}
diff --git a/backend/internal/util/smtp_transport/smtp_transport_test.go b/backend/internal/util/smtp_transport/smtp_transport_test.go
new file mode 100644
index 00000000..75bf38c3
--- /dev/null
+++ b/backend/internal/util/smtp_transport/smtp_transport_test.go
@@ -0,0 +1,147 @@
+package smtp_transport
+
+import (
+ "context"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_Send_WithTLS_DeliversOverEncryptedConnection(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ implicitTLSConfig: newSelfSignedTLSConfig(t),
+ authMechanisms: []string{mechanismPlain},
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityTLS), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ assert.Len(t, server.getMessages(), 1)
+ assert.Equal(t, "EHLO backup.example.com", server.getCommands()[0])
+}
+
+func Test_Send_WithStartTLS_UpgradesBeforeAnyOtherCommand(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ startTLSConfig: newSelfSignedTLSConfig(t),
+ authMechanisms: []string{mechanismPlain},
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityStartTLS), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ assert.Equal(
+ t,
+ []string{"EHLO", "STARTTLS", "EHLO", "AUTH", "MAIL", "RCPT", "DATA", "QUIT"},
+ server.getCommandVerbs(),
+ )
+ assert.Equal(t, "EHLO backup.example.com", server.getCommands()[2])
+ assert.Len(t, server.getMessages(), 1)
+}
+
+func Test_Send_WithStartTLSWhenServerDoesNotOfferIt_FailsWithNothingSentAfterGreeting(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ authMechanisms: []string{mechanismPlain, mechanismLogin},
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityStartTLS), newTestMessage(t))
+ require.ErrorIs(t, err, ErrStartTLSNotOffered)
+
+ server.waitForSessionEnd(t)
+ assert.Equal(t, []string{"EHLO backup.example.com"}, server.getCommands())
+ assert.Empty(t, server.getMessages())
+}
+
+func Test_Send_WithNone_NeverUpgradesAndAuthenticates(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{
+ startTLSConfig: newSelfSignedTLSConfig(t),
+ authMechanisms: []string{mechanismPlain},
+ })
+
+ err := Send(t.Context(), server.getConnection(SecurityNone), newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ assert.Equal(t, []string{"EHLO", "AUTH", "MAIL", "RCPT", "DATA", "QUIT"}, server.getCommandVerbs())
+ assert.Len(t, server.getMessages(), 1)
+}
+
+func Test_Send_WithUntrustedCertificate_FailsUnlessVerificationIsOff(t *testing.T) {
+ testCases := []struct {
+ name string
+ security Security
+ options fakeServerOptions
+ }{
+ {"tls", SecurityTLS, fakeServerOptions{implicitTLSConfig: newSelfSignedTLSConfig(t)}},
+ {"starttls", SecurityStartTLS, fakeServerOptions{startTLSConfig: newSelfSignedTLSConfig(t)}},
+ }
+
+ for _, testCase := range testCases {
+ t.Run(testCase.name, func(t *testing.T) {
+ testCase.options.authMechanisms = []string{mechanismPlain}
+ server := startFakeServer(t, testCase.options)
+
+ verifyingConnection := server.getConnection(testCase.security)
+ verifyingConnection.IsInsecureSkipVerify = false
+
+ err := Send(t.Context(), verifyingConnection, newTestMessage(t))
+ require.Error(t, err)
+ assert.Contains(t, err.Error(), "certificate")
+
+ server.waitForSessionEnd(t)
+ assert.NotContains(t, server.getCommandVerbs(), "AUTH")
+
+ err = Send(t.Context(), server.getConnection(testCase.security), newTestMessage(t))
+ require.NoError(t, err)
+ })
+ }
+}
+
+func Test_Send_WhenServerGoesSilentAfterGreeting_FailsWithTimeoutWithinDeadline(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{isSilentAfterGreeting: true})
+
+ callerCtx, cancel := context.WithTimeout(t.Context(), 300*time.Millisecond)
+ defer cancel()
+
+ startedAt := time.Now().UTC()
+ err := Send(callerCtx, server.getConnection(SecurityNone), newTestMessage(t))
+
+ require.ErrorIs(t, err, ErrSessionTimeout)
+ assert.Less(t, time.Since(startedAt), 2*time.Second)
+}
+
+func Test_Send_WithoutGreetingName_GreetsWithFallbackName(t *testing.T) {
+ server := startFakeServer(t, fakeServerOptions{authMechanisms: []string{mechanismPlain}})
+
+ connection := server.getConnection(SecurityNone)
+ connection.HeloName = ""
+
+ err := Send(t.Context(), connection, newTestMessage(t))
+ require.NoError(t, err)
+
+ server.waitForSessionEnd(t)
+ assert.Equal(t, "EHLO "+fallbackHeloName, server.getCommands()[0])
+}
+
+func Test_Send_WithUnknownSecurity_Fails(t *testing.T) {
+ err := Send(t.Context(), Connection{Host: "127.0.0.1", Port: 25, Security: "ssl"}, newTestMessage(t))
+
+ require.ErrorIs(t, err, ErrUnknownSecurity)
+}
+
+func newTestMessage(t *testing.T) Message {
+ t.Helper()
+
+ sender, err := ParseSender("[email protected]")
+ require.NoError(t, err)
+
+ return Message{
+ Sender: sender,
+ Recipient: "[email protected]",
+ Subject: "Test",
+ HTMLBody: "<p>Hello</p>",
+ }
+}
diff --git a/backend/internal/util/testing/mailpit/mailpit.go b/backend/internal/util/testing/mailpit/mailpit.go
index cb9e95be..7fd0f5b7 100644
--- a/backend/internal/util/testing/mailpit/mailpit.go
+++ b/backend/internal/util/testing/mailpit/mailpit.go
@@ -12,11 +12,12 @@ import (
const requestTimeout = 5 * time.Second
type Message struct {
- ID string `json:"ID"`
- From Address `json:"From"`
- To []Address `json:"To"`
- Subject string `json:"Subject"`
- Snippet string `json:"Snippet"`
+ ID string `json:"ID"`
+ From Address `json:"From"`
+ To []Address `json:"To"`
+ Subject string `json:"Subject"`
+ MessageID string `json:"MessageID"`
+ Snippet string `json:"Snippet"`
}
type Address struct {
diff --git a/backend/migrations/20260921210940_add_security_to_email_notifiers.sql b/backend/migrations/20260921210940_add_security_to_email_notifiers.sql
new file mode 100644
index 00000000..590b4abc
--- /dev/null
+++ b/backend/migrations/20260921210940_add_security_to_email_notifiers.sql
@@ -0,0 +1,37 @@
+-- +goose Up
+-- +goose StatementBegin
+
+-- Every existing channel gets the mode its port implied before: implicit TLS on 465 and
+-- STARTTLS elsewhere, now mandatory rather than optional.
+ALTER TABLE email_notifiers
+ ADD COLUMN security VARCHAR(16) NOT NULL DEFAULT 'starttls';
+
+UPDATE email_notifiers
+ SET security = 'tls'
+ WHERE smtp_port = 465;
+
+ALTER TABLE email_notifiers
+ ALTER COLUMN security DROP DEFAULT;
+
+ALTER TABLE email_notifiers
+ ADD CONSTRAINT ck_email_notifiers_security
+ CHECK (security IN ('tls', 'starttls', 'none'));
+
+ALTER TABLE email_notifiers
+ ADD COLUMN helo_name VARCHAR(255) NOT NULL DEFAULT '';
+
+-- +goose StatementEnd
+
+-- +goose Down
+-- +goose StatementBegin
+
+ALTER TABLE email_notifiers
+ DROP CONSTRAINT IF EXISTS ck_email_notifiers_security;
+
+ALTER TABLE email_notifiers
+ DROP COLUMN IF EXISTS helo_name;
+
+ALTER TABLE email_notifiers
+ DROP COLUMN IF EXISTS security;
+
+-- +goose StatementEnd
diff --git a/docker/start.sh b/docker/start.sh
index e25e05f3..c41a0840 100755
--- a/docker/start.sh
+++ b/docker/start.sh
@@ -144,7 +144,7 @@ configure_runtime_identity() {
generate_frontend_runtime_configuration() {
local is_email_configured=false
- if [ -n "${SMTP_HOST:-}" ] && [ -n "${DATABASUS_URL:-}" ]; then
+ if [ -n "${SMTP_HOST:-}" ]; then
is_email_configured=true
fi
diff --git a/frontend/src/entity/notifiers/index.ts b/frontend/src/entity/notifiers/index.ts
index 0ff65357..aa3f3bc6 100644
--- a/frontend/src/entity/notifiers/index.ts
+++ b/frontend/src/entity/notifiers/index.ts
@@ -5,6 +5,10 @@ export { NotificationType } from './models/NotificationType';
export type { EmailNotifier } from './models/email/EmailNotifier';
export { validateEmailNotifier } from './models/email/validateEmailNotifier';
+export { EmailNotifierSecurity } from './models/email/EmailNotifierSecurity';
+export { EMAIL_NOTIFIER_SECURITY_LABEL_KEYS } from './models/email/EmailNotifierSecurityLabelKeys';
+export { getDefaultEmailNotifierSecurity } from './models/email/getDefaultEmailNotifierSecurity';
+export { getSecurityAfterPortChange } from './models/email/getSecurityAfterPortChange';
export type { TelegramNotifier } from './models/telegram/TelegramNotifier';
export { validateTelegramNotifier } from './models/telegram/validateTelegramNotifier';
diff --git a/frontend/src/entity/notifiers/models/email/EmailNotifier.ts b/frontend/src/entity/notifiers/models/email/EmailNotifier.ts
index 91e17ca9..b4fe9e7c 100644
--- a/frontend/src/entity/notifiers/models/email/EmailNotifier.ts
+++ b/frontend/src/entity/notifiers/models/email/EmailNotifier.ts
@@ -1,3 +1,5 @@
+import type { EmailNotifierSecurity } from './EmailNotifierSecurity';
+
export interface EmailNotifier {
targetEmail: string;
smtpHost: string;
@@ -6,4 +8,6 @@ export interface EmailNotifier {
smtpPassword: string;
from: string;
isInsecureSkipVerify: boolean;
+ security: EmailNotifierSecurity;
+ heloName: string;
}
diff --git a/frontend/src/entity/notifiers/models/email/EmailNotifierSecurity.ts b/frontend/src/entity/notifiers/models/email/EmailNotifierSecurity.ts
new file mode 100644
index 00000000..fe9ac44d
--- /dev/null
+++ b/frontend/src/entity/notifiers/models/email/EmailNotifierSecurity.ts
@@ -0,0 +1,5 @@
+export enum EmailNotifierSecurity {
+ TLS = 'tls',
+ STARTTLS = 'starttls',
+ NONE = 'none',
+}
diff --git a/frontend/src/entity/notifiers/models/email/EmailNotifierSecurityLabelKeys.ts b/frontend/src/entity/notifiers/models/email/EmailNotifierSecurityLabelKeys.ts
new file mode 100644
index 00000000..bcaec7a1
--- /dev/null
+++ b/frontend/src/entity/notifiers/models/email/EmailNotifierSecurityLabelKeys.ts
@@ -0,0 +1,8 @@
+import type { TranslationKey } from '../../../../shared/i18n';
+import { EmailNotifierSecurity } from './EmailNotifierSecurity';
+
+export const EMAIL_NOTIFIER_SECURITY_LABEL_KEYS: Record<EmailNotifierSecurity, TranslationKey> = {
+ [EmailNotifierSecurity.TLS]: 'notifiers.email.securityModes.tls',
+ [EmailNotifierSecurity.STARTTLS]: 'notifiers.email.securityModes.starttls',
+ [EmailNotifierSecurity.NONE]: 'notifiers.email.securityModes.none',
+};
diff --git a/frontend/src/entity/notifiers/models/email/getDefaultEmailNotifierSecurity.ts b/frontend/src/entity/notifiers/models/email/getDefaultEmailNotifierSecurity.ts
new file mode 100644
index 00000000..1a99bb1c
--- /dev/null
+++ b/frontend/src/entity/notifiers/models/email/getDefaultEmailNotifierSecurity.ts
@@ -0,0 +1,6 @@
+import { EmailNotifierSecurity } from './EmailNotifierSecurity';
+
+const IMPLICIT_TLS_PORT = 465;
+
+export const getDefaultEmailNotifierSecurity = (port: number): EmailNotifierSecurity =>
+ port === IMPLICIT_TLS_PORT ? EmailNotifierSecurity.TLS : EmailNotifierSecurity.STARTTLS;
diff --git a/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.test.ts b/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.test.ts
new file mode 100644
index 00000000..b6247a0d
--- /dev/null
+++ b/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { EmailNotifierSecurity } from './EmailNotifierSecurity';
+import { getDefaultEmailNotifierSecurity } from './getDefaultEmailNotifierSecurity';
+import { getSecurityAfterPortChange } from './getSecurityAfterPortChange';
+
+describe('getDefaultEmailNotifierSecurity', () => {
+ it('returns tls only for port 465', () => {
+ expect(getDefaultEmailNotifierSecurity(465)).toBe(EmailNotifierSecurity.TLS);
+ expect(getDefaultEmailNotifierSecurity(587)).toBe(EmailNotifierSecurity.STARTTLS);
+ expect(getDefaultEmailNotifierSecurity(25)).toBe(EmailNotifierSecurity.STARTTLS);
+ expect(getDefaultEmailNotifierSecurity(0)).toBe(EmailNotifierSecurity.STARTTLS);
+ });
+});
+
+describe('getSecurityAfterPortChange', () => {
+ it('follows the new port when the mode is the previous port default', () => {
+ expect(getSecurityAfterPortChange(EmailNotifierSecurity.STARTTLS, 587, 465)).toBe(
+ EmailNotifierSecurity.TLS,
+ );
+ expect(getSecurityAfterPortChange(EmailNotifierSecurity.TLS, 465, 587)).toBe(
+ EmailNotifierSecurity.STARTTLS,
+ );
+ });
+
+ it('keeps a mode that differs from the previous port default', () => {
+ expect(getSecurityAfterPortChange(EmailNotifierSecurity.NONE, 25, 2525)).toBe(
+ EmailNotifierSecurity.NONE,
+ );
+ expect(getSecurityAfterPortChange(EmailNotifierSecurity.TLS, 587, 2525)).toBe(
+ EmailNotifierSecurity.TLS,
+ );
+ });
+});
diff --git a/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.ts b/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.ts
new file mode 100644
index 00000000..0e9cb159
--- /dev/null
+++ b/frontend/src/entity/notifiers/models/email/getSecurityAfterPortChange.ts
@@ -0,0 +1,13 @@
+import type { EmailNotifierSecurity } from './EmailNotifierSecurity';
+import { getDefaultEmailNotifierSecurity } from './getDefaultEmailNotifierSecurity';
+
+// A mode that differs from the previous port's default was chosen on purpose, whether in this
+// session or before the channel was saved, so a port change must not overwrite it.
+export const getSecurityAfterPortChange = (
+ currentSecurity: EmailNotifierSecurity,
+ previousPort: number,
+ nextPort: number,
+): EmailNotifierSecurity =>
+ currentSecurity === getDefaultEmailNotifierSecurity(previousPort)
+ ? getDefaultEmailNotifierSecurity(nextPort)
+ : currentSecurity;
diff --git a/frontend/src/entity/users/api/settingsApi.ts b/frontend/src/entity/users/api/settingsApi.ts
index 6ef29388..1c3e87f1 100644
--- a/frontend/src/entity/users/api/settingsApi.ts
+++ b/frontend/src/entity/users/api/settingsApi.ts
@@ -1,6 +1,7 @@
import { getApplicationServer } from '../../../constants';
import RequestOptions from '../../../shared/api/RequestOptions';
import { apiHelper } from '../../../shared/api/apiHelper';
+import type { SendTestEmailResponse } from '../model/SendTestEmailResponse';
import type { UsersSettings } from '../model/UsersSettings';
import type { UsersSettingsResponse } from '../model/UsersSettingsResponse';
@@ -21,4 +22,12 @@ export const settingsApi = {
requestOptions,
);
},
+
+ // No retry: every attempt sends a message and counts against the rate limit.
+ async sendTestEmail(): Promise<SendTestEmailResponse> {
+ return apiHelper.fetchPostJson(
+ `${getApplicationServer()}/api/v1/users/settings/test-email`,
+ new RequestOptions(),
+ );
+ },
};
diff --git a/frontend/src/entity/users/index.ts b/frontend/src/entity/users/index.ts
index 1021728f..94d814d5 100644
--- a/frontend/src/entity/users/index.ts
+++ b/frontend/src/entity/users/index.ts
@@ -21,6 +21,7 @@ export type { ListUsersResponse } from './model/ListUsersResponse';
export type { ChangeUserRoleRequest } from './model/ChangeUserRoleRequest';
export type { UsersSettings } from './model/UsersSettings';
export type { UsersSettingsResponse } from './model/UsersSettingsResponse';
+export type { SendTestEmailResponse } from './model/SendTestEmailResponse';
export type { SendResetPasswordCodeRequest } from './model/SendResetPasswordCodeRequest';
export type { ResetPasswordRequest } from './model/ResetPasswordRequest';
export { UserRole } from './model/UserRole';
diff --git a/frontend/src/entity/users/model/SendTestEmailResponse.ts b/frontend/src/entity/users/model/SendTestEmailResponse.ts
new file mode 100644
index 00000000..62ffba64
--- /dev/null
+++ b/frontend/src/entity/users/model/SendTestEmailResponse.ts
@@ -0,0 +1,3 @@
+export interface SendTestEmailResponse {
+ recipientEmail: string;
+}
diff --git a/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx
index fa47c967..027f10be 100644
--- a/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx
+++ b/frontend/src/features/notifiers/ui/edit/EditNotifierComponent.tsx
@@ -8,6 +8,7 @@ import {
type Notifier,
NotifierType,
WebhookMethod,
+ getDefaultEmailNotifierSecurity,
notifierApi,
validateDiscordNotifier,
validateEmailNotifier,
@@ -124,14 +125,18 @@ export function EditNotifierComponent({
}
if (type === NotifierType.EMAIL) {
+ const defaultSmtpPort = 0;
+
notifier.emailNotifier = {
targetEmail: '',
smtpHost: '',
- smtpPort: 0,
+ smtpPort: defaultSmtpPort,
smtpUser: '',
smtpPassword: '',
from: '',
isInsecureSkipVerify: false,
+ security: getDefaultEmailNotifierSecurity(defaultSmtpPort),
+ heloName: '',
};
}
diff --git a/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx b/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx
index c2b4b083..6a184ec1 100644
--- a/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx
+++ b/frontend/src/features/notifiers/ui/edit/notifiers/EditEmailNotifierComponent.tsx
@@ -1,9 +1,15 @@
import { DownOutlined, InfoCircleOutlined, UpOutlined } from '@ant-design/icons';
-import { Checkbox, Input, Tooltip } from 'antd';
-import { useState } from 'react';
+import { Checkbox, Input, Select, Tooltip } from 'antd';
+import { type ReactNode, useState } from 'react';
import { useTranslation } from 'react-i18next';
-import type { Notifier } from '../../../../../entity/notifiers';
+import {
+ EMAIL_NOTIFIER_SECURITY_LABEL_KEYS,
+ EmailNotifierSecurity,
+ type Notifier,
+ getDefaultEmailNotifierSecurity,
+ getSecurityAfterPortChange,
+} from '../../../../../entity/notifiers';
interface Props {
notifier: Notifier;
@@ -13,7 +19,12 @@ interface Props {
export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }: Props) {
const { t } = useTranslation();
- const hasAdvancedValues = !!notifier?.emailNotifier?.isInsecureSkipVerify;
+ const emailNotifier = notifier?.emailNotifier;
+ const hasAdvancedValues =
+ !!emailNotifier?.isInsecureSkipVerify ||
+ !!emailNotifier?.heloName ||
+ (!!emailNotifier &&
+ emailNotifier.security !== getDefaultEmailNotifierSecurity(emailNotifier.smtpPort));
const [showAdvanced, setShowAdvanced] = useState(hasAdvancedValues);
return (
@@ -77,11 +88,18 @@ export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }
onChange={(e) => {
if (!notifier?.emailNotifier) return;
+ const nextPort = Number(e.target.value);
+
setNotifier({
...notifier,
emailNotifier: {
...notifier.emailNotifier,
- smtpPort: Number(e.target.value),
+ smtpPort: nextPort,
+ security: getSecurityAfterPortChange(
+ notifier.emailNotifier.security,
+ notifier.emailNotifier.smtpPort,
+ nextPort,
+ ),
},
});
setUnsaved();
@@ -183,11 +201,56 @@ export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }
</div>
{showAdvanced && (
- <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
- <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">
- {t('notifiers.fields.skipTlsVerify')}
- </div>
- <div className="flex items-center">
+ <>
+ <AdvancedFieldRowComponent
+ label={t('notifiers.email.security')}
+ tooltip={t('notifiers.email.securityTooltip')}
+ >
+ <Select
+ value={notifier?.emailNotifier?.security}
+ onChange={(security: EmailNotifierSecurity) => {
+ if (!notifier?.emailNotifier) return;
+
+ setNotifier({
+ ...notifier,
+ emailNotifier: { ...notifier.emailNotifier, security },
+ });
+ setUnsaved();
+ }}
+ size="small"
+ className="w-[250px] max-w-[250px]"
+ options={Object.values(EmailNotifierSecurity).map((security) => ({
+ value: security,
+ label: t(EMAIL_NOTIFIER_SECURITY_LABEL_KEYS[security]),
+ }))}
+ />
+ </AdvancedFieldRowComponent>
+
+ <AdvancedFieldRowComponent
+ label={t('notifiers.email.heloName')}
+ tooltip={t('notifiers.email.heloNameTooltip')}
+ >
+ <Input
+ value={notifier?.emailNotifier?.heloName || ''}
+ onChange={(e) => {
+ if (!notifier?.emailNotifier) return;
+
+ setNotifier({
+ ...notifier,
+ emailNotifier: { ...notifier.emailNotifier, heloName: e.target.value.trim() },
+ });
+ setUnsaved();
+ }}
+ size="small"
+ className="w-full max-w-[250px]"
+ placeholder={t('notifiers.email.heloNamePlaceholder')}
+ />
+ </AdvancedFieldRowComponent>
+
+ <AdvancedFieldRowComponent
+ label={t('notifiers.fields.skipTlsVerify')}
+ tooltip={t('notifiers.email.skipTlsTooltip')}
+ >
<Checkbox
checked={notifier?.emailNotifier?.isInsecureSkipVerify || false}
onChange={(e) => {
@@ -205,13 +268,30 @@ export function EditEmailNotifierComponent({ notifier, setNotifier, setUnsaved }
>
{t('notifiers.fields.skipTls')}
</Checkbox>
-
- <Tooltip className="cursor-pointer" title={t('notifiers.email.skipTlsTooltip')}>
- <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
- </Tooltip>
- </div>
- </div>
+ </AdvancedFieldRowComponent>
+ </>
)}
</>
);
}
+
+interface AdvancedFieldRowProps {
+ label: string;
+ tooltip: string;
+ children: ReactNode;
+}
+
+function AdvancedFieldRowComponent({ label, tooltip, children }: AdvancedFieldRowProps) {
+ return (
+ <div className="mb-1 flex w-full flex-col items-start sm:flex-row sm:items-center">
+ <div className="mb-1 min-w-[150px] sm:mb-0 sm:pr-2">{label}</div>
+ <div className="flex items-center">
+ {children}
+
+ <Tooltip className="cursor-pointer" title={tooltip}>
+ <InfoCircleOutlined className="ml-2" style={{ color: 'gray' }} />
+ </Tooltip>
+ </div>
+ </div>
+ );
+}
diff --git a/frontend/src/features/settings/ui/MailServerComponent.tsx b/frontend/src/features/settings/ui/MailServerComponent.tsx
new file mode 100644
index 00000000..f4d5c88c
--- /dev/null
+++ b/frontend/src/features/settings/ui/MailServerComponent.tsx
@@ -0,0 +1,80 @@
+import { App, Button } from 'antd';
+import { useState } from 'react';
+import { Trans, useTranslation } from 'react-i18next';
+
+import { settingsApi } from '../../../entity/users';
+import { getWebsitePageUrl, translateApiError, useLocale } from '../../../shared/i18n';
+
+interface Props {
+ isEmailConfigured: boolean;
+}
+
+export function MailServerComponent({ isEmailConfigured }: Props) {
+ const { t } = useTranslation();
+ const { locale } = useLocale();
+ const { message } = App.useApp();
+ const [isSendingTestEmail, setIsSendingTestEmail] = useState(false);
+ const [testEmailError, setTestEmailError] = useState<unknown>(undefined);
+
+ const sendTestEmail = async () => {
+ setIsSendingTestEmail(true);
+ setTestEmailError(undefined);
+
+ try {
+ const response = await settingsApi.sendTestEmail();
+ message.success(t('settings.mailServer.testEmailSent', { email: response.recipientEmail }));
+ } catch (error: unknown) {
+ setTestEmailError(error);
+ } finally {
+ setIsSendingTestEmail(false);
+ }
+ };
+
+ return (
+ <section className="my-8 max-w-2xl text-sm">
+ <h2 className="mb-3 text-xl font-bold dark:text-white">{t('settings.mailServer.title')}</h2>
+
+ <div className="font-medium text-gray-900 dark:text-white">
+ {isEmailConfigured
+ ? t('settings.mailServer.configured')
+ : t('settings.mailServer.notConfigured')}
+ </div>
+
+ <div className="mt-1 text-gray-500 dark:text-gray-400">
+ {t('settings.mailServer.description')}
+ </div>
+
+ <div className="mt-1 text-gray-500 dark:text-gray-400">
+ <Trans
+ i18nKey="settings.mailServer.docs"
+ components={{
+ docsLink: (
+ <a
+ href={getWebsitePageUrl('advancedConfigEmailSmtp', locale)}
+ target="_blank"
+ rel="noreferrer"
+ className="!text-blue-600"
+ />
+ ),
+ }}
+ />
+ </div>
+
+ <Button
+ className="mt-3"
+ type="primary"
+ ghost
+ size="small"
+ onClick={sendTestEmail}
+ loading={isSendingTestEmail}
+ disabled={!isEmailConfigured || isSendingTestEmail}
+ >
+ {t('settings.mailServer.sendTestEmail')}
+ </Button>
+
+ {testEmailError !== undefined && (
+ <div className="mt-2 break-words text-red-600">{translateApiError(testEmailError, t)}</div>
+ )}
+ </section>
+ );
+}
diff --git a/frontend/src/features/settings/ui/SettingsComponent.tsx b/frontend/src/features/settings/ui/SettingsComponent.tsx
index 12f8979b..9a3381b1 100644
--- a/frontend/src/features/settings/ui/SettingsComponent.tsx
+++ b/frontend/src/features/settings/ui/SettingsComponent.tsx
@@ -9,6 +9,7 @@ import { getWebsitePageUrl, translateApiError, useLocale } from '../../../shared
import { ClipboardHelper } from '../../../shared/lib/ClipboardHelper';
import { VerificationAgentsComponent } from '../../verification/agents';
import { AuditLogsComponent } from './AuditLogsComponent';
+import { MailServerComponent } from './MailServerComponent';
interface Props {
contentHeight: number;
@@ -326,6 +327,8 @@ export function SettingsComponent({ contentHeight }: Props) {
<VerificationAgentsComponent />
+ {settings && <MailServerComponent isEmailConfigured={settings.isEmailConfigured} />}
+
<AuditLogsComponent scrollContainerRef={scrollContainerRef} />
</div>
</div>
diff --git a/frontend/src/shared/i18n/locales/en.ts b/frontend/src/shared/i18n/locales/en.ts
index 86a6ce33..fcf3974f 100644
--- a/frontend/src/shared/i18n/locales/en.ts
+++ b/frontend/src/shared/i18n/locales/en.ts
@@ -139,6 +139,8 @@ export const en = {
signInCodeResentTooSoon:
'A code was sent less than a minute ago. Wait a minute before requesting another.',
rateLimitExceeded: 'Too many attempts. Wait a little and try again.',
+ emailNotConfigured: 'The instance has no mail server configured.',
+ adminEmailMissing: 'Your account has no valid email address to send a test email to.',
},
status: {
logicalBackup: {
@@ -256,6 +258,16 @@ export const en = {
reset: 'Reset',
updated: 'Settings updated successfully',
readMore: 'Read more about settings you can <docsLink>here</docsLink>',
+ mailServer: {
+ title: 'Mail server',
+ configured: 'The mail server is configured.',
+ notConfigured: 'The mail server is not configured.',
+ description:
+ 'It sends invitations, password reset codes and sign-in codes. Email notifiers have SMTP settings of their own.',
+ docs: 'See <docsLink>the SMTP documentation</docsLink> for how to connect a mail server.',
+ sendTestEmail: 'Send test email',
+ testEmailSent: 'Test email sent to {{email}}',
+ },
healthcheck: {
title: 'Health-check',
openInNewTab: 'Click to open in new tab',
@@ -1197,11 +1209,23 @@ export const en = {
smtpPasswordPlaceholder: 'password',
from: 'From',
fromTooltip:
- 'Optional. Email address to use as sender. If empty, will use SMTP user or auto-generate from host',
+ 'Optional. Sender address, with or without a name: Acme Backups <[email protected]>. If empty, the SMTP user is used when it is an email address, otherwise noreply@ and the SMTP host',
fromAuto: '(auto)',
advancedSettings: 'Advanced settings',
skipTlsTooltip:
'Skip TLS certificate verification. Enable this if your SMTP server uses a self-signed certificate. Warning: this reduces security.',
+ security: 'Connection security',
+ securityTooltip:
+ 'TLS encrypts the connection from the start and is usual on port 465. STARTTLS upgrades the connection and fails if the server does not offer it. None sends the password and messages unencrypted - use it only for a trusted relay without STARTTLS.',
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: 'None (unencrypted)',
+ },
+ heloName: 'Greeting name',
+ heloNamePlaceholder: 'Automatic',
+ heloNameTooltip:
+ 'The name Databasus introduces itself with to the mail server (EHLO). If empty, the host from DATABASUS_URL is used, or the machine host name.',
},
telegram: {
botTokenHelpLink: 'How to get Telegram bot API token?',
diff --git a/frontend/src/shared/i18n/locales/es.ts b/frontend/src/shared/i18n/locales/es.ts
index 5016f50a..dfcfe00e 100644
--- a/frontend/src/shared/i18n/locales/es.ts
+++ b/frontend/src/shared/i18n/locales/es.ts
@@ -143,6 +143,9 @@ export const es: typeof en = {
signInCodeResentTooSoon:
'Se envió un código hace menos de un minuto. Espere un minuto antes de pedir otro.',
rateLimitExceeded: 'Demasiados intentos. Espere un poco e inténtelo de nuevo.',
+ emailNotConfigured: 'La instancia no tiene un servidor de correo configurado.',
+ adminEmailMissing:
+ 'Su cuenta no tiene una dirección de correo válida a la que enviar un correo de prueba.',
},
status: {
logicalBackup: {
@@ -261,6 +264,16 @@ export const es: typeof en = {
reset: 'Restablecer',
updated: 'Ajustes guardados',
readMore: 'Más información sobre los ajustes <docsLink>en la documentación</docsLink>',
+ mailServer: {
+ title: 'Servidor de correo',
+ configured: 'El servidor de correo está configurado.',
+ notConfigured: 'El servidor de correo no está configurado.',
+ description:
+ 'Envía las invitaciones, los códigos para restablecer la contraseña y los códigos de acceso. Los canales de notificación por correo tienen su propia configuración SMTP.',
+ docs: 'La <docsLink>documentación de SMTP</docsLink> explica cómo conectar un servidor de correo.',
+ sendTestEmail: 'Enviar correo de prueba',
+ testEmailSent: 'Correo de prueba enviado a {{email}}',
+ },
healthcheck: {
title: 'Comprobación de disponibilidad',
openInNewTab: 'Abrir en una pestaña nueva',
@@ -1223,11 +1236,23 @@ export const es: typeof en = {
smtpPasswordPlaceholder: 'contraseña',
from: 'Remitente',
fromTooltip:
- 'Opcional. Dirección de correo electrónico del remitente. Si se deja vacía, se usa el usuario SMTP o una dirección generada a partir del host',
+ 'Opcional. Dirección del remitente, con o sin nombre: Acme Backups <[email protected]>. Si se deja vacía, se usa el usuario SMTP cuando es una dirección de correo y, si no, noreply@ con el host SMTP',
fromAuto: '(automático)',
advancedSettings: 'Ajustes avanzados',
skipTlsTooltip:
'No verifica el certificado TLS. Active esta opción si su servidor SMTP usa un certificado autofirmado. Advertencia: esto reduce la seguridad.',
+ security: 'Seguridad de la conexión',
+ securityTooltip:
+ 'TLS cifra la conexión desde el principio y suele usarse en el puerto 465. STARTTLS cifra la conexión después de abrirla y falla si el servidor no lo admite. «Sin cifrado» envía la contraseña y los mensajes sin cifrar: úselo solo con un relé de confianza que no admita STARTTLS.',
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: 'Sin cifrado',
+ },
+ heloName: 'Nombre de saludo',
+ heloNamePlaceholder: 'Automático',
+ heloNameTooltip:
+ 'El nombre con el que Databasus se presenta al servidor de correo (EHLO). Si se deja vacío, se usa el host de DATABASUS_URL o el nombre del equipo.',
},
telegram: {
botTokenHelpLink: '¿Cómo obtener el token de API del bot de Telegram?',
diff --git a/frontend/src/shared/i18n/locales/fr.ts b/frontend/src/shared/i18n/locales/fr.ts
index 5dbf5024..5959dcf4 100644
--- a/frontend/src/shared/i18n/locales/fr.ts
+++ b/frontend/src/shared/i18n/locales/fr.ts
@@ -142,6 +142,9 @@ export const fr: typeof en = {
signInCodeResentTooSoon:
"Un code a été envoyé il y a moins d'une minute. Attendez une minute avant d'en demander un autre.",
rateLimitExceeded: 'Trop de tentatives. Patientez un peu et réessayez.',
+ emailNotConfigured: "L'instance n'a pas de serveur de messagerie configuré.",
+ adminEmailMissing:
+ "Votre compte n'a pas d'adresse e-mail valide à laquelle envoyer un e-mail de test.",
},
status: {
logicalBackup: {
@@ -261,6 +264,16 @@ export const fr: typeof en = {
updated: 'Paramètres enregistrés',
readMore:
'Pour en savoir plus sur ces paramètres, <docsLink>consultez la documentation</docsLink>',
+ mailServer: {
+ title: 'Serveur de messagerie',
+ configured: 'Le serveur de messagerie est configuré.',
+ notConfigured: "Le serveur de messagerie n'est pas configuré.",
+ description:
+ 'Il envoie les invitations, les codes de réinitialisation du mot de passe et les codes de connexion. Les canaux de notification par e-mail ont leurs propres paramètres SMTP.',
+ docs: 'La <docsLink>documentation SMTP</docsLink> explique comment connecter un serveur de messagerie.',
+ sendTestEmail: 'Envoyer un e-mail de test',
+ testEmailSent: 'E-mail de test envoyé à {{email}}',
+ },
healthcheck: {
title: 'Vérification de disponibilité',
openInNewTab: 'Cliquez pour ouvrir dans un nouvel onglet',
@@ -1231,11 +1244,23 @@ export const fr: typeof en = {
smtpPasswordPlaceholder: 'mot de passe',
from: 'Expéditeur',
fromTooltip:
- "Facultatif. Adresse e-mail de l'expéditeur. Si le champ est vide, l'utilisateur SMTP est utilisé, ou une adresse est générée à partir de l'hôte",
+ "Facultatif. Adresse de l'expéditeur, avec ou sans nom : Acme Backups <[email protected]>. Si le champ est vide, l'utilisateur SMTP est utilisé s'il s'agit d'une adresse e-mail, sinon noreply@ suivi de l'hôte SMTP",
fromAuto: '(automatique)',
advancedSettings: 'Paramètres avancés',
skipTlsTooltip:
'Ne pas vérifier le certificat TLS. Activez cette option si votre serveur SMTP utilise un certificat auto-signé. Attention : cela réduit la sécurité.',
+ security: 'Sécurité de la connexion',
+ securityTooltip:
+ "TLS chiffre la connexion dès le départ, généralement sur le port 465. STARTTLS chiffre la connexion après son ouverture et échoue si le serveur ne le propose pas. « Sans chiffrement » envoie le mot de passe et les messages en clair : ne l'utilisez qu'avec un relais de confiance sans STARTTLS.",
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: 'Sans chiffrement',
+ },
+ heloName: 'Nom annoncé',
+ heloNamePlaceholder: 'Automatique',
+ heloNameTooltip:
+ "Le nom sous lequel Databasus se présente au serveur de messagerie (EHLO). S'il est vide, l'hôte de DATABASUS_URL est utilisé, ou à défaut le nom de la machine.",
},
telegram: {
botTokenHelpLink: "Comment obtenir le jeton d'API d'un bot Telegram ?",
diff --git a/frontend/src/shared/i18n/locales/pt.ts b/frontend/src/shared/i18n/locales/pt.ts
index 4938a2b8..a0048eae 100644
--- a/frontend/src/shared/i18n/locales/pt.ts
+++ b/frontend/src/shared/i18n/locales/pt.ts
@@ -143,6 +143,9 @@ export const pt: typeof en = {
signInCodeResentTooSoon:
'Um código foi enviado há menos de um minuto. Espere um minuto antes de pedir outro.',
rateLimitExceeded: 'Tentativas demais. Espere um pouco e tente novamente.',
+ emailNotConfigured: 'A instância não tem um servidor de e-mail configurado.',
+ adminEmailMissing:
+ 'Sua conta não tem um endereço de e-mail válido para receber o e-mail de teste.',
},
status: {
logicalBackup: {
@@ -261,6 +264,16 @@ export const pt: typeof en = {
reset: 'Redefinir',
updated: 'Configurações salvas',
readMore: 'Saiba mais sobre as configurações <docsLink>na documentação</docsLink>',
+ mailServer: {
+ title: 'Servidor de e-mail',
+ configured: 'O servidor de e-mail está configurado.',
+ notConfigured: 'O servidor de e-mail não está configurado.',
+ description:
+ 'Ele envia os convites, os códigos de redefinição de senha e os códigos de acesso. Os canais de notificação por e-mail têm configurações SMTP próprias.',
+ docs: 'Veja como conectar um servidor de e-mail na <docsLink>documentação de SMTP</docsLink>.',
+ sendTestEmail: 'Enviar e-mail de teste',
+ testEmailSent: 'E-mail de teste enviado para {{email}}',
+ },
healthcheck: {
title: 'Verificação de disponibilidade',
openInNewTab: 'Abrir em uma nova aba',
@@ -1215,11 +1228,23 @@ export const pt: typeof en = {
smtpPasswordPlaceholder: 'senha',
from: 'Remetente',
fromTooltip:
- 'Opcional. Endereço de e-mail usado como remetente. Se ficar vazio, será usado o usuário SMTP ou um endereço gerado a partir do host',
+ 'Opcional. Endereço do remetente, com ou sem nome: Acme Backups <[email protected]>. Se ficar vazio, será usado o usuário SMTP quando ele for um endereço de e-mail; caso contrário, noreply@ com o host SMTP',
fromAuto: '(automático)',
advancedSettings: 'Configurações avançadas',
skipTlsTooltip:
'Não verifica o certificado TLS. Ative se o seu servidor SMTP usa um certificado autoassinado. Atenção: isso reduz a segurança.',
+ security: 'Segurança da conexão',
+ securityTooltip:
+ 'TLS criptografa a conexão desde o início e costuma ser usado na porta 465. STARTTLS criptografa a conexão depois de aberta e falha se o servidor não oferecer esse recurso. “Sem criptografia” envia a senha e as mensagens sem proteção: use apenas com um relay confiável que não tenha STARTTLS.',
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: 'Sem criptografia',
+ },
+ heloName: 'Nome de saudação',
+ heloNamePlaceholder: 'Automático',
+ heloNameTooltip:
+ 'O nome com que o Databasus se apresenta ao servidor de e-mail (EHLO). Se ficar vazio, será usado o host de DATABASUS_URL ou o nome da máquina.',
},
telegram: {
botTokenHelpLink: 'Como obter o token da API do bot do Telegram?',
diff --git a/frontend/src/shared/i18n/locales/ru.ts b/frontend/src/shared/i18n/locales/ru.ts
index 103da617..b94b5e5d 100644
--- a/frontend/src/shared/i18n/locales/ru.ts
+++ b/frontend/src/shared/i18n/locales/ru.ts
@@ -139,6 +139,9 @@ export const ru: typeof en = {
signInCodeResentTooSoon:
'Код отправлен меньше минуты назад. Подождите минуту, прежде чем запрашивать новый.',
rateLimitExceeded: 'Слишком много попыток. Подождите немного и попробуйте снова.',
+ emailNotConfigured: 'Почтовый сервер не настроен.',
+ adminEmailMissing:
+ 'У вашего аккаунта нет корректного адреса почты, на который можно отправить тестовое письмо.',
},
status: {
logicalBackup: {
@@ -256,6 +259,16 @@ export const ru: typeof en = {
reset: 'Сбросить',
updated: 'Настройки сохранены',
readMore: 'Подробнее о настройках — <docsLink>в документации</docsLink>',
+ mailServer: {
+ title: 'Почтовый сервер',
+ configured: 'Почтовый сервер настроен.',
+ notConfigured: 'Почтовый сервер не настроен.',
+ description:
+ 'Через него уходят приглашения, коды сброса пароля и коды входа. У каналов уведомлений по email свои настройки SMTP.',
+ docs: 'Как подключить почтовый сервер, описано <docsLink>в документации по SMTP</docsLink>.',
+ sendTestEmail: 'Отправить тестовое письмо',
+ testEmailSent: 'Тестовое письмо отправлено на {{email}}',
+ },
healthcheck: {
title: 'Проверка доступности',
openInNewTab: 'Открыть в новой вкладке',
@@ -1200,11 +1213,23 @@ export const ru: typeof en = {
smtpPasswordPlaceholder: 'пароль',
from: 'Отправитель',
fromTooltip:
- 'Необязательно. Адрес, от имени которого уходят письма. Если поле пустое, используется пользователь SMTP или адрес, созданный по имени хоста',
+ 'Необязательно. Адрес отправителя, можно с именем: Acme Backups <[email protected]>. Если поле пустое, используется пользователь SMTP, когда это адрес почты, а иначе noreply@ и хост SMTP',
fromAuto: '(автоматически)',
advancedSettings: 'Дополнительные настройки',
skipTlsTooltip:
'Не проверять TLS-сертификат. Включите, если SMTP-сервер использует самоподписанный сертификат. Внимание: это снижает безопасность.',
+ security: 'Защита соединения',
+ securityTooltip:
+ 'TLS шифрует соединение с самого начала, обычно на порту 465. STARTTLS переводит соединение в зашифрованное и не отправляет письмо, если сервер этого не поддерживает. «Без шифрования» передает пароль и письма открытым текстом — выбирайте этот режим только для доверенного релея без STARTTLS.',
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: 'Без шифрования',
+ },
+ heloName: 'Имя в приветствии',
+ heloNamePlaceholder: 'Автоматически',
+ heloNameTooltip:
+ 'Имя, которым Databasus представляется почтовому серверу (EHLO). Если поле пустое, берется хост из DATABASUS_URL или имя машины.',
},
telegram: {
botTokenHelpLink: 'Как получить API-токен бота Telegram?',
diff --git a/frontend/src/shared/i18n/locales/zh.ts b/frontend/src/shared/i18n/locales/zh.ts
index 48f9da4a..81eb5940 100644
--- a/frontend/src/shared/i18n/locales/zh.ts
+++ b/frontend/src/shared/i18n/locales/zh.ts
@@ -134,6 +134,8 @@ export const zh: typeof en = {
tooManySignInCodes: '该账户在过去一小时内请求的登录验证码过多,请稍后重试。',
signInCodeResentTooSoon: '验证码发送不到一分钟,请稍等一分钟后再请求新的验证码。',
rateLimitExceeded: '尝试次数过多,请稍后重试。',
+ emailNotConfigured: '实例没有配置邮件服务器。',
+ adminEmailMissing: '你的账号没有可以接收测试邮件的有效邮箱地址。',
},
status: {
logicalBackup: {
@@ -249,6 +251,15 @@ export const zh: typeof en = {
reset: '重置',
updated: '设置已更新',
readMore: '关于这些设置的详细说明,请<docsLink>查看文档</docsLink>',
+ mailServer: {
+ title: '邮件服务器',
+ configured: '邮件服务器已配置。',
+ notConfigured: '邮件服务器未配置。',
+ description: '它负责发送邀请、密码重置码和登录验证码。邮件通知渠道有自己的 SMTP 设置。',
+ docs: '连接邮件服务器的方法见 <docsLink>SMTP 文档</docsLink>。',
+ sendTestEmail: '发送测试邮件',
+ testEmailSent: '测试邮件已发送至 {{email}}',
+ },
healthcheck: {
title: '可用性检查',
openInNewTab: '点击在新标签页中打开',
@@ -1153,11 +1164,24 @@ export const zh: typeof en = {
smtpPassword: 'SMTP 密码',
smtpPasswordPlaceholder: '密码',
from: '发件人',
- fromTooltip: '可选。用作发件人的邮箱地址。留空时使用 SMTP 用户,或根据主机自动生成',
+ fromTooltip:
+ '可选。发件人地址,可以带名称:Acme Backups <[email protected]>。留空时,如果 SMTP 用户是邮箱地址就使用它,否则使用 noreply@ 加 SMTP 主机',
fromAuto: '(自动)',
advancedSettings: '高级设置',
skipTlsTooltip:
'跳过 TLS 证书验证。如果 SMTP 服务器使用自签名证书,请开启此项。警告:这会降低安全性。',
+ security: '连接安全',
+ securityTooltip:
+ 'TLS 从一开始就加密连接,通常用于 465 端口。STARTTLS 在连接建立后升级为加密连接,服务器不支持时发送失败。“不加密”会以明文发送密码和邮件,只应在不支持 STARTTLS 的可信中继上使用。',
+ securityModes: {
+ tls: 'TLS',
+ starttls: 'STARTTLS',
+ none: '不加密',
+ },
+ heloName: '问候名称',
+ heloNamePlaceholder: '自动',
+ heloNameTooltip:
+ 'Databasus 向邮件服务器介绍自己时使用的名称(EHLO)。留空时使用 DATABASUS_URL 中的主机,或本机的主机名。',
},
telegram: {
botTokenHelpLink: '如何获取 Telegram 机器人 API 令牌?',
diff --git a/frontend/src/shared/i18n/translateApiError.ts b/frontend/src/shared/i18n/translateApiError.ts
index fa2e8983..2afebecd 100644
--- a/frontend/src/shared/i18n/translateApiError.ts
+++ b/frontend/src/shared/i18n/translateApiError.ts
@@ -15,6 +15,8 @@ const API_ERROR_CODE_KEYS: Record<string, TranslationKey> = {
sign_in_code_not_sent: 'errors.signInCodeNotSent',
too_many_sign_in_codes: 'errors.tooManySignInCodes',
sign_in_code_resent_too_soon: 'errors.signInCodeResentTooSoon',
+ email_not_configured: 'errors.emailNotConfigured',
+ admin_email_missing: 'errors.adminEmailMissing',
};
// The one way an error reaches the screen. The message of anything that is not an ApiError comes
diff --git a/openspec/changes/archive/2026-09-22-rework-smtp-sending/.openspec.yaml b/openspec/changes/archive/2026-09-22-rework-smtp-sending/.openspec.yaml
new file mode 100644
index 00000000..563fab5a
--- /dev/null
+++ b/openspec/changes/archive/2026-09-22-rework-smtp-sending/.openspec.yaml
@@ -0,0 +1,2 @@
+schema: spec-driven
+created: 2026-09-21
diff --git a/openspec/changes/archive/2026-09-22-rework-smtp-sending/design.md b/openspec/changes/archive/2026-09-22-rework-smtp-sending/design.md
new file mode 100644
index 00000000..40196761
--- /dev/null
+++ b/openspec/changes/archive/2026-09-22-rework-smtp-sending/design.md
@@ -0,0 +1,166 @@
+## Context
+
+See proposal.md for the motivation and `specs/outgoing-email/spec.md` for the behavior contract. This section covers only the current code the approach has to work with.
+
+Two copies of the SMTP code exist, and they have already drifted apart:
+
+| | Instance sender (`backend/internal/features/email/email.go`) | Notification channel (`backend/internal/features/notifiers/models/email_notifier/model.go`) |
+|---|---|---|
+| Encryption | port 465 means TLS, otherwise STARTTLS only if advertised (`:137-170`) | same rule (`:220-275`) |
+| Greeting | literal `localhost` (`:152`); the TLS path sends none, so the standard library greets as `localhost` too | `os.Hostname()` (`:124-134`), which in a container is its ID |
+| Authentication | PLAIN, then a second connection with LOGIN (`:172-206`) | same (`:277-312`) |
+| LOGIN prompts | also accepts `User Name\x00` and `Password\x00`, and answers any other prompt with the username (`:246-258`) | answers only `Username:` and `Password:` (`auth.go:17-27`) |
+| Headers | hand-assembled, no `Message-ID`, `MIME-version: 1.0;` (`:61-80`) | the same, plus `Message-ID` on the SMTP host's domain and CR/LF stripping (`:146-180`) |
+| Time limit | 5 s to open the connection, nothing after (`:121`, `:139`) | same |
+
+Two facts correct what the table might suggest. Go's DATA writer turns every bare LF into CRLF on the wire (`net/textproto`, `dotWriter.Write`), so the LF-only line endings in the header builders never reach the server. The standard library's Q-encoding also encodes any control character, so an invitation subject built from a workspace name (`backend/internal/features/workspaces/services/membership_service.go:107`) cannot add a header today. The injection requirement in the spec pins that property for the shared code; it is not fixing a live hole.
+
+The live hole is authentication, explained in proposal.md. `smtp.PlainAuth` refuses to run over an unencrypted connection to anything but localhost. The LOGIN fallback has no such check (`email.go:242-244`), and the two-connection retry that reaches it means one wrong password also costs two failed logins.
+
+Other code this change touches:
+
+- The instance sender is a singleton built from the environment. It counts as configured when `SMTP_HOST` and `SMTP_PORT` are both set (`backend/internal/features/email/di.go:13-22`). `backend/internal/config/config.go:158-161` already refuses to start with a host and no port. The container entrypoint derives the frontend's `IS_EMAIL_CONFIGURED` from `SMTP_HOST` and `DATABASUS_URL` (`docker/start.sh:144-149`), and the sign-in screen shows the password reset link only when that flag is set (`frontend/src/features/users/ui/SignInComponent.tsx:178`).
+- The users feature sees the sender through `EmailSender{IsConfigured; SendEmail(to, subject, body)}` (`backend/internal/features/users/interfaces/interfaces.go:13-18`). The workspaces feature sees only `SendEmail` (`backend/internal/features/workspaces/interfaces/interfaces.go:10`). Neither passes a context.
+- `SettingsService` already holds the sender and answers `IsEmailConfigured()` (`backend/internal/features/users/services/settings_service.go:52-54`). It also has a validator that decides whether an administrator's address is usable (`:20`, `:187`).
+- The only rate-limit helper that answers 429 is a method on `UserController` (`backend/internal/features/users/controllers/user_controller.go:426-443`). `SettingsController` has no limiter (`backend/internal/features/users/controllers/di.go:15-17`).
+- The frontend API helper turns every 502 and 504 into a generic "request failed" and drops the body (`frontend/src/shared/api/apiHelper.ts:18-19`). Other error statuses keep the backend's `error` text, and `translateApiError` shows it when the response carries no known `code` (`frontend/src/shared/i18n/translateApiError.ts:22-34`).
+- A failed notification is logged and stored as the channel's `LastSendError`, which the channel shows in the interface (`backend/internal/features/notifiers/service.go:310-325`).
+- The backend tests deliver notification mail to a Mailpit container that accepts any login over an unencrypted connection (`backend/internal/util/testing/containers/mailpit.go:31-34`). No compose file runs a Mailpit: the `test-mailpit` host in `.env.example`, which CI copies to `.env` (`.github/workflows/ci-release.yml:285`), resolves to nothing, so instance mail in tests that keep the real sender fails at the lookup and is only logged.
+- The password reset request returns any service error to the caller as `error` (`backend/internal/features/users/controllers/user_controller.go:391-394`), including a failed delivery (`user_services.go:590-592`), while an unknown address succeeds silently (`:511-514`). `Test_ResetPassword_EmailSendFailure_ReturnsError` pins today's 400. The change keeps that answer on purpose, as proposal.md explains, so the reworked transport errors reach the person who asked for the code.
+- Password sign-in with the second factor on fails closed when the code cannot be sent (`backend/internal/features/users/services/two_factor_auth.go:246-255`).
+
+The approach is constrained by [`backend/AGENTS.md`](../../../backend/AGENTS.md): positional DI, sentinel errors in `errors.go`, migrations with separate constraint statements, controller tests over unit tests, and the logging rules that forbid secrets and route emails through central redaction. [`frontend/AGENTS.md`](../../../frontend/AGENTS.md) adds the dictionary rule, enum label tables and progressive disclosure in forms. [`website/AGENTS.md`](../../../website/AGENTS.md) adds the six-language sync rule with identical heading anchors. The root [`AGENTS.md`](../../../AGENTS.md) forbids keeping the old encryption behavior as a compatibility mode.
+
+## Goals / Non-Goals
+
+**Goals:**
+
+- One implementation of the SMTP conversation, with no environment or database access, so it can be tested against fake servers.
+- Instance mail and notification channels differ only in where their settings come from.
+- A test message that surfaces the mail server's own words when delivery fails.
+
+**Non-Goals:**
+
+- Changing the `Send` signature every notifier backend implements. The email channel supplies its own deadline internally.
+- A queue or retry for instance mail. A delivery is still one synchronous attempt.
+
+## Decisions
+
+### The shared transport is a pure package under `internal/util/smtp_transport`
+
+The package exposes `Send(ctx, Connection, Message) error`. `Connection` holds host, port, security mode, username, password, greeting name and the certificate-verification switch. `Message` holds the sender, the recipient, the subject and the HTML body. The package also owns the rules both callers share: `GetDefaultSecurityForPort`, `ParseSender` (a bare address or a display name with an address, with the `Databasus` default name), `ResolveSender(from, username, host)`, `ValidateHeloName` and `GetDefaultHeloName(databasusURL)`. It reads no environment variables and no database.
+
+`features/email` builds a `Connection` from the environment once, answers `IsConfigured()` and sends through the transport. The notification model builds a `Connection` from its row and decrypted password and keeps only validation, encryption and its message text. The notification model reads `DATABASUS_URL` through `config.GetEnv()` for the default greeting name, as `backend/internal/features/storages/models/local/model.go` already reads the environment from a model.
+
+Alternatives rejected:
+
+- **Keep the code in `features/email` and have the notification model import it.** One feature's model would depend on another feature's package, and that package also carries the environment singleton the model has no business touching.
+- **Adopt a third-party mail library.** It would solve message building and TLS policy, but the user asked for the code to stay in the repository, and it adds a dependency for about 300 lines whose behavior the tests must pin either way.
+- **Name the package `smtp` or `email`.** `smtp` shadows `net/smtp` inside the package. `email` collides with `features/email` in the one file that imports both.
+
+### An explicit security mode replaces the port rule and optional STARTTLS
+
+`Security` is a string enum with the values `tls`, `starttls` and `none`. It lives in the transport's `enums.go`. `starttls` checks the server's EHLO answer and fails with `ErrStartTLSNotOffered` before any other command when the upgrade is not offered. `none` never attempts an upgrade. The certificate-verification switch applies to `tls` and `starttls` only.
+
+Alternatives rejected:
+
+- **Keep optional STARTTLS, or add it as a fourth `opportunistic` mode for migrated channels.** Either keeps the downgrade hole, and the root `AGENTS.md` rules out keeping the old behavior as a compatibility layer.
+- **A boolean `SMTP_TLS`.** It cannot tell a server that expects encryption from the first byte apart from one that expects an upgrade.
+- **Keep the port rule and only make STARTTLS mandatory.** TLS on a port other than 465 and a deliberately unencrypted relay would still have no way to be expressed.
+
+### Authentication is chosen from the server's offer, and both mechanisms check the connection
+
+After the connection is established and, where the mode requires it, upgraded, the transport reads the `AUTH` mechanisms from EHLO. It uses PLAIN when offered, then LOGIN, and fails with a clear error when credentials are configured but neither is offered. Both mechanisms are implemented in the package, and both refuse to start unless the connection is encrypted or the mode is `none`. When `starttls` fails because the upgrade is not offered, the transport closes the socket without sending `QUIT`, so the server sees nothing after `EHLO`. The LOGIN prompt match accepts the union of both current prompt sets, compared without regard to case. Any other prompt ends the attempt with an error rather than a guessed answer.
+
+Alternatives rejected:
+
+- **Keep PLAIN, then reconnect and try LOGIN.** It needs a second connection, and a wrong password becomes two failed logins, which brings account lockouts at some providers closer.
+- **Use `smtp.PlainAuth` from the standard library.** It permits unencrypted PLAIN to localhost regardless of the chosen mode and rejects it everywhere else even when the operator chose `none`. The mode, not the host name, has to decide.
+
+### One deadline covers the whole conversation
+
+`Send` derives a context with a 30-second timeout from the caller's context, dials with it and sets the same deadline on the connection. A caller with a shorter deadline wins. The notification channel passes `context.Background()`, because its `Send` has no context.
+
+Alternatives rejected:
+
+- **A `SMTP_TIMEOUT` variable.** No one has asked for it, and the proposal lists it as out of scope.
+- **Keep the dial timeout only.** A server that stops answering after the greeting holds the invitation request, or a sign-in waiting for its code, indefinitely.
+
+### Messages are built from parsed addresses, not from strings
+
+`From` and `To` are formatted with `net/mail.Address`, which encodes a non-ASCII display name. The subject has CR, LF and NUL removed and is Q-encoded. `Message-ID` is `<uuid@domain of the sender address>`. The body is sent as `text/html; charset="UTF-8"` with quoted-printable transfer encoding. The recipient is parsed with `net/mail.ParseAddress` and rejected if it carries anything but an address. The notification model applies the same parse to `TargetEmail` in `Validate`, so a bad recipient is refused on save rather than at the next backup event.
+
+Alternatives rejected:
+
+- **Keep `sanitizeHeaderValue` over hand-built header strings.** It works, but only for headers whose author remembers to call it.
+- **`Message-ID` on the SMTP host's domain, as the channel does today.** It leaks the internal relay's name into every message and has nothing to do with the sender.
+- **8-bit body without a transfer encoding.** HTML templates can hold lines longer than the 998 characters SMTP allows, and some servers would reject or break them.
+
+### "Configured" means `SMTP_HOST` is set, and the entrypoint agrees
+
+`features/email` computes `IsConfigured()` as `SMTPHost != ""`. The startup check guarantees a port whenever a host is set. `docker/start.sh` drops `DATABASUS_URL` from its condition, so the sign-in screen's reset link follows the same rule. The settings screen keeps reading `isEmailConfigured` from `GET /users/settings`, which already carries it.
+
+Alternatives rejected:
+
+- **Keep `DATABASUS_URL` in the rule.** It only adds a link to invitations. Requiring it hides password reset on instances that can send the reset code perfectly well.
+- **Let the sign-in screen ask the backend.** Anyone who is not signed in would need a public endpoint that answers the question, and the build-time flag already answers it correctly once the entrypoint uses the right condition.
+
+### `SMTP_FROM` accepts a display name instead of a new `SMTP_FROM_NAME`
+
+`ParseSender` accepts `[email protected]` or `Acme Backups <[email protected]>`. An unreadable `SMTP_FROM` stops startup, next to the existing port check. The channel's `from` field goes through the same parser in `Validate`.
+
+`ResolveSender` applies the fallback order both callers share. An explicit sender is parsed and its error returned. Without one, the username is used only when it parses as a bare address; otherwise the sender is `noreply@` and the host. Relays such as SendGrid (`apikey`) and SES (an access key ID) log in with a username that is not an address, and today that username becomes the envelope sender and every message is refused.
+
+`SMTP_HELO_NAME` and the channel's `heloName` go through `ValidateHeloName`: a host name of letters, digits, hyphens and dots, or an address literal in brackets (`[192.0.2.1]`, `[IPv6:2001:db8::1]`). An invalid `SMTP_HELO_NAME` stops startup; an invalid channel value is refused on save.
+
+Alternatives rejected:
+
+- **A separate `SMTP_FROM_NAME` variable and a `from_name` column.** That gives two ways to set a name, which then need a precedence rule. A `SMTP_FROM` already written with a display name, which fails at every send today, would still fail.
+- **Refuse any display name in `SMTP_FROM`.** It would turn setups that are broken today into instances that refuse to start, when accepting the form repairs them instead.
+- **Refuse at startup a username that is not an address when `SMTP_FROM` is unset.** It would stop instances whose relay accepts `noreply@host` as the sender.
+
+### The test message is a settings action for administrators
+
+`POST /users/settings/test-email` is registered in `SettingsController` behind `RequireRole(UserRoleAdmin)`. It is limited to five attempts per administrator per ten minutes, with the scope `test_email` and the user ID as identifier. `SettingsService.SendTestEmail(ctx, admin)` returns `ErrEmailNotConfigured` when the sender is not configured and `ErrAdminEmailMissing` when the address fails the validator the service already uses or `net/mail.ParseAddress`. Checking both keeps an address the transport would reject from surfacing as a delivery error instead of the refusal. Otherwise it sends and writes one audit entry with the outcome, whatever stage the failure happened at: `Test email sent to <address>` or `Test email to <address> failed`.
+
+The controller answers 200 with `{"recipientEmail": ...}` on success. The two refusals get 400 with the codes `email_not_configured` and `admin_email_missing`, and the frontend translates them. A delivery failure gets 400 with the transport's error as `error` and no code, so `translateApiError` shows the mail server's response.
+
+The rate-limit helper becomes a package-level function in `users/controllers`, which both controllers call. `SettingsController` gains the counter and a logger through positional DI.
+
+The frontend calls the endpoint with `fetchPostJson` and its default `isRetryOnError = false`. With retries on, `apiHelper` repeats a failed request up to 30 times (`frontend/src/shared/api/apiHelper.ts:6-7`), which would send a message per repeat and burn the rate limit.
+
+Alternatives rejected:
+
+- **502 for a delivery failure.** It is the honest status for a failing upstream, but `apiHelper.ts:18-19` replaces its body with a generic message, and the server's response is the reason the button exists.
+- **A recipient field.** It would let the instance mail any address. Proving that the server delivers only needs the administrator's own mailbox.
+- **Send through the unconfigured path and let it skip silently.** Then a test on an unconfigured instance would report success, which is the exact confusion this change removes.
+
+### The notification channel gains two columns with a port-based backfill
+
+The migration adds `security VARCHAR(16) NOT NULL DEFAULT 'starttls'`, sets `tls` where `smtp_port = 465`, drops the default and adds a `CHECK` constraint in its own statement. It adds `helo_name VARCHAR(255) NOT NULL DEFAULT ''`.
+
+A request may omit `security`. For a channel without a stored row, whether it is being created or sent a test notification before its first save (`backend/internal/features/notifiers/service.go:95-100` and the unsaved branch of `SendTestNotificationToNotifier`), the service calls a `FillDefaults` step that sets an empty mode from `GetDefaultSecurityForPort` before `Validate`. `Validate` itself stays free of side effects. On update, `Update` keeps the stored mode when the incoming one is empty, as it already keeps the stored password; a non-empty mode replaces it. `Validate` then requires a known mode, so an explicit unknown value is refused. `Update` copies `HeloName` unconditionally, since an empty greeting name is a valid choice.
+
+In the form, the security select and the greeting-name input join the existing advanced section. The section opens by itself when either field differs from its default. When the port changes, the form replaces the security mode with the new port's default only if the current mode equals the previous port's default. A mode that differs, whether picked in this session or stored earlier, is left alone. The rule holds for new and existing channels alike and needs no record of what the user touched. The proposal comes from the same port rule as the backend, kept in `entity/notifiers`.
+
+Alternatives rejected:
+
+- **Backfill every row with `none`.** It would quietly send every existing channel's credentials in cleartext.
+- **Keep the port rule on the server when `security` is empty.** Channels would have two sources of truth, and a stored row would not say what it actually does. Filling the mode once on create keeps the row explicit.
+- **Require `security` in every request.** Every existing API client that creates an email channel would start getting 400.
+- **Propose a mode only until the user picks one in the current editing session.** Changing only the port of a channel stored with `none` would silently switch it to `starttls`.
+
+## Risks / Trade-offs
+
+- **A relay without STARTTLS on a port other than 465 stops receiving mail after the upgrade.** → The proposal marks it BREAKING. The documentation tells the operator to use `none`. A notification channel shows the failure as its last send error, and the instance mail server shows it through the new test button.
+- **With the second factor on, the same relay locks everyone out of password sign-in, including the administrator who would press the test button.** → The documentation warns to set `SMTP_SECURITY` before upgrading when the second factor is on, and names the existing console command that switches it off. OAuth sign-in is unaffected.
+- **The default greeting name comes from `DATABASUS_URL`, which may hold an IP address or a port.** → Only the host part is used. An IP address is sent as an address literal in brackets, as the SMTP standard requires.
+- **Choosing PLAIN because it is offered can fail on a server that offers PLAIN but accepts only LOGIN.** → Such a server is rare, and the error names the mechanism that failed. Retrying across mechanisms is what doubled the failed logins, so it is not reinstated.
+- **A sign-in waiting for its second-factor code can now wait up to 30 seconds and then fail.** → Before this change it could wait indefinitely. The two-factor flow already fails closed when a code cannot be sent.
+- **An `SMTP_FROM` that cannot be read as an address now stops startup.** → Such a value could never have delivered mail. The log line names the variable, as the port check does.
+
+## Migration Plan
+
+1. The migration runs on startup and backfills `security` from the stored port. Its `down` drops both columns and the constraint.
+2. Operators on a relay without STARTTLS set `SMTP_SECURITY=none`, or pick `none` in the channel's advanced settings.
+3. Rolling back the code restores optional STARTTLS for instance mail. An older version ignores `SMTP_SECURITY` and `SMTP_HELO_NAME`, so nothing has to be removed from the environment.
diff --git a/openspec/changes/archive/2026-09-22-rework-smtp-sending/proposal.md b/openspec/changes/archive/2026-09-22-rework-smtp-sending/proposal.md
new file mode 100644
index 00000000..3724a45c
--- /dev/null
+++ b/openspec/changes/archive/2026-09-22-rework-smtp-sending/proposal.md
@@ -0,0 +1,57 @@
+## Why
+
+An operator configures SMTP for a backup-notification channel, sees those emails arrive, and still gets no workspace invitations. Invitations, password reset codes and sign-in codes go through a second, instance-wide mail server that is configured only through environment variables (`backend/internal/config/config.go:95-101`). When it is missing, a send is skipped with a warning and reported as a success (`backend/internal/features/email/email.go:38-41`). When it is present but broken, the invitation still succeeds and the failure reaches only the server log (`backend/internal/features/workspaces/services/membership_service.go:110-112`). Nothing in the interface tells an administrator which of the two cases they are in.
+
+Both senders also carry their own copy of the SMTP code (`email/email.go:82-258`, `notifiers/models/email_notifier/model.go:182-337`), and both copies share a flaw. STARTTLS is used only when the server advertises it. Without that advertisement the session stays unencrypted, the standard PLAIN authentication refuses to run, and the fallback LOGIN authentication sends the username and password in cleartext (`email/email.go:158-167`, `:172-205`). An attacker positioned between the instance and the mail server can strip the advertisement and read the credentials.
+
+## Governing docs
+
+This change answers to [`AGENTS.md`](../../../AGENTS.md) at the repo root, [`backend/AGENTS.md`](../../../backend/AGENTS.md), [`frontend/AGENTS.md`](../../../frontend/AGENTS.md) and [`website/AGENTS.md`](../../../website/AGENTS.md). The verification agent and the readme translations are untouched, so [`agent/verification/AGENTS.md`](../../../agent/verification/AGENTS.md) and [`assets/readme/AGENTS.md`](../../../assets/readme/AGENTS.md) do not apply.
+
+## What Changes
+
+- Move SMTP sending into one shared package under `backend/internal/util/`. The instance mail server and the email notification channel both call it. The notification channel keeps only its own concerns: validation, password encryption, and the text of its messages. The instance sender keeps only reading its configuration from the environment and answering whether it is configured.
+- Add an explicit connection security mode with three values: `tls` (encrypted from the first byte), `starttls` (upgrade required, the session is dropped if the server does not offer it) and `none` (no encryption, chosen deliberately). It replaces the rule that port 465 means TLS and every other port means optional STARTTLS.
+- **BREAKING** for any mail server on a port other than 465 that does not offer STARTTLS. Such servers used to receive mail in cleartext and now refuse the connection until the operator selects `none`: through `SMTP_SECURITY=none` for the instance, or in the channel's advanced settings for a notification channel. Existing notification channels are migrated to `tls` on port 465 and to `starttls` everywhere else. The optional-STARTTLS behavior is deleted, not kept as a fourth mode. A channel broken by this shows the failure through its existing last-send error. An instance that requires the emailed second factor at sign-in and sends through such a server admits nobody through password sign-in after the upgrade, because sign-in fails closed when the code cannot be sent. The documentation tells operators to set `SMTP_SECURITY` before upgrading and names the console command that switches the second factor off.
+- Add two instance variables: `SMTP_SECURITY` and `SMTP_HELO_NAME`, the name the instance greets the server with. By default that name is the host of `DATABASUS_URL`. The instance refuses to start when `SMTP_SECURITY` holds an unknown value or `SMTP_HELO_NAME` is neither a host name nor an address literal.
+- Let the sender address carry a display name in the usual form, `Acme Backups <[email protected]>`, in `SMTP_FROM` and in a channel's sender field. Today such a value goes into the envelope sender whole and the mail server rejects every message, so no working setup changes. A sender without a display name is shown as `Databasus`. When no sender is set, the username stands in for it only if it is an address. A username such as `apikey` or an access key ID falls through to `noreply@` and the host, where today it goes into the envelope sender and the message is rejected.
+- **BREAKING** for an `SMTP_FROM` that cannot be read as an address at all: the instance now refuses to start and names the variable, as it already does for a host without a port. A channel whose sender cannot be read as an address is refused when it is next saved.
+- Give the email notification channel the same two options in its existing "Advanced settings" section: connection security and greeting name. Two columns are added to `email_notifiers`. A request that omits the security mode keeps working: a new channel gets the mode its port implies, and an update keeps the stored mode. A channel's recipient and greeting name are checked when it is saved, as its sender already is.
+- Put a time limit on the whole SMTP session, not only on opening the connection. Today a server that accepts the connection and then goes quiet holds the invitation request open indefinitely.
+- Build every message the same way: `Message-ID` on instance mail as well, a well-formed `MIME-Version` header, a body encoded so long HTML lines survive transport, the display name kept out of the envelope sender, and header values that cannot add further headers.
+- Make "the instance mail server is configured" mean one thing everywhere: `SMTP_HOST` is set, since the instance already refuses to start with a host and no port (`config.go:158-161`). The container entrypoint currently also requires `DATABASUS_URL` before it shows the forgot-password link (`docker/start.sh:147`), and the configuration page documents that stricter rule. Both are aligned to the backend. `DATABASUS_URL` stays optional: it only adds a link to invitation messages (`membership_service.go:371-376`) and supplies the default greeting name.
+- Add a "Mail server" block to the settings screen, directly above the audit logs. It shows whether the instance mail server is configured and links to the SMTP section of the configuration documentation. It also says that notification channels have SMTP settings of their own, which is the confusion that started this work.
+- Add a "Send test email" button to that block, drawn as an outlined button. It sends a message to the signed-in administrator's own address and shows the mail server's actual error when delivery fails. It is disabled while the mail server is not configured. The backend endpoint behind it is available to administrators only, is rate-limited, refuses outright when nothing is configured, and records each attempt in the audit log.
+- Rewrite the SMTP section of the configuration documentation in English and in the five translated copies: the new variables, the corrected configured rule, the security modes, and the difference between the instance mail server and a notification channel.
+- Add `SMTP_SECURITY=none` to `.env.example`. Its SMTP block names a host, `test-mailpit`, that no compose file provides, so nothing depends on it today. A developer who points it at a local Mailpit, which offers no STARTTLS, would otherwise hit the stricter default.
+
+### Out of scope
+
+- Reporting an unsent invitation to the person who sent it. Invitations keep logging the failure and nothing more. Telling the inviter would mean storing the delivery outcome, and this change adds no table for that.
+- The password reset audit entry that says a code was sent when the send was skipped (`backend/internal/features/users/services/user_services.go:557-599`).
+- Hiding a failed password reset delivery. The reset request keeps answering 400 with the delivery error (`backend/internal/features/users/controllers/user_controller.go:391-394`), while an unknown address answers 200 (`user_services.go:511-514`). The person asking is almost always the account owner, and telling them the mail server is broken helps more than a code that silently never arrives. The difference it reveals about registered addresses shows only while the mail server is broken, and the request is already limited to three per address per hour (`user_controller.go:382-389`).
+- Access to `GET /users/settings`. Its description says "admin only", but every signed-in user needs it: the main screen loads it for everyone (`frontend/src/widgets/main/MainScreenComponent.tsx:61-66`), and the create-workspace dialog reads a member's permission from it. Only the incorrect description is fixed.
+- A configurable session timeout, a manual choice of authentication mechanism, and OAuth2 (XOAUTH2) authentication for mail providers.
+- Sending test messages to an arbitrary address. The test goes to the administrator's own address only.
+- Showing the host, port or any other part of the mail server configuration on the settings screen. The block reports configured or not configured, nothing more.
+- Other notification channels and other sections of the configuration documentation.
+
+## Capabilities
+
+### New Capabilities
+
+- `outgoing-email`: how the instance and email notification channels deliver mail. It covers connection security and credential protection, sender identity, message format, the session time limit, instance configuration and the single configured rule, the settings-screen status with its test message, and the published documentation.
+
+### Modified Capabilities
+
+None. `two-factor-authentication` already requires the settings screen to ask the instance whether its mail server is configured and to link to the SMTP documentation. The new block reuses the same answer and the same link, so that requirement holds unchanged. Sign-in codes travel through the reworked sender and gain its security guarantees without any change to the second-factor flow.
+
+## Impact
+
+- **Backend**: a new shared SMTP package under `internal/util/`; the instance sender in `internal/features/email/`, which gains a context-aware send; the email notification channel model; environment parsing and startup validation in `internal/config/config.go`; the settings controller and service, which gain the test-message endpoint and its audit entry; and the three callers of the instance sender (invitations, password reset, sign-in codes), which now pass their request context.
+- **Database**: one migration that adds two columns to `email_notifiers` and backfills the security mode from the stored port.
+- **API**: `POST /users/settings/test-email`, for administrators only. The email notification channel gains `security` and `heloName` in its request and response bodies; both are optional in a request. Its `from` field accepts a display name, and a `targetEmail` that is not a single address is refused on save. The generated API documentation changes with them.
+- **Frontend**: the settings screen gains the mail server block; the email notification channel form gains two advanced fields; the notifier type gains two fields, a security mode enum and its label table; the settings API client gains the test call; six interface dictionaries gain the new copy.
+- **Container**: `docker/start.sh` derives the forgot-password link flag from `SMTP_HOST` alone.
+- **Docs**: the SMTP section of `website/app/(en)/advanced-config/page.tsx` and its five translated copies.
+- **Config**: `.env.example` gains `SMTP_SECURITY=none`.
diff --git a/openspec/changes/archive/2026-09-22-rework-smtp-sending/specs/outgoing-email/spec.md b/openspec/changes/archive/2026-09-22-rework-smtp-sending/specs/outgoing-email/spec.md
new file mode 100644
index 00000000..eb2c3aee
--- /dev/null
+++ b/openspec/changes/archive/2026-09-22-rework-smtp-sending/specs/outgoing-email/spec.md
@@ -0,0 +1,308 @@
+## Purpose
+
+Describes how Databasus delivers email: the instance-wide mail server that sends invitations, password reset codes and sign-in codes, and the email notification channels that report backup events. It covers connection security, sender identity, message format, configuration, and the tools an administrator has to check the instance mail server.
+
+## ADDED Requirements
+
+### Requirement: One delivery behavior for instance mail and notification channels
+
+The instance mail server and every email notification channel SHALL deliver mail with the same behavior. Given the same server, port, credentials, security mode, sender and greeting name, both SHALL open the same kind of connection, authenticate the same way, build the message the same way and report failures the same way.
+
+#### Scenario: Same settings, same outcome
+
+- **WHEN** the instance mail server and an email notification channel are configured with identical connection settings and the mail server rejects the credentials
+- **THEN** both deliveries fail, and both report the mail server's rejection
+
+### Requirement: Explicit connection security mode
+
+Every delivery SHALL use one of three connection security modes:
+
+- `tls`: the connection is encrypted from its first byte.
+- `starttls`: the connection starts unencrypted and SHALL be upgraded to an encrypted one before any credential or message is sent. If the mail server does not offer the upgrade, the delivery SHALL fail.
+- `none`: the connection is never encrypted.
+
+In the `tls` and `starttls` modes the mail server's certificate SHALL be verified unless the operator has explicitly turned verification off.
+
+#### Scenario: Encrypted from the start
+
+- **WHEN** a delivery uses `tls` against a server that expects encryption from the first byte
+- **THEN** the message is delivered over an encrypted connection
+
+#### Scenario: Upgrade offered
+
+- **WHEN** a delivery uses `starttls` and the server offers the upgrade
+- **THEN** the connection is upgraded before authentication, and the message is delivered
+
+#### Scenario: Upgrade not offered
+
+- **WHEN** a delivery uses `starttls` and the server does not offer the upgrade
+- **THEN** the delivery fails with an error saying the server does not offer STARTTLS, and nothing after the greeting is sent to the server, not even `QUIT`
+
+#### Scenario: Deliberately unencrypted
+
+- **WHEN** a delivery uses `none`
+- **THEN** the message is delivered without encryption, with authentication if credentials are configured
+
+#### Scenario: Untrusted certificate
+
+- **WHEN** a delivery uses `tls` or `starttls` and the server presents a certificate that does not verify, and verification has not been turned off
+- **THEN** the delivery fails before any credential is sent
+
+### Requirement: Credentials and message content never cross an unencrypted connection by accident
+
+A username, a password or any part of a message SHALL NOT be sent over an unencrypted connection unless the operator selected the `none` mode for that delivery. This SHALL hold even when an attacker between the instance and the mail server removes the server's offer to upgrade the connection.
+
+#### Scenario: Upgrade offer stripped in transit
+
+- **WHEN** a delivery configured for `starttls` with credentials reaches a server whose upgrade offer an attacker has removed from the conversation
+- **THEN** the delivery fails, and neither the username nor the password nor any part of the message has been sent
+
+### Requirement: Delivery errors never reveal the mail server password
+
+An error produced by a delivery SHALL NOT contain the mail server password, wherever the error is shown: an API response, a notification channel's last-send error, the audit log or the server log.
+
+#### Scenario: Rejected credentials
+
+- **WHEN** the mail server rejects the configured credentials
+- **THEN** the reported error states that authentication failed and includes the server's response, and it does not include the password
+
+### Requirement: Instance mail server configuration
+
+The instance mail server SHALL be configured through environment variables: `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM`, `SMTP_SECURITY`, `SMTP_HELO_NAME` and `SMTP_INSECURE_SKIP_VERIFY`. `SMTP_INSECURE_SKIP_VERIFY` has no effect in the `none` mode.
+
+When `SMTP_SECURITY` is not set, the mode SHALL be `tls` for port 465 and `starttls` for every other port. The instance SHALL refuse to start, with a message naming the variable, when `SMTP_HOST` is set without a positive `SMTP_PORT`, when `SMTP_SECURITY` holds a value other than `tls`, `starttls` or `none`, when `SMTP_HELO_NAME` is set to something that is neither a host name nor an address literal, or when `SMTP_FROM` is set to something that is neither an email address nor a display name followed by an address in angle brackets.
+
+#### Scenario: Security mode left unset on port 587
+
+- **WHEN** the instance starts with `SMTP_HOST` set, `SMTP_PORT=587` and no `SMTP_SECURITY`
+- **THEN** instance mail is delivered in the `starttls` mode
+
+#### Scenario: Security mode left unset on port 465
+
+- **WHEN** the instance starts with `SMTP_HOST` set, `SMTP_PORT=465` and no `SMTP_SECURITY`
+- **THEN** instance mail is delivered in the `tls` mode
+
+#### Scenario: Unknown security mode
+
+- **WHEN** the instance starts with `SMTP_SECURITY=ssl`
+- **THEN** it refuses to start and names `SMTP_SECURITY` and the accepted values
+
+#### Scenario: Unreadable sender address
+
+- **WHEN** the instance starts with `SMTP_FROM=noreply at example.com`
+- **THEN** it refuses to start and names `SMTP_FROM`
+
+#### Scenario: Invalid greeting name
+
+- **WHEN** the instance starts with `SMTP_HELO_NAME=my relay`
+- **THEN** it refuses to start and names `SMTP_HELO_NAME`
+
+### Requirement: One answer to whether the instance mail server is configured
+
+The instance mail server SHALL count as configured exactly when `SMTP_HOST` is set. `DATABASUS_URL` SHALL NOT affect that answer. The settings screen, the second-factor switch, the sign-in screen's password reset link and the backend's own checks SHALL all rely on this one answer.
+
+#### Scenario: Mail server without a public address
+
+- **WHEN** the instance runs with `SMTP_HOST` and `SMTP_PORT` set and `DATABASUS_URL` unset
+- **THEN** the settings screen reports the mail server as configured, and the sign-in screen offers the password reset link
+
+#### Scenario: No mail server
+
+- **WHEN** the instance runs without `SMTP_HOST`
+- **THEN** the settings screen reports the mail server as not configured, and the sign-in screen does not offer the password reset link
+
+### Requirement: Sender identity
+
+Every message SHALL name its sender as a display name and an address. The envelope sender that the mail server sees SHALL be the address alone.
+
+A sender SHALL be accepted either as a bare address (`[email protected]`) or as a display name followed by an address in angle brackets (`Acme Backups <[email protected]>`). When the sender carries no display name, the display name SHALL be `Databasus`.
+
+For instance mail the sender SHALL be `SMTP_FROM`; when it is not set, `SMTP_USER` if that is a bare email address; otherwise `noreply@` followed by `SMTP_HOST`. For a notification channel it SHALL follow the same order over the channel's own sender, username and host. A channel whose sender is set but cannot be read in either accepted form SHALL be refused when it is saved.
+
+#### Scenario: Display name in the sender
+
+- **WHEN** the instance runs with `SMTP_FROM` set to `Acme Backups <[email protected]>`
+- **THEN** recipients see the sender as `Acme Backups <[email protected]>`, and the mail server receives `[email protected]` alone as the envelope sender
+
+#### Scenario: Bare sender address
+
+- **WHEN** the instance runs with `[email protected]`
+- **THEN** recipients see the sender as `Databasus <[email protected]>`
+
+#### Scenario: Username that is not an address
+
+- **WHEN** the instance runs with `SMTP_HOST=smtp.sendgrid.net`, `SMTP_USER=apikey` and no `SMTP_FROM`
+- **THEN** the envelope sender is `[email protected]`, and `apikey` appears nowhere in the sender
+
+#### Scenario: Non-ASCII display name
+
+- **WHEN** the display name in the sender contains characters outside ASCII
+- **THEN** recipients see the name exactly as configured
+
+#### Scenario: Notification channel with an unreadable sender
+
+- **WHEN** a user saves an email notification channel whose sender is `ops at example`
+- **THEN** the save is refused with a message that the sender must be an address, optionally preceded by a display name
+
+### Requirement: Greeting name
+
+Every delivery SHALL introduce itself to the mail server with a greeting name. That name SHALL be the configured greeting name (`SMTP_HELO_NAME` for instance mail, the channel's own setting for a notification channel). When none is configured, it SHALL be the host name from `DATABASUS_URL`, or the machine's host name when `DATABASUS_URL` is not set, or `localhost` when the host name is unavailable. When the name is an IP address, it SHALL be sent as an address literal: `[192.0.2.1]` for IPv4 and `[IPv6:2001:db8::1]` for IPv6. The greeting SHALL use the same name in every security mode.
+
+A configured greeting name SHALL be either a host name or an address literal in that form.
+
+#### Scenario: Greeting derived from the public address
+
+- **WHEN** the instance runs with `DATABASUS_URL=https://backup.example.com` and no greeting name is configured
+- **THEN** deliveries greet the mail server as `backup.example.com`
+
+#### Scenario: Explicit greeting name
+
+- **WHEN** `SMTP_HELO_NAME=mail.example.com` is set
+- **THEN** instance mail greets the mail server as `mail.example.com`
+
+#### Scenario: Public address given as an IPv6 address
+
+- **WHEN** the instance runs with `DATABASUS_URL=http://[2001:db8::1]:4005` and no greeting name is configured
+- **THEN** deliveries greet the mail server as `[IPv6:2001:db8::1]`
+
+### Requirement: Delivery time limit
+
+A single delivery SHALL finish or fail within 30 seconds of its start, counting the whole conversation with the mail server and not only opening the connection.
+
+#### Scenario: Server goes silent
+
+- **WHEN** the mail server accepts the connection and then stops responding
+- **THEN** the delivery fails with a timeout error within 30 seconds, and the request that triggered it completes
+
+### Requirement: Well-formed messages
+
+Every message SHALL carry a `From`, `To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Content-Type` and `Content-Transfer-Encoding` header. The `Message-ID` SHALL be unique per message. A subject or a name containing characters outside ASCII SHALL reach the recipient intact without requiring the server to support UTF-8 addressing. The body SHALL be encoded so that no line on the wire exceeds the limit mail servers enforce, whatever the length of the lines in the original text.
+
+#### Scenario: Instance mail carries a message identifier
+
+- **WHEN** the instance sends an invitation
+- **THEN** the delivered message has a `Message-ID` header that differs from every other message the instance has sent
+
+#### Scenario: Long body line
+
+- **WHEN** a message body contains a single line of 5,000 characters
+- **THEN** the recipient reads the body exactly as it was written
+
+### Requirement: Header values cannot add headers
+
+No value placed in a header SHALL be able to add a header or end the header block. This covers subjects built from user-supplied text such as a workspace name, the recipient address, and the sender's display name and address.
+
+#### Scenario: Line break in a workspace name
+
+- **WHEN** a workspace is named `Ops\r\nBcc: [email protected]` and an invitation to it is sent
+- **THEN** the delivered message has no `Bcc` header, and the recipient list holds only the invited address
+
+### Requirement: Failed instance mail is logged
+
+When instance mail cannot be delivered for an invitation, the invitation SHALL still be created, and the failure SHALL be written to the server log with the reason. When the instance mail server is not configured, an attempted send SHALL be written to the server log as skipped.
+
+#### Scenario: Invitation with a broken mail server
+
+- **WHEN** an administrator invites a user while the mail server rejects every message
+- **THEN** the invitation is created, and the server log records that the invitation email failed and why
+
+### Requirement: Notification channel connection options
+
+An email notification channel SHALL let its owner choose the connection security mode and the greeting name. These options SHALL sit in the channel form's advanced settings next to the existing certificate verification switch. The default mode for a port SHALL be `tls` for 465 and `starttls` for every other port. When the port changes in the form, the security mode SHALL follow the new port's default only if it equals the previous port's default; any other mode SHALL be kept.
+
+A request that omits the security mode SHALL be accepted: a new channel SHALL be saved with its port's default, and an updated channel SHALL keep its stored mode. A request naming an unknown mode SHALL be refused. A channel SHALL be refused on save when its recipient is not a single email address or its greeting name is neither a host name nor an address literal.
+
+Channels that existed before this capability SHALL be given `tls` if their port is 465 and `starttls` otherwise, with no greeting name.
+
+#### Scenario: New channel on port 465
+
+- **WHEN** a user creates an email notification channel, enters port 465 and does not touch the security mode
+- **THEN** the form proposes `tls`, and the channel is saved with `tls`
+
+#### Scenario: Port change keeps a deliberate choice
+
+- **WHEN** the owner of a channel stored with `none` on port 25 changes its port to 2525 and saves
+- **THEN** the channel is saved with `none`
+
+#### Scenario: API client that does not know the security mode
+
+- **WHEN** a client creates an email notification channel on port 587 without a security mode, and later updates it without one
+- **THEN** the channel is created with `starttls`, and the update keeps `starttls`
+
+#### Scenario: Existing channel after upgrade
+
+- **WHEN** an instance upgrades with an email notification channel on port 587
+- **THEN** the channel uses `starttls`, and its advanced settings show that mode
+
+#### Scenario: Existing channel pointed at a server without STARTTLS
+
+- **WHEN** an upgraded channel on port 25 points at a server that does not offer STARTTLS
+- **THEN** its next notification fails, the channel shows the failure as its last send error, and it delivers again once its owner selects `none`
+
+### Requirement: Mail server status on the settings screen
+
+The settings screen SHALL show administrators a mail server block directly above the audit logs. The block SHALL say whether the instance mail server is configured and link to the SMTP section of the published configuration documentation. It SHALL state that instance mail covers invitations, password reset codes and sign-in codes, and that email notification channels use SMTP settings of their own. It SHALL NOT show the host, port, username, sender or any other part of the configuration.
+
+#### Scenario: Configured
+
+- **WHEN** an administrator opens the settings screen on an instance with `SMTP_HOST` set
+- **THEN** the mail server block says the mail server is configured
+
+#### Scenario: Not configured
+
+- **WHEN** an administrator opens the settings screen on an instance without `SMTP_HOST`
+- **THEN** the mail server block says the mail server is not configured and links to the documentation that explains how to connect one
+
+### Requirement: Test message from the settings screen
+
+The mail server block SHALL offer a button that sends a test message to the signed-in administrator's own address. The button SHALL be unavailable while the mail server is not configured. After a send, the screen SHALL either confirm the delivery and name the address it went to, or show the error the delivery produced, including the mail server's response.
+
+The instance SHALL refuse a test send, and say why, when the mail server is not configured or when the administrator's account has no valid email address. It SHALL NOT fall back to skipping the send silently.
+
+#### Scenario: Successful test
+
+- **WHEN** an administrator presses the test button with a working mail server
+- **THEN** a test message arrives at the administrator's address, and the screen confirms which address it was sent to
+
+#### Scenario: Mail server rejects the login
+
+- **WHEN** an administrator presses the test button and the mail server rejects the credentials
+- **THEN** the screen shows that authentication failed together with the mail server's response
+
+#### Scenario: Mail server not configured
+
+- **WHEN** a test send is requested on an instance without `SMTP_HOST`
+- **THEN** the request is refused with an answer saying the mail server is not configured, and nothing is sent
+
+#### Scenario: Account without a usable address
+
+- **WHEN** an administrator whose account holds no valid email address requests a test send
+- **THEN** the request is refused with an answer saying the account has no address to send to
+
+### Requirement: Test message access, abuse limits and audit
+
+Only administrators SHALL be able to request a test message. Each administrator SHALL be limited to five test messages in ten minutes. Every test send the instance attempts, whatever stage it fails at, SHALL be recorded in the audit log with the administrator, the recipient address and whether it was delivered.
+
+#### Scenario: Member requests a test message
+
+- **WHEN** a signed-in user who is not an administrator requests a test send
+- **THEN** the request is refused as forbidden, and nothing is sent
+
+#### Scenario: Too many test messages
+
+- **WHEN** an administrator requests a sixth test send within ten minutes
+- **THEN** the request is refused as rate-limited, and nothing is sent
+
+#### Scenario: Failed test in the audit log
+
+- **WHEN** an administrator's test send fails at the mail server
+- **THEN** the audit log shows an entry naming the administrator, the recipient address and that the delivery failed
+
+### Requirement: Published mail server documentation
+
+The SMTP section of the published configuration documentation SHALL describe every instance mail variable, the three security modes and the default mode for each port, the rule that decides whether the mail server counts as configured, and the difference between the instance mail server and an email notification channel. It SHALL warn that `none` sends credentials and messages unencrypted. It SHALL warn that an instance requiring the emailed second factor admits nobody through password sign-in while its mail server cannot deliver, tell operators on a relay without STARTTLS to set `SMTP_SECURITY` before upgrading, and name the console command that switches the second factor off. The section SHALL be published in every language the website ships and keep the same anchor in each.
+
+#### Scenario: Operator migrating a plain relay
+
+- **WHEN** an operator whose relay on port 25 does not offer STARTTLS reads the SMTP section in any published language
+- **THEN** the section tells them to set `SMTP_SECURITY=none` before upgrading, warns what that setting exposes, and warns that with the second factor on a missed setting locks password sign-in until it is fixed or the second factor is switched off
diff --git a/openspec/changes/archive/2026-09-22-rework-smtp-sending/tasks.md b/openspec/changes/archive/2026-09-22-rework-smtp-sending/tasks.md
new file mode 100644
index 00000000..e269ac9a
--- /dev/null
+++ b/openspec/changes/archive/2026-09-22-rework-smtp-sending/tasks.md
@@ -0,0 +1,51 @@
+Backend commands run from `backend/`, frontend commands from `frontend/`, website commands from `website/`. Package tests use `go test ./internal/<path>/... -count=1`, as the root `AGENTS.md` recommends; the full `make test` (or `make test-fedora` on a Fedora host) runs once, in section 7.
+
+## 1. Shared SMTP transport
+
+- [x] 1.1 Create `backend/internal/util/smtp_transport` with the `Security` enum (`tls`, `starttls`, `none`) in `enums.go`, sentinel errors in `errors.go`, the `Connection` and `Message` types, and `Send(ctx, Connection, Message)`, which opens the connection in the chosen mode and greets with the configured name in every mode. Verify with tests against in-process fake SMTP servers: `tls` delivers, `starttls` upgrades before any other command, `starttls` against a server that does not offer the upgrade fails with `ErrStartTLSNotOffered` and closes the socket having sent nothing past EHLO, not even `QUIT`, `none` never upgrades, and an untrusted certificate fails unless verification is switched off.
+- [x] 1.2 Implement PLAIN and LOGIN authentication inside the package. Choose the mechanism from the server's `AUTH` offer (PLAIN first, then LOGIN), refuse either one on an unencrypted connection unless the mode is `none`, match LOGIN prompts from both current prompt sets without regard to case, and fail on any other prompt. Verify with fake-server tests: a stripped STARTTLS offer never produces an `AUTH` command, PLAIN is used when both are offered, LOGIN is used when only it is offered, an unknown prompt ends the attempt, and an authentication error carries the server's response but not the password.
+- [x] 1.3 Build messages from parsed addresses: `From` and `To` through `net/mail.Address`, the subject with CR, LF and NUL removed and then Q-encoded, `Message-ID` on the sender's domain, `MIME-Version: 1.0`, `Content-Type: text/html; charset="UTF-8"` and a quoted-printable body. Verify with tests that read the message a fake server received: a subject containing `\r\nBcc: [email protected]` produces no `Bcc` header and a single recipient, a non-ASCII display name decodes back to the original, a 5,000-character body line arrives unchanged after decoding with no wire line over 998 characters, and two messages carry different `Message-ID` values.
+- [x] 1.4 Bound the whole conversation with a 30-second deadline derived from the caller's context and applied to both the dial and the connection. Verify with a test against a server that greets and then goes silent, using a shorter caller deadline so the test runs quickly, and assert that `Send` returns a timeout error within that deadline.
+- [x] 1.5 Add `GetDefaultSecurityForPort`, `ParseSender` (a bare address or a display name with an address, with `Databasus` as the default name), `ResolveSender(from, username, host)` (the explicit sender, else the username only if it parses as a bare address, else `noreply@` and the host), `ValidateHeloName` (a host name or an address literal) and `GetDefaultHeloName(databasusURL)` (the host part only, then the machine host name, then `localhost`; an IPv4 address as `[192.0.2.1]`, an IPv6 address as `[IPv6:2001:db8::1]`). Verify with table tests for each function, including a URL with a port, an IPv4 and an IPv6 host, a sender such as `ops at example`, which must be rejected, a username `apikey` resolving to `noreply@<host>`, and greeting names `my relay` and `[::1]`, which must be rejected.
+- [x] 1.6 Run `make lint` and `go test ./internal/util/smtp_transport/... -count=1`.
+
+## 2. Instance mail server
+
+- [x] 2.1 Add `SMTP_SECURITY` and `SMTP_HELO_NAME` to `backend/internal/config/config.go`. Move the SMTP startup checks into a function that returns an error, so the existing port check, the security value check, the `SMTP_HELO_NAME` check and the `SMTP_FROM` check can be tested without exiting the process. Verify with tests for an unknown `SMTP_SECURITY`, an invalid `SMTP_HELO_NAME`, an unreadable `SMTP_FROM`, a display-name `SMTP_FROM`, which must be accepted, and a host without a port.
+- [x] 2.2 Rebuild `backend/internal/features/email` on the transport. The singleton builds a `Connection` from the environment, resolves the sender through `ResolveSender`, `IsConfigured()` becomes `SMTPHost != ""`, `SendEmail` takes a context, and the unconfigured path keeps logging a skip. Delete the old connection, authentication and header code together with its `loginAuth`, and move the existing TLS test to the transport package if the transport tests do not already cover it. Verify with `go test ./internal/features/email/... -count=1` and `make lint`.
+- [x] 2.3 Add a context parameter to `SendEmail` in `users/interfaces/interfaces.go`, `workspaces/interfaces/interfaces.go` and both mocks. Pass the request context from the sign-in code send (`two_factor_auth.go:246`), the password reset send (`user_services.go:590`) and the invitation send (`membership_service.go:110`). Verify with `go test ./internal/features/users/... ./internal/features/workspaces/... -count=1`.
+- [x] 2.4 Change the condition in `generate_frontend_runtime_configuration` in `docker/start.sh` to `SMTP_HOST` alone. Verify by running that function in a shell with `SMTP_HOST` set and `DATABASUS_URL` unset and reading `IS_EMAIL_CONFIGURED: 'true'` in the generated file.
+- [x] 2.5 Add `SMTP_SECURITY=none` to `.env.example` next to the other SMTP lines, after the user confirms this edit explicitly, because `.env*` files change only with that confirmation. Its `test-mailpit` host is provided by no compose file, so the line matters only to a developer who points the block at a local Mailpit. Verify that the backend still starts with the resulting `.env` and that the users and workspaces package tests from 2.3 pass.
+
+## 3. Email notification channel
+
+- [x] 3.1 Create the migration with `make migration-create name=add_security_to_email_notifiers`. Add `security` with a temporary `starttls` default, set `tls` where `smtp_port = 465`, drop the default, add the `CHECK` constraint in its own statement, and add `helo_name` with an empty default. The down step drops the constraint and both columns. Verify with `make migration-up` and `make migration-down` on a scratch database, and by checking that a row on port 465 comes out as `tls` and a row on port 587 as `starttls`.
+- [x] 3.2 Add `Security` and `HeloName` to `EmailNotifier`. In `Validate`, require a known security mode, a readable `From`, a `TargetEmail` that parses as a single bare address and a `HeloName` that is empty or passes `ValidateHeloName`. In `Update`, keep the stored `Security` when the incoming one is empty and copy `HeloName` as given. Add a `FillDefaults` step on `Notifier` that delegates to the email model and sets an empty `Security` from the port, and call it before `Validate` in the create branch of `SaveNotifier` and the unsaved branch of `SendTestNotificationToNotifier` in `notifiers/service.go`. Rewrite `Send` to build a `Connection` from the row, with the sender from `ResolveSender` and the default greeting name from `DATABASUS_URL`, and call the transport with `context.Background()`. Delete the old SMTP code, `getHelloName`, `sanitizeHeaderValue` and `auth.go`. Verify with the Mailpit test in `model_test.go` switched to `none`, plus a new test that the same Mailpit server with `starttls` fails with the STARTTLS error.
+- [x] 3.3 Add notifier controller tests: a channel whose sender is `ops at example` is refused on save, a display-name sender is accepted, an unknown security mode is refused, a recipient `ops at example` and a greeting name `my relay` are refused, a channel created on port 587 without `security` is saved with `starttls`, an update without `security` keeps the stored mode, a test notification for an unsaved channel without `security` is not refused by validation, and `security` and `heloName` come back as saved. Verify with `go test ./internal/features/notifiers/... -count=1`.
+- [x] 3.4 Run `make swagger` and `make lint`.
+
+## 4. Test message endpoint
+
+- [x] 4.1 Turn `checkRateLimitOrRespond` (`user_controller.go:426-443`) into a package-level function in `users/controllers` that takes the counter and the logger, and call it from `UserController`. Verify that the existing sign-in and password reset rate-limit tests pass unchanged.
+- [x] 4.2 Add `ErrEmailNotConfigured` and `ErrAdminEmailMissing` and `SettingsService.SendTestEmail(ctx, admin)`. It checks configuration, checks the address with the validator already in `settings_service.go` and with `net/mail.ParseAddress`, sends a short test message and writes one audit entry with the outcome, whatever stage a failure happens at. Add `POST /users/settings/test-email` to `SettingsController` behind `RequireRole(UserRoleAdmin)` and the `test_email` rate limit of five per administrator per ten minutes, and give the controller the counter and a logger through positional DI. Answer 200 with `recipientEmail` on success, 400 with `email_not_configured` or `admin_email_missing` on a refusal, and 400 with the delivery error and no code on a failed send. In the same file, correct the `GetUsersSettings` description, which claims the endpoint is for administrators only. Verify with `make swagger` and `make lint`.
+- [x] 4.3 Add controller tests for the endpoint: a successful send reaches the mock sender at the administrator's address and writes a "sent" audit entry, a member gets 403, an unconfigured sender gets `email_not_configured` and nothing is sent, an administrator with the bootstrap login gets `admin_email_missing`, a sixth request within the window gets 429, and a failing sender returns its error text and writes a "failed" audit entry. Verify with `go test ./internal/features/users/... -count=1`.
+
+## 5. Frontend
+
+- [x] 5.1 In `entity/notifiers`, add the `EmailNotifierSecurity` enum in its own file, `EMAIL_NOTIFIER_SECURITY_LABEL_KEYS`, `security` and `heloName` on `EmailNotifier`, `getDefaultEmailNotifierSecurity(port)` using the backend's port rule, and `getSecurityAfterPortChange(currentSecurity, previousPort, nextPort)`, which returns the next port's default only when the current mode equals the previous port's default. Export them through the slice's `index.ts`. Verify with `pnpm test` cases for the port rule and for the port change: `starttls` on 587 becomes `tls` on 465, and `none` on 25 stays `none` on 2525.
+- [x] 5.2 Add the security select and the greeting-name input to the advanced section of `EditEmailNotifierComponent.tsx`. Open the section by itself when either field differs from its default, and apply `getSecurityAfterPortChange` on every port change. Verify in the running application: creating a channel on port 465 saves `tls`, editing a migrated channel shows its stored mode, and a channel stored with `none` keeps `none` after only its port is changed and it is saved.
+- [x] 5.3 Add `sendTestEmail` to `entity/users/api/settingsApi.ts` with its response type in its own model file. Call `fetchPostJson` with the default `isRetryOnError = false`, so a failed send is not repeated. Map `email_not_configured` and `admin_email_missing` in the API error code table used by `translateApiError`. Verify with `pnpm build`.
+- [x] 5.4 Add `MailServerComponent` in `features/settings/ui` and render it in `SettingsComponent.tsx` directly above `AuditLogsComponent`. It shows the configured state from the settings response, the documentation link through `getWebsitePageUrl('advancedConfigEmailSmtp', locale)`, and the note that notification channels have their own SMTP settings. It also has a `type="primary" ghost` "Send test email" button that is disabled when the mail server is not configured, confirms delivery with the recipient address and shows failures through `translateApiError`. Verify in the running application with the mail server configured against Mailpit, with it unconfigured, and with a wrong password.
+- [x] 5.5 Add the new copy to all six dictionaries in `shared/i18n/locales/`, using the interface terms from `website/AGENTS.md` and a plain hyphen in English. Verify with `pnpm test`, which runs the placeholder check in `dictionaries.test.ts`, and `pnpm build`, which fails on a missing key.
+- [x] 5.6 Run `pnpm format`, `pnpm lint`, `pnpm test` and `pnpm build`.
+
+## 6. Documentation
+
+- [x] 6.1 Rewrite the SMTP section of `website/app/(en)/advanced-config/page.tsx` under the unchanged `email-smtp` anchor. It covers the rule that `SMTP_HOST` makes the mail server configured, the sender fallback that skips a username which is not an address, a warning that an instance requiring the emailed second factor must set `SMTP_SECURITY` before upgrading if its relay offers no STARTTLS, with the console command that switches the second factor off, the variable table with `SMTP_SECURITY`, `SMTP_HELO_NAME` and the display-name form of `SMTP_FROM`, the three security modes with the default for each port and a warning that `none` sends credentials and messages unencrypted, the advice to use `none` for a relay without STARTTLS, `DATABASUS_URL` as optional (invitation links and the default greeting name), and the difference between the instance mail server and an email notification channel. Update the page description and metadata if they mention the old rule. Verify with `npm run build` and `npm run lint`.
+- [x] 6.2 Apply the same section to the five copies in `website/app/[lang]/advanced-config/content/`, keeping the hierarchy, the anchor and every technical string byte-identical to English, and following the translation rules in `website/AGENTS.md`. Verify with `npm run build` and by checking that `out/{ru,es,pt,zh,fr}/advanced-config/index.html` each contain the `email-smtp` anchor and the `SMTP_SECURITY` row.
+
+## 7. Verification and review
+
+- [x] 7.1 Run `make test` in `backend/` (`make test-fedora` on a Fedora host) and `make lint`, then `pnpm lint`, `pnpm test` and `pnpm build` in `frontend/`, and `npm run lint` and `npm run build` in `website/`.
+- [x] 7.2 In the running application, reproduce the reported situation. No compose file provides a Mailpit, so start one first: `docker run -d --name databasus-mailpit -p 1025:1025 -p 8025:8025 -e MP_SMTP_AUTH_ACCEPT_ANY=true -e MP_SMTP_AUTH_ALLOW_INSECURE=true axllent/mailpit:v1.20.5`, the image and settings the backend tests use. With a notification channel configured and no `SMTP_HOST`, the settings screen shows the mail server as not configured and the button is disabled. After `SMTP_HOST=localhost`, `SMTP_PORT=1025` and `SMTP_SECURITY=none` are set, the test message arrives, and a workspace invitation arrives with `Databasus` as the sender name and a `Message-ID`.
+- [x] 7.3 Pass the mandatory post-implementation review that the hooks run, resolve every finding, and list refactor suggestions for the diff as the root `AGENTS.md` requires.
diff --git a/openspec/specs/outgoing-email/spec.md b/openspec/specs/outgoing-email/spec.md
new file mode 100644
index 00000000..50b9e10b
--- /dev/null
+++ b/openspec/specs/outgoing-email/spec.md
@@ -0,0 +1,310 @@
+# Outgoing Email Specification
+
+## Purpose
+
+Describes how Databasus delivers email: the instance-wide mail server that sends invitations, password reset codes and sign-in codes, and the email notification channels that report backup events. It covers connection security, sender identity, message format, configuration, and the tools an administrator has to check the instance mail server.
+
+## Requirements
+
+### Requirement: One delivery behavior for instance mail and notification channels
+
+The instance mail server and every email notification channel SHALL deliver mail with the same behavior. Given the same server, port, credentials, security mode, sender and greeting name, both SHALL open the same kind of connection, authenticate the same way, build the message the same way and report failures the same way.
+
+#### Scenario: Same settings, same outcome
+
+- **WHEN** the instance mail server and an email notification channel are configured with identical connection settings and the mail server rejects the credentials
+- **THEN** both deliveries fail, and both report the mail server's rejection
+
+### Requirement: Explicit connection security mode
+
+Every delivery SHALL use one of three connection security modes:
+
+- `tls`: the connection is encrypted from its first byte.
+- `starttls`: the connection starts unencrypted and SHALL be upgraded to an encrypted one before any credential or message is sent. If the mail server does not offer the upgrade, the delivery SHALL fail.
+- `none`: the connection is never encrypted.
+
+In the `tls` and `starttls` modes the mail server's certificate SHALL be verified unless the operator has explicitly turned verification off.
+
+#### Scenario: Encrypted from the start
+
+- **WHEN** a delivery uses `tls` against a server that expects encryption from the first byte
+- **THEN** the message is delivered over an encrypted connection
+
+#### Scenario: Upgrade offered
+
+- **WHEN** a delivery uses `starttls` and the server offers the upgrade
+- **THEN** the connection is upgraded before authentication, and the message is delivered
+
+#### Scenario: Upgrade not offered
+
+- **WHEN** a delivery uses `starttls` and the server does not offer the upgrade
+- **THEN** the delivery fails with an error saying the server does not offer STARTTLS, and nothing after the greeting is sent to the server, not even `QUIT`
+
+#### Scenario: Deliberately unencrypted
+
+- **WHEN** a delivery uses `none`
+- **THEN** the message is delivered without encryption, with authentication if credentials are configured
+
+#### Scenario: Untrusted certificate
+
+- **WHEN** a delivery uses `tls` or `starttls` and the server presents a certificate that does not verify, and verification has not been turned off
+- **THEN** the delivery fails before any credential is sent
+
+### Requirement: Credentials and message content never cross an unencrypted connection by accident
+
+A username, a password or any part of a message SHALL NOT be sent over an unencrypted connection unless the operator selected the `none` mode for that delivery. This SHALL hold even when an attacker between the instance and the mail server removes the server's offer to upgrade the connection.
+
+#### Scenario: Upgrade offer stripped in transit
+
+- **WHEN** a delivery configured for `starttls` with credentials reaches a server whose upgrade offer an attacker has removed from the conversation
+- **THEN** the delivery fails, and neither the username nor the password nor any part of the message has been sent
+
+### Requirement: Delivery errors never reveal the mail server password
+
+An error produced by a delivery SHALL NOT contain the mail server password, wherever the error is shown: an API response, a notification channel's last-send error, the audit log or the server log.
+
+#### Scenario: Rejected credentials
+
+- **WHEN** the mail server rejects the configured credentials
+- **THEN** the reported error states that authentication failed and includes the server's response, and it does not include the password
+
+### Requirement: Instance mail server configuration
+
+The instance mail server SHALL be configured through environment variables: `SMTP_HOST`, `SMTP_PORT`, `SMTP_USER`, `SMTP_PASSWORD`, `SMTP_FROM`, `SMTP_SECURITY`, `SMTP_HELO_NAME` and `SMTP_INSECURE_SKIP_VERIFY`. `SMTP_INSECURE_SKIP_VERIFY` has no effect in the `none` mode.
+
+When `SMTP_SECURITY` is not set, the mode SHALL be `tls` for port 465 and `starttls` for every other port. The instance SHALL refuse to start, with a message naming the variable, when `SMTP_HOST` is set without a positive `SMTP_PORT`, when `SMTP_SECURITY` holds a value other than `tls`, `starttls` or `none`, when `SMTP_HELO_NAME` is set to something that is neither a host name nor an address literal, or when `SMTP_FROM` is set to something that is neither an email address nor a display name followed by an address in angle brackets.
+
+#### Scenario: Security mode left unset on port 587
+
+- **WHEN** the instance starts with `SMTP_HOST` set, `SMTP_PORT=587` and no `SMTP_SECURITY`
+- **THEN** instance mail is delivered in the `starttls` mode
+
+#### Scenario: Security mode left unset on port 465
+
+- **WHEN** the instance starts with `SMTP_HOST` set, `SMTP_PORT=465` and no `SMTP_SECURITY`
+- **THEN** instance mail is delivered in the `tls` mode
+
+#### Scenario: Unknown security mode
+
+- **WHEN** the instance starts with `SMTP_SECURITY=ssl`
+- **THEN** it refuses to start and names `SMTP_SECURITY` and the accepted values
+
+#### Scenario: Unreadable sender address
+
+- **WHEN** the instance starts with `SMTP_FROM=noreply at example.com`
+- **THEN** it refuses to start and names `SMTP_FROM`
+
+#### Scenario: Invalid greeting name
+
+- **WHEN** the instance starts with `SMTP_HELO_NAME=my relay`
+- **THEN** it refuses to start and names `SMTP_HELO_NAME`
+
+### Requirement: One answer to whether the instance mail server is configured
+
+The instance mail server SHALL count as configured exactly when `SMTP_HOST` is set. `DATABASUS_URL` SHALL NOT affect that answer. The settings screen, the second-factor switch, the sign-in screen's password reset link and the backend's own checks SHALL all rely on this one answer.
+
+#### Scenario: Mail server without a public address
+
+- **WHEN** the instance runs with `SMTP_HOST` and `SMTP_PORT` set and `DATABASUS_URL` unset
+- **THEN** the settings screen reports the mail server as configured, and the sign-in screen offers the password reset link
+
+#### Scenario: No mail server
+
+- **WHEN** the instance runs without `SMTP_HOST`
+- **THEN** the settings screen reports the mail server as not configured, and the sign-in screen does not offer the password reset link
+
+### Requirement: Sender identity
+
+Every message SHALL name its sender as a display name and an address. The envelope sender that the mail server sees SHALL be the address alone.
+
+A sender SHALL be accepted either as a bare address (`[email protected]`) or as a display name followed by an address in angle brackets (`Acme Backups <[email protected]>`). When the sender carries no display name, the display name SHALL be `Databasus`.
+
+For instance mail the sender SHALL be `SMTP_FROM`; when it is not set, `SMTP_USER` if that is a bare email address; otherwise `noreply@` followed by `SMTP_HOST`. For a notification channel it SHALL follow the same order over the channel's own sender, username and host. A channel whose sender is set but cannot be read in either accepted form SHALL be refused when it is saved.
+
+#### Scenario: Display name in the sender
+
+- **WHEN** the instance runs with `SMTP_FROM` set to `Acme Backups <[email protected]>`
+- **THEN** recipients see the sender as `Acme Backups <[email protected]>`, and the mail server receives `[email protected]` alone as the envelope sender
+
+#### Scenario: Bare sender address
+
+- **WHEN** the instance runs with `[email protected]`
+- **THEN** recipients see the sender as `Databasus <[email protected]>`
+
+#### Scenario: Username that is not an address
+
+- **WHEN** the instance runs with `SMTP_HOST=smtp.sendgrid.net`, `SMTP_USER=apikey` and no `SMTP_FROM`
+- **THEN** the envelope sender is `[email protected]`, and `apikey` appears nowhere in the sender
+
+#### Scenario: Non-ASCII display name
+
+- **WHEN** the display name in the sender contains characters outside ASCII
+- **THEN** recipients see the name exactly as configured
+
+#### Scenario: Notification channel with an unreadable sender
+
+- **WHEN** a user saves an email notification channel whose sender is `ops at example`
+- **THEN** the save is refused with a message that the sender must be an address, optionally preceded by a display name
+
+### Requirement: Greeting name
+
+Every delivery SHALL introduce itself to the mail server with a greeting name. That name SHALL be the configured greeting name (`SMTP_HELO_NAME` for instance mail, the channel's own setting for a notification channel). When none is configured, it SHALL be the host name from `DATABASUS_URL`, or the machine's host name when `DATABASUS_URL` is not set, or `localhost` when the host name is unavailable. When the name is an IP address, it SHALL be sent as an address literal: `[192.0.2.1]` for IPv4 and `[IPv6:2001:db8::1]` for IPv6. The greeting SHALL use the same name in every security mode.
+
+A configured greeting name SHALL be either a host name or an address literal in that form.
+
+#### Scenario: Greeting derived from the public address
+
+- **WHEN** the instance runs with `DATABASUS_URL=https://backup.example.com` and no greeting name is configured
+- **THEN** deliveries greet the mail server as `backup.example.com`
+
+#### Scenario: Explicit greeting name
+
+- **WHEN** `SMTP_HELO_NAME=mail.example.com` is set
+- **THEN** instance mail greets the mail server as `mail.example.com`
+
+#### Scenario: Public address given as an IPv6 address
+
+- **WHEN** the instance runs with `DATABASUS_URL=http://[2001:db8::1]:4005` and no greeting name is configured
+- **THEN** deliveries greet the mail server as `[IPv6:2001:db8::1]`
+
+### Requirement: Delivery time limit
+
+A single delivery SHALL finish or fail within 30 seconds of its start, counting the whole conversation with the mail server and not only opening the connection.
+
+#### Scenario: Server goes silent
+
+- **WHEN** the mail server accepts the connection and then stops responding
+- **THEN** the delivery fails with a timeout error within 30 seconds, and the request that triggered it completes
+
+### Requirement: Well-formed messages
+
+Every message SHALL carry a `From`, `To`, `Subject`, `Date`, `Message-ID`, `MIME-Version`, `Content-Type` and `Content-Transfer-Encoding` header. The `Message-ID` SHALL be unique per message. A subject or a name containing characters outside ASCII SHALL reach the recipient intact without requiring the server to support UTF-8 addressing. The body SHALL be encoded so that no line on the wire exceeds the limit mail servers enforce, whatever the length of the lines in the original text.
+
+#### Scenario: Instance mail carries a message identifier
+
+- **WHEN** the instance sends an invitation
+- **THEN** the delivered message has a `Message-ID` header that differs from every other message the instance has sent
+
+#### Scenario: Long body line
+
+- **WHEN** a message body contains a single line of 5,000 characters
+- **THEN** the recipient reads the body exactly as it was written
+
+### Requirement: Header values cannot add headers
+
+No value placed in a header SHALL be able to add a header or end the header block. This covers subjects built from user-supplied text such as a workspace name, the recipient address, and the sender's display name and address.
+
+#### Scenario: Line break in a workspace name
+
+- **WHEN** a workspace is named `Ops\r\nBcc: [email protected]` and an invitation to it is sent
+- **THEN** the delivered message has no `Bcc` header, and the recipient list holds only the invited address
+
+### Requirement: Failed instance mail is logged
+
+When instance mail cannot be delivered for an invitation, the invitation SHALL still be created, and the failure SHALL be written to the server log with the reason. When the instance mail server is not configured, an attempted send SHALL be written to the server log as skipped.
+
+#### Scenario: Invitation with a broken mail server
+
+- **WHEN** an administrator invites a user while the mail server rejects every message
+- **THEN** the invitation is created, and the server log records that the invitation email failed and why
+
+### Requirement: Notification channel connection options
+
+An email notification channel SHALL let its owner choose the connection security mode and the greeting name. These options SHALL sit in the channel form's advanced settings next to the existing certificate verification switch. The default mode for a port SHALL be `tls` for 465 and `starttls` for every other port. When the port changes in the form, the security mode SHALL follow the new port's default only if it equals the previous port's default; any other mode SHALL be kept.
+
+A request that omits the security mode SHALL be accepted: a new channel SHALL be saved with its port's default, and an updated channel SHALL keep its stored mode. A request naming an unknown mode SHALL be refused. A channel SHALL be refused on save when its recipient is not a single email address or its greeting name is neither a host name nor an address literal.
+
+Channels that existed before this capability SHALL be given `tls` if their port is 465 and `starttls` otherwise, with no greeting name.
+
+#### Scenario: New channel on port 465
+
+- **WHEN** a user creates an email notification channel, enters port 465 and does not touch the security mode
+- **THEN** the form proposes `tls`, and the channel is saved with `tls`
+
+#### Scenario: Port change keeps a deliberate choice
+
+- **WHEN** the owner of a channel stored with `none` on port 25 changes its port to 2525 and saves
+- **THEN** the channel is saved with `none`
+
+#### Scenario: API client that does not know the security mode
+
+- **WHEN** a client creates an email notification channel on port 587 without a security mode, and later updates it without one
+- **THEN** the channel is created with `starttls`, and the update keeps `starttls`
+
+#### Scenario: Existing channel after upgrade
+
+- **WHEN** an instance upgrades with an email notification channel on port 587
+- **THEN** the channel uses `starttls`, and its advanced settings show that mode
+
+#### Scenario: Existing channel pointed at a server without STARTTLS
+
+- **WHEN** an upgraded channel on port 25 points at a server that does not offer STARTTLS
+- **THEN** its next notification fails, the channel shows the failure as its last send error, and it delivers again once its owner selects `none`
+
+### Requirement: Mail server status on the settings screen
+
+The settings screen SHALL show administrators a mail server block directly above the audit logs. The block SHALL say whether the instance mail server is configured and link to the SMTP section of the published configuration documentation. It SHALL state that instance mail covers invitations, password reset codes and sign-in codes, and that email notification channels use SMTP settings of their own. It SHALL NOT show the host, port, username, sender or any other part of the configuration.
+
+#### Scenario: Configured
+
+- **WHEN** an administrator opens the settings screen on an instance with `SMTP_HOST` set
+- **THEN** the mail server block says the mail server is configured
+
+#### Scenario: Not configured
+
+- **WHEN** an administrator opens the settings screen on an instance without `SMTP_HOST`
+- **THEN** the mail server block says the mail server is not configured and links to the documentation that explains how to connect one
+
+### Requirement: Test message from the settings screen
+
+The mail server block SHALL offer a button that sends a test message to the signed-in administrator's own address. The button SHALL be unavailable while the mail server is not configured. After a send, the screen SHALL either confirm the delivery and name the address it went to, or show the error the delivery produced, including the mail server's response.
+
+The instance SHALL refuse a test send, and say why, when the mail server is not configured or when the administrator's account has no valid email address. It SHALL NOT fall back to skipping the send silently.
+
+#### Scenario: Successful test
+
+- **WHEN** an administrator presses the test button with a working mail server
+- **THEN** a test message arrives at the administrator's address, and the screen confirms which address it was sent to
+
+#### Scenario: Mail server rejects the login
+
+- **WHEN** an administrator presses the test button and the mail server rejects the credentials
+- **THEN** the screen shows that authentication failed together with the mail server's response
+
+#### Scenario: Mail server not configured
+
+- **WHEN** a test send is requested on an instance without `SMTP_HOST`
+- **THEN** the request is refused with an answer saying the mail server is not configured, and nothing is sent
+
+#### Scenario: Account without a usable address
+
+- **WHEN** an administrator whose account holds no valid email address requests a test send
+- **THEN** the request is refused with an answer saying the account has no address to send to
+
+### Requirement: Test message access, abuse limits and audit
+
+Only administrators SHALL be able to request a test message. Each administrator SHALL be limited to five test messages in ten minutes. Every test send the instance attempts, whatever stage it fails at, SHALL be recorded in the audit log with the administrator, the recipient address and whether it was delivered.
+
+#### Scenario: Member requests a test message
+
+- **WHEN** a signed-in user who is not an administrator requests a test send
+- **THEN** the request is refused as forbidden, and nothing is sent
+
+#### Scenario: Too many test messages
+
+- **WHEN** an administrator requests a sixth test send within ten minutes
+- **THEN** the request is refused as rate-limited, and nothing is sent
+
+#### Scenario: Failed test in the audit log
+
+- **WHEN** an administrator's test send fails at the mail server
+- **THEN** the audit log shows an entry naming the administrator, the recipient address and that the delivery failed
+
+### Requirement: Published mail server documentation
+
+The SMTP section of the published configuration documentation SHALL describe every instance mail variable, the three security modes and the default mode for each port, the rule that decides whether the mail server counts as configured, and the difference between the instance mail server and an email notification channel. It SHALL warn that `none` sends credentials and messages unencrypted. It SHALL warn that an instance requiring the emailed second factor admits nobody through password sign-in while its mail server cannot deliver, tell operators on a relay without STARTTLS to set `SMTP_SECURITY` before upgrading, and name the console command that switches the second factor off. The section SHALL be published in every language the website ships and keep the same anchor in each.
+
+#### Scenario: Operator migrating a plain relay
+
+- **WHEN** an operator whose relay on port 25 does not offer STARTTLS reads the SMTP section in any published language
+- **THEN** the section tells them to set `SMTP_SECURITY=none` before upgrading, warns what that setting exposes, and warns that with the second factor on a missed setting locks password sign-in until it is fixed or the second factor is switched off
diff --git a/website/app/(en)/advanced-config/page.tsx b/website/app/(en)/advanced-config/page.tsx
index fa40f6ee..9424e273 100644
--- a/website/app/(en)/advanced-config/page.tsx
+++ b/website/app/(en)/advanced-config/page.tsx
@@ -237,16 +237,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">Email (SMTP)</h2>
<p>
- Connect an SMTP server so Databasus can send transactional email
- such as password-reset links and workspace invitations. Email is
- treated as configured{" "}
- <strong>
- only when both <code>SMTP_HOST</code> and{" "}
- <code>DATABASUS_URL</code> are set
- </strong>{" "}
- — until then, email features stay hidden in the UI.
+ Connect a mail server so Databasus can send workspace invitations, password reset codes and sign-in codes. The mail server counts as configured <strong>as soon as <code>SMTP_HOST</code> is set</strong>. Without it, the settings screen reports the mail server as not configured, and the sign-in screen hides the password reset link.
</p>
+ <p>
+ This is the instance mail server. Email notifiers, which report backup events, have SMTP settings of their own in each notifier&apos;s form, so a notifier that delivers mail tells you nothing about this server. To check the instance mail server, open <strong>Databasus settings → Mail server</strong> and press <strong>Send test email</strong>. The message goes to your own address, and a failed delivery shows the mail server&apos;s response.
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>If your relay does not offer STARTTLS, set <code>SMTP_SECURITY=none</code> before upgrading.</strong> On any port other than 465 the default mode is <code>starttls</code>, which refuses to continue without encryption, so such a relay receives nothing until the variable is set. If the instance requires the emailed sign-in code, nobody gets in with a password while mail cannot be delivered. To get back in, switch the second factor off with <code>docker exec -it databasus ./main --disable-2fa</code> (see <a href="/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">Stop requiring a sign-in code</a>).
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -260,8 +279,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Description">
- SMTP server hostname (e.g. <code>smtp.gmail.com</code>).
- Enables email together with <code>DATABASUS_URL</code>.
+ Mail server host name (e.g. <code>smtp.gmail.com</code>). Setting it turns instance mail on.
</td>
</tr>
<tr>
@@ -269,8 +287,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Description">
- SMTP server port (e.g. <code>587</code>). Must be a
- positive integer when <code>SMTP_HOST</code> is set.
+ Mail server port (e.g. <code>587</code>). Must be a positive integer when <code>SMTP_HOST</code> is set.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Description">
+ Connection security: <code>tls</code>, <code>starttls</code> or <code>none</code>, described below. Defaults to <code>tls</code> on port 465 and to <code>starttls</code> on every other port. The instance refuses to start with any other value.
</td>
</tr>
<tr>
@@ -286,8 +311,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_PASSWORD</code>
</td>
<td data-label="Description">
- Password for SMTP authentication. For Gmail, use an App
- Password — not your account password.
+ Password for SMTP authentication. For Gmail, use an App Password, not your account password.
</td>
</tr>
<tr>
@@ -295,7 +319,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Description">
- The &quot;From&quot; address on outgoing email.
+ Sender address, either bare (<code>[email protected]</code>) or with a name (<code>Acme Backups &lt;[email protected]&gt;</code>). Without a name, recipients see <code>Databasus</code>. When it is not set, <code>SMTP_USER</code> is used if it is an email address, and otherwise <code>noreply@</code> followed by <code>SMTP_HOST</code>, so a username such as <code>apikey</code> never becomes the sender. The instance refuses to start when the value cannot be read as an address.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Description">
+ The name the instance greets the mail server with. Defaults to the host of <code>DATABASUS_URL</code>, then to the machine&apos;s host name. Must be a host name or an address literal such as <code>[192.0.2.1]</code> or <code>[IPv6:2001:db8::1]</code>, or the instance refuses to start.
</td>
</tr>
<tr>
@@ -303,11 +335,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Description">
- Set to <code>true</code> to skip TLS certificate
- verification when connecting to the SMTP server. Defaults
- to <code>false</code>. Use it only for servers with a
- self-signed certificate on a trusted network — it disables
- protection against man-in-the-middle attacks.
+ Set to <code>true</code> to skip TLS certificate verification in the <code>tls</code> and <code>starttls</code> modes. Defaults to <code>false</code>. Use it only for servers with a self-signed certificate on a trusted network, because it disables protection against man-in-the-middle attacks.
</td>
</tr>
<tr>
@@ -315,15 +343,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Description">
- Public base URL of your instance (e.g.{" "}
- <code>https://backup.example.com</code>). Used to build
- links inside emails. Required together with{" "}
- <code>SMTP_HOST</code>.
+ Public base URL of your instance (e.g. <code>https://backup.example.com</code>). Optional: it adds a link to invitation emails and supplies the default greeting name. Mail works without it.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p>
+ <code>SMTP_SECURITY</code> selects one of three modes. Email notifiers offer the same choice under <strong>Advanced settings</strong>.
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>Mode</th>
+ <th>Behavior</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Behavior">
+ The connection is encrypted from the first byte. Usual on port 465.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Behavior">
+ The connection starts unencrypted and is upgraded before the password or any message is sent. If the server does not offer the upgrade, the delivery fails instead of continuing unencrypted. Usual on port 587.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Behavior">
+ The connection is never encrypted. Use it for a relay that does not offer STARTTLS, such as a local Postfix on port 25.
</td>
</tr>
</tbody>
</table>
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <code>none</code> sends the SMTP password and every message unencrypted, and anyone between Databasus and the relay can read them. Use it only for a relay on the same host or on a trusted private network.
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">
Sign up captcha (Cloudflare Turnstile)
</h2>
diff --git a/website/app/[lang]/advanced-config/content/es.tsx b/website/app/[lang]/advanced-config/content/es.tsx
index 5c118bc8..92b475ab 100644
--- a/website/app/[lang]/advanced-config/content/es.tsx
+++ b/website/app/[lang]/advanced-config/content/es.tsx
@@ -244,18 +244,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">Correo electrónico (SMTP)</h2>
<p>
- Conecte un servidor SMTP para que Databasus pueda enviar correo
- transaccional, como enlaces de restablecimiento de contraseña e
- invitaciones a espacios de trabajo. El correo se considera
- configurado{" "}
- <strong>
- solo cuando están definidos tanto <code>SMTP_HOST</code> como{" "}
- <code>DATABASUS_URL</code>
- </strong>
- ; hasta entonces, las funciones de correo permanecen ocultas en
- la interfaz.
+ Conecte un servidor de correo para que Databasus pueda enviar invitaciones a espacios de trabajo, códigos para restablecer la contraseña y códigos de acceso. El servidor de correo se considera configurado <strong>en cuanto se define <code>SMTP_HOST</code></strong>. Sin él, la pantalla de ajustes indica que el servidor de correo no está configurado y la pantalla de inicio de sesión oculta el enlace para restablecer la contraseña.
</p>
+ <p>
+ Este es el servidor de correo de la instancia. Los canales de notificación por correo, que informan sobre las copias de seguridad, tienen su propia configuración SMTP en el formulario de cada canal. Por eso, que un canal de notificación entregue correo no dice nada de este servidor. Para comprobar el servidor de correo de la instancia, abra <strong>Databasus settings → Mail server</strong> y pulse <strong>Send test email</strong>. El mensaje llega a su propia dirección y, si la entrega falla, verá la respuesta del servidor de correo.
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>Si su relé no admite STARTTLS, defina <code>SMTP_SECURITY=none</code> antes de actualizar.</strong> En cualquier puerto distinto del 465 el modo predeterminado es <code>starttls</code>, que no continúa sin cifrado, así que ese relé no recibirá nada hasta que defina la variable. Si la instancia exige el código de acceso por correo, nadie podrá entrar con contraseña mientras el correo no se entregue. Para recuperar el acceso, desactive el segundo factor con <code>docker exec -it databasus ./main --disable-2fa</code> (consulte <a href="/es/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">Dejar de pedir un código al iniciar sesión</a>).
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -269,9 +286,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Description">
- Nombre de host del servidor SMTP (p. ej.{" "}
- <code>smtp.gmail.com</code>). Activa el correo junto con{" "}
- <code>DATABASUS_URL</code>.
+ Nombre de host del servidor de correo (por ejemplo, <code>smtp.gmail.com</code>). Al definirla se activa el correo de la instancia.
</td>
</tr>
<tr>
@@ -279,9 +294,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Description">
- Puerto del servidor SMTP (p. ej. <code>587</code>). Debe
- ser un entero positivo cuando <code>SMTP_HOST</code> está
- definido.
+ Puerto del servidor de correo (por ejemplo, <code>587</code>). Debe ser un entero positivo cuando <code>SMTP_HOST</code> está definido.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Description">
+ Seguridad de la conexión: <code>tls</code>, <code>starttls</code> o <code>none</code>, descritos más abajo. Por defecto es <code>tls</code> en el puerto 465 y <code>starttls</code> en cualquier otro. Con otro valor, la instancia no arranca.
</td>
</tr>
<tr>
@@ -297,8 +318,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_PASSWORD</code>
</td>
<td data-label="Description">
- Contraseña para la autenticación SMTP. Para Gmail, use una
- App Password, no la contraseña de su cuenta.
+ Contraseña para la autenticación SMTP. Para Gmail, use una App Password, no la contraseña de su cuenta.
</td>
</tr>
<tr>
@@ -306,7 +326,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Description">
- La dirección &quot;From&quot; del correo saliente.
+ Dirección del remitente, sola (<code>[email protected]</code>) o con un nombre (<code>Acme Backups &lt;[email protected]&gt;</code>). Sin nombre, los destinatarios ven <code>Databasus</code>. Si no está definida, se usa <code>SMTP_USER</code> cuando es una dirección de correo y, si no, <code>noreply@</code> seguido de <code>SMTP_HOST</code>, de modo que un usuario como <code>apikey</code> nunca pasa a ser el remitente. Si el valor no se puede leer como dirección, la instancia no arranca.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Description">
+ El nombre con el que la instancia saluda al servidor de correo. Por defecto es el host de <code>DATABASUS_URL</code> y, si no existe, el nombre del equipo. Debe ser un nombre de host o un literal de dirección como <code>[192.0.2.1]</code> o <code>[IPv6:2001:db8::1]</code>; de lo contrario, la instancia no arranca.
</td>
</tr>
<tr>
@@ -314,12 +342,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Description">
- Póngalo en <code>true</code> para omitir la verificación
- del certificado TLS al conectar con el servidor SMTP. Por
- defecto es <code>false</code>. Úselo solo con servidores
- con certificado autofirmado en una red de confianza:
- desactiva la protección contra ataques de intermediario
- (man-in-the-middle).
+ Póngalo en <code>true</code> para omitir la verificación del certificado TLS en los modos <code>tls</code> y <code>starttls</code>. Por defecto es <code>false</code>. Úselo solo con servidores con certificado autofirmado en una red de confianza: desactiva la protección contra ataques de intermediario (man-in-the-middle).
</td>
</tr>
<tr>
@@ -327,15 +350,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Description">
- URL base pública de su instancia (p. ej.{" "}
- <code>https://backup.example.com</code>). Se usa para
- construir los enlaces dentro de los correos. Requerida
- junto con <code>SMTP_HOST</code>.
+ URL base pública de su instancia (por ejemplo, <code>https://backup.example.com</code>). Opcional: añade un enlace a los correos de invitación y aporta el nombre de saludo predeterminado. El correo funciona sin ella.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p>
+ <code>SMTP_SECURITY</code> elige uno de tres modos. Los canales de notificación por correo ofrecen la misma elección en <strong>Advanced settings</strong>.
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>Modo</th>
+ <th>Comportamiento</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Comportamiento">
+ La conexión va cifrada desde el primer byte. Lo habitual en el puerto 465.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Comportamiento">
+ La conexión empieza sin cifrar y se cifra antes de enviar la contraseña o cualquier mensaje. Si el servidor no lo admite, la entrega falla en lugar de continuar sin cifrado. Lo habitual en el puerto 587.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Comportamiento">
+ La conexión nunca se cifra. Úselo para un relé que no admite STARTTLS, como un Postfix local en el puerto 25.
</td>
</tr>
</tbody>
</table>
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <code>none</code> envía la contraseña SMTP y todos los mensajes sin cifrar, y cualquiera que esté entre Databasus y el relé puede leerlos. Úselo solo con un relé en el mismo host o en una red privada de confianza.
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">
Captcha de registro (Cloudflare Turnstile)
</h2>
diff --git a/website/app/[lang]/advanced-config/content/fr.tsx b/website/app/[lang]/advanced-config/content/fr.tsx
index 61320e44..1c58e034 100644
--- a/website/app/[lang]/advanced-config/content/fr.tsx
+++ b/website/app/[lang]/advanced-config/content/fr.tsx
@@ -245,18 +245,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">E-mail (SMTP)</h2>
<p>
- Connectez un serveur SMTP pour que Databasus puisse envoyer des
- e-mails transactionnels, comme les liens de réinitialisation de
- mot de passe et les invitations aux espaces de travail.
- L&apos;e-mail est considéré comme configuré{" "}
- <strong>
- uniquement quand <code>SMTP_HOST</code> et{" "}
- <code>DATABASUS_URL</code> sont tous deux définis
- </strong>{" "}
- ; jusque-là, les fonctionnalités e-mail restent masquées dans
- l&apos;interface.
+ Connectez un serveur de messagerie pour que Databasus puisse envoyer les invitations aux espaces de travail, les codes de réinitialisation du mot de passe et les codes de connexion. Le serveur de messagerie est considéré comme configuré <strong>dès que <code>SMTP_HOST</code> est défini</strong>. Sans lui, l&apos;écran des paramètres indique que le serveur de messagerie n&apos;est pas configuré, et l&apos;écran de connexion masque le lien de réinitialisation du mot de passe.
</p>
+ <p>
+ Il s&apos;agit du serveur de messagerie de l&apos;instance. Les canaux de notification par e-mail, qui signalent les sauvegardes, ont leurs propres paramètres SMTP dans le formulaire de chaque canal : un canal de notification qui délivre ses e-mails ne dit donc rien de ce serveur. Pour vérifier le serveur de messagerie de l&apos;instance, ouvrez <strong>Databasus settings → Mail server</strong> et cliquez sur <strong>Send test email</strong>. Le message part vers votre propre adresse et, si la livraison échoue, vous voyez la réponse du serveur de messagerie.
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>Si votre relais ne propose pas STARTTLS, définissez <code>SMTP_SECURITY=none</code> avant la mise à jour.</strong> Sur tout port autre que 465, le mode par défaut est <code>starttls</code>, qui refuse de continuer sans chiffrement : un tel relais ne reçoit donc rien tant que la variable n&apos;est pas définie. Si l&apos;instance exige le code de connexion envoyé par e-mail, personne ne peut se connecter par mot de passe tant que les e-mails ne partent pas. Pour retrouver l&apos;accès, désactivez le second facteur avec <code>docker exec -it databasus ./main --disable-2fa</code> (voir <a href="/fr/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">Cesser de demander un code à la connexion</a>).
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -270,9 +287,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Description">
- Nom d&apos;hôte du serveur SMTP (par ex.{" "}
- <code>smtp.gmail.com</code>). Active l&apos;e-mail avec{" "}
- <code>DATABASUS_URL</code>.
+ Nom d&apos;hôte du serveur de messagerie (par ex. <code>smtp.gmail.com</code>). Le définir active l&apos;e-mail de l&apos;instance.
</td>
</tr>
<tr>
@@ -280,8 +295,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Description">
- Port du serveur SMTP (par ex. <code>587</code>). Doit être
- un entier positif quand <code>SMTP_HOST</code> est défini.
+ Port du serveur de messagerie (par ex. <code>587</code>). Doit être un entier positif quand <code>SMTP_HOST</code> est défini.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Description">
+ Sécurité de la connexion : <code>tls</code>, <code>starttls</code> ou <code>none</code>, décrits plus bas. Vaut <code>tls</code> par défaut sur le port 465 et <code>starttls</code> sur tous les autres. Avec toute autre valeur, l&apos;instance refuse de démarrer.
</td>
</tr>
<tr>
@@ -297,9 +319,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_PASSWORD</code>
</td>
<td data-label="Description">
- Mot de passe pour l&apos;authentification SMTP. Pour
- Gmail, utilisez un App Password, pas le mot de passe de
- votre compte.
+ Mot de passe pour l&apos;authentification SMTP. Pour Gmail, utilisez un App Password, pas le mot de passe de votre compte.
</td>
</tr>
<tr>
@@ -307,7 +327,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Description">
- L&apos;adresse &quot;From&quot; des e-mails sortants.
+ Adresse de l&apos;expéditeur, seule (<code>[email protected]</code>) ou avec un nom (<code>Acme Backups &lt;[email protected]&gt;</code>). Sans nom, les destinataires voient <code>Databasus</code>. Si elle n&apos;est pas définie, <code>SMTP_USER</code> est utilisé s&apos;il s&apos;agit d&apos;une adresse e-mail, sinon <code>noreply@</code> suivi de <code>SMTP_HOST</code> : un nom d&apos;utilisateur comme <code>apikey</code> ne devient donc jamais l&apos;expéditeur. Si la valeur ne peut pas être lue comme une adresse, l&apos;instance refuse de démarrer.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Description">
+ Le nom sous lequel l&apos;instance se présente au serveur de messagerie. Par défaut, l&apos;hôte de <code>DATABASUS_URL</code>, ou à défaut le nom de la machine. Doit être un nom d&apos;hôte ou un littéral d&apos;adresse comme <code>[192.0.2.1]</code> ou <code>[IPv6:2001:db8::1]</code>, sinon l&apos;instance refuse de démarrer.
</td>
</tr>
<tr>
@@ -315,12 +343,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Description">
- Mettez <code>true</code> pour ignorer la vérification du
- certificat TLS lors de la connexion au serveur SMTP. Vaut{" "}
- <code>false</code> par défaut. À réserver aux serveurs
- avec un certificat auto-signé sur un réseau de confiance :
- cette option désactive la protection contre les attaques
- de l&apos;homme du milieu.
+ Mettez <code>true</code> pour ignorer la vérification du certificat TLS dans les modes <code>tls</code> et <code>starttls</code>. Vaut <code>false</code> par défaut. À réserver aux serveurs avec un certificat auto-signé sur un réseau de confiance : cette option désactive la protection contre les attaques de l&apos;homme du milieu.
</td>
</tr>
<tr>
@@ -328,15 +351,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Description">
- URL de base publique de votre instance (par ex.{" "}
- <code>https://backup.example.com</code>). Sert à
- construire les liens dans les e-mails. Requis avec{" "}
- <code>SMTP_HOST</code>.
+ URL de base publique de votre instance (par ex. <code>https://backup.example.com</code>). Facultative : elle ajoute un lien aux e-mails d&apos;invitation et fournit le nom annoncé par défaut. L&apos;e-mail fonctionne sans elle.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p>
+ <code>SMTP_SECURITY</code> choisit l&apos;un des trois modes. Les canaux de notification par e-mail proposent le même choix dans <strong>Advanced settings</strong>.
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>Mode</th>
+ <th>Comportement</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Comportement">
+ La connexion est chiffrée dès le premier octet. Habituel sur le port 465.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Comportement">
+ La connexion démarre en clair puis passe en chiffré avant l&apos;envoi du mot de passe ou de tout message. Si le serveur ne le propose pas, la livraison échoue au lieu de continuer sans chiffrement. Habituel sur le port 587.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Comportement">
+ La connexion n&apos;est jamais chiffrée. À utiliser pour un relais qui ne propose pas STARTTLS, comme un Postfix local sur le port 25.
</td>
</tr>
</tbody>
</table>
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <code>none</code> envoie le mot de passe SMTP et chaque message en clair, et toute personne placée entre Databasus et le relais peut les lire. Ne l&apos;utilisez qu&apos;avec un relais sur le même hôte ou sur un réseau privé de confiance.
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">
Captcha à l&apos;inscription (Cloudflare Turnstile)
</h2>
diff --git a/website/app/[lang]/advanced-config/content/pt.tsx b/website/app/[lang]/advanced-config/content/pt.tsx
index 1ca7aa7c..ff98c9e0 100644
--- a/website/app/[lang]/advanced-config/content/pt.tsx
+++ b/website/app/[lang]/advanced-config/content/pt.tsx
@@ -240,16 +240,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">Email (SMTP)</h2>
<p>
- Conecte um servidor SMTP para o Databasus enviar emails
- transacionais, como links de redefinição de senha e convites
- para workspaces. O email só é considerado configurado{" "}
- <strong>
- quando tanto <code>SMTP_HOST</code> quanto{" "}
- <code>DATABASUS_URL</code> estão definidos
- </strong>{" "}
- — até lá, os recursos de email ficam ocultos na interface.
+ Conecte um servidor de e-mail para que o Databasus possa enviar convites para espaços de trabalho, códigos de redefinição de senha e códigos de acesso. O servidor de e-mail é considerado configurado <strong>assim que <code>SMTP_HOST</code> é definido</strong>. Sem ele, a tela de configurações informa que o servidor de e-mail não está configurado, e a tela de login esconde o link de redefinição de senha.
</p>
+ <p>
+ Este é o servidor de e-mail da instância. Os canais de notificação por e-mail, que avisam sobre os backups, têm configurações SMTP próprias no formulário de cada canal. Por isso, um canal de notificação que entrega e-mails não diz nada sobre este servidor. Para testar o servidor de e-mail da instância, abra <strong>Databasus settings → Mail server</strong> e clique em <strong>Send test email</strong>. A mensagem vai para o seu próprio endereço e, se a entrega falhar, você vê a resposta do servidor de e-mail.
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>Se o seu relay não oferece STARTTLS, defina <code>SMTP_SECURITY=none</code> antes de atualizar.</strong> Em qualquer porta diferente da 465, o modo padrão é <code>starttls</code>, que não continua sem criptografia, então esse relay não recebe nada até a variável ser definida. Se a instância exige o código de acesso por e-mail, ninguém entra com senha enquanto os e-mails não forem entregues. Para recuperar o acesso, desative o segundo fator com <code>docker exec -it databasus ./main --disable-2fa</code> (veja <a href="/pt/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">Parar de pedir um código no login</a>).
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -263,9 +282,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Descrição">
- Nome do servidor SMTP (por exemplo{" "}
- <code>smtp.gmail.com</code>). Ativa o email junto com{" "}
- <code>DATABASUS_URL</code>.
+ Host do servidor de e-mail (por exemplo, <code>smtp.gmail.com</code>). Definir esta variável ativa o e-mail da instância.
</td>
</tr>
<tr>
@@ -273,9 +290,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Descrição">
- Porta do servidor SMTP (por exemplo <code>587</code>).
- Deve ser um inteiro positivo quando <code>SMTP_HOST</code>{" "}
- está definido.
+ Porta do servidor de e-mail (por exemplo, <code>587</code>). Precisa ser um inteiro positivo quando <code>SMTP_HOST</code> está definido.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Descrição">
+ Segurança da conexão: <code>tls</code>, <code>starttls</code> ou <code>none</code>, descritos abaixo. O padrão é <code>tls</code> na porta 465 e <code>starttls</code> em qualquer outra porta. Com outro valor, a instância não inicia.
</td>
</tr>
<tr>
@@ -283,7 +306,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_USER</code>
</td>
<td data-label="Descrição">
- Nome de login para a autenticação SMTP.
+ Nome de usuário para a autenticação SMTP.
</td>
</tr>
<tr>
@@ -291,8 +314,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_PASSWORD</code>
</td>
<td data-label="Descrição">
- Senha para a autenticação SMTP. No Gmail, use uma App
- Password — não a senha da conta.
+ Senha para a autenticação SMTP. No Gmail, use uma App Password, não a senha da conta.
</td>
</tr>
<tr>
@@ -300,7 +322,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Descrição">
- O endereço &quot;From&quot; dos emails enviados.
+ Endereço do remetente, só o endereço (<code>[email protected]</code>) ou com um nome (<code>Acme Backups &lt;[email protected]&gt;</code>). Sem nome, os destinatários veem <code>Databasus</code>. Quando não está definido, é usado <code>SMTP_USER</code> se ele for um endereço de e-mail; caso contrário, <code>noreply@</code> seguido de <code>SMTP_HOST</code>, então um usuário como <code>apikey</code> nunca vira o remetente. Se o valor não puder ser lido como endereço, a instância não inicia.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Descrição">
+ O nome com que a instância se apresenta ao servidor de e-mail. O padrão é o host de <code>DATABASUS_URL</code> e, na falta dele, o nome da máquina. Precisa ser um nome de host ou um literal de endereço como <code>[192.0.2.1]</code> ou <code>[IPv6:2001:db8::1]</code>; caso contrário, a instância não inicia.
</td>
</tr>
<tr>
@@ -308,11 +338,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Descrição">
- Defina como <code>true</code> para pular a verificação do
- certificado TLS ao conectar ao servidor SMTP. O padrão é{" "}
- <code>false</code>. Use apenas para servidores com
- certificado autoassinado numa rede confiável: desativa a
- proteção contra ataques man-in-the-middle.
+ Defina como <code>true</code> para pular a verificação do certificado TLS nos modos <code>tls</code> e <code>starttls</code>. O padrão é <code>false</code>. Use apenas para servidores com certificado autoassinado numa rede confiável: desativa a proteção contra ataques man-in-the-middle.
</td>
</tr>
<tr>
@@ -320,15 +346,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Descrição">
- URL base pública da sua instância (por exemplo{" "}
- <code>https://backup.example.com</code>). Usada para
- construir os links dentro dos emails. Necessária junto com{" "}
- <code>SMTP_HOST</code>.
+ URL base pública da sua instância (por exemplo, <code>https://backup.example.com</code>). Opcional: adiciona um link aos e-mails de convite e fornece o nome de saudação padrão. O e-mail funciona sem ela.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p>
+ <code>SMTP_SECURITY</code> escolhe um de três modos. Os canais de notificação por e-mail oferecem a mesma escolha em <strong>Advanced settings</strong>.
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>Modo</th>
+ <th>Comportamento</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Comportamento">
+ A conexão é criptografada desde o primeiro byte. Comum na porta 465.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Comportamento">
+ A conexão começa sem criptografia e passa a ser criptografada antes do envio da senha ou de qualquer mensagem. Se o servidor não oferecer esse recurso, a entrega falha em vez de continuar sem criptografia. Comum na porta 587.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Comportamento">
+ A conexão nunca é criptografada. Use para um relay que não oferece STARTTLS, como um Postfix local na porta 25.
</td>
</tr>
</tbody>
</table>
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <code>none</code> envia a senha SMTP e todas as mensagens sem criptografia, e qualquer pessoa entre o Databasus e o relay consegue lê-las. Use apenas com um relay no mesmo host ou numa rede privada confiável.
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">
Captcha no registro (Cloudflare Turnstile)
</h2>
diff --git a/website/app/[lang]/advanced-config/content/ru.tsx b/website/app/[lang]/advanced-config/content/ru.tsx
index aa71b07e..39d493f0 100644
--- a/website/app/[lang]/advanced-config/content/ru.tsx
+++ b/website/app/[lang]/advanced-config/content/ru.tsx
@@ -239,16 +239,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">Почта (SMTP)</h2>
<p>
- Подключите SMTP-сервер, чтобы Databasus мог отправлять служебные
- письма: ссылки для сброса пароля и приглашения в рабочие
- пространства. Почта считается настроенной,{" "}
- <strong>
- только когда заданы и <code>SMTP_HOST</code>, и{" "}
- <code>DATABASUS_URL</code>
- </strong>{" "}
- — до этого почтовые функции скрыты в интерфейсе.
+ Подключите почтовый сервер, чтобы Databasus мог отправлять приглашения в рабочие пространства, коды сброса пароля и коды входа. Почтовый сервер считается настроенным, <strong>как только задан <code>SMTP_HOST</code></strong>. Без него экран настроек показывает, что почтовый сервер не настроен, а на экране входа нет ссылки для сброса пароля.
</p>
+ <p>
+ Это почтовый сервер инстанса. У каналов уведомлений по email, которые сообщают о бекапах, свои настройки SMTP в форме каждого канала. Поэтому если письма от канала уведомлений доходят, это ничего не говорит о почтовом сервере инстанса. Чтобы проверить его, откройте <strong>Databasus settings → Mail server</strong> и нажмите <strong>Send test email</strong>. Письмо придет на ваш адрес, а если доставка не удалась, вы увидите ответ почтового сервера.
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>Если ваш релей не поддерживает STARTTLS, задайте <code>SMTP_SECURITY=none</code> до обновления.</strong> На любом порту, кроме 465, по умолчанию действует режим <code>starttls</code>, а он не продолжает работу без шифрования, так что такой релей не получит ни одного письма, пока переменная не задана. Если инстанс требует код входа по почте, то пока письма не доходят, по паролю не войдет никто. Чтобы вернуть доступ, выключите второй фактор командой <code>docker exec -it databasus ./main --disable-2fa</code> (подробнее — в разделе <a href="/ru/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">Перестать запрашивать код при входе</a>).
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -262,8 +281,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Описание">
- Хост SMTP-сервера (например <code>smtp.gmail.com</code>).
- Вместе с <code>DATABASUS_URL</code> включает почту.
+ Хост почтового сервера (например, <code>smtp.gmail.com</code>). Если переменная задана, почта инстанса включена.
</td>
</tr>
<tr>
@@ -271,9 +289,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Описание">
- Порт SMTP-сервера (например <code>587</code>). Должен быть
- положительным целым числом, если задан{" "}
- <code>SMTP_HOST</code>.
+ Порт почтового сервера (например, <code>587</code>). Должен быть положительным целым числом, если задан <code>SMTP_HOST</code>.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Описание">
+ Защита соединения: <code>tls</code>, <code>starttls</code> или <code>none</code>, подробнее — ниже. По умолчанию <code>tls</code> на порту 465 и <code>starttls</code> на всех остальных. С любым другим значением инстанс не запустится.
</td>
</tr>
<tr>
@@ -289,8 +313,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_PASSWORD</code>
</td>
<td data-label="Описание">
- Пароль для аутентификации на SMTP. Для Gmail используйте
- App Password, а не пароль аккаунта.
+ Пароль для аутентификации на SMTP. Для Gmail используйте App Password, а не пароль аккаунта.
</td>
</tr>
<tr>
@@ -298,7 +321,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Описание">
- Адрес отправителя (&quot;From&quot;) в исходящих письмах.
+ Адрес отправителя: просто адрес (<code>[email protected]</code>) или адрес с именем (<code>Acme Backups &lt;[email protected]&gt;</code>). Если имени нет, получатели видят <code>Databasus</code>. Если переменная не задана, используется <code>SMTP_USER</code>, когда это адрес почты, а иначе <code>noreply@</code> и <code>SMTP_HOST</code>, так что логин вроде <code>apikey</code> никогда не станет отправителем. Если значение нельзя разобрать как адрес, инстанс не запустится.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Описание">
+ Имя, которым инстанс представляется почтовому серверу. По умолчанию берется хост из <code>DATABASUS_URL</code>, а если его нет — имя машины. Должно быть именем хоста или адресным литералом вроде <code>[192.0.2.1]</code> или <code>[IPv6:2001:db8::1]</code>, иначе инстанс не запустится.
</td>
</tr>
<tr>
@@ -306,12 +337,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Описание">
- Установите <code>true</code>, чтобы пропускать проверку
- TLS-сертификата при подключении к SMTP-серверу. По
- умолчанию <code>false</code>. Используйте только для
- серверов с самоподписанным сертификатом в доверенной сети
- — эта настройка отключает защиту от атак «человек
- посередине».
+ Установите <code>true</code>, чтобы пропускать проверку TLS-сертификата в режимах <code>tls</code> и <code>starttls</code>. По умолчанию <code>false</code>. Используйте только для серверов с самоподписанным сертификатом в доверенной сети: эта настройка отключает защиту от атак «человек посередине».
</td>
</tr>
<tr>
@@ -319,15 +345,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Описание">
- Публичный базовый URL вашего инстанса (например{" "}
- <code>https://backup.example.com</code>). Используется для
- сборки ссылок в письмах. Нужен вместе с{" "}
- <code>SMTP_HOST</code>.
+ Публичный базовый URL инстанса (например, <code>https://backup.example.com</code>). Необязателен: добавляет ссылку в письма-приглашения и задает имя в приветствии по умолчанию. Почта работает и без него.
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <p>
+ <code>SMTP_SECURITY</code> выбирает один из трех режимов. У каналов уведомлений по email такой же выбор есть в разделе <strong>Advanced settings</strong>.
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>Режим</th>
+ <th>Что происходит</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Что происходит">
+ Соединение зашифровано с первого байта. Обычно порт 465.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Что происходит">
+ Соединение начинается без шифрования и переводится в зашифрованное до отправки пароля и писем. Если сервер этого не поддерживает, доставка завершается ошибкой, а не продолжается без шифрования. Обычно порт 587.
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Что происходит">
+ Соединение никогда не шифруется. Подходит для релея без STARTTLS, например локального Postfix на порту 25.
</td>
</tr>
</tbody>
</table>
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ В режиме <code>none</code> пароль SMTP и все письма передаются без шифрования, и их может прочитать любой, кто находится между Databasus и релеем. Выбирайте его только для релея на том же хосте или в доверенной частной сети.
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">
Капча при регистрации (Cloudflare Turnstile)
</h2>
diff --git a/website/app/[lang]/advanced-config/content/zh.tsx b/website/app/[lang]/advanced-config/content/zh.tsx
index db0d9719..13f83d95 100644
--- a/website/app/[lang]/advanced-config/content/zh.tsx
+++ b/website/app/[lang]/advanced-config/content/zh.tsx
@@ -234,14 +234,35 @@ export default function AdvancedConfigPage() {
<h2 id="email-smtp">邮件 (SMTP)</h2>
<p>
- 连接一个 SMTP 服务器,Databasus
- 就能发送事务性邮件,例如密码重置链接和工作区邀请。只有{" "}
- <strong>
- <code>SMTP_HOST</code> 和 <code>DATABASUS_URL</code> 都设置了
- </strong>
- ,邮件才视为已配置;在那之前,邮件相关功能在界面中保持隐藏。
+ 连接邮件服务器后,Databasus 就能发送工作区邀请、密码重置码和登录验证码。<strong>只要设置了 <code>SMTP_HOST</code></strong>,邮件服务器就算已配置。没有它时,设置页面会显示邮件服务器未配置,登录页面也不会显示重置密码的链接。
</p>
+ <p>
+ 这是实例的邮件服务器。邮件通知渠道用来报告备份情况,它们在各自的表单里有自己的 SMTP 设置,所以某个通知渠道能收发邮件,并不能说明这台服务器可用。要检查实例的邮件服务器,请打开 <strong>Databasus settings → Mail server</strong> 并点击 <strong>Send test email</strong>。测试邮件会发到你自己的地址,发送失败时会显示邮件服务器的回复。
+ </p>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <strong>如果你的中继不支持 STARTTLS,请在升级前设置 <code>SMTP_SECURITY=none</code>。</strong> 除 465 以外的端口默认使用 <code>starttls</code> 模式,它不会在没有加密的情况下继续,因此在设置这个变量之前,这样的中继收不到任何邮件。如果实例要求通过邮件发送登录验证码,在邮件无法送达期间,任何人都无法用密码登录。要恢复访问,请用 <code>docker exec -it databasus ./main --disable-2fa</code> 关闭第二因素(见<a href="/zh/password/#disable-two-factor" className="text-blue-400 hover:text-blue-300">不再要求登录验证码</a>)。
+ </p>
+ </div>
+ </div>
+
<table>
<thead>
<tr>
@@ -255,8 +276,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_HOST</code>
</td>
<td data-label="Description">
- SMTP 服务器主机名(例如 <code>smtp.gmail.com</code>
- )。与 <code>DATABASUS_URL</code> 一起设置即启用邮件。
+ 邮件服务器主机名(例如 <code>smtp.gmail.com</code>)。设置后即启用实例邮件。
</td>
</tr>
<tr>
@@ -264,15 +284,24 @@ export default function AdvancedConfigPage() {
<code>SMTP_PORT</code>
</td>
<td data-label="Description">
- SMTP 服务器端口(例如 <code>587</code>)。设置了{" "}
- <code>SMTP_HOST</code> 时必须是正整数。
+ 邮件服务器端口(例如 <code>587</code>)。设置了 <code>SMTP_HOST</code> 时必须是正整数。
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_SECURITY</code>
+ </td>
+ <td data-label="Description">
+ 连接安全:<code>tls</code>、<code>starttls</code> 或 <code>none</code>,说明见下文。465 端口默认 <code>tls</code>,其他端口默认 <code>starttls</code>。取其他值时实例拒绝启动。
</td>
</tr>
<tr>
<td>
<code>SMTP_USER</code>
</td>
- <td data-label="Description">SMTP 认证用户名。</td>
+ <td data-label="Description">
+ SMTP 认证用户名。
+ </td>
</tr>
<tr>
<td>
@@ -287,7 +316,15 @@ export default function AdvancedConfigPage() {
<code>SMTP_FROM</code>
</td>
<td data-label="Description">
- 发出邮件的&quot;From&quot;地址。
+ 发件人地址,可以只写地址(<code>[email protected]</code>),也可以带名称(<code>Acme Backups &lt;[email protected]&gt;</code>)。不带名称时,收件人看到的是 <code>Databasus</code>。未设置时,如果 <code>SMTP_USER</code> 是邮箱地址就使用它,否则使用 <code>noreply@</code> 加 <code>SMTP_HOST</code>,因此 <code>apikey</code> 这样的用户名不会成为发件人。值无法解析为地址时,实例拒绝启动。
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>SMTP_HELO_NAME</code>
+ </td>
+ <td data-label="Description">
+ 实例向邮件服务器问候时使用的名称。默认取 <code>DATABASUS_URL</code> 中的主机,没有时取本机主机名。必须是主机名,或 <code>[192.0.2.1]</code>、<code>[IPv6:2001:db8::1]</code> 这样的地址字面量,否则实例拒绝启动。
</td>
</tr>
<tr>
@@ -295,9 +332,7 @@ export default function AdvancedConfigPage() {
<code>SMTP_INSECURE_SKIP_VERIFY</code>
</td>
<td data-label="Description">
- 设为 <code>true</code> 时连接 SMTP 服务器跳过 TLS
- 证书校验。默认 <code>false</code>
- 。只在可信网络内的自签名证书服务器上使用:它会关闭对中间人攻击的防护。
+ 设为 <code>true</code> 时,在 <code>tls</code> 和 <code>starttls</code> 模式下跳过 TLS 证书校验。默认 <code>false</code>。只在可信网络内的自签名证书服务器上使用:它会关闭对中间人攻击的防护。
</td>
</tr>
<tr>
@@ -305,17 +340,73 @@ export default function AdvancedConfigPage() {
<code>DATABASUS_URL</code>
</td>
<td data-label="Description">
- 你的实例的公开基础 URL(例如{" "}
- <code>https://backup.example.com</code>
- )。用于生成邮件内的链接。必须与 <code>
- SMTP_HOST
- </code>{" "}
- 一起设置。
+ 实例的公开基础 URL(例如 <code>https://backup.example.com</code>)。可选:它会在邀请邮件里加上链接,并提供默认的问候名称。没有它邮件也能正常发送。
</td>
</tr>
</tbody>
</table>
+ <p>
+ <code>SMTP_SECURITY</code> 从三种模式中选一种。邮件通知渠道在 <strong>Advanced settings</strong> 里提供同样的选择。
+ </p>
+
+ <table>
+ <thead>
+ <tr>
+ <th>模式</th>
+ <th>行为</th>
+ </tr>
+ </thead>
+ <tbody>
+ <tr>
+ <td>
+ <code>tls</code>
+ </td>
+ <td data-label="Description">
+ 从第一个字节开始加密连接。通常用于 465 端口。
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>starttls</code>
+ </td>
+ <td data-label="Description">
+ 连接先以明文建立,在发送密码或任何邮件之前升级为加密连接。服务器不支持时发送失败,而不是继续以明文发送。通常用于 587 端口。
+ </td>
+ </tr>
+ <tr>
+ <td>
+ <code>none</code>
+ </td>
+ <td data-label="Description">
+ 连接始终不加密。适用于不支持 STARTTLS 的中继,例如 25 端口上的本地 Postfix。
+ </td>
+ </tr>
+ </tbody>
+ </table>
+
+ <div className="bg-[#1f2937]/50 border border-[#ffffff20] border-l-[3px] my-4 border-l-red-500 rounded-lg px-4 py-4 flex items-start gap-3">
+ <svg
+ width="20"
+ height="20"
+ viewBox="0 0 24 24"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="2"
+ strokeLinecap="round"
+ strokeLinejoin="round"
+ className="text-red-500 mt-0.5 shrink-0"
+ >
+ <path d="M10.29 3.86 1.82 18a2 2 0 0 0 1.71 3h16.94a2 2 0 0 0 1.71-3L13.71 3.86a2 2 0 0 0-3.42 0z" />
+ <path d="M12 9v4M12 17h.01" />
+ </svg>
+ <div>
+ <p className="text-gray-300 my-0!">
+ <code>none</code> 会以明文发送 SMTP 密码和所有邮件,Databasus 与中继之间的任何人都能读取。只应在同一主机或可信私有网络中的中继上使用。
+ </p>
+ </div>
+ </div>
+
<h2 id="signup-captcha">注册验证码(Cloudflare Turnstile)</h2>
<p>