275 lines
10 KiB
Go
275 lines
10 KiB
Go
// Package mailtemplate renders the service emails that Lincodex sends: email
|
|
// verification, password reset, and short notifications. One rendering gives
|
|
// the subject, the plain-text part, and the HTML part of one message; every
|
|
// transport sends the same rendering, so templates never depend on a provider
|
|
// or on the sender address.
|
|
//
|
|
// Templates are embedded files named <kind>.v<N>.<part>.tmpl, where part is
|
|
// subject, txt, or html. A released version is immutable: a copy change adds
|
|
// the next version and switches the current constant below, and each version
|
|
// is self-contained (no shared partials), so editing one version can never
|
|
// change the body of another. The renderer does not log.
|
|
package mailtemplate
|
|
|
|
import (
|
|
"bytes"
|
|
"crypto/sha256"
|
|
"embed"
|
|
"errors"
|
|
"fmt"
|
|
htmltemplate "html/template"
|
|
"io"
|
|
"io/fs"
|
|
"net/url"
|
|
"path"
|
|
"regexp"
|
|
"strings"
|
|
texttemplate "text/template"
|
|
"unicode/utf8"
|
|
)
|
|
|
|
// Kind names what a message is for.
|
|
type Kind string
|
|
|
|
const (
|
|
KindVerification Kind = "verification"
|
|
KindPasswordReset Kind = "password_reset"
|
|
KindNotification Kind = "notification"
|
|
)
|
|
|
|
// TemplateVersion names one immutable template revision, "<kind>.v<N>".
|
|
type TemplateVersion string
|
|
|
|
// The versions that new renderings use. Changing copy means adding new
|
|
// template files with the next version and pointing the constant at them.
|
|
const (
|
|
currentVerificationVersion TemplateVersion = "verification.v1"
|
|
currentPasswordResetVersion TemplateVersion = "password_reset.v1"
|
|
currentNotificationVersion TemplateVersion = "notification.v1"
|
|
)
|
|
|
|
const (
|
|
templateDirectory = "templates"
|
|
partSubject = "subject"
|
|
partText = "txt"
|
|
partHTML = "html"
|
|
// maxSubjectRunes bounds the rendered subject. RFC 5322 recommends lines
|
|
// of at most 78 characters, and long subjects are cut by mail clients
|
|
// anyway; the bound leaves room for a caller subject plus fixed copy.
|
|
maxSubjectRunes = 150
|
|
)
|
|
|
|
// ErrInvalidTemplateData reports data that cannot be rendered safely: a
|
|
// missing token, an out-of-range lifetime, caller text out of bounds, or a
|
|
// link outside the application. Errors name the field, never its value.
|
|
var ErrInvalidTemplateData = errors.New("invalid template data")
|
|
|
|
//go:embed templates/*.tmpl
|
|
var embeddedTemplates embed.FS
|
|
|
|
var templateFileName = regexp.MustCompile(`^([a-z_]+\.v[1-9][0-9]*)\.(subject|txt|html)\.tmpl$`)
|
|
|
|
var templateFuncs = map[string]any{"plural": russianPlural}
|
|
|
|
// Renderer turns typed data into a RenderedMail. It is safe for concurrent use:
|
|
// the parsed templates are read-only after construction.
|
|
type Renderer struct {
|
|
origin url.URL
|
|
templates map[TemplateVersion]versionTemplates
|
|
}
|
|
|
|
type versionTemplates struct {
|
|
subject *texttemplate.Template
|
|
text *texttemplate.Template
|
|
html *htmltemplate.Template
|
|
}
|
|
|
|
// page is what the text and HTML parts receive: the final subject and the
|
|
// kind-specific view. The subject part receives the view alone.
|
|
type page struct {
|
|
Subject string
|
|
View any
|
|
}
|
|
|
|
// NewRenderer parses every embedded template once and binds links to
|
|
// publicOrigin, the APP_PUBLIC_URL value. A malformed template file, a missing
|
|
// part, a missing current version, or an invalid origin fails construction.
|
|
func NewRenderer(publicOrigin string) (*Renderer, error) {
|
|
origin, err := parsePublicOrigin(publicOrigin)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("mailtemplate.NewRenderer - parse public origin: %w", err)
|
|
}
|
|
templates, err := parseTemplates(embeddedTemplates)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("mailtemplate.NewRenderer - parse templates: %w", err)
|
|
}
|
|
for _, version := range []TemplateVersion{currentVerificationVersion, currentPasswordResetVersion, currentNotificationVersion} {
|
|
if _, ok := templates[version]; !ok {
|
|
return nil, fmt.Errorf("mailtemplate.NewRenderer - current template version %s is missing", version)
|
|
}
|
|
}
|
|
return &Renderer{origin: origin, templates: templates}, nil
|
|
}
|
|
|
|
// RenderVerification renders the email confirmation message. The link is
|
|
// <origin>/verify-email#token=<token>.
|
|
func (renderer *Renderer) RenderVerification(data VerificationData) (RenderedMail, error) {
|
|
view, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
|
|
if err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.RenderVerification - validate data: %w", err)
|
|
}
|
|
return renderer.render(KindVerification, currentVerificationVersion, view)
|
|
}
|
|
|
|
// RenderPasswordReset renders the password reset message. The link is
|
|
// <origin>/reset-password#token=<token>.
|
|
func (renderer *Renderer) RenderPasswordReset(data PasswordResetData) (RenderedMail, error) {
|
|
view, err := renderer.tokenLinkView(resetPasswordPath, data.Token, data.TokenLifetime)
|
|
if err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.RenderPasswordReset - validate data: %w", err)
|
|
}
|
|
return renderer.render(KindPasswordReset, currentPasswordResetVersion, view)
|
|
}
|
|
|
|
// RenderNotification renders a short notification with caller text and a link
|
|
// to a path inside the application.
|
|
func (renderer *Renderer) RenderNotification(data NotificationData) (RenderedMail, error) {
|
|
view, err := renderer.notificationView(data)
|
|
if err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.RenderNotification - validate data: %w", err)
|
|
}
|
|
return renderer.render(KindNotification, currentNotificationVersion, view)
|
|
}
|
|
|
|
func (renderer *Renderer) render(kind Kind, version TemplateVersion, view any) (RenderedMail, error) {
|
|
templates := renderer.templates[version]
|
|
|
|
var subject bytes.Buffer
|
|
if err := templates.subject.Execute(&subject, view); err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.render - execute %s subject: %w", version, err)
|
|
}
|
|
finalSubject := normalizeSubject(subject.String())
|
|
if length := utf8.RuneCountInString(finalSubject); length == 0 || length > maxSubjectRunes {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.render - %s subject must have 1 to %d characters: %w", version, maxSubjectRunes, ErrInvalidTemplateData)
|
|
}
|
|
|
|
content := page{Subject: finalSubject, View: view}
|
|
var text bytes.Buffer
|
|
if err := templates.text.Execute(&text, content); err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.render - execute %s text: %w", version, err)
|
|
}
|
|
var html bytes.Buffer
|
|
if err := templates.html.Execute(&html, content); err != nil {
|
|
return RenderedMail{}, fmt.Errorf("Renderer.render - execute %s html: %w", version, err)
|
|
}
|
|
|
|
return newRenderedMail(kind, version, finalSubject, finishPart(text.String()), finishPart(html.String())), nil
|
|
}
|
|
|
|
// finishPart drops the whitespace that template actions leave at the edges
|
|
// and ends the part with exactly one newline.
|
|
func finishPart(part string) string {
|
|
return strings.TrimSpace(part) + "\n"
|
|
}
|
|
|
|
// contentHash is SHA-256 over the parts encoded as netstrings ("<len>:<part>,"),
|
|
// so moving bytes from one part to the next changes the digest.
|
|
func contentHash(parts ...string) ContentHash {
|
|
digest := sha256.New()
|
|
for _, part := range parts {
|
|
// hash.Hash.Write never returns an error.
|
|
_, _ = fmt.Fprintf(digest, "%d:", len(part))
|
|
_, _ = io.WriteString(digest, part)
|
|
_, _ = io.WriteString(digest, ",")
|
|
}
|
|
var sum ContentHash
|
|
copy(sum[:], digest.Sum(nil))
|
|
return sum
|
|
}
|
|
|
|
// parseTemplates reads every file in the template directory. Each version
|
|
// must provide the subject, text, and HTML parts, and no other file may be
|
|
// present, so a misnamed file cannot be silently ignored.
|
|
func parseTemplates(files fs.FS) (map[TemplateVersion]versionTemplates, error) {
|
|
entries, err := fs.ReadDir(files, templateDirectory)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("mailtemplate.parseTemplates - read directory: %w", err)
|
|
}
|
|
sources := make(map[TemplateVersion]map[string]string)
|
|
for _, entry := range entries {
|
|
match := templateFileName.FindStringSubmatch(entry.Name())
|
|
if entry.IsDir() || match == nil {
|
|
return nil, fmt.Errorf("mailtemplate.parseTemplates - unexpected template file %q", entry.Name())
|
|
}
|
|
content, err := fs.ReadFile(files, path.Join(templateDirectory, entry.Name()))
|
|
if err != nil {
|
|
return nil, fmt.Errorf("mailtemplate.parseTemplates - read %s: %w", entry.Name(), err)
|
|
}
|
|
version := TemplateVersion(match[1])
|
|
if sources[version] == nil {
|
|
sources[version] = make(map[string]string)
|
|
}
|
|
sources[version][match[2]] = string(content)
|
|
}
|
|
|
|
templates := make(map[TemplateVersion]versionTemplates, len(sources))
|
|
for version, parts := range sources {
|
|
parsed, err := parseVersion(version, parts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
templates[version] = parsed
|
|
}
|
|
return templates, nil
|
|
}
|
|
|
|
func parseVersion(version TemplateVersion, parts map[string]string) (versionTemplates, error) {
|
|
for _, part := range []string{partSubject, partText, partHTML} {
|
|
if _, ok := parts[part]; !ok {
|
|
return versionTemplates{}, fmt.Errorf("mailtemplate.parseVersion - %s has no %s part", version, part)
|
|
}
|
|
}
|
|
name := string(version)
|
|
subject, err := texttemplate.New(name + ".subject").Funcs(templateFuncs).Parse(parts[partSubject])
|
|
if err != nil {
|
|
return versionTemplates{}, fmt.Errorf("mailtemplate.parseVersion - parse %s subject: %w", version, err)
|
|
}
|
|
text, err := texttemplate.New(name + ".txt").Funcs(templateFuncs).Parse(parts[partText])
|
|
if err != nil {
|
|
return versionTemplates{}, fmt.Errorf("mailtemplate.parseVersion - parse %s text: %w", version, err)
|
|
}
|
|
html, err := htmltemplate.New(name + ".html").Funcs(templateFuncs).Parse(parts[partHTML])
|
|
if err != nil {
|
|
return versionTemplates{}, fmt.Errorf("mailtemplate.parseVersion - parse %s html: %w", version, err)
|
|
}
|
|
// html/template escapes on the first Execute. Running it once without
|
|
// data moves escaping errors, such as an unclosed attribute, to
|
|
// construction; the expected failure on the missing data is not one.
|
|
var escapeErr *htmltemplate.Error
|
|
if err := html.Execute(io.Discard, nil); errors.As(err, &escapeErr) {
|
|
return versionTemplates{}, fmt.Errorf("mailtemplate.parseVersion - escape %s html: %w", version, err)
|
|
}
|
|
return versionTemplates{subject: subject, text: text, html: html}, nil
|
|
}
|
|
|
|
// russianPlural picks the Russian noun form for count: one (1, 21), few
|
|
// (2-4, 22-24), or many (0, 5-20, 25). The forms stay in the template, so the
|
|
// copy belongs to the template version.
|
|
func russianPlural(count int, one, few, many string) string {
|
|
lastTwo := count % 100
|
|
if lastTwo < 0 {
|
|
lastTwo = -lastTwo
|
|
}
|
|
if lastTwo >= 11 && lastTwo <= 14 {
|
|
return many
|
|
}
|
|
switch lastTwo % 10 {
|
|
case 1:
|
|
return one
|
|
case 2, 3, 4:
|
|
return few
|
|
default:
|
|
return many
|
|
}
|
|
}
|