From 777383111e8f1e1f4c20f58a23aa7c91ed74f9a7 Mon Sep 17 00:00:00 2001 From: Carlos Lopez Date: Fri, 20 Nov 2026 19:06:52 +0100 Subject: [PATCH] feat(email): alert templates, mail queue with retries and shared layout (#81) - _layout.html shared by every email (header, content, footer with the reason and a link to manage the alert); invite and password reset moved onto it, still sent directly because their links carry tokens - alert.html (field table built from the catalog), alert-code-report-analysis.html (service, branch, commit, coloured severities, violated policies) and system-access-changed / system-security-notice for the fixed notices - EventDefinition.mailTemplate, link(context) and mailSummary(payload); subject "[GitOps] : "; absolute links from ORIGIN, omitted without it; recipient language or English; stripped from the client catalog - MailQueue: concurrency 3, withRetry 4 attempts 1s/4s/16s with jitter only for network errors and 4xx SMTP replies, definitive failures logged with a recipient hash and no content, drained on sveltekit:shutdown (10 s) - without SMTP: startup warning, debug per skipped event, banner on the alert pages - e2e no longer inherits SMTP settings from a developer's .env - docs: README email section, CLAUDE.md, .env.example, optional mailpit service Co-Authored-By: Claude Opus 5.5 --- .env.example | 15 +- CLAUDE.md | 22 +- README.md | 30 +- docker-compose.yml | 10 + e2e/env-private.ts | 1 + e2e/global-setup.ts | 9 + e2e/specs/alerts.spec.ts | 2 + src/env.ts | 1 + src/lib/alerts/types.ts | 9 +- src/lib/components/alerts/AlertEditor.svelte | 13 +- src/lib/components/alerts/AlertList.svelte | 13 +- src/lib/events/catalog/access.events.ts | 21 ++ src/lib/events/catalog/code-report.events.ts | 20 ++ src/lib/events/catalog/links.ts | 11 + src/lib/events/catalog/organization.events.ts | 2 + src/lib/events/catalog/projects.events.ts | 4 + src/lib/events/catalog/types.ts | 17 + src/lib/events/catalog/vault.events.ts | 7 + src/lib/i18n/locales/en.json | 37 ++- src/lib/i18n/locales/es.json | 37 ++- src/lib/server/alerts/operations.ts | 12 +- src/lib/server/alerts/page.ts | 10 +- src/lib/server/infra/notifications/config.ts | 23 ++ src/lib/server/infra/notifications/index.ts | 49 ++- .../infra/notifications/mail-queue.test.ts | 167 ++++++++++ .../server/infra/notifications/mail-queue.ts | 126 ++++++++ src/lib/server/infra/notifications/retry.ts | 64 ++++ .../server/infra/notifications/template.ts | 39 +++ .../alerts/application/alert-engine.ts | 19 +- .../alerts/application/recipient-resolver.ts | 6 +- src/modules/alerts/application/testing.ts | 6 + src/modules/alerts/application/types.ts | 8 +- src/modules/alerts/index.ts | 35 +- .../alert-mail.notifier.test.ts | 281 +++++++++++++--- .../infrastructure/alert-mail.notifier.ts | 300 ++++++++++++++---- .../alerts/infrastructure/event-summary.ts | 4 + .../infrastructure/platform-directory.ts | 12 +- .../notifications/invitation.notifier.ts | 44 +-- .../notifications/password-reset.notifier.ts | 30 +- src/notifications/email/_layout.html | 97 ++++++ .../email/alert-code-report-analysis.html | 39 +++ src/notifications/email/alert.html | 15 + src/notifications/email/invite.html | 155 ++------- src/notifications/email/password-reset.html | 155 ++------- .../email/system-access-changed.html | 6 + .../email/system-security-notice.html | 18 ++ src/routes/api/alerts/server.test.ts | 3 + 47 files changed, 1566 insertions(+), 438 deletions(-) create mode 100644 src/lib/events/catalog/links.ts create mode 100644 src/lib/server/infra/notifications/mail-queue.test.ts create mode 100644 src/lib/server/infra/notifications/mail-queue.ts create mode 100644 src/lib/server/infra/notifications/retry.ts create mode 100644 src/notifications/email/_layout.html create mode 100644 src/notifications/email/alert-code-report-analysis.html create mode 100644 src/notifications/email/alert.html create mode 100644 src/notifications/email/system-access-changed.html create mode 100644 src/notifications/email/system-security-notice.html diff --git a/.env.example b/.env.example index c1d6bc38..08039b46 100644 --- a/.env.example +++ b/.env.example @@ -2,6 +2,7 @@ GITDB_REPOSITORY_URL=https://github.com/your-org/your-gitdb-repository.git GITDB_ENCRYPTION_KEY=replace-with-a-long-random-secret +# Public URL of the app: SvelteKit's CSRF check and the absolute links in emails ORIGIN=http://localhost:3000 # Optional GitDB configuration @@ -20,15 +21,19 @@ GITDB_SYNC_POLL_SECONDS=60 # GITDB_USERNAME= # GITDB_PASSWORD= -# Optional SMTP notifications +# Optional SMTP notifications: invitations, password resets, alerts and access notices. +# Without HOST and FROM no email is sent (alerts are kept, the UI shows a warning). +# Links in emails are built from ORIGIN above; without it emails go out without links. +# For local testing: `docker compose --profile mail up mailpit`, HOST=localhost, PORT=1025, +# then read the emails at http://localhost:8025 # NOTIFICATION_SMTP_HOST=smtp.example.com -# NOTIFICATION_SMTP_PORT=587 -# NOTIFICATION_SMTP_SECURE=false -# NOTIFICATION_SMTP_USER= +# NOTIFICATION_SMTP_PORT=587 # 465 turns TLS on by default +# NOTIFICATION_SMTP_SECURE=false # force TLS on/off +# NOTIFICATION_SMTP_USER= # USER and PASSWORD go together # NOTIFICATION_SMTP_PASSWORD= # NOTIFICATION_SMTP_FROM=noreply@example.com # NOTIFICATION_SMTP_FROM_NAME=GitOps -# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true +# NOTIFICATION_SMTP_REJECT_UNAUTHORIZED=true # only set false for self-signed test servers # Optional cluster-wide Google sign-in (OpenID Connect). Shown on the login page when both the # client ID and secret are set. Redirect URI to register in GCP: /auth/sso/google/callback diff --git a/CLAUDE.md b/CLAUDE.md index 7c702c3e..a6f7e76e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -176,8 +176,26 @@ in `docs/adr/0001-event-bus-and-alerts.md`. throttle (`throttleMinutes`) suppresses repeats and the next email reports how many were skipped. - Recipients = selected users ∪ members with the selected roles, minus disabled users and users without an email, then **filtered with `cancanService.can(userId, readPermission, event scope)`** - (most-specific-wins applies). One email per recipient (`AlertMailNotifier`, texts under - `alerts.email.*`, base locale); a failed email only affects that recipient. + (most-specific-wins applies). One email per recipient (`AlertMailNotifier`); a failed email + only affects that recipient. An organization alert and a project alert on the same event fire + independently. +- Email (`#lib/server/infra/notifications`): every email is wrapped by `renderEmail()` in + `src/notifications/email/_layout.html` (header, content, footer with the reason and a manage + link). Alerts use `alert.html` (field table built from the catalog) unless the definition sets + `mailTemplate` (`alert-code-report-analysis.html`); `link(context)` gives the app path of the + resource and `mailSummary(payload)` the subject summary (`[GitOps] : `). System + notices use `system-access-changed.html` / `system-security-notice.html`. Escape every user or + event value with `{{ }}`; `{{{ }}}` only for HTML built internally with `renderTemplateString`. + Texts are `alerts.email.*`, in the recipient's locale or English. Links are absolute with + `ORIGIN` (`absoluteUrl()`), omitted without it. These functions never reach the client: the + catalog endpoint strips them. +- Sending: alert and system emails go through `mailQueue` (concurrency 3, `withRetry` 4 attempts + 1 s → 4 s → 16 s with jitter, only for `isRetryableMailError`: network errors and 4xx replies). + Definitive failures are logged by `createLogger('mail')` with the alert, the event and a + recipient hash, never the content or the address. `registerMailShutdown()` drains it on + `sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their + tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the + engine skips events (debug log), warns once at startup and the alert pages show a banner. - HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`, `GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test` diff --git a/README.md b/README.md index 0acde952..d6a87575 100644 --- a/README.md +++ b/README.md @@ -125,8 +125,8 @@ automatic sign-up without domains), the Google button is hidden and the reason i Organizations and projects can get an email when something happens. Alerts live in **Settings → Alerts** of the organization (they cover all of its projects) or of a project. Each alert watches -one event, filters it on the event's fields and emails users or roles. Emails need the -`NOTIFICATION_SMTP_*` variables; without SMTP, alerts are kept but nothing is sent. +one event, filters it on the event's fields and emails users or roles. The same event can fire an +organization alert and a project alert; each one sends its own email. Guided example: *tell the security team when an analysis of the `api-gateway` service has critical vulnerabilities*. @@ -163,6 +163,32 @@ fields. Only recipients allowed to view the event get the email, and you can onl events you can view yourself. Some notifications are always on: users are told when their access to an organization or project changes and when a personal API key is created on their account. +### Email + +Invitations, password resets, alerts and access notices are sent by SMTP: + +| Variable | Default | | +|---|---|---| +| `NOTIFICATION_SMTP_HOST` | — | Required to send email | +| `NOTIFICATION_SMTP_FROM` | — | Required, sender address | +| `NOTIFICATION_SMTP_FROM_NAME` | — | Sender display name | +| `NOTIFICATION_SMTP_PORT` | `587` | `465` turns TLS on by default | +| `NOTIFICATION_SMTP_SECURE` | port-based | Force TLS on or off | +| `NOTIFICATION_SMTP_USER` / `NOTIFICATION_SMTP_PASSWORD` | — | Set both or neither | +| `NOTIFICATION_SMTP_REJECT_UNAUTHORIZED` | `true` | `false` only for self-signed test servers | +| `ORIGIN` | — | Public URL; links in emails are absolute. Without it emails have no links | + +Without SMTP nothing breaks: alerts are kept, the alert pages show a warning and the server logs +it once at startup. Alert and notice emails go through an in-process queue (3 at a time) that +retries network errors and temporary SMTP replies (4 attempts: 1 s, 4 s, 16 s) and is drained for +up to 10 s on shutdown; invitations and password resets are sent directly because their links carry +tokens. Emails are in the recipient's language when known, English otherwise. + +To try them locally, start [Mailpit](https://mailpit.axllent.org/) with +`docker compose --profile mail up mailpit`, set `NOTIFICATION_SMTP_HOST=localhost`, +`NOTIFICATION_SMTP_PORT=1025` and `NOTIFICATION_SMTP_FROM=gitops@localhost`, and open +http://localhost:8025. + ## Development ```bash diff --git a/docker-compose.yml b/docker-compose.yml index b96ea9e2..5f284fdb 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -13,3 +13,13 @@ services: - ./data:/app/data - /run/host-services/ssh-auth.sock:/ssh-agent restart: unless-stopped + + # local SMTP for trying emails: `docker compose --profile mail up`, then set + # NOTIFICATION_SMTP_HOST=mailpit (or localhost outside Docker), NOTIFICATION_SMTP_PORT=1025, + # NOTIFICATION_SMTP_FROM=gitops@localhost and open http://localhost:8025 + mailpit: + image: axllent/mailpit:v1.21 + profiles: ['mail'] + ports: + - '1025:1025' + - '8025:8025' diff --git a/e2e/env-private.ts b/e2e/env-private.ts index d04c4f5c..e355c661 100644 --- a/e2e/env-private.ts +++ b/e2e/env-private.ts @@ -14,6 +14,7 @@ export const GITDB_SYNC_MODE = process.env.GITDB_SYNC_MODE; export const GITDB_DATA_PATH = process.env.GITDB_DATA_PATH; export const GITDB_ENCRYPTION_KEY = process.env.GITDB_ENCRYPTION_KEY; export const VAULT_ENCRYPTION_KEY = process.env.VAULT_ENCRYPTION_KEY; +export const ORIGIN = process.env.ORIGIN; export const NOTIFICATION_SMTP_HOST = process.env.NOTIFICATION_SMTP_HOST; export const NOTIFICATION_SMTP_PORT = process.env.NOTIFICATION_SMTP_PORT; export const NOTIFICATION_SMTP_SECURE = process.env.NOTIFICATION_SMTP_SECURE; diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index 97ba1be4..eec93581 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -49,6 +49,15 @@ function buildEnv(): Record { GITDB_USERNAME: '', GITDB_TOKEN: '', GITDB_PASSWORD: '', + // never reach a real SMTP from a developer's `.env`: the suite runs with email disabled + NOTIFICATION_SMTP_HOST: '', + NOTIFICATION_SMTP_PORT: '', + NOTIFICATION_SMTP_SECURE: '', + NOTIFICATION_SMTP_USER: '', + NOTIFICATION_SMTP_PASSWORD: '', + NOTIFICATION_SMTP_FROM: '', + NOTIFICATION_SMTP_FROM_NAME: '', + NOTIFICATION_SMTP_REJECT_UNAUTHORIZED: '', PORT: String(E2E_PORT), }; } diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts index 786ed957..d7e3e1ed 100644 --- a/e2e/specs/alerts.spec.ts +++ b/e2e/specs/alerts.spec.ts @@ -25,6 +25,8 @@ test.describe('project alerts', () => { await loginAs('projectAdmin'); await expectAllowed(page, alertsUrl); await expect(page.getByText('Todavía no hay alertas')).toBeVisible(); + // e2e runs without SMTP: the page says alerts won't be sent + await expect(page.getByTestId('mail-disabled')).toBeVisible(); await expect(page.getByRole('link', { name: 'Crear alerta' }).first()).toHaveAttribute( 'href', `${alertsUrl}/new`, diff --git a/src/env.ts b/src/env.ts index 9f995c2c..da5dff00 100644 --- a/src/env.ts +++ b/src/env.ts @@ -16,6 +16,7 @@ export const variables = defineEnvVars({ GITDB_DATA_PATH: optional, GITDB_ENCRYPTION_KEY: optional, VAULT_ENCRYPTION_KEY: optional, + ORIGIN: optional, NOTIFICATION_SMTP_HOST: optional, NOTIFICATION_SMTP_PORT: optional, NOTIFICATION_SMTP_SECURE: optional, diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts index ea6cdb62..c552527c 100644 --- a/src/lib/alerts/types.ts +++ b/src/lib/alerts/types.ts @@ -10,7 +10,12 @@ export type CatalogField = Omit & { derived?: boolean; }; -export type CatalogEntry = Omit & { fields: CatalogField[] }; +export type CatalogEntry = Omit< + EventDefinition, + 'fields' | 'link' | 'mailSummary' | 'mailTemplate' +> & { + fields: CatalogField[]; +}; export type AlertOption = { id: string; label: string }; @@ -40,6 +45,8 @@ type Shared = { referenceOptions: Record; users: AlertOption[]; roles: AlertOption[]; + /** `false` when SMTP is not configured: alerts are saved but nothing is sent. */ + mailConfigured: boolean; }; export type AlertListData = Shared & { diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte index 4ef199d1..f63a2e3d 100644 --- a/src/lib/components/alerts/AlertEditor.svelte +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -2,7 +2,7 @@ import { untrack } from 'svelte'; import { enhance } from '$app/forms'; import type { SubmitFunction } from '$app/forms'; - import { ArrowLeft, FlaskConical, Info, Save, Trash2 } from '@lucide/svelte'; + import { ArrowLeft, FlaskConical, Info, MailWarning, Save, Trash2 } from '@lucide/svelte'; import { _ } from '#lib/i18n'; import type { AlertEditorData, @@ -115,6 +115,17 @@ {/if} + {#if !data.mailConfigured} +

+ + {$_('alerts.mailDisabled')} +

+ {/if} +

diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte index cfc44630..6adbd62e 100644 --- a/src/lib/components/alerts/AlertList.svelte +++ b/src/lib/components/alerts/AlertList.svelte @@ -1,6 +1,6 @@ '; +const ORIGIN = 'https://gitops.example.com'; + +function analysisEvent(): AnyDomainEvent { + return { + id: 'event-1', + type: 'code_report.analysis.completed', + occurredAt: '2026-11-20T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: 'org-1', projectId: 'p1' }, + payload: { + analysisId: 'analysis-1', + serviceId: 'svc-gateway', + tool: 'trivy', + gitInfo: { + repositoryUrl: null, + branch: 'feature/', + commit: 'abcdef1234567890', + version: null, + }, + summary: { critical: 3, high: 5, medium: 1, low: 0, unknown: 0, total: 9, secrets: 0 }, + policies: { + status: 'violated', + totalViolations: 2, + blockingFailures: 1, + failedPolicyIds: ['p'], + }, + }, + }; +} + +function alertEmail(overrides: Partial = {}): AlertEmail { + return { + recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' }, + alert: { id: 'alert-1', name: 'Críticas en api-gateway', description: null, scope: 'project' }, + event: analysisEvent(), + definition: getEventDefinition('code_report.analysis.completed') as EventDefinition, + suppressed: 0, + names: new Map([['svc-gateway', `api-gateway ${XSS}`]]), + where: { organization: 'Kettu', organizationSlug: 'kettu', project: 'Web', projectSlug: 'web' }, + ...overrides, + }; +} + +function expectClean(html: string) { + expect(html).not.toMatch(/\{\{|\}\}/); + expect(html).not.toContain('