From 65d66b6f7dffc963587684b71d96d423dcf78c26 Mon Sep 17 00:00:00 2001 From: shira Date: Tue, 6 Oct 2026 02:09:10 +0300 Subject: [PATCH] feat(mail): add versioned service email templates --- .../internal/usecase/notification/.gitkeep | 0 .../usecase/notification/mailtemplate/data.go | 232 +++++++++ .../usecase/notification/mailtemplate/link.go | 130 +++++ .../notification/mailtemplate/rendered.go | 116 +++++ .../notification/mailtemplate/renderer.go | 274 ++++++++++ .../mailtemplate/renderer_test.go | 480 ++++++++++++++++++ .../templates/notification.v1.html.tmpl | 22 + .../templates/notification.v1.subject.tmpl | 1 + .../templates/notification.v1.txt.tmpl | 10 + .../templates/password_reset.v1.html.tmpl | 24 + .../templates/password_reset.v1.subject.tmpl | 1 + .../templates/password_reset.v1.txt.tmpl | 12 + .../templates/verification.v1.html.tmpl | 24 + .../templates/verification.v1.subject.tmpl | 1 + .../templates/verification.v1.txt.tmpl | 12 + .../testdata/notification.v1.html.golden | 23 + .../testdata/notification.v1.txt.golden | 15 + .../testdata/password_reset.v1.html.golden | 24 + .../testdata/password_reset.v1.txt.golden | 14 + .../testdata/verification.v1.html.golden | 24 + .../testdata/verification.v1.txt.golden | 14 + backend/pkg/emailtemplate/templates/.gitkeep | 0 docs/en/ARCHITECTURE.md | 5 +- docs/en/DEPLOY.md | 11 + docs/ru/ARCHITECTURE.md | 5 +- docs/ru/DEPLOY.md | 11 + 26 files changed, 1481 insertions(+), 4 deletions(-) delete mode 100644 backend/internal/usecase/notification/.gitkeep create mode 100644 backend/internal/usecase/notification/mailtemplate/data.go create mode 100644 backend/internal/usecase/notification/mailtemplate/link.go create mode 100644 backend/internal/usecase/notification/mailtemplate/rendered.go create mode 100644 backend/internal/usecase/notification/mailtemplate/renderer.go create mode 100644 backend/internal/usecase/notification/mailtemplate/renderer_test.go create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/notification.v1.html.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/notification.v1.subject.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/notification.v1.txt.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/password_reset.v1.html.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/password_reset.v1.subject.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/password_reset.v1.txt.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v1.html.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v1.subject.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/templates/verification.v1.txt.tmpl create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/notification.v1.html.golden create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/notification.v1.txt.golden create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.html.golden create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.txt.golden create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden create mode 100644 backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden delete mode 100644 backend/pkg/emailtemplate/templates/.gitkeep diff --git a/backend/internal/usecase/notification/.gitkeep b/backend/internal/usecase/notification/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/backend/internal/usecase/notification/mailtemplate/data.go b/backend/internal/usecase/notification/mailtemplate/data.go new file mode 100644 index 0000000..2dd42fe --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/data.go @@ -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) +} diff --git a/backend/internal/usecase/notification/mailtemplate/link.go b/backend/internal/usecase/notification/mailtemplate/link.go new file mode 100644 index 0000000..fd9247c --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/link.go @@ -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 #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 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" +} diff --git a/backend/internal/usecase/notification/mailtemplate/rendered.go b/backend/internal/usecase/notification/mailtemplate/rendered.go new file mode 100644 index 0000000..44b88c5 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/rendered.go @@ -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()), + ) +} diff --git a/backend/internal/usecase/notification/mailtemplate/renderer.go b/backend/internal/usecase/notification/mailtemplate/renderer.go new file mode 100644 index 0000000..5cbf2b3 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/renderer.go @@ -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 .v..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, ".v". +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 +// /verify-email#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 +// /reset-password#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 (":,"), +// 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 + } +} diff --git a/backend/internal/usecase/notification/mailtemplate/renderer_test.go b/backend/internal/usecase/notification/mailtemplate/renderer_test.go new file mode 100644 index 0000000..81944c6 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/renderer_test.go @@ -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 = "Приглашение & 'кавычки'\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 = "Компания \"Тест & Ко\" пригласила вас.\r\nВторая строка\u202eреверс\u0007\r\n\n\n\nВторой абзац: ёжик 🚀 " +) + +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(), ``) { + 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+"") { + 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{" & 'кавычки' X-Injected: yes + +Приглашение & 'кавычки' X-Injected: yes + +Компания "Тест & Ко" пригласила вас. +Вторая строкареверс + +Второй абзац: ёжик 🚀 + +Подробнее в личном кабинете: + +https://lincodex.example/candidate/invitations + +-- +Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.html.golden b/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.html.golden new file mode 100644 index 0000000..05431ad --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.html.golden @@ -0,0 +1,24 @@ + + + + + + +Сброс пароля в Lincodex + + +
+
+

Lincodex

+

Сброс пароля

+

Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку.

+

Задать новый пароль

+

Если кнопка не работает, скопируйте ссылку в адресную строку браузера:

+

https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv

+

Ссылка действует 1 час.

+

Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.

+
+

Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.

+
+ + diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.txt.golden new file mode 100644 index 0000000..e59fa5a --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/testdata/password_reset.v1.txt.golden @@ -0,0 +1,14 @@ +Subject: Сброс пароля в Lincodex + +Сброс пароля + +Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку: + +https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv + +Ссылка действует 1 час. + +Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним. + +-- +Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden new file mode 100644 index 0000000..bcbdb86 --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.html.golden @@ -0,0 +1,24 @@ + + + + + + +Подтвердите почту в Lincodex + + +
+
+

Lincodex

+

Подтвердите адрес почты

+

Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице.

+

Подтвердить почту

+

Если кнопка не работает, скопируйте ссылку в адресную строку браузера:

+

https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv

+

Ссылка действует 24 часа.

+

Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован.

+
+

Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.

+
+ + diff --git a/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden new file mode 100644 index 0000000..6e9827d --- /dev/null +++ b/backend/internal/usecase/notification/mailtemplate/testdata/verification.v1.txt.golden @@ -0,0 +1,14 @@ +Subject: Подтвердите почту в Lincodex + +Подтвердите адрес почты + +Чтобы завершить регистрацию в Lincodex, откройте ссылку и подтвердите адрес на открывшейся странице: + +https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv + +Ссылка действует 24 часа. + +Если вы не регистрировались в Lincodex, просто не открывайте ссылку: без подтверждения аккаунт не будет активирован. + +-- +Lincodex. Письмо отправлено автоматически, отвечать на него не нужно. diff --git a/backend/pkg/emailtemplate/templates/.gitkeep b/backend/pkg/emailtemplate/templates/.gitkeep deleted file mode 100644 index e69de29..0000000 diff --git a/docs/en/ARCHITECTURE.md b/docs/en/ARCHITECTURE.md index 5cc992b..455627b 100644 --- a/docs/en/ARCHITECTURE.md +++ b/docs/en/ARCHITECTURE.md @@ -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. diff --git a/docs/en/DEPLOY.md b/docs/en/DEPLOY.md index 692df20..6cad9b8 100644 --- a/docs/en/DEPLOY.md +++ b/docs/en/DEPLOY.md @@ -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: `.v.subject.tmpl`, `.v.txt.tmpl`, and `.v.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: `/verify-email#token=`; password reset: `/reset-password#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. diff --git a/docs/ru/ARCHITECTURE.md b/docs/ru/ARCHITECTURE.md index c5c7257..06ef4dc 100644 --- a/docs/ru/ARCHITECTURE.md +++ b/docs/ru/ARCHITECTURE.md @@ -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. diff --git a/docs/ru/DEPLOY.md b/docs/ru/DEPLOY.md index d49b36e..a82bbc4 100644 --- a/docs/ru/DEPLOY.md +++ b/docs/ru/DEPLOY.md @@ -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; сломанный шаблон останавливает создание. У каждой версии три файла: `.v.subject.tmpl`, `.v.txt.tmpl` и `.v.html.tmpl`. HTML часть использует `html/template`, текстовая часть и тема используют `text/template`. Любой транспорт отправляет один и тот же результат; в шаблонах нет настроек провайдера, ключей и адреса отправителя. +- Ссылки начинаются с `APP_PUBLIC_URL`, который renderer повторно проверяет по тем же правилам. Подтверждение: `/verify-email#token=`; сброс пароля: `/reset-password#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 пуст.