360 lines
14 KiB
Go
360 lines
14 KiB
Go
package config
|
|
|
|
import (
|
|
"errors"
|
|
"fmt"
|
|
"net"
|
|
"net/mail"
|
|
"net/url"
|
|
"regexp"
|
|
"strconv"
|
|
"strings"
|
|
"time"
|
|
|
|
"lincodex/backend/internal/domain"
|
|
)
|
|
|
|
// EmailProvider selects exactly one mail transport. There is no implicit
|
|
// fallback between transports.
|
|
type EmailProvider string
|
|
|
|
const (
|
|
EmailProviderResend EmailProvider = "resend"
|
|
EmailProviderSMTP EmailProvider = "smtp"
|
|
EmailProviderDisabled EmailProvider = "disabled"
|
|
)
|
|
|
|
// SMTPTLSMode selects how the SMTP transport protects the connection.
|
|
// Plaintext SMTP is not supported.
|
|
type SMTPTLSMode string
|
|
|
|
const (
|
|
// SMTPTLSModeStartTLS upgrades the connection with STARTTLS and fails
|
|
// when the server does not offer it (submission, usually port 587).
|
|
SMTPTLSModeStartTLS SMTPTLSMode = "starttls"
|
|
// SMTPTLSModeImplicit opens TLS before the SMTP dialog (usually port 465).
|
|
SMTPTLSModeImplicit SMTPTLSMode = "tls"
|
|
)
|
|
|
|
const (
|
|
// defaultEmailAccount labels the only provider account of a stand that
|
|
// never switched accounts.
|
|
defaultEmailAccount = "default"
|
|
defaultEmailTimeout = 10 * time.Second
|
|
// One attempt waits at least long enough for a TLS handshake and an API
|
|
// answer, and at most one minute so that a hung provider cannot hold a
|
|
// delivery worker indefinitely.
|
|
minEmailTimeout = time.Second
|
|
maxEmailTimeout = time.Minute
|
|
|
|
// The defaults are the Resend Free plan limits checked on 2026-10-05:
|
|
// 100 recipients per UTC day and 3000 per month. They apply to resend
|
|
// and to disabled, which sends nothing. smtp has no default: a relay's
|
|
// limits are not Resend's, so the operator states them.
|
|
defaultEmailQuotaDaily = 100
|
|
defaultEmailQuotaMonthly = 3000
|
|
// defaultEmailServiceReserveShare sets the service reserve default to one
|
|
// part of the limit of each window: a fifth, so 20 recipients a day and 600
|
|
// a month on the Resend Free plan. Product notifications share the rest.
|
|
defaultEmailServiceReserveShare = 5
|
|
// maxEmailQuota is far above any plan this project can afford; a larger
|
|
// value is a typo, not a plan.
|
|
maxEmailQuota = 1_000_000_000
|
|
)
|
|
|
|
// emailAccountPattern matches domain.NewMailProviderAccount: a lowercase
|
|
// label that cannot hold the mixed-case characters of an API key.
|
|
var emailAccountPattern = regexp.MustCompile(`^[a-z0-9][a-z0-9._-]{0,63}$`)
|
|
|
|
// loadMail reads the common mail settings and only the settings of the
|
|
// selected transport, so settings of an inactive transport, including its
|
|
// secrets, never reach Config.
|
|
//
|
|
// EMAIL_PROVIDER has no default. The working stand uses resend, but a default
|
|
// would either pick a transport that this build may not provide or silently
|
|
// turn mail off; an explicit choice makes both visible at deployment time.
|
|
func (config *Config) loadMail(lookup LookupEnv) error {
|
|
provider := strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "EMAIL_PROVIDER", "")))
|
|
config.EmailProvider = EmailProvider(provider)
|
|
config.EmailFrom = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_FROM", ""))
|
|
config.EmailAccount = strings.TrimSpace(valueOrDefault(lookup, "EMAIL_ACCOUNT", defaultEmailAccount))
|
|
// One trailing slash is accepted and dropped so that the stored value is
|
|
// an origin that links can be appended to.
|
|
config.AppPublicURL = strings.TrimSuffix(strings.TrimSpace(valueOrDefault(lookup, "APP_PUBLIC_URL", "")), "/")
|
|
|
|
var err error
|
|
config.EmailTimeout, err = durationOrDefault(lookup, "EMAIL_TIMEOUT", defaultEmailTimeout)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := config.loadMailQuota(lookup); err != nil {
|
|
return err
|
|
}
|
|
|
|
switch config.EmailProvider {
|
|
case EmailProviderResend:
|
|
config.ResendAPIKey = valueOrDefault(lookup, "RESEND_API_KEY", "")
|
|
case EmailProviderSMTP:
|
|
return config.loadSMTP(lookup)
|
|
case EmailProviderDisabled:
|
|
// No transport settings are read.
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// loadMailQuota reads the quota of the configured provider account. The
|
|
// quota is read for every provider, so no transport can run without one.
|
|
// For smtp an unset value stays zero, which validation reports as missing.
|
|
//
|
|
// An empty value counts as unset, as for SMTP_PORT: Compose passes an unset
|
|
// variable as an empty string, and a Compose-side default would give smtp
|
|
// the Resend limits without the operator stating them.
|
|
func (config *Config) loadMailQuota(lookup LookupEnv) error {
|
|
daily, monthly := defaultEmailQuotaDaily, defaultEmailQuotaMonthly
|
|
if config.EmailProvider == EmailProviderSMTP {
|
|
daily, monthly = 0, 0
|
|
}
|
|
setOnly := func(key string) (string, bool) {
|
|
value, ok := lookup(key)
|
|
if strings.TrimSpace(value) == "" {
|
|
return "", false
|
|
}
|
|
return value, ok
|
|
}
|
|
var err error
|
|
if config.EmailQuotaDaily, err = intOrDefault(setOnly, "EMAIL_QUOTA_DAILY", daily); err != nil {
|
|
return err
|
|
}
|
|
if config.EmailQuotaMonthly, err = intOrDefault(setOnly, "EMAIL_QUOTA_MONTHLY", monthly); err != nil {
|
|
return err
|
|
}
|
|
return config.loadServiceReserve(setOnly)
|
|
}
|
|
|
|
// loadServiceReserve reads the recipients of each window that product
|
|
// notifications leave to service mail. An unset value takes a fifth of the
|
|
// configured limit, so the default follows the plan; a set value of 0 keeps
|
|
// the whole window for notifications too.
|
|
func (config *Config) loadServiceReserve(setOnly func(key string) (string, bool)) error {
|
|
var err error
|
|
if config.EmailServiceReserveDaily, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_DAILY", config.EmailQuotaDaily/defaultEmailServiceReserveShare); err != nil {
|
|
return err
|
|
}
|
|
if config.EmailServiceReserveMonthly, err = intOrDefault(setOnly, "EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailQuotaMonthly/defaultEmailServiceReserveShare); err != nil {
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (config *Config) loadSMTP(lookup LookupEnv) error {
|
|
config.SMTPHost = strings.TrimSpace(valueOrDefault(lookup, "SMTP_HOST", ""))
|
|
config.SMTPUsername = strings.TrimSpace(valueOrDefault(lookup, "SMTP_USERNAME", ""))
|
|
config.SMTPPassword = valueOrDefault(lookup, "SMTP_PASSWORD", "")
|
|
config.SMTPTLSMode = SMTPTLSMode(strings.ToLower(strings.TrimSpace(valueOrDefault(lookup, "SMTP_TLS_MODE", ""))))
|
|
|
|
// An unset or empty port stays zero, which validation reports as missing.
|
|
port := strings.TrimSpace(valueOrDefault(lookup, "SMTP_PORT", ""))
|
|
if port == "" {
|
|
return nil
|
|
}
|
|
number, err := strconv.Atoi(port)
|
|
if err != nil {
|
|
return fmt.Errorf("Config.loadSMTP - SMTP_PORT must be an integer between 1 and %d", maxPortNumber)
|
|
}
|
|
config.SMTPPort = number
|
|
return nil
|
|
}
|
|
|
|
// ValidateMail checks the common mail settings and the selected transport.
|
|
// Errors name the setting and never include secret values.
|
|
func (config Config) ValidateMail() error {
|
|
// The value is not echoed: a misplaced secret must not reach the logs.
|
|
switch config.EmailProvider {
|
|
case EmailProviderResend, EmailProviderSMTP, EmailProviderDisabled:
|
|
case "":
|
|
return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be set to resend, smtp, or disabled")
|
|
default:
|
|
return errors.New("Config.ValidateMail - EMAIL_PROVIDER must be one of resend, smtp, or disabled")
|
|
}
|
|
if err := validateEmailFrom(config.EmailFrom); err != nil {
|
|
return err
|
|
}
|
|
// The value is not echoed: an API key pasted here must not reach logs.
|
|
if !emailAccountPattern.MatchString(config.EmailAccount) {
|
|
return errors.New("Config.ValidateMail - EMAIL_ACCOUNT must be a label of 1 to 64 lowercase letters, digits, '.', '_', or '-' that starts with a letter or digit")
|
|
}
|
|
if err := validateAppPublicURL(config.AppPublicURL); err != nil {
|
|
return err
|
|
}
|
|
if config.EmailTimeout < minEmailTimeout || config.EmailTimeout > maxEmailTimeout {
|
|
return fmt.Errorf("Config.ValidateMail - EMAIL_TIMEOUT must be between %s and %s", minEmailTimeout, maxEmailTimeout)
|
|
}
|
|
if err := config.validateMailQuota(); err != nil {
|
|
return err
|
|
}
|
|
|
|
switch config.EmailProvider {
|
|
case EmailProviderResend:
|
|
return validateResendAPIKey(config.ResendAPIKey)
|
|
case EmailProviderSMTP:
|
|
return config.validateSMTP()
|
|
case EmailProviderDisabled:
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateMailQuota accepts limits from 1 to maxEmailQuota where the daily
|
|
// limit does not exceed the monthly one. There is no value that turns the
|
|
// quota off: zero is refused rather than read as "unlimited", so switching
|
|
// EMAIL_PROVIDER, for example to smtp, never skips the quota gate.
|
|
func (config Config) validateMailQuota() error {
|
|
for _, quota := range []struct {
|
|
name string
|
|
value int
|
|
}{{"EMAIL_QUOTA_DAILY", config.EmailQuotaDaily}, {"EMAIL_QUOTA_MONTHLY", config.EmailQuotaMonthly}} {
|
|
if quota.value >= 1 && quota.value <= maxEmailQuota {
|
|
continue
|
|
}
|
|
if config.EmailProvider == EmailProviderSMTP {
|
|
return fmt.Errorf("Config.validateMailQuota - %s must be set to an integer from 1 to %d when EMAIL_PROVIDER is smtp; the Resend defaults do not apply to a relay", quota.name, maxEmailQuota)
|
|
}
|
|
return fmt.Errorf("Config.validateMailQuota - %s must be an integer from 1 to %d", quota.name, maxEmailQuota)
|
|
}
|
|
if config.EmailQuotaDaily > config.EmailQuotaMonthly {
|
|
return errors.New("Config.validateMailQuota - EMAIL_QUOTA_DAILY must not exceed EMAIL_QUOTA_MONTHLY")
|
|
}
|
|
return config.validateServiceReserve()
|
|
}
|
|
|
|
// validateServiceReserve accepts a reserve from 0 up to, not including, each
|
|
// limit. A reserve equal to a limit would leave product notifications no
|
|
// recipient in that window, so it is refused rather than read as "off".
|
|
func (config Config) validateServiceReserve() error {
|
|
for _, reserve := range []struct {
|
|
name string
|
|
value int
|
|
limit int
|
|
}{
|
|
{"EMAIL_SERVICE_RESERVE_DAILY", config.EmailServiceReserveDaily, config.EmailQuotaDaily},
|
|
{"EMAIL_SERVICE_RESERVE_MONTHLY", config.EmailServiceReserveMonthly, config.EmailQuotaMonthly},
|
|
} {
|
|
if reserve.value < 0 || reserve.value >= reserve.limit {
|
|
return fmt.Errorf("Config.validateServiceReserve - %s must be an integer from 0 to below its quota limit", reserve.name)
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateEmailFrom accepts one RFC 5322 mailbox, with or without a display
|
|
// name. The address itself follows the account address rules of
|
|
// domain.NewEmailAddress: ASCII only, because the mailer does not support
|
|
// SMTPUTF8, an unquoted local part, and a DNS domain with at least two labels.
|
|
func validateEmailFrom(raw string) error {
|
|
if raw == "" {
|
|
return errors.New("config.validateEmailFrom - EMAIL_FROM must be set")
|
|
}
|
|
// Control characters such as CR and LF could inject header lines.
|
|
if !isPrintableASCII(raw) {
|
|
return errors.New("config.validateEmailFrom - EMAIL_FROM must contain printable ASCII characters only")
|
|
}
|
|
mailbox, err := mail.ParseAddress(raw)
|
|
if err != nil {
|
|
return errors.New("config.validateEmailFrom - EMAIL_FROM must be one mailbox such as Lincodex <no-reply@example.com>")
|
|
}
|
|
if _, err := domain.NewEmailAddress(mailbox.Address); err != nil {
|
|
return errors.New("config.validateEmailFrom - EMAIL_FROM address must be an ASCII addr-spec with a DNS domain of at least two labels")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// validateAppPublicURL accepts the public origin that links in mail point
|
|
// to. Plain HTTP is accepted only for a loopback host in local runs.
|
|
func validateAppPublicURL(raw string) error {
|
|
if raw == "" {
|
|
return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be set")
|
|
}
|
|
origin, err := url.Parse(raw)
|
|
if err != nil || origin.Hostname() == "" || !validHostOrIP(origin.Hostname()) {
|
|
return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an absolute URL with a valid host")
|
|
}
|
|
switch {
|
|
case origin.Scheme == "https":
|
|
case origin.Scheme == "http" && isLoopbackHost(origin.Hostname()):
|
|
default:
|
|
return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must use https; http is allowed only for localhost, 127.0.0.1, or [::1]")
|
|
}
|
|
|
|
if !isBareOrigin(origin, raw) {
|
|
return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must be an origin without credentials, a path, query, or fragment")
|
|
}
|
|
if !validEndpointPort(origin) {
|
|
return errors.New("config.validateAppPublicURL - APP_PUBLIC_URL must have a valid nonzero port")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// isBareOrigin reports a URL with nothing after the authority. raw is checked
|
|
// for "#" because url.Parse drops an empty fragment.
|
|
func isBareOrigin(origin *url.URL, raw string) bool {
|
|
hasCredentials := origin.User != nil
|
|
hasPath := origin.Path != "" || origin.RawPath != ""
|
|
hasQuery := origin.RawQuery != "" || origin.ForceQuery
|
|
hasFragment := origin.Fragment != "" || strings.Contains(raw, "#")
|
|
return !hasCredentials && !hasPath && !hasQuery && !hasFragment
|
|
}
|
|
|
|
// validateResendAPIKey checks only what the Authorization header needs. Resend
|
|
// shows keys as "re_..." in examples but does not document a stable format,
|
|
// so the prefix is not enforced; the provider itself rejects a wrong key.
|
|
func validateResendAPIKey(key string) error {
|
|
if key == "" {
|
|
return errors.New("config.validateResendAPIKey - RESEND_API_KEY must be set when EMAIL_PROVIDER is resend")
|
|
}
|
|
if !isPrintableASCII(key) || strings.Contains(key, " ") {
|
|
return errors.New("config.validateResendAPIKey - RESEND_API_KEY must not contain whitespace or non-ASCII characters")
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (config Config) validateSMTP() error {
|
|
if config.SMTPHost == "" {
|
|
return errors.New("Config.validateSMTP - SMTP_HOST must be set when EMAIL_PROVIDER is smtp")
|
|
}
|
|
if !validHostOrIP(config.SMTPHost) {
|
|
return errors.New("Config.validateSMTP - SMTP_HOST must be a hostname or IP address without a port")
|
|
}
|
|
if config.SMTPPort < 1 || config.SMTPPort > maxPortNumber {
|
|
return fmt.Errorf("Config.validateSMTP - SMTP_PORT must be set to a port between 1 and %d when EMAIL_PROVIDER is smtp", maxPortNumber)
|
|
}
|
|
// An anonymous relay is not supported: both credentials are required.
|
|
if config.SMTPUsername == "" {
|
|
return errors.New("Config.validateSMTP - SMTP_USERNAME must be set when EMAIL_PROVIDER is smtp")
|
|
}
|
|
if config.SMTPPassword == "" {
|
|
return errors.New("Config.validateSMTP - SMTP_PASSWORD must be set when EMAIL_PROVIDER is smtp")
|
|
}
|
|
switch config.SMTPTLSMode {
|
|
case SMTPTLSModeStartTLS, SMTPTLSModeImplicit:
|
|
return nil
|
|
default:
|
|
return errors.New("Config.validateSMTP - SMTP_TLS_MODE must be starttls or tls; plaintext SMTP is not supported")
|
|
}
|
|
}
|
|
|
|
func validHostOrIP(host string) bool {
|
|
return net.ParseIP(host) != nil || validHostname(host)
|
|
}
|
|
|
|
func isLoopbackHost(host string) bool {
|
|
return strings.EqualFold(host, "localhost") || host == "127.0.0.1" || host == "::1"
|
|
}
|
|
|
|
func isPrintableASCII(value string) bool {
|
|
for index := range len(value) {
|
|
if value[index] < ' ' || value[index] > '~' {
|
|
return false
|
|
}
|
|
}
|
|
return true
|
|
}
|