- Add List-Id, List-Post, List-Unsubscribe and Precedence headers - Add one-click unsubscribe (RFC 8058) when a base URL is configured - Strip incoming List-* headers to prevent spoofing - Rewrite From as "Name via List" and keep the original in Reply-To - Copy the message body byte for byte
64 lines
1.6 KiB
Go
64 lines
1.6 KiB
Go
package router
|
|
|
|
import (
|
|
"bufio"
|
|
"bytes"
|
|
"fmt"
|
|
"io"
|
|
"net/mail"
|
|
"strings"
|
|
|
|
"github.com/emersion/go-message/textproto"
|
|
|
|
"codeberg.org/squidd/parsimony/internal/store"
|
|
)
|
|
|
|
// rewrite adds list headers and rewrites From so DMARC alignment holds.
|
|
// The body is copied byte for byte.
|
|
func rewrite(l store.List, baseURL string, data []byte) ([]byte, error) {
|
|
br := bufio.NewReader(bytes.NewReader(data))
|
|
h, err := textproto.ReadHeader(br)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("parse header: %w", err)
|
|
}
|
|
|
|
// Never trust list headers coming from outside.
|
|
for _, k := range []string{"List-Id", "List-Post", "List-Unsubscribe", "List-Unsubscribe-Post", "Precedence"} {
|
|
h.Del(k)
|
|
}
|
|
|
|
id := l.Name + "." + l.Domain
|
|
h.Set("List-Id", fmt.Sprintf("%s <%s>", l.Title, id))
|
|
h.Set("List-Post", "<mailto:"+l.Address()+">")
|
|
unsub := "<mailto:" + l.Name + "+unsubscribe@" + l.Domain + ">"
|
|
if baseURL != "" {
|
|
unsub = "<" + strings.TrimRight(baseURL, "/") + "/unsubscribe/" + id + ">, " + unsub
|
|
h.Set("List-Unsubscribe-Post", "List-Unsubscribe=One-Click")
|
|
}
|
|
h.Set("List-Unsubscribe", unsub)
|
|
h.Set("Precedence", "list")
|
|
|
|
if orig := h.Get("From"); orig != "" {
|
|
name := orig
|
|
if a, err := mail.ParseAddress(orig); err == nil {
|
|
name = a.Name
|
|
if name == "" {
|
|
name = a.Address
|
|
}
|
|
}
|
|
if h.Get("Reply-To") == "" {
|
|
h.Set("Reply-To", orig)
|
|
}
|
|
from := mail.Address{Name: name + " via " + l.Title, Address: l.Address()}
|
|
h.Set("From", from.String())
|
|
}
|
|
|
|
var out bytes.Buffer
|
|
if err := textproto.WriteHeader(&out, h); err != nil {
|
|
return nil, err
|
|
}
|
|
if _, err := io.Copy(&out, br); err != nil {
|
|
return nil, err
|
|
}
|
|
return out.Bytes(), nil
|
|
}
|