feat(mail): add versioned service email templates

This commit is contained in:
shira committed 2026-10-06 02:09:10 +03:00
1 parent 4cd7d060bd
commit 65d66b6f7d
26 files changed
+1481 -4

No files matched your search

Whitespace-only changes.
@@ -0,0 +1,232 @@
package mailtemplate
import (
"fmt"
"log/slog"
"strings"
"unicode"
"unicode/utf8"
"lincodex/backend/internal/domain"
)
const (
verifyEmailPath = "/verify-email"
resetPasswordPath = "/reset-password"
// maxTokenLifetime matches the upper bound of the policy's verification
// token lifetime; a longer value in the copy would be a caller bug.
maxTokenLifetime = domain.Hours(7 * 24)
// Caller text bounds keep a notification short; longer content belongs
// in the cabinet page the link points to.
maxNotificationSubjectRunes = 100
maxNotificationBodyRunes = 2000
redactedNotificationData = "[redacted notification data]"
)
// VerificationData is the input of the email confirmation message. The
// message carries no name and no address: the recipient already knows both,
// and a forwarded or leaked message then reveals less.
type VerificationData struct {
// Token is revealed only into the link fragment, never into a query or a
// log. SecretToken redacts itself in fmt and slog output.
Token domain.SecretToken
// TokenLifetime is the policy value stated in the copy, from 1 hour to
// 7 days.
TokenLifetime domain.Hours
}
// PasswordResetData is the input of the password reset message.
type PasswordResetData struct {
Token domain.SecretToken
TokenLifetime domain.Hours
}
// NotificationData is the input of a short notification. Subject and Body are
// plain text written by the caller and are escaped for each part; they must
// not contain other people's contacts. LinkPath is a path inside the
// application, such as /candidate/invitations, that the link appends to the
// public origin.
//
// String, GoString, Format, and LogValue redact the whole value, because the
// text can carry personal data. As with outbound.OutgoingMail, fmt cannot call
// them for an unexported field of an enclosing struct, so do not print such a
// struct.
type NotificationData struct {
Subject string
Body string
LinkPath string
}
func (data NotificationData) String() string { return redactedNotificationData }
func (data NotificationData) GoString() string { return redactedNotificationData }
// Format redacts every verb; without it %+v would print the fields.
func (data NotificationData) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(redactedNotificationData))
}
func (data NotificationData) LogValue() slog.Value { return slog.StringValue(redactedNotificationData) }
// tokenLinkView is what the verification and reset templates receive.
type tokenLinkView struct {
Link string
LifetimeHours int
}
// notificationView is what the notification templates receive. TextBody is
// the sanitized body for the plain-text part; Paragraphs holds the same lines
// for the HTML part, where html/template escapes each line.
type notificationView struct {
Subject string
TextBody string
Paragraphs [][]string
Link string
}
func (renderer *Renderer) tokenLinkView(linkPath string, token domain.SecretToken, lifetime domain.Hours) (tokenLinkView, error) {
if token.IsZero() {
return tokenLinkView{}, invalidData("Renderer.tokenLinkView", "token must be set")
}
if lifetime < 1 || lifetime > maxTokenLifetime {
return tokenLinkView{}, invalidData("Renderer.tokenLinkView", fmt.Sprintf("token lifetime must be from 1 to %d hours", maxTokenLifetime))
}
return tokenLinkView{Link: renderer.tokenLink(linkPath, token), LifetimeHours: int(lifetime)}, nil
}
func (renderer *Renderer) notificationView(data NotificationData) (notificationView, error) {
if !utf8.ValidString(data.Subject) || !utf8.ValidString(data.Body) {
return notificationView{}, invalidData("Renderer.notificationView", "subject and body must be valid UTF-8")
}
subject := normalizeSubject(data.Subject)
if length := utf8.RuneCountInString(subject); length == 0 || length > maxNotificationSubjectRunes {
return notificationView{}, invalidData("Renderer.notificationView", fmt.Sprintf("subject must have 1 to %d characters", maxNotificationSubjectRunes))
}
paragraphs := splitParagraphs(sanitizeBody(data.Body))
if len(paragraphs) == 0 {
return notificationView{}, invalidData("Renderer.notificationView", "body must not be empty")
}
textBody := joinParagraphs(paragraphs)
if utf8.RuneCountInString(textBody) > maxNotificationBodyRunes {
return notificationView{}, invalidData("Renderer.notificationView", fmt.Sprintf("body must have at most %d characters", maxNotificationBodyRunes))
}
link, err := renderer.appLink(data.LinkPath)
if err != nil {
return notificationView{}, err
}
return notificationView{Subject: subject, TextBody: textBody, Paragraphs: paragraphs, Link: link}, nil
}
// normalizeSubject turns a subject into one header-safe line: control,
// line-separator, and bidirectional-override characters become spaces, so CR
// and LF cannot inject header lines, and runs of whitespace collapse.
func normalizeSubject(subject string) string {
return strings.Join(strings.Fields(strings.Map(func(character rune) rune {
if isUnsafeCharacter(character) || isLineBreak(character) {
return ' '
}
return character
}, subject)), " ")
}
// sanitizeBody keeps line breaks as "\n", turns tabs into spaces, and drops
// every other control and bidirectional-override character. The plain-text
// part is not escaped, so this is what keeps it free of terminal escapes and
// visually reordered text.
func sanitizeBody(body string) string {
body = strings.ReplaceAll(body, "\r\n", "\n")
return strings.Map(func(character rune) rune {
switch {
case isLineBreak(character):
return '\n'
case character == '\t':
return ' '
case isUnsafeCharacter(character):
return -1
default:
return character
}
}, body)
}
// splitParagraphs trims every line and groups non-empty lines into
// paragraphs separated by blank lines.
func splitParagraphs(body string) [][]string {
var paragraphs [][]string
var current []string
for line := range strings.SplitSeq(body, "\n") {
line = strings.TrimSpace(line)
if line == "" {
if len(current) > 0 {
paragraphs = append(paragraphs, current)
current = nil
}
continue
}
current = append(current, line)
}
if len(current) > 0 {
paragraphs = append(paragraphs, current)
}
return paragraphs
}
func joinParagraphs(paragraphs [][]string) string {
joined := make([]string, 0, len(paragraphs))
for _, lines := range paragraphs {
joined = append(joined, strings.Join(lines, "\n"))
}
return strings.Join(joined, "\n\n")
}
func isLineBreak(character rune) bool {
switch character {
case '\n', '\r', nextLine, lineSeparator, paragraphSeparator:
return true
default:
return false
}
}
// Line break and bidirectional control code points. They are named numbers so
// that the source itself never contains an invisible control character.
const (
nextLine = 0x0085
lineSeparator = 0x2028
paragraphSeparator = 0x2029
arabicLetterMark = 0x061c
leftToRightMark = 0x200e
rightToLeftMark = 0x200f
firstBidiEmbedding = 0x202a // LEFT-TO-RIGHT EMBEDDING
lastBidiEmbedding = 0x202e // RIGHT-TO-LEFT OVERRIDE
firstBidiIsolate = 0x2066 // LEFT-TO-RIGHT ISOLATE
lastBidiIsolate = 0x2069 // POP DIRECTIONAL ISOLATE
)
// isUnsafeCharacter reports C0 and C1 controls other than line breaks, DEL,
// and the Unicode bidirectional controls, which can make displayed text read
// differently from its bytes.
func isUnsafeCharacter(character rune) bool {
switch {
case isLineBreak(character):
return false
case unicode.IsControl(character):
return true
case character == arabicLetterMark, character == leftToRightMark, character == rightToLeftMark:
return true
case character >= firstBidiEmbedding && character <= lastBidiEmbedding:
return true
case character >= firstBidiIsolate && character <= lastBidiIsolate:
return true
default:
return false
}
}
// invalidData names the field and the rule, never the rejected value.
func invalidData(location, reason string) error {
return fmt.Errorf("%s - %s: %w", location, reason, ErrInvalidTemplateData)
}
@@ -0,0 +1,130 @@
package mailtemplate
import (
"errors"
"net"
"net/url"
"strconv"
"strings"
"lincodex/backend/internal/domain"
)
const (
maxPortNumber = 65535
// maxLinkPathLength keeps notification links short enough to read and to
// copy from the plain-text part.
maxLinkPathLength = 256
)
// tokenLink builds <origin><linkPath>#token=<token>. The token travels only
// in the fragment, which browsers never send to a server, so it stays out of
// access logs and Referer headers; it is never put in the query.
func (renderer *Renderer) tokenLink(linkPath string, token domain.SecretToken) string {
link := renderer.origin
link.Path = linkPath
link.Fragment = "token=" + token.Reveal()
return link.String()
}
// appLink builds <origin><linkPath> for a path inside the application. Only
// a rooted path of letters, digits, "-", ".", "_", "~", and "/" is accepted, so
// a scheme (javascript:, https:), a host (//evil.example), a backslash, a
// percent-encoded byte, a query, or a fragment cannot reach the link, and "."
// or ".." segments cannot step out of the cabinet path the caller named.
func (renderer *Renderer) appLink(linkPath string) (string, error) {
const location = "Renderer.appLink"
if linkPath == "" || len(linkPath) > maxLinkPathLength {
return "", invalidData(location, "link path must have 1 to 256 characters")
}
if linkPath[0] != '/' {
return "", invalidData(location, "link path must be a path inside the application that starts with /")
}
for index := range len(linkPath) {
if !isPathCharacter(linkPath[index]) {
return "", invalidData(location, "link path may contain only letters, digits, -, ., _, ~, and /")
}
}
for segment := range strings.SplitSeq(linkPath[1:], "/") {
if segment == "" || segment == "." || segment == ".." {
return "", invalidData(location, "link path must not contain empty, . or .. segments")
}
}
link := renderer.origin
link.Path = linkPath
return link.String(), nil
}
func isPathCharacter(character byte) bool {
isLetter := ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z')
isDigit := '0' <= character && character <= '9'
return isLetter || isDigit || strings.IndexByte("-._~/", character) >= 0
}
// parsePublicOrigin applies the APP_PUBLIC_URL rules of the config package
// again, because links in mail are a trust boundary of their own: https, or
// http only for a loopback host; a valid host and port; no credentials, path,
// query, or fragment. One trailing slash is dropped, as config does.
func parsePublicOrigin(raw string) (url.URL, error) {
const location = "mailtemplate.parsePublicOrigin"
raw = strings.TrimSuffix(strings.TrimSpace(raw), "/")
origin, err := url.Parse(raw)
if err != nil || origin.Hostname() == "" || !validHost(origin.Hostname()) {
return url.URL{}, errors.New(location + " - public origin must be an absolute URL with a valid host")
}
switch {
case origin.Scheme == "https":
case origin.Scheme == "http" && isLoopbackHost(origin.Hostname()):
default:
return url.URL{}, errors.New(location + " - public origin must use https; http is allowed only for localhost, 127.0.0.1, or [::1]")
}
if !isBareOrigin(origin, raw) {
return url.URL{}, errors.New(location + " - public origin must not contain credentials, a path, query, or fragment")
}
if !validPort(origin) {
return url.URL{}, errors.New(location + " - public origin must have a valid nonzero port")
}
return url.URL{Scheme: origin.Scheme, Host: origin.Host}, 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 != "" || origin.Opaque != ""
hasQuery := origin.RawQuery != "" || origin.ForceQuery
hasFragment := origin.Fragment != "" || strings.Contains(raw, "#")
return !hasCredentials && !hasPath && !hasQuery && !hasFragment
}
func validHost(host string) bool {
if net.ParseIP(host) != nil {
return true
}
for label := range strings.SplitSeq(host, ".") {
if label == "" || strings.HasPrefix(label, "-") || strings.HasSuffix(label, "-") {
return false
}
for _, character := range label {
isLetter := ('a' <= character && character <= 'z') || ('A' <= character && character <= 'Z')
isDigit := '0' <= character && character <= '9'
if !isLetter && !isDigit && character != '-' && character != '_' {
return false
}
}
}
return true
}
func validPort(origin *url.URL) bool {
port := origin.Port()
if port == "" {
return !strings.HasSuffix(origin.Host, ":")
}
number, err := strconv.Atoi(port)
return err == nil && number >= 1 && number <= maxPortNumber
}
func isLoopbackHost(host string) bool {
return strings.EqualFold(host, "localhost") || host == "127.0.0.1" || host == "::1"
}
@@ -0,0 +1,116 @@
package mailtemplate
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"log/slog"
"lincodex/backend/internal/domain"
"lincodex/backend/internal/port/outbound"
)
// ContentHash is the SHA-256 digest of a rendering: its template version,
// subject, text part, and HTML part. The same version and data always give
// the same digest, and any change to any part gives another one. The delivery
// layer can store it with the idempotency key to pin the body of one logical
// delivery and to detect a different body offered under the same key.
type ContentHash [sha256.Size]byte
// String returns the lowercase hex digest. It is not secret: SHA-256 over a
// body that holds a 256-bit token cannot be reversed.
func (hash ContentHash) String() string { return hex.EncodeToString(hash[:]) }
// RenderedMail is one immutable rendering, built only by Renderer. The
// subject and bodies are what a transport sends; the link in a verification
// or reset body carries a bearer token.
//
// The content sits behind a pointer with read-only accessors, so a caller
// cannot change a body after its ContentHash was computed, and printing an
// enclosing struct, even through an unexported field, shows only an address.
// String, GoString, Format, and LogValue show the kind, the template version,
// and the content hash, never the subject or the bodies.
type RenderedMail struct {
content *renderedContent
}
type renderedContent struct {
kind Kind
version TemplateVersion
subject string
text string
html string
contentHash ContentHash
}
func newRenderedMail(kind Kind, version TemplateVersion, subject, text, html string) RenderedMail {
return RenderedMail{content: &renderedContent{
kind: kind,
version: version,
subject: subject,
text: text,
html: html,
contentHash: contentHash(string(version), subject, text, html),
}}
}
// IsZero reports a RenderedMail not built by Renderer.
func (mail RenderedMail) IsZero() bool { return mail.content == nil }
func (mail RenderedMail) Kind() Kind { return mail.read().kind }
func (mail RenderedMail) TemplateVersion() TemplateVersion { return mail.read().version }
func (mail RenderedMail) Subject() string { return mail.read().subject }
// Text returns the plain-text part. It may contain a bearer token; never log it.
func (mail RenderedMail) Text() string { return mail.read().text }
// HTML returns the HTML part. It may contain a bearer token; never log it.
func (mail RenderedMail) HTML() string { return mail.read().html }
func (mail RenderedMail) ContentHash() ContentHash { return mail.read().contentHash }
func (mail RenderedMail) read() renderedContent {
if mail.content == nil {
return renderedContent{}
}
return *mail.content
}
// ToOutgoingMail addresses the rendering for the MailSender port. The
// recipient and the idempotency key come from the delivery, never from the
// template data.
func (mail RenderedMail) ToOutgoingMail(to domain.EmailAddress, idempotencyKey string) outbound.OutgoingMail {
content := mail.read()
return outbound.OutgoingMail{
To: to,
Subject: content.subject,
TextBody: content.text,
HTMLBody: content.html,
IdempotencyKey: idempotencyKey,
}
}
func (mail RenderedMail) String() string {
if mail.IsZero() {
return "[empty rendered mail]"
}
return fmt.Sprintf("[rendered mail %s %s, content redacted]", mail.content.version, mail.content.contentHash)
}
func (mail RenderedMail) GoString() string { return mail.String() }
// Format applies String to every verb; without it %+v would print the fields.
func (mail RenderedMail) Format(state fmt.State, _ rune) {
_, _ = state.Write([]byte(mail.String()))
}
func (mail RenderedMail) LogValue() slog.Value {
content := mail.read()
return slog.GroupValue(
slog.String("kind", string(content.kind)),
slog.String("template_version", string(content.version)),
slog.String("content_hash", content.contentHash.String()),
)
}
@@ -0,0 +1,274 @@
// 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
}
}
@@ -0,0 +1,480 @@
package mailtemplate
import (
"bytes"
"errors"
"flag"
"fmt"
"log/slog"
"net/url"
"os"
"path/filepath"
"strings"
"testing"
"testing/fstest"
"lincodex/backend/internal/domain"
)
// Run "go test ./internal/usecase/notification/mailtemplate -update" from
// backend/ after an intended copy change, then review the golden diff.
var updateGolden = flag.Bool("update", false, "rewrite the golden renderings in testdata")
const (
testOrigin = "https://lincodex.example"
// syntheticToken matches the contract token pattern and is fixed so that
// golden files stay stable. It is not a real credential.
syntheticToken = "SyntheticToken_0123456789-abcdefghijklmnopqrstuv"
// hostileSubject tries markup, quotes, and a header line injection.
hostileSubject = "Приглашение <script>alert(\"x\")</script> & 'кавычки'\r\nX-Injected: yes"
// hostileBody adds a bidi override, a bell, a stray CR, extra blank
// lines, an ampersand, markup, and non-ASCII text.
hostileBody = "Компания \"Тест & Ко\" <b>пригласила</b> вас.\r\nВторая строка\u202eреверс\u0007\r\n\n\n\nВторой абзац: ёжик 🚀 <img src=x onerror=alert(1)>"
)
func newTestRenderer(t *testing.T) *Renderer {
t.Helper()
renderer, err := NewRenderer(testOrigin)
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
return renderer
}
func testToken(t *testing.T) domain.SecretToken {
t.Helper()
token, err := domain.ParseSecretToken(syntheticToken)
if err != nil {
t.Fatalf("ParseSecretToken() error = %v", err)
}
return token
}
func hostileNotification() NotificationData {
return NotificationData{Subject: hostileSubject, Body: hostileBody, LinkPath: "/candidate/invitations"}
}
// renderAll renders one message of every kind with the fixed test data.
func renderAll(t *testing.T, renderer *Renderer) map[Kind]RenderedMail {
t.Helper()
token := testToken(t)
verification, err := renderer.RenderVerification(VerificationData{Token: token, TokenLifetime: 24})
if err != nil {
t.Fatalf("RenderVerification() error = %v", err)
}
reset, err := renderer.RenderPasswordReset(PasswordResetData{Token: token, TokenLifetime: 1})
if err != nil {
t.Fatalf("RenderPasswordReset() error = %v", err)
}
notification, err := renderer.RenderNotification(hostileNotification())
if err != nil {
t.Fatalf("RenderNotification() error = %v", err)
}
return map[Kind]RenderedMail{KindVerification: verification, KindPasswordReset: reset, KindNotification: notification}
}
func TestRenderingsMatchGoldenFiles(t *testing.T) {
for kind, mail := range renderAll(t, newTestRenderer(t)) {
t.Run(string(kind), func(t *testing.T) {
base := filepath.Join("testdata", string(mail.TemplateVersion()))
assertGolden(t, base+".txt.golden", "Subject: "+mail.Subject()+"\n\n"+mail.Text())
assertGolden(t, base+".html.golden", mail.HTML())
})
}
}
func assertGolden(t *testing.T, path, got string) {
t.Helper()
if *updateGolden {
if err := os.WriteFile(path, []byte(got), 0o600); err != nil {
t.Fatalf("write %s: %v", path, err)
}
return
}
want, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read %s: %v (run with -update to create it)", path, err)
}
if got != string(want) {
t.Fatalf("%s differs from the rendering; review the copy change and run with -update\n--- got ---\n%s", path, got)
}
}
func TestRenderingCarriesKindAndVersion(t *testing.T) {
want := map[Kind]TemplateVersion{
KindVerification: "verification.v1",
KindPasswordReset: "password_reset.v1",
KindNotification: "notification.v1",
}
for kind, mail := range renderAll(t, newTestRenderer(t)) {
if mail.Kind() != kind || mail.TemplateVersion() != want[kind] {
t.Fatalf("rendering for %s has kind %s and version %s", kind, mail.Kind(), mail.TemplateVersion())
}
if !strings.Contains(mail.HTML(), `<html lang="ru">`) {
t.Fatalf("%s HTML does not declare lang=ru", kind)
}
}
}
func TestTokenLinksUseOriginPathAndFragment(t *testing.T) {
renderer := newTestRenderer(t)
mails := renderAll(t, renderer)
for kind, path := range map[Kind]string{KindVerification: "/verify-email", KindPasswordReset: "/reset-password"} {
mail := mails[kind]
want := testOrigin + path + "#token=" + syntheticToken
link, err := url.Parse(want)
if err != nil {
t.Fatalf("url.Parse() error = %v", err)
}
if link.RawQuery != "" || link.Fragment != "token="+syntheticToken {
t.Fatalf("%s link must carry the token only in the fragment", kind)
}
if !strings.Contains(mail.Text(), "\n"+want+"\n") {
t.Fatalf("%s text part does not contain the link on its own line", kind)
}
if strings.Count(mail.HTML(), `href="`+want+`"`) != 2 || !strings.Contains(mail.HTML(), ">"+want+"</a>") {
t.Fatalf("%s HTML part does not contain the link as a button, a visible link, and text", kind)
}
if strings.Contains(mail.Text()+mail.HTML(), "?token=") {
t.Fatalf("%s puts the token in a query", kind)
}
}
}
func TestLoopbackOriginKeepsPort(t *testing.T) {
renderer, err := NewRenderer("http://localhost:5173/")
if err != nil {
t.Fatalf("NewRenderer() error = %v", err)
}
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 24})
if err != nil {
t.Fatalf("RenderVerification() error = %v", err)
}
if !strings.Contains(mail.Text(), "http://localhost:5173/verify-email#token="+syntheticToken+"\n") {
t.Fatal("verification link does not use the loopback origin")
}
}
func TestNotificationEscapesCallerText(t *testing.T) {
mail, err := newTestRenderer(t).RenderNotification(hostileNotification())
if err != nil {
t.Fatalf("RenderNotification() error = %v", err)
}
if strings.ContainsAny(mail.Subject(), "\r\n") || !strings.HasSuffix(mail.Subject(), "'кавычки' X-Injected: yes") {
t.Fatalf("subject is not one sanitized line: %q", mail.Subject())
}
html := mail.HTML()
for _, raw := range []string{"<script>", "<b>", "<img", `"Тест`, "'кавычки'", "& Ко", "\u202e", "\u0007"} {
if strings.Contains(html, raw) {
t.Fatalf("HTML part contains unescaped %q", raw)
}
}
for _, escaped := range []string{"&lt;script&gt;", "&lt;b&gt;пригласила&lt;/b&gt;", "&#34;Тест &amp; Ко&#34;", "&#39;кавычки&#39;", "Вторая строка", "<br>", "ёжик 🚀"} {
if !strings.Contains(html, escaped) {
t.Fatalf("HTML part does not contain %q", escaped)
}
}
text := mail.Text()
if strings.ContainsAny(text, "\r\u202e\u0007") {
t.Fatalf("text part contains a control or bidi character: %q", text)
}
if !strings.Contains(text, "<b>пригласила</b> вас.\nВторая строкареверс\n\nВторой абзац") {
t.Fatalf("text part does not keep the plain caller text and paragraphs: %q", text)
}
if !strings.Contains(text, "\n"+testOrigin+"/candidate/invitations\n") {
t.Fatal("text part does not contain the cabinet link")
}
}
func TestRejectsUnsafeOrigins(t *testing.T) {
for _, origin := range []string{
"",
"lincodex.example",
"//lincodex.example",
"http://lincodex.example",
"ftp://lincodex.example",
"javascript:alert(1)",
"https://user:secret@lincodex.example",
"https://lincodex.example/app",
"https://lincodex.example?next=x",
"https://lincodex.example#",
"https://lincodex.example:0",
"https://lincodex.example:",
"https://bad host.example",
} {
if _, err := NewRenderer(origin); err == nil {
t.Fatalf("NewRenderer(%q) accepted an unsafe origin", origin)
} else if origin != "" && strings.Contains(err.Error(), origin) {
t.Fatalf("NewRenderer(%q) error echoes the value: %v", origin, err)
}
}
for _, origin := range []string{"https://lincodex.example:8443", "http://127.0.0.1:8080", "http://[::1]:8080", "HTTPS://Lincodex.Example"} {
if _, err := NewRenderer(origin); err != nil {
t.Fatalf("NewRenderer(%q) error = %v", origin, err)
}
}
}
func TestNotificationRejectsLinksOutsideTheApp(t *testing.T) {
renderer := newTestRenderer(t)
for _, linkPath := range []string{
"",
"candidate/invitations",
"//evil.example/candidate",
"https://evil.example/candidate",
"javascript:alert(1)",
"/candidate/../admin",
"/candidate/./invitations",
"/candidate/",
"/",
"/candidate?next=https://evil.example",
"/candidate#token=x",
`/\evil.example`,
"/candidate/%2e%2e",
"/candidate invitations",
"/" + strings.Repeat("a", maxLinkPathLength),
} {
data := hostileNotification()
data.LinkPath = linkPath
_, err := renderer.RenderNotification(data)
if !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderNotification(LinkPath %q) error = %v, want ErrInvalidTemplateData", linkPath, err)
}
}
data := hostileNotification()
data.LinkPath = "/employer/candidates/0190a5e4-7c1b-7d2e-9f00-1a2b3c4d5e6f"
if _, err := renderer.RenderNotification(data); err != nil {
t.Fatalf("RenderNotification() rejected a cabinet path: %v", err)
}
}
func TestRejectsInvalidData(t *testing.T) {
renderer := newTestRenderer(t)
token := testToken(t)
tokenCases := map[string]VerificationData{
"missing token": {TokenLifetime: 24},
"zero lifetime": {Token: token},
"negative": {Token: token, TokenLifetime: -1},
"lifetime too big": {Token: token, TokenLifetime: maxTokenLifetime + 1},
}
for name, data := range tokenCases {
if _, err := renderer.RenderVerification(data); !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderVerification(%s) error = %v", name, err)
}
reset := PasswordResetData(data)
if _, err := renderer.RenderPasswordReset(reset); !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderPasswordReset(%s) error = %v", name, err)
}
}
notificationCases := map[string]func(*NotificationData){
"blank subject": func(data *NotificationData) { data.Subject = " \r\n\t" },
"long subject": func(data *NotificationData) { data.Subject = strings.Repeat("я", maxNotificationSubjectRunes+1) },
"invalid UTF-8": func(data *NotificationData) { data.Body = "abc\xff" },
"only control body": func(data *NotificationData) { data.Body = "\u202e\u0007\r\n \n" },
"long body": func(data *NotificationData) { data.Body = strings.Repeat("я", maxNotificationBodyRunes+1) },
"invalid UTF-8 title": func(data *NotificationData) { data.Subject = "\xc3\x28" },
}
for name, mutate := range notificationCases {
data := hostileNotification()
mutate(&data)
if _, err := renderer.RenderNotification(data); !errors.Is(err, ErrInvalidTemplateData) {
t.Fatalf("RenderNotification(%s) error = %v", name, err)
}
}
}
func TestLifetimeCopyUsesRussianPlural(t *testing.T) {
renderer := newTestRenderer(t)
for hours, want := range map[domain.Hours]string{1: "1 час.", 3: "3 часа.", 11: "11 часов.", 21: "21 час.", 24: "24 часа.", 48: "48 часов.", 168: "168 часов."} {
mail, err := renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: hours})
if err != nil {
t.Fatalf("RenderVerification(%d) error = %v", hours, err)
}
if !strings.Contains(mail.Text(), "Ссылка действует "+want) {
t.Fatalf("lifetime %d is not phrased as %q", hours, want)
}
}
}
func TestContentHashPinsTheBody(t *testing.T) {
renderer := newTestRenderer(t)
first := renderAll(t, renderer)
second := renderAll(t, renderer)
seen := make(map[ContentHash]Kind)
for kind, mail := range first {
if mail.ContentHash() != second[kind].ContentHash() {
t.Fatalf("%s content hash differs for the same version and data", kind)
}
if mail.ContentHash() != contentHash(string(mail.TemplateVersion()), mail.Subject(), mail.Text(), mail.HTML()) {
t.Fatalf("%s content hash does not cover the version, subject, and parts", kind)
}
seen[mail.ContentHash()] = kind
}
if len(seen) != len(first) {
t.Fatal("different kinds share a content hash")
}
otherToken, err := domain.NewSecretToken()
if err != nil {
t.Fatalf("NewSecretToken() error = %v", err)
}
changed := []struct {
name string
render func() (RenderedMail, error)
base Kind
}{
{"token", func() (RenderedMail, error) {
return renderer.RenderVerification(VerificationData{Token: otherToken, TokenLifetime: 24})
}, KindVerification},
{"lifetime", func() (RenderedMail, error) {
return renderer.RenderVerification(VerificationData{Token: testToken(t), TokenLifetime: 25})
}, KindVerification},
{"body", func() (RenderedMail, error) {
data := hostileNotification()
data.Body += "!"
return renderer.RenderNotification(data)
}, KindNotification},
{"link", func() (RenderedMail, error) {
data := hostileNotification()
data.LinkPath = "/candidate/results"
return renderer.RenderNotification(data)
}, KindNotification},
}
for _, change := range changed {
mail, err := change.render()
if err != nil {
t.Fatalf("render with changed %s: %v", change.name, err)
}
if mail.ContentHash() == first[change.base].ContentHash() {
t.Fatalf("content hash did not change with the %s", change.name)
}
}
base := contentHash("verification.v1", "subject", "text", "html")
for name, other := range map[string]ContentHash{
"version": contentHash("verification.v2", "subject", "text", "html"),
"subject": contentHash("verification.v1", "subject!", "text", "html"),
"text": contentHash("verification.v1", "subject", "text!", "html"),
"html": contentHash("verification.v1", "subject", "text", "html!"),
"shifted border": contentHash("verification.v1", "subjec", "ttext", "html"),
} {
if other == base {
t.Fatalf("content hash ignores a change of the %s", name)
}
}
}
// TestRenderingNeverReachesLogs plays the render harness: it prints every
// input, rendering, and error through fmt and slog, then checks that no
// token, link, subject, or body text appears.
func TestRenderingNeverReachesLogs(t *testing.T) {
renderer := newTestRenderer(t)
token := testToken(t)
mails := renderAll(t, renderer)
var output bytes.Buffer
loggers := []*slog.Logger{
slog.New(slog.NewTextHandler(&output, nil)),
slog.New(slog.NewJSONHandler(&output, nil)),
}
verification := VerificationData{Token: token, TokenLifetime: 24}
notification := hostileNotification()
// RenderedMail hides its content even in an unexported field.
// NotificationData redacts itself only where fmt can call its methods.
type envelope struct {
mail RenderedMail
Notification NotificationData
}
for _, mail := range mails {
for _, logger := range loggers {
logger.Info("rendered", "mail", mail, "verification", verification, "notification", notification)
}
nested := envelope{mail: mail, Notification: notification}
fmt.Fprintf(&output, "%v %+v %#v %s %v %+v %v %+v\n", mail, mail, mail, mail, verification, verification, nested, &nested)
}
badLink := hostileNotification()
badLink.LinkPath = "javascript:alert('" + syntheticToken + "')"
_, linkErr := renderer.RenderNotification(badLink)
badSubject := hostileNotification()
badSubject.Subject = strings.Repeat(syntheticToken, 4)
_, subjectErr := renderer.RenderNotification(badSubject)
_, originErr := NewRenderer("https://user:" + syntheticToken + "@lincodex.example")
for _, err := range []error{linkErr, subjectErr, originErr} {
if err == nil {
t.Fatal("invalid input was rendered")
}
fmt.Fprintln(&output, err)
for _, logger := range loggers {
logger.Error("render failed", "error", err)
}
}
logs := output.String()
for kind, mail := range mails {
if !strings.Contains(logs, mail.ContentHash().String()) || !strings.Contains(logs, string(kind)) {
t.Fatalf("logs do not identify the %s rendering by kind and content hash", kind)
}
assertAbsent(t, logs, mail.Subject(), mail.Text(), mail.HTML())
}
assertAbsent(t, logs, syntheticToken, "token=", "Подтвердите", "Сброс пароля", "Приглашение", "пригласила", "Компания", "<html")
}
func assertAbsent(t *testing.T, output string, secrets ...string) {
t.Helper()
for _, secret := range secrets {
if strings.Contains(output, secret) {
t.Fatalf("render harness output exposes %q:\n%s", secret, output)
}
}
}
func TestToOutgoingMailIsValidForThePort(t *testing.T) {
recipient, err := domain.NewEmailAddress("candidate@lincodex.example")
if err != nil {
t.Fatalf("NewEmailAddress() error = %v", err)
}
for kind, mail := range renderAll(t, newTestRenderer(t)) {
outgoing := mail.ToOutgoingMail(recipient, "email_verification/0190a5e4-7c1b-7d2e-9f00-1a2b3c4d5e6f")
if err := outgoing.Validate(); err != nil {
t.Fatalf("%s rendering is not a valid OutgoingMail: %v", kind, err)
}
if outgoing.Subject != mail.Subject() || outgoing.TextBody != mail.Text() || outgoing.HTMLBody != mail.HTML() {
t.Fatalf("%s OutgoingMail does not carry the rendering unchanged", kind)
}
}
if !(RenderedMail{}).IsZero() || (RenderedMail{}).Text() != "" {
t.Fatal("zero RenderedMail is not empty")
}
}
func TestTemplateSetIsComplete(t *testing.T) {
part := func(body string) *fstest.MapFile { return &fstest.MapFile{Data: []byte(body)} }
complete := func() fstest.MapFS {
return fstest.MapFS{
"templates/verification.v1.subject.tmpl": part("s"),
"templates/verification.v1.txt.tmpl": part("t"),
"templates/verification.v1.html.tmpl": part("<p>h</p>"),
}
}
if _, err := parseTemplates(complete()); err != nil {
t.Fatalf("parseTemplates(complete) error = %v", err)
}
cases := map[string]func(fstest.MapFS){
"missing part": func(files fstest.MapFS) { delete(files, "templates/verification.v1.html.tmpl") },
"stray file": func(files fstest.MapFS) { files["templates/verification.html"] = part("x") },
"bad version": func(files fstest.MapFS) { files["templates/verification.v0.txt.tmpl"] = part("x") },
"bad text": func(files fstest.MapFS) { files["templates/verification.v1.txt.tmpl"] = part("{{.Link") },
"bad html": func(files fstest.MapFS) {
files["templates/verification.v1.html.tmpl"] = part(`<a href="{{.Link}}`)
},
}
for name, mutate := range cases {
files := complete()
mutate(files)
if _, err := parseTemplates(files); err == nil {
t.Fatalf("parseTemplates(%s) accepted a broken template set", name)
}
}
}
@@ -0,0 +1,22 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>{{.Subject}}</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">{{.Subject}}</h1>
{{range .View.Paragraphs}}<p style="margin:0 0 16px;">{{range $index, $line := .}}{{if $index}}<br>{{end}}{{$line}}{{end}}</p>
{{end}}<p style="margin:8px 0 24px;"><a href="{{.View.Link}}" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Открыть личный кабинет</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0;font-size:14px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;">{{.View.Link}}</a></p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1,10 @@
{{.Subject}}
{{.View.TextBody}}
Подробнее в личном кабинете:
{{.View.Link}}
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>{{.Subject}}</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Сброс пароля</h1>
<p style="margin:0 0 24px;">Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку.</p>
<p style="margin:0 0 24px;"><a href="{{.View.Link}}" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Задать новый пароль</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;">{{.View.Link}}</a></p>
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
<p style="margin:0;">Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1 @@
Сброс пароля в Lincodex
@@ -0,0 +1,12 @@
Сброс пароля
Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку:
{{.View.Link}}
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>{{.Subject}}</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 24px;">Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.</p>
<p style="margin:0 0 24px;"><a href="{{.View.Link}}" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;">{{.View.Link}}</a></p>
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
<p style="margin:0;">Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1 @@
Подтвердите почту в Lincodex
@@ -0,0 +1,12 @@
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице:
{{.View.Link}}
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,23 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>Приглашение &lt;script&gt;alert(&#34;x&#34;)&lt;/script&gt; &amp; &#39;кавычки&#39; X-Injected: yes</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Приглашение &lt;script&gt;alert(&#34;x&#34;)&lt;/script&gt; &amp; &#39;кавычки&#39; X-Injected: yes</h1>
<p style="margin:0 0 16px;">Компания &#34;Тест &amp; Ко&#34; &lt;b&gt;пригласила&lt;/b&gt; вас.<br>Вторая строкареверс</p>
<p style="margin:0 0 16px;">Второй абзац: ёжик 🚀 &lt;img src=x onerror=alert(1)&gt;</p>
<p style="margin:8px 0 24px;"><a href="https://lincodex.example/candidate/invitations" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Открыть личный кабинет</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0;font-size:14px;word-break:break-all;"><a href="https://lincodex.example/candidate/invitations" style="color:#402fff;">https://lincodex.example/candidate/invitations</a></p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1,15 @@
Subject: Приглашение <script>alert("x")</script> & 'кавычки' X-Injected: yes
Приглашение <script>alert("x")</script> & 'кавычки' X-Injected: yes
Компания "Тест & Ко" <b>пригласила</b> вас.
Вторая строкареверс
Второй абзац: ёжик 🚀 <img src=x onerror=alert(1)>
Подробнее в личном кабинете:
https://lincodex.example/candidate/invitations
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>Сброс пароля в Lincodex</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Сброс пароля</h1>
<p style="margin:0 0 24px;">Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку.</p>
<p style="margin:0 0 24px;"><a href="https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Задать новый пароль</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;">https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
<p style="margin:0 0 16px;">Ссылка действует 1 час.</p>
<p style="margin:0;">Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1,14 @@
Subject: Сброс пароля в Lincodex
Сброс пароля
Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку:
https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
Ссылка действует 1 час.
Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,24 @@
<!DOCTYPE html>
<html lang="ru">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>Подтвердите почту в Lincodex</title>
</head>
<body style="margin:0;padding:0;background-color:#ededed;color:#1b1c21;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:1.5;">
<div style="max-width:560px;margin:0 auto;padding:24px 12px;">
<div style="background-color:#ffffff;border-top:4px solid #402fff;border-radius:8px;padding:28px 24px;">
<p style="margin:0 0 24px;font-size:18px;font-weight:bold;letter-spacing:0.02em;color:#1b1c21;">Lincodex</p>
<h1 style="margin:0 0 16px;font-size:22px;line-height:1.3;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 24px;">Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.</p>
<p style="margin:0 0 24px;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;padding:12px 24px;border-radius:6px;background-color:#402fff;color:#ffffff;font-weight:bold;text-decoration:none;">Подтвердить почту</a></p>
<p style="margin:0 0 8px;font-size:14px;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;word-break:break-all;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;">https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
<p style="margin:0 0 16px;">Ссылка действует 24 часа.</p>
<p style="margin:0;">Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.</p>
</div>
<p style="margin:16px 12px 0;font-size:13px;color:#2d2e37;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</div>
</body>
</html>
@@ -0,0 +1,14 @@
Subject: Подтвердите почту в Lincodex
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице:
https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv
Ссылка действует 24 часа.
Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.
--
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
Whitespace-only changes.
+3 -2
View File
@@ -175,6 +175,7 @@ backend/
port/inbound/ readiness input boundary
usecase/identity/ password validation before hashing (Credentials)
usecase/policy/ publication of policy versions and the demo policy seed
usecase/notification/mailtemplate/ pure rendering of versioned service emails for identity and delivery usecases (not wired yet)
port/outbound/ readiness, cache, object storage, transaction, outbox, identity, policy, password hashing, and mail boundaries
adapter/primary/http/
api/ generated ogen handler
@@ -201,9 +202,9 @@ Domain types live directly in `backend/internal/domain/`: `user.go`, `candidate.
Product domain types and usecase modules, the Resend, SMTP, and FSP adapters, and the worker are reserved areas; their business behavior is not implemented. Keep `main.go` limited to starting bootstrap and handling process errors. The public generated transport uses ogen v1.24.0 and the contracts declare OpenAPI 3.2.0. Verify only the feature subset used by the repository, not every specification feature.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, and the `MailSender` port with the `disabled` transport. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
This is a compact map, not a claim that every planned product package exists. Current Go code includes health usecases and adapters, generated API clients, bootstrap with startup migrations, a PostgreSQL health query, the transactional outbox writer, identity repositories without the usecases that will use them, the versioned policy store with its publisher and the demo policy seed at startup, the `PasswordHasher` port with the Argon2id adapter and the password check that registration will call, a Redis cache adapter, a SeaweedFS S3 adapter, the `MailSender` port with the `disabled` transport, and the mail template renderer that no flow calls yet. Account behavior (registration, verification, login, sessions), resumes, assessments, invitations, worker jobs, file workflows, mail delivery, the Resend and SMTP transports, and FSP adapters remain planned. Do not create empty module directories before a real use case exists.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `emailtemplate`, `mailer`, and test helpers. Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`backend/pkg/` is reserved for small technical packages with a justified shared boundary, not product usecases or domain types. Candidate future packages are `mailer` and test helpers. Mail templates live in `internal/usecase/notification/mailtemplate/` instead: they hold product copy and use domain types such as `SecretToken`. It is a pure rendering package without I/O or logging; the identity usecases (verification and password reset) and the planned delivery usecase are expected to call it, and that wiring is planned. Templates, versions, and link format are described in [DEPLOY.md](DEPLOY.md#mail-templates). Keep the S3 client in the SeaweedFS adapter. Keep service-specific behavior private under `internal/`.
`api/` contains contract sources and tools; it is not a runtime hop in the request path. `api/core/` and `api/ml/` each own OpenAPI source, route and component fragments, and a committed bundle. Root `scripts/` merges schema fragments. Generated Go output belongs to its consumer: the public handler under `backend/internal/adapter/primary/http/api/`, the internal ML client under `backend/internal/adapter/secondary/ml/api/`, and sqlc output under `backend/internal/adapter/secondary/postgres/sqlc/`. The first is transport code mounted in chi; the latter two are outbound adapters. `backend/cmd/app/main.go` remains a small process entry point; bootstrap owns dependency wiring and graceful shutdown.
+11
View File
@@ -88,6 +88,17 @@ Current state: this build contains only the `disabled` transport. With `resend`
Compose passes these variables from the root `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM`, and `APP_PUBLIC_URL` are required, so Compose refuses to render the project without them; copy the mail block from `.env.example` into an existing `.env`. Keep `RESEND_API_KEY` and `SMTP_PASSWORD` in the server environment or a deployment secret store and never commit them. Configuration errors name the setting but never print its value, and the startup log names only the selected provider.
### Mail templates
Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate/` with templates for email verification, password reset, and a short notification. Nothing calls it yet: registration, verification, password reset, and mail delivery are planned, so the current build renders and sends no message.
- Templates are embedded in the binary with `go:embed` and parsed once when the renderer is created; a broken template fails its creation. Each version has three files: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl`, and `<kind>.v<N>.html.tmpl`. The HTML part uses `html/template`, the plain-text part and the subject use `text/template`. Every transport sends the same rendering; templates hold no provider settings, keys, or sender address.
- Links start with `APP_PUBLIC_URL`, which the renderer checks again with the same rules. Verification: `<APP_PUBLIC_URL>/verify-email#token=<token>`; password reset: `<APP_PUBLIC_URL>/reset-password#token=<token>` (the page and the API for the reset are planned). The token is only in the URL fragment, never in the query. A notification link is a path inside the application, such as `/candidate/invitations`; an absolute URL, `//host`, a scheme such as `javascript:`, a query, a fragment, a percent sign, and `.` or `..` segments are rejected.
- Messages contain no name, email address, or other contact. Caller text in a notification is escaped in the HTML part; control and bidirectional characters are removed from the plain-text part, and the subject becomes one line, so CR and LF cannot add header lines. The notification subject is limited to 100 characters and the body to 2000.
- Copy is in Russian. A released version is immutable: changing copy adds the next version, for example `verification.v2`, and switches the current version in code. Versions share no files, so one version cannot change the body of another. Each rendering carries its version and a SHA-256 content hash over the version, subject, and both parts; the same version and data always give the same body. The planned delivery layer is expected to store the rendered body with the hash and resend the stored body on retry instead of rendering again; keep the files of an old version while stored deliveries name it.
- The renderer does not log. A rendering and notification data print only the kind, version, and content hash in `fmt` and `slog` output; tokens, links, and bodies are never printed.
- Golden files in `testdata/` make every copy change visible in review. After an intended change, run `go test ./internal/usecase/notification/mailtemplate -update` from `backend/` and review the diff.
## Separate ML Compose project
ML uses a separate Compose file and project; it does not require or start Redis or SeaweedFS in the current scaffold. Its default host bind is 127.0.0.1:8000. Set ML_BIND_ADDRESS only after choosing a private address and preparing firewall rules. Prometheus does not scrape remote ML while ML_METRICS_TARGET is empty.
+3 -2
View File
@@ -175,6 +175,7 @@ backend/
port/inbound/ inbound граница readiness
usecase/identity/ проверка пароля до хеширования (Credentials)
usecase/policy/ публикация версий политики и начальное заполнение демонстрационной политики
usecase/notification/mailtemplate/ чистый рендеринг версионированных служебных писем для usecase identity и доставки (пока не подключен)
port/outbound/ границы readiness, кеша, объектного хранилища, транзакции, outbox, identity, политики, хеширования паролей и почты
adapter/primary/http/
api/ generated ogen handler
@@ -201,9 +202,9 @@ backend/
`domain/`, продуктовые `usecase/`, адаптеры Resend, SMTP и FSP, а также worker зарезервированы; их бизнес-логика не реализована. `main.go` только запускает bootstrap и обрабатывает ошибку процесса. Для публичного generated transport выбран ogen v1.24.0, контракты используют OpenAPI 3.2.0. Проверяется только применяемое подмножество, не вся спецификация.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS и порт `MailSender` с транспортом `disabled`. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
Это компактная карта, а не обещание, что все запланированные продуктовые пакеты уже существуют. Сейчас Go-код включает health usecase/adapters, generated API clients, bootstrap с миграциями при старте, PostgreSQL health query, транзакционную запись outbox, репозитории identity без использующих их usecase, версионированное хранилище политики с публикацией и начальным заполнением демонстрационной политики при старте, порт `PasswordHasher` с адаптером Argon2id и проверку пароля, которую вызовет регистрация, Redis cache adapter, S3-адаптер SeaweedFS, порт `MailSender` с транспортом `disabled` и renderer шаблонов писем, который пока не вызывает ни один сценарий. Поведение аккаунтов (регистрация, подтверждение, вход, сессии), резюме, оценивание, приглашения, worker jobs, файловые сценарии, отправка почты, транспорты Resend и SMTP и FSP adapters остаются планом. Не создавайте пустые каталоги будущих модулей.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `emailtemplate`, `mailer` и тестовые helpers. S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`backend/pkg/` зарезервирован для небольших технических пакетов с оправданной общей границей, а не для продуктовых usecase или domain types. Возможные пакеты на будущее: `mailer` и тестовые helpers. Шаблоны писем вместо этого находятся в `internal/usecase/notification/mailtemplate/`: они содержат продуктовые тексты и используют domain types, например `SecretToken`. Это чистый пакет рендеринга без I/O и логирования; его должны вызывать usecase identity (подтверждение почты и сброс пароля) и запланированный usecase доставки, это подключение запланировано. Шаблоны, версии и формат ссылок описаны в [DEPLOY.md](DEPLOY.md#шаблоны-писем). S3-клиент остается в адаптере SeaweedFS. Поведение, специфичное для этого сервиса, остается внутри `internal/`.
`api/` хранит контракты и инструменты и не является runtime hop в пути запроса. `api/core/` и `api/ml/` владеют исходным OpenAPI, fragments маршрутов и компонентов, а также коммитируемыми bundles. Схемы объединяет корневой `scripts/`. Сгенерированный Go-код лежит у потребителя: публичный handler - в `backend/internal/adapter/primary/http/api/`, внутренний ML client - в `backend/internal/adapter/secondary/ml/api/`, sqlc output - в `backend/internal/adapter/secondary/postgres/sqlc/`. Первый пакет монтируется в chi; два последних реализуют outbound adapters. `backend/cmd/app/main.go` остается точкой входа, а bootstrap отвечает за wiring и graceful shutdown.
+11
View File
@@ -90,6 +90,17 @@ Backend отправляет почту через порт `MailSender`. `EMAIL
Compose передает эти переменные из корневого `.env`. `EMAIL_PROVIDER`, `EMAIL_FROM` и `APP_PUBLIC_URL` обязательны, поэтому без них Compose не соберет конфигурацию проекта; перенесите блок почты из `.env.example` в существующий `.env`. Храните `RESEND_API_KEY` и `SMTP_PASSWORD` в окружении сервера или в хранилище секретов деплоя и никогда не коммитьте их. Ошибки конфигурации называют настройку, но не печатают ее значение, а лог запуска называет только выбранного провайдера.
### Шаблоны писем
Реализовано: renderer в `backend/internal/usecase/notification/mailtemplate/` с шаблонами подтверждения почты, сброса пароля и короткого уведомления. Пока его никто не вызывает: регистрация, подтверждение, сброс пароля и доставка почты запланированы, поэтому текущая сборка не формирует и не отправляет писем.
- Шаблоны встроены в бинарник через `go:embed` и разбираются один раз при создании renderer; сломанный шаблон останавливает создание. У каждой версии три файла: `<kind>.v<N>.subject.tmpl`, `<kind>.v<N>.txt.tmpl` и `<kind>.v<N>.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя.
- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `<APP_PUBLIC_URL>/verify-email#token=<token>`; сброс пароля: `<APP_PUBLIC_URL>/reset-password#token=<token>` (страница и API сброса запланированы). Токен находится только во fragment URL и никогда в query. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
- В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000.
- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Запланированный слой доставки должен сохранять сформированное тело вместе с hash и при повторе отправлять сохраненное тело, а не формировать его заново; храните файлы старой версии, пока на нее ссылаются сохраненные доставки.
- Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются.
- Golden файлы в `testdata/` делают каждое изменение текста видимым на ревью. После намеренного изменения выполните `go test ./internal/usecase/notification/mailtemplate -update` из `backend/` и проверьте diff.
## Отдельный ML Compose
ML имеет отдельный Compose-файл и проект; Redis и SeaweedFS ему пока не требуются и здесь не запускаются. По умолчанию он слушает на 127.0.0.1:8000. Настройте ML_BIND_ADDRESS только если выбранный приватный адрес и firewall уже подготовлены. Метрики удаленного ML target не собираются, пока ML_METRICS_TARGET пуст.