Files
supermarket/internal/appmail/appmail.go
T
davidandClaude Opus 5.5 8040512a18 Phase 10, part 3: signing in and out, resets, locks and two-factor
The server edition now starts. Sign-in by email and password, limited per
address and per IP; ten failures in a row lock the account and email its
owner, and a reset by email (or an admin) unlocks it. Settings → Your
account has the profile, the password, where you're signed in, and
two-factor sign-in with an authenticator app (TOTP, from a QR code) and
ten recovery codes. The app's own mail goes through SUPERMARKET_MAIL_URL.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-25 09:01:29 -07:00

174 lines
4.2 KiB
Go

// Package appmail sends the app's own mail on the server editions:
// invitations, password-reset links, and notices about someone's account.
// It goes through the mail server in SUPERMARKET_MAIL_URL, not the
// outreach mailbox a team sets up under Settings → Email.
package appmail
import (
"bytes"
"context"
"crypto/rand"
"crypto/tls"
"encoding/hex"
"errors"
"fmt"
"mime"
"mime/quotedprintable"
"net"
"net/mail"
"net/smtp"
"strings"
"sync"
"time"
"supermarket/internal/config"
)
// Message is a plain-text email to one person.
type Message struct {
To string // an address
ToName string
Subject string
Body string
}
// Sender sends messages.
type Sender interface {
Send(ctx context.Context, m Message) error
}
// SMTP sends through a mail server.
type SMTP struct {
Conf *config.Mail
}
// Send hands one message to the mail server.
func (s *SMTP) Send(ctx context.Context, m Message) error {
from, err := mail.ParseAddress(s.Conf.From)
if err != nil {
return err
}
raw, err := compose(from, m, time.Now())
if err != nil {
return err
}
host, _, err := net.SplitHostPort(s.Conf.Host)
if err != nil {
return err
}
dialer := &net.Dialer{Timeout: 30 * time.Second}
tlsConf := &tls.Config{ServerName: host}
var conn net.Conn
if s.Conf.TLS {
conn, err = (&tls.Dialer{NetDialer: dialer, Config: tlsConf}).DialContext(ctx, "tcp", s.Conf.Host)
} else {
conn, err = dialer.DialContext(ctx, "tcp", s.Conf.Host)
}
if err != nil {
return fmt.Errorf("connecting to %s: %w", s.Conf.Host, err)
}
_ = conn.SetDeadline(time.Now().Add(time.Minute))
c, err := smtp.NewClient(conn, host)
if err != nil {
conn.Close()
return err
}
defer c.Close()
if !s.Conf.TLS {
ok, _ := c.Extension("STARTTLS")
if !ok {
return fmt.Errorf("%s doesn't offer STARTTLS: use smtps:// (port 465) or a server that does", s.Conf.Host)
}
if err := c.StartTLS(tlsConf); err != nil {
return fmt.Errorf("starting TLS with %s: %w", s.Conf.Host, err)
}
}
if s.Conf.User != "" {
if err := c.Auth(smtp.PlainAuth("", s.Conf.User, s.Conf.Password, host)); err != nil {
return fmt.Errorf("signing in to %s: %w", s.Conf.Host, err)
}
}
if err := c.Mail(from.Address); err != nil {
return err
}
if err := c.Rcpt(m.To); err != nil {
return fmt.Errorf("the mail server refused %s: %w", m.To, err)
}
w, err := c.Data()
if err != nil {
return err
}
if _, err := w.Write(raw); err != nil {
return err
}
if err := w.Close(); err != nil {
return err
}
return c.Quit()
}
func compose(from *mail.Address, m Message, now time.Time) ([]byte, error) {
to, err := mail.ParseAddress(m.To)
if err != nil {
return nil, err
}
to.Name = m.ToName
if strings.ContainsAny(m.Subject, "\r\n") {
return nil, errors.New("a subject has one line")
}
id := make([]byte, 12)
_, _ = rand.Read(id)
domain := from.Address[strings.LastIndex(from.Address, "@")+1:]
var b bytes.Buffer
h := func(k, v string) { b.WriteString(k + ": " + v + "\r\n") }
h("From", from.String())
h("To", to.String())
h("Subject", mime.QEncoding.Encode("utf-8", m.Subject))
h("Date", now.Format(time.RFC1123Z))
h("Message-ID", "<"+hex.EncodeToString(id)+"@"+domain+">")
h("Auto-Submitted", "auto-generated")
h("MIME-Version", "1.0")
h("Content-Type", "text/plain; charset=utf-8")
h("Content-Transfer-Encoding", "quoted-printable")
b.WriteString("\r\n")
text := strings.ReplaceAll(strings.ReplaceAll(strings.TrimSpace(m.Body), "\r\n", "\n"), "\n", "\r\n") + "\r\n"
qp := quotedprintable.NewWriter(&b)
_, _ = qp.Write([]byte(text))
_ = qp.Close()
return b.Bytes(), nil
}
// Outbox keeps messages instead of sending them: for tests.
type Outbox struct {
mu sync.Mutex
Sent []Message
}
// Send keeps the message.
func (o *Outbox) Send(_ context.Context, m Message) error {
o.mu.Lock()
defer o.mu.Unlock()
o.Sent = append(o.Sent, m)
return nil
}
// Last is the last message sent to an address, or nil.
func (o *Outbox) Last(to string) *Message {
o.mu.Lock()
defer o.mu.Unlock()
for i := len(o.Sent) - 1; i >= 0; i-- {
if strings.EqualFold(o.Sent[i].To, to) {
m := o.Sent[i]
return &m
}
}
return nil
}
// Count is how many messages were sent.
func (o *Outbox) Count() int {
o.mu.Lock()
defer o.mu.Unlock()
return len(o.Sent)
}