feat(mail): redesign the email templates in the Lincodex style

This commit is contained in:
shira committed 2026-10-10 02:21:45 +03:00
1 parent 3c4acff803
commit a0869d81a1
26 files changed
+363 -103

No files matched your search

+16 -15
View File
@@ -42,8 +42,9 @@ const (
deliveryAccount = "integration"
deliveryOtherAccount = "integration-eu"
deliveryMessageID = "4ef9a417-02e9-4d39-ad75-9611e0fcc33c"
// deliveryV2Version is a template version that exists only in this test.
deliveryV2Version = "notification.v2"
// deliveryLaterVersion is a template version that exists only in this test:
// it is later than the committed notification.v2.
deliveryLaterVersion = "notification.v3"
// renamedDeliveryConsumer replays requests as a renamed consumer would:
// the dedup markers of the real name do not apply to it.
renamedDeliveryConsumer = "notification_delivery_replay"
@@ -91,12 +92,12 @@ func (buffer *syncBuffer) String() string {
return buffer.buffer.String()
}
// v2Renderer stands for a later template version: it renders other copy
// under notification.v2 without touching the committed templates.
type v2Renderer struct{}
// laterVersionRenderer stands for a later template version: it renders other
// copy under deliveryLaterVersion without touching the committed templates.
type laterVersionRenderer struct{}
func (v2Renderer) RenderNotification(mailtemplate.NotificationData) (domain.MailContent, error) {
return domain.NewMailContent(domain.MailKindNotification, deliveryV2Version,
func (laterVersionRenderer) RenderNotification(mailtemplate.NotificationData) (domain.MailContent, error) {
return domain.NewMailContent(domain.MailKindNotification, deliveryLaterVersion,
"Новая версия письма", "Текст новой версии шаблона.\n", "<p>Текст новой версии шаблона.</p>\n")
}
@@ -181,7 +182,7 @@ func TestMailDelivery(t *testing.T) {
t.Fatal("the delivery does not name the event it came from")
case delivery.RecipientUserID() != recipient.ID || delivery.Recipient().Address() != deliveryRecipientAddress:
t.Fatal("the delivery is not addressed to the recipient account")
case delivery.Kind() != domain.MailKindNotification || content.TemplateVersion() != "notification.v1":
case delivery.Kind() != domain.MailKindNotification || content.TemplateVersion() != "notification.v2":
t.Fatalf("delivery kind %s, version %s", delivery.Kind(), content.TemplateVersion())
case delivery.ProviderAccount() != harness.account:
t.Fatal("the delivery is not pinned to the configured provider account")
@@ -203,22 +204,22 @@ func TestMailDelivery(t *testing.T) {
harness.apply(ctx, t, notification.DeliveryConsumerName, harness.handler, firstEvent)
original := harness.getDelivery(ctx, t, pool, first)
// The template moves to notification.v2. A new request gets the new
// The template moves on to a later version. A new request gets the new
// version; a replay of the first request under another consumer name
// finds the request consumed and stores nothing.
v2Handler := harness.newHandler(v2Renderer{})
laterHandler := harness.newHandler(laterVersionRenderer{})
second := harness.requestNotification(ctx, t, recipient)
harness.apply(ctx, t, notification.DeliveryConsumerName, v2Handler, harness.outboxEvent(ctx, t, second))
harness.apply(ctx, t, renamedDeliveryConsumer, v2Handler, firstEvent)
harness.apply(ctx, t, notification.DeliveryConsumerName, laterHandler, harness.outboxEvent(ctx, t, second))
harness.apply(ctx, t, renamedDeliveryConsumer, laterHandler, firstEvent)
assertRowCount(ctx, t, pool, pgx.Identifier{"deliveries"}, 2)
if got := harness.getDelivery(ctx, t, pool, second).Content(); got.TemplateVersion() != deliveryV2Version {
t.Fatalf("the new request rendered %s, want %s", got.TemplateVersion(), deliveryV2Version)
if got := harness.getDelivery(ctx, t, pool, second).Content(); got.TemplateVersion() != deliveryLaterVersion {
t.Fatalf("the new request rendered %s, want %s", got.TemplateVersion(), deliveryLaterVersion)
}
// Read through a fresh pool and store, as another instance would.
kept := harness.getDelivery(ctx, t, newPoolFor(ctx, t, env.Config.DatabaseURL), first).Content()
want := original.Content()
if kept.TemplateVersion() != "notification.v1" || kept.Subject() != want.Subject() ||
if kept.TemplateVersion() != "notification.v2" || kept.Subject() != want.Subject() ||
kept.Text() != want.Text() || kept.HTML() != want.HTML() || kept.Hash() != want.Hash() {
t.Fatal("the stored delivery changed after the template version changed")
}
@@ -42,9 +42,9 @@ 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.v2"
currentPasswordResetVersion TemplateVersion = "password_reset.v1"
currentNotificationVersion TemplateVersion = "notification.v1"
currentVerificationVersion TemplateVersion = "verification.v3"
currentPasswordResetVersion TemplateVersion = "password_reset.v2"
currentNotificationVersion TemplateVersion = "notification.v2"
)
const (
@@ -118,9 +118,9 @@ func assertGolden(t *testing.T, path, got string) {
func TestRenderingCarriesKindAndVersion(t *testing.T) {
want := map[Kind]TemplateVersion{
KindVerification: "verification.v2",
KindPasswordReset: "password_reset.v1",
KindNotification: "notification.v1",
KindVerification: "verification.v3",
KindPasswordReset: "password_reset.v2",
KindNotification: "notification.v2",
}
for kind, mail := range renderAll(t, newTestRenderer(t)) {
if mail.Kind() != kind || mail.TemplateVersion() != want[kind] {
@@ -0,0 +1,43 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Уведомление в личном кабинете Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">УВЕДОМЛЕНИЕ</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;color:#1b1c21;">{{.Subject}}</h1>
{{range .View.Paragraphs}}<p style="margin:0 0 16px;color:#1b1c21;">{{range $index, $line := .}}{{if $index}}<br>{{end}}{{$line}}{{end}}</p>
{{end}}<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="{{.View.Link}}" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Открыть личный кабинет</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0;font-size:14px;line-height:22px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;text-decoration:underline;">{{.View.Link}}</a></p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что в Lincodex пришло уведомление на ваш подтвержденный адрес.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -0,0 +1,11 @@
{{.Subject}}
{{.View.TextBody}}
Подробнее в личном кабинете:
{{.View.Link}}
--
Вы получили это письмо, потому что в Lincodex пришло уведомление на ваш подтвержденный адрес.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,45 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Откройте ссылку, чтобы задать новый пароль в Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">ВОССТАНОВЛЕНИЕ ДОСТУПА</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;color:#1b1c21;">Сброс пароля</h1>
<p style="margin:0 0 24px;color:#1b1c21;">Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку.</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="{{.View.Link}}" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Задать новый пароль</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;text-decoration:underline;">{{.View.Link}}</a></p>
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#4a4c55;">Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.</p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что для аккаунта Lincodex с этим адресом запросили сброс пароля.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -0,0 +1 @@
Сброс пароля в Lincodex
@@ -0,0 +1,13 @@
Сброс пароля
Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку:
{{.View.Link}}
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.
--
Вы получили это письмо, потому что для аккаунта Lincodex с этим адресом запросили сброс пароля.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -0,0 +1,53 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Введите код или откройте ссылку, чтобы подтвердить почту в Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">РЕГИСТРАЦИЯ</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 24px;color:#1b1c21;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">Код подтверждения</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 12px;">
<tr>
<td align="center" style="background-color:#1b1c21;border-radius:12px;padding:20px 16px;text-indent:0.3em;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:36px;line-height:44px;font-weight:700;letter-spacing:0.3em;color:#ffffff;">{{.View.Code}}</td>
</tr>
</table>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;color:#4a4c55;">Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.</p>
<p style="margin:0 0 16px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="{{.View.Link}}" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Подтвердить почту</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;word-break:break-all;"><a href="{{.View.Link}}" style="color:#402fff;text-decoration:underline;">{{.View.Link}}</a></p>
<p style="margin:0 0 16px;">Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#4a4c55;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что этот адрес указали при регистрации в Lincodex.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -0,0 +1 @@
Подтвердите почту в Lincodex
@@ -0,0 +1,19 @@
Подтвердите адрес почты
Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации:
Код подтверждения: {{.View.Code}}
Код действует {{.View.CodeLifetimeMinutes}} {{plural .View.CodeLifetimeMinutes "минуту" "минуты" "минут"}}.
Или откройте ссылку и подтвердите адрес на открывшейся странице:
{{.View.Link}}
Ссылка действует {{.View.LifetimeHours}} {{plural .View.LifetimeHours "час" "часа" "часов"}}.
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
--
Вы получили это письмо, потому что этот адрес указали при регистрации в Lincodex.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -1,23 +0,0 @@
<!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,44 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Уведомление в личном кабинете Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">УВЕДОМЛЕНИЕ</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;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;color:#1b1c21;">Компания &#34;Тест &amp; Ко&#34; &lt;b&gt;пригласила&lt;/b&gt; вас.<br>Вторая строкареверс</p>
<p style="margin:0 0 16px;color:#1b1c21;">Второй абзац: ёжик 🚀 &lt;img src=x onerror=alert(1)&gt;</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="https://lincodex.example/candidate/invitations" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Открыть личный кабинет</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0;font-size:14px;line-height:22px;word-break:break-all;"><a href="https://lincodex.example/candidate/invitations" style="color:#402fff;text-decoration:underline;">https://lincodex.example/candidate/invitations</a></p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что в Lincodex пришло уведомление на ваш подтвержденный адрес.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -12,4 +12,5 @@ Subject: Приглашение <script>alert("x")</script> & 'кавычки' X
https://lincodex.example/candidate/invitations
--
Вы получили это письмо, потому что в Lincodex пришло уведомление на ваш подтвержденный адрес.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -1,24 +0,0 @@
<!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,45 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Откройте ссылку, чтобы задать новый пароль в Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">ВОССТАНОВЛЕНИЕ ДОСТУПА</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;color:#1b1c21;">Сброс пароля</h1>
<p style="margin:0 0 24px;color:#1b1c21;">Мы получили запрос на сброс пароля для аккаунта Lincodex, связанного с этим адресом. Чтобы задать новый пароль, откройте ссылку.</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Задать новый пароль</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;word-break:break-all;"><a href="https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;text-decoration:underline;">https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
<p style="margin:0 0 16px;">Ссылка действует 1 час.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#4a4c55;">Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.</p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что для аккаунта Lincodex с этим адресом запросили сброс пароля.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -11,4 +11,5 @@ https://lincodex.example/reset-password#token=SyntheticToken_0123456789-abcdefgh
Если вы не запрашивали сброс, просто не открывайте ссылку: текущий пароль останется прежним.
--
Вы получили это письмо, потому что для аккаунта Lincodex с этим адресом запросили сброс пароля.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -1,28 +0,0 @@
<!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 16px;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
<p style="margin:0 0 8px;font-size:14px;">Код подтверждения:</p>
<p style="margin:0 0 8px;padding:16px;border-radius:6px;background-color:#f3f2ff;color:#1b1c21;font-family:'Courier New',Courier,monospace;font-size:32px;font-weight:bold;letter-spacing:0.3em;text-align:center;">482915</p>
<p style="margin:0 0 24px;font-size:14px;">Код действует 30 минут.</p>
<p style="margin:0 0 8px;font-size:14px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</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,53 @@
<!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:#1b1c21;">
<div style="display:none;max-height:0;line-height:0;font-size:0;opacity:0;overflow:hidden;mso-hide:all;">Введите код или откройте ссылку, чтобы подтвердить почту в Lincodex.</div>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#1b1c21;">
<tr>
<td align="center" style="padding:24px 16px;">
<table role="presentation" width="560" cellpadding="0" cellspacing="0" border="0" style="width:100%;max-width:560px;">
<tr>
<td style="background-color:#202129;border-radius:16px 16px 0 0;padding:24px 32px;font-family:Unbounded,'Arial Black','Helvetica Neue',Helvetica,Arial,sans-serif;font-size:22px;line-height:28px;font-weight:700;color:#ffffff;white-space:nowrap;"><span style="letter-spacing:-0.02em;">Lincodex</span><span style="display:inline-block;width:6px;height:16px;margin-left:6px;background-color:#402fff;"></span></td>
</tr>
<tr>
<td style="background-color:#ffffff;border-radius:0 0 16px 16px;padding:32px 32px 28px;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:24px;color:#1b1c21;">
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">РЕГИСТРАЦИЯ</p>
<h1 style="margin:0 0 16px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:24px;line-height:32px;font-weight:700;color:#1b1c21;">Подтвердите адрес почты</h1>
<p style="margin:0 0 24px;color:#1b1c21;">Чтобы завершить регистрацию в Lincodex, введите код на странице подтверждения вместе с паролем, который вы выбрали при регистрации.</p>
<p style="margin:0 0 8px;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:12px;line-height:16px;letter-spacing:0.08em;color:#4a4c55;">Код подтверждения</p>
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 12px;">
<tr>
<td align="center" style="background-color:#1b1c21;border-radius:12px;padding:20px 16px;text-indent:0.3em;font-family:ui-monospace,'JetBrains Mono',Menlo,Consolas,monospace;font-size:36px;line-height:44px;font-weight:700;letter-spacing:0.3em;color:#ffffff;">482915</td>
</tr>
</table>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;color:#4a4c55;">Код действует 30 минут.</p>
<p style="margin:0 0 16px;">Или откройте ссылку и подтвердите адрес на открывшейся странице:</p>
<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 0 24px;">
<tr>
<td align="center" bgcolor="#402fff" style="background-color:#402fff;border-radius:999px;padding:14px 28px;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="display:inline-block;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:16px;line-height:20px;font-weight:700;color:#ffffff;text-decoration:none;">Подтвердить почту</a></td>
</tr>
</table>
<p style="margin:0 0 8px;font-size:14px;line-height:22px;color:#4a4c55;">Если кнопка не работает, скопируйте ссылку в адресную строку браузера:</p>
<p style="margin:0 0 24px;font-size:14px;line-height:22px;word-break:break-all;"><a href="https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv" style="color:#402fff;text-decoration:underline;">https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghijklmnopqrstuv</a></p>
<p style="margin:0 0 16px;">Ссылка действует 24 часа.</p>
<p style="margin:0;font-size:14px;line-height:22px;color:#4a4c55;">Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.</p>
</td>
</tr>
<tr>
<td style="padding:20px 32px 0;font-family:Inter,'Segoe UI',-apple-system,BlinkMacSystemFont,Roboto,'Helvetica Neue',Arial,sans-serif;font-size:12px;line-height:18px;color:#9b9c9e;">
<p style="margin:0 0 8px;">Вы получили это письмо, потому что этот адрес указали при регистрации в Lincodex.</p>
<p style="margin:0;">Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.</p>
</td>
</tr>
</table>
</td>
</tr>
</table>
</body>
</html>
@@ -17,4 +17,5 @@ https://lincodex.example/verify-email#token=SyntheticToken_0123456789-abcdefghij
Если вы не регистрировались в Lincodex, ничего не делайте: без подтверждения аккаунт не будет активирован.
--
Вы получили это письмо, потому что этот адрес указали при регистрации в Lincodex.
Lincodex. Письмо отправлено автоматически, отвечать на него не нужно.
@@ -293,7 +293,7 @@ func TestDeliveryHandlerStoresTheRenderedRequest(t *testing.T) {
t.Fatal("the delivery does not name its source event")
case delivery.RecipientUserID() != h.recipient.ID || delivery.Recipient().Address() != testRecipientAddress:
t.Fatal("the delivery is not addressed to the account email")
case delivery.Kind() != domain.MailKindNotification || delivery.Content().TemplateVersion() != "notification.v1":
case delivery.Kind() != domain.MailKindNotification || delivery.Content().TemplateVersion() != "notification.v2":
t.Fatalf("the delivery has kind %s and version %s", delivery.Kind(), delivery.Content().TemplateVersion())
case !strings.Contains(delivery.Content().Text(), "PRIVATE-BODY") || !strings.Contains(delivery.Content().Text(), testOrigin+testLinkPath):
t.Fatal("the stored body is not the rendering of the request")
+3 -2
View File
@@ -347,7 +347,7 @@ A worker claims it within one poll interval and runs it with fresh attempts. To
The backend sends mail through the `MailSender` port. `EMAIL_PROVIDER` selects exactly one transport: `resend` (the Resend HTTP API, the primary provider for the working stand), `smtp` (a separate SMTP relay), or `disabled`. It has no default, and there is no fallback: when the selected transport cannot start, the backend stops instead of switching to another one. Settings of transports that are not selected are not read.
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented, and product notifications are stored as deliveries but not sent until product notification sending is implemented. See [Sending service mail](#sending-service-mail).
Current state: this build contains the `disabled` and `resend` transports. With `smtp`, the backend validates the SMTP settings and then exits with `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; under Compose, `restart: unless-stopped` restarts the container repeatedly. SMTP is outside the MVP. `.env.example` and `make -C deploy smoke` use `disabled`, so local runs need no key; the working stand sets `EMAIL_PROVIDER=resend` and `RESEND_API_KEY` explicitly. With `EMAIL_PROVIDER=resend`, the backend runs a worker for service identity mail (email verification and password reset), and registration queues a verification email. Password reset is not implemented. Product notifications are sent by a separate notification worker: it leaves a quota reserve to service mail and checks the recipient's rights again before every send (see [ARCHITECTURE.md](ARCHITECTURE.md)). See [Sending service mail](#sending-service-mail).
Release compatibility: `ConfirmEmail` requires both `token` and the password selected for that registration. Clients that send only the token must be updated. Migration `00016_bind_registration_consent.sql` adds the registration version to C1 and backfills legacy records from the current account version without requiring a live token. It checks that a registration C1 is not older than the latest registration and that an account has at most one active registration C1; on inconsistency, the migration stops without partial changes. A trigger fills the version when an old backend omits it and rejects a mismatched version sent by the new backend. A partial unique index allows at most one unrevoked registration C1 per account and registration version. Apply the migration before updating the backend. To roll back, deploy the old backend before reverting the migration. No new environment variable is needed. `APP_PUBLIC_URL` also defines the Origin that confirmation requests must send. The new `ConfirmEmailByCode` operation (`POST /api/v1/identity/email-verifications/code`) and migration `00046_add_email_verification_codes.sql` are additive: existing clients keep confirming by link. The migration can be rolled back once no usable code is left; its down step refuses until then.
@@ -376,7 +376,7 @@ Compose passes these variables from the root `.env`; it passes an unset `EMAIL_Q
### Mail deliveries
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are only stored for now: the sending worker claims verification and password reset mail only, so a notification stays `pending` until product notification sending is implemented. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
A notification request is a row in `mail_requests` until the consumer `notification_delivery` turns it into a row in `deliveries` and deletes it; the model is in [ARCHITECTURE.md](ARCHITECTURE.md#mail-deliveries). Migration 00006 creates `mail_requests`, `deliveries`, and `delivery_attempts` at startup; migration 00017 adds the unknown-outcome decision journal and rebuilds the due partial index under a table lock. Rolling 00017 back drops that journal and its audit history, so export the decisions before rollback. Neither migration needs a setting. Notification deliveries are sent by a separate notification worker through its own queue; the service mail worker still claims verification and password reset mail only. Notifications are created only for accounts with a verified address; a request for an unverified address is dropped with a log line.
- Each delivery is pinned to `EMAIL_PROVIDER` and `EMAIL_ACCOUNT` at creation, and a later configuration change applies only to new deliveries. Change `EMAIL_ACCOUNT` together with `RESEND_API_KEY` whenever the key belongs to another Resend account, so deliveries that started under the old account are never sent through the new one. Service mail created while `EMAIL_PROVIDER=disabled` stays pinned to `disabled` until the backend runs with a transport: the sending worker then moves it with `Rebind` (allowed only before the first attempt) and sends it if its token and account still pass the check. Do not rebind by hand. Product notifications follow the same rule, and their loop rebinds them the same way.
- The rows hold the recipient address and the rendered bodies, and a waiting `mail_requests` row holds the raw notification text; verification and password reset bodies hold a live one-time token until it is used or expires. Treat read access to `deliveries` like access to those links, and keep database dumps and backups under the same protection. Retention of finished deliveries is not implemented yet.
@@ -422,6 +422,7 @@ Implemented: the renderer in `backend/internal/usecase/notification/mailtemplate
- 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 path or the query: a browser does not send the fragment to a server, so the nginx access log (which records `$uri`) and Referer headers never hold it. The frontend reads and removes the fragment, waits for explicit user action, then sends the token and registration password to the API. 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.
- The HTML part uses table layout with inline styles only: no `<style>` block, external stylesheets, web fonts, images, or tracking pixels. Apart from the action link the message already carries, the HTML has no links. The header is dark with the text wordmark Lincodex and a blue caret; the body is a light card with dark text. Every text and background pair meets WCAG AA both with the designed colors and when a client inverts them. The footer states why the message was sent.
- 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. A delivery stores the rendered body with the hash, and a retry sends the stored body instead of rendering again, so a new version applies to new deliveries only and an old version's files are not needed to send a stored delivery.
- 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.
+1 -1
View File
@@ -206,7 +206,7 @@ Unit tests (`make -C backend test`) cover the delivery model and its creation pa
`TestMailDelivery` in `backend/integration_test/delivery_test.go` uses `bootstrap(t, postgresService, kafkaService)` and the real request usecase, handler, relay, consumer runtime, and stores. Its sequential cases are:
- One event processed twice through the consumer: a request for a verified account is recorded in a business transaction, the relay publishes its event, the row is marked unpublished again as after a crash before the `published_at` commit, and the relay publishes it a second time with the same event ID. The consumer commits offset 2 and counts one `applied` and one `duplicate` record; the database holds exactly one delivery, addressed to the account, rendered with `notification.v1`, pinned to the configured provider account, naming the event as its source, and `pending` with no attempt, and no mail request remains.
- A template change after creation: a first request is stored with `notification.v1`. A handler with a test renderer that stands for `notification.v2` stores a second request with the new version, and a replay of the first request under another consumer name finds its request consumed and stores nothing. The first delivery, read through a new pool, still has the `notification.v1` subject, parts, and hash, and a direct `UPDATE` of its body fails with `deliveries_content_immutable`.
- A template change after creation: a first request is stored with `notification.v2`. A handler with a test renderer that stands for the later version `notification.v3` stores a second request with the new version, and a replay of the first request under another consumer name finds its request consumed and stores nothing. The first delivery, read through a new pool, still has the `notification.v2` subject, parts, and hash, and a direct `UPDATE` of its body fails with `deliveries_content_immutable`.
- Restart persistence: one pool records an `unknown` attempt with a provider code and a wait hint with sub-millisecond parts, loses a second write of the same attempt with `ErrDeliveryVersionConflict`, records an `accepted` attempt with a provider message ID, and closes. A new pool and store read the delivery as `accepted` with that ID, two attempts, and version 3, and both attempt rows exactly as written, the wait hint to the nanosecond; a further attempt is refused, and an `UPDATE` of an attempt fails with `delivery_attempts_immutable`.
- Rebind and quota wait: a delivery without attempts is moved to another provider account and parked in `waiting_quota` with an unknown reset, a stale second write fails with a version conflict, and no attempt row exists; after an attempt, `Rebind` is refused by the domain and a direct `UPDATE` of the provider account fails with `deliveries_provider_pinned`.
- A notification to an unverified address stores no delivery, deletes its request, and logs the delivery ID.
+3 -2
View File
@@ -349,7 +349,7 @@ Worker захватит его в течение одного интервала
Backend отправляет почту через порт `MailSender`. `EMAIL_PROVIDER` выбирает ровно один транспорт: `resend` (HTTP API Resend, основной провайдер рабочего стенда), `smtp` (отдельный SMTP relay) или `disabled`. Значения по умолчанию нет, и запасного варианта тоже нет: если выбранный транспорт не может запуститься, backend останавливается, а не переключается на другой. Настройки невыбранных транспортов не читаются.
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. При `EMAIL_PROVIDER=resend` backend запускает worker служебной почты identity (подтверждение почты и сброс пароля); регистрация ставит письмо подтверждения в очередь. Сброс пароля не реализован, а продуктовые уведомления сохраняются как доставки, но не отправляются до реализации их отправки. См. [Отправка служебной почты](#отправка-служебной-почты).
Текущее состояние: в этой сборке есть транспорты `disabled` и `resend`. С `smtp` backend проверяет настройки SMTP и затем завершается с ошибкой `EMAIL_PROVIDER=smtp: mail transport is not available in this build`; в Compose `restart: unless-stopped` будет перезапускать контейнер снова и снова. SMTP вне MVP. `.env.example` и `make -C deploy smoke` используют `disabled`, поэтому локальному запуску ключ не нужен; рабочий стенд явно задает `EMAIL_PROVIDER=resend` и `RESEND_API_KEY`. При `EMAIL_PROVIDER=resend` backend запускает worker служебной почты identity (подтверждение почты и сброс пароля); регистрация ставит письмо подтверждения в очередь. Сброс пароля не реализован. Продуктовые уведомления отправляет отдельный worker уведомлений: он оставляет служебной почте резерв квоты и перед каждой отправкой заново проверяет права получателя (см. [ARCHITECTURE.md](ARCHITECTURE.md)). См. [Отправка служебной почты](#отправка-служебной-почты).
Совместимость выпуска: `ConfirmEmail` требует `token` и пароль, выбранный при соответствующей регистрации. Клиенты, которые отправляли только токен, нужно обновить. Миграция `00016_bind_registration_consent.sql` добавляет версию регистрации к C1 и заполняет ее для прежних записей по текущей версии аккаунта, без требования живого токена. Она проверяет, что регистрационная C1 не старше последней регистрации и что у аккаунта нет нескольких активных регистрационных C1; при несоответствии миграция останавливается без частичных изменений. Триггер заполняет версию, если старый backend не передал ее, и отклоняет несовпадающую версию от нового backend. Частичный уникальный индекс допускает не больше одной неотозванной регистрационной C1 на аккаунт и версию регистрации. Миграцию можно применить до обновления backend. При откате сначала верните старый backend, затем отмените миграцию. Новые переменные окружения не нужны. `APP_PUBLIC_URL` также задает Origin, который должен передавать запрос подтверждения. Новая операция `ConfirmEmailByCode` (`POST /api/v1/identity/email-verifications/code`) и миграция `00046_add_email_verification_codes.sql` аддитивны: прежние клиенты продолжают подтверждать по ссылке. Откат миграции возможен, когда не осталось действующих кодов; ее down-шаг до этого момента отказывает.
@@ -378,7 +378,7 @@ Compose передает эти переменные из корневого `.e
### Доставки писем
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений пока только сохраняются: worker отправки берет только письма подтверждения и сброса пароля, поэтому уведомление остается в `pending`, пока не реализована отправка продуктовых уведомлений. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
Запрос уведомления - строка `mail_requests`, пока обработчик `notification_delivery` не превратит его в строку `deliveries` и не удалит; модель описана в [ARCHITECTURE.md](ARCHITECTURE.md#доставки-писем). Миграция 00006 создает `mail_requests`, `deliveries` и `delivery_attempts` при запуске; настройки для этого не нужны. Доставки уведомлений отправляет отдельный worker уведомлений через свою очередь; worker служебной почты по-прежнему берет только письма подтверждения и сброса пароля. Уведомления создаются только для аккаунтов с подтвержденным адресом; запрос на неподтвержденный адрес отбрасывается со строкой в логе.
- Каждая доставка закрепляется за `EMAIL_PROVIDER` и `EMAIL_ACCOUNT` в момент создания, а последующее изменение конфигурации применяется только к новым доставкам. Меняйте `EMAIL_ACCOUNT` вместе с `RESEND_API_KEY` каждый раз, когда ключ принадлежит другому аккаунту Resend, чтобы доставки, начатые под старым аккаунтом, никогда не отправлялись через новый. Служебная почта, созданная при `EMAIL_PROVIDER=disabled`, остается закрепленной за `disabled`, пока backend не запущен с транспортом: тогда worker отправки переносит ее через `Rebind` (разрешено только до первой попытки) и отправляет, если ее токен и аккаунт все еще проходят проверку. Не переносите вручную. Продуктовые уведомления подчиняются тому же правилу, а их цикл переносит их так же.
- Строки содержат адрес получателя и сформированные тела писем, а ожидающая строка `mail_requests` - исходный текст уведомления; тела писем подтверждения почты и сброса пароля содержат действующий одноразовый токен, пока его не использовали или пока не истек срок. Относитесь к доступу на чтение к `deliveries` как к доступу к этим ссылкам и защищайте дампы и резервные копии базы так же. Срок хранения завершенных доставок пока не реализован.
@@ -424,6 +424,7 @@ Compose передает эти переменные из корневого `.e
- Шаблоны встроены в бинарник через `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: браузер не отправляет fragment серверу, поэтому access log nginx (он пишет `$uri`) и заголовки Referer его никогда не содержат. Frontend читает и удаляет fragment, дожидается явного действия пользователя и отправляет в API токен вместе с паролем регистрации. Ссылка уведомления указывает на путь внутри приложения, например `/candidate/invitations`; абсолютный URL, `//host`, схема вроде `javascript:`, query, fragment, знак процента и сегменты `.` или `..` отклоняются.
- В письмах нет имени, email или других контактов. Текст вызывающего кода в уведомлении экранируется в HTML части; управляющие и bidi символы удаляются из текстовой части, а тема сводится к одной строке, поэтому CR и LF не могут добавить строки заголовка. Тема уведомления ограничена 100 символами, текст 2000.
- HTML часть собрана таблицами с инлайн-стилями: без блока `<style>`, внешних таблиц стилей, веб-шрифтов, изображений и пикселей отслеживания. Кроме ссылки, которая уже есть в письме, ссылок в HTML нет. Шапка тёмная, с текстовым логотипом Lincodex и синим курсором; тело - светлая карточка с тёмным текстом. Каждая пара текста и фона проходит WCAG AA и с исходными цветами, и при инверсии цветов клиентом. Футер объясняет, почему пришло письмо.
- Тексты на русском языке. Выпущенная версия неизменяема: изменение текста добавляет следующую версию, например `verification.v2`, и переключает текущую версию в коде. Версии не делят файлы, поэтому одна версия не может изменить тело другой. Каждый результат содержит свою версию и SHA-256 content hash по версии, теме и обеим частям; одна и та же версия с теми же данными всегда дает то же тело. Доставка хранит сформированное тело вместе с hash, а повтор отправляет сохраненное тело, а не формирует его заново, поэтому новая версия применяется только к новым доставкам, а файлы старой версии для отправки сохраненной доставки не нужны.
- Renderer ничего не пишет в лог. Результат и данные уведомления в выводе `fmt` и `slog` показывают только тип, версию и content hash; токены, ссылки и тела писем не печатаются.
- Golden файлы в `testdata/` делают каждое изменение текста видимым на ревью. После намеренного изменения выполните `go test ./internal/usecase/notification/mailtemplate -update` из `backend/` и проверьте diff.
+1 -1
View File
@@ -206,7 +206,7 @@ Unit-тесты (`make -C backend test`) покрывают модель дос
`TestMailDelivery` в `backend/integration_test/delivery_test.go` использует `bootstrap(t, postgresService, kafkaService)` и настоящие usecase запроса, обработчик, relay, runtime обработчиков и хранилища. Последовательные случаи:
- Одно событие обрабатывается дважды: запрос для подтвержденного аккаунта записывается в бизнес-транзакции, relay публикует его событие, строка снова помечается неопубликованной, как после сбоя до фиксации `published_at`, и relay публикует ее второй раз с тем же ID события. Обработчик фиксирует offset 2 и считает одну запись `applied` и одну `duplicate`; в базе ровно одна доставка: адресована аккаунту, сформирована версией `notification.v1`, закреплена за настроенным аккаунтом провайдера, называет событие своим источником и находится в `pending` без попыток, а запросов писем не остается.
- Изменение шаблона после создания: первый запрос сохраняется с `notification.v1`. Обработчик с тестовым renderer, изображающим `notification.v2`, сохраняет второй запрос с новой версией, а повтор первого запроса под другим именем обработчика находит запрос уже обработанным и ничего не сохраняет. Первая доставка, прочитанная через новый пул, сохраняет тему, части и hash `notification.v1`, а прямой `UPDATE` ее тела завершается ошибкой `deliveries_content_immutable`.
- Изменение шаблона после создания: первый запрос сохраняется с `notification.v2`. Обработчик с тестовым renderer, изображающим более позднюю версию `notification.v3`, сохраняет второй запрос с новой версией, а повтор первого запроса под другим именем обработчика находит запрос уже обработанным и ничего не сохраняет. Первая доставка, прочитанная через новый пул, сохраняет тему, части и hash `notification.v2`, а прямой `UPDATE` ее тела завершается ошибкой `deliveries_content_immutable`.
- Сохранение после перезапуска: один пул записывает попытку `unknown` с кодом провайдера и подсказкой ожидания с долями миллисекунды, проигрывает повторную запись той же попытки с `ErrDeliveryVersionConflict`, записывает попытку `accepted` с ID письма у провайдера и закрывается. Новый пул и хранилище читают доставку как `accepted` с этим ID, двумя попытками и версией 3, а обе строки попыток - ровно в записанном виде, подсказку ожидания до наносекунды; следующая попытка отклоняется, а `UPDATE` попытки завершается ошибкой `delivery_attempts_immutable`.
- Перенос и ожидание квоты: доставка без попыток переносится на другой аккаунт провайдера и переводится в `waiting_quota` с неизвестным сбросом, повторная запись по устаревшей версии получает конфликт версии, строк попыток нет; после попытки `Rebind` отклоняется domain, а прямой `UPDATE` аккаунта провайдера завершается ошибкой `deliveries_provider_pinned`.
- Уведомление на неподтвержденный адрес не сохраняет доставку, удаляет свой запрос и записывает в лог ID доставки.