Files
lincodex/backend/internal/usecase/notification/mailtemplate/data.go
T

269 lines
9.4 KiB
Go

package mailtemplate
import (
"fmt"
"log/slog"
"strings"
"time"
"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
// Code is the six-digit code the message shows. VerificationCode redacts
// itself in fmt and slog output.
Code domain.VerificationCode
// CodeLifetime is the validity of the code stated in the copy: whole
// minutes, from 1 to 60.
CodeLifetime time.Duration
}
// 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
}
// verificationCodeView is what the verification templates receive: the link
// view plus the code and its validity in whole minutes.
type verificationCodeView struct {
tokenLinkView
Code string
CodeLifetimeMinutes 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
}
// maxCodeLifetimeMinutes bounds the code copy; the code lifetime is a fixed
// product value of 30 minutes, so a longer value in the copy would be a bug.
const maxCodeLifetimeMinutes = 60
func (renderer *Renderer) verificationCodeView(data VerificationData) (verificationCodeView, error) {
const location = "Renderer.verificationCodeView"
link, err := renderer.tokenLinkView(verifyEmailPath, data.Token, data.TokenLifetime)
if err != nil {
return verificationCodeView{}, err
}
if data.Code.IsZero() {
return verificationCodeView{}, invalidData(location, "verification code must be set")
}
minutes := data.CodeLifetime / time.Minute
if data.CodeLifetime%time.Minute != 0 || minutes < 1 || minutes > maxCodeLifetimeMinutes {
return verificationCodeView{}, invalidData(location, fmt.Sprintf("code lifetime must be whole minutes from 1 to %d", maxCodeLifetimeMinutes))
}
return verificationCodeView{tokenLinkView: link, Code: data.Code.Reveal(), CodeLifetimeMinutes: int(minutes)}, 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)
}