From b72af36ed7e8ed6aef439f72833f4b04d3f17d8b Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Tue, 24 Nov 2026 10:28:20 +0100
Subject: [PATCH 1/2] Feat: Add alerts destination external email
---
.github/copilot-instructions.md | 63 ++--
CLAUDE.md | 56 ++-
README.md | 21 +-
src/hooks.server.ts | 16 +-
src/lib/alerts/summary.ts | 3 +-
src/lib/alerts/types.ts | 18 +-
src/lib/components/AppSidebar.svelte | 22 +-
.../components/NotificationLinkPage.svelte | 86 +++++
src/lib/components/alerts/AlertEditor.svelte | 154 +++++++-
src/lib/config/permissions.ts | 11 +
src/lib/database/schemas.ts | 40 ++
src/lib/events/catalog/code-report.events.ts | 11 +
src/lib/events/catalog/types.ts | 4 +
src/lib/events/catalog/vault.events.ts | 11 +-
src/lib/i18n/locales/en.json | 104 +++++-
src/lib/i18n/locales/es.json | 104 +++++-
src/lib/notifications/status.ts | 15 +
src/lib/notifications/types.ts | 4 +
src/lib/server/alerts/operations.ts | 96 ++++-
src/lib/server/alerts/page.ts | 51 ++-
.../server/infra/notifications/config.test.ts | 37 +-
src/lib/server/infra/notifications/config.ts | 24 +-
.../server/infra/notifications/email-parts.ts | 21 ++
src/lib/server/infra/notifications/i18n.ts | 32 ++
src/lib/server/infra/notifications/index.ts | 24 +-
.../notifications/mail-notification.test.ts | 27 ++
.../infra/notifications/mail-notification.ts | 12 +
.../infra/notifications/mail-queue.test.ts | 6 +-
.../server/infra/notifications/mail-queue.ts | 52 ++-
.../infra/notifications/mail.transport.ts | 1 +
src/lib/server/infra/rate-limit.test.ts | 27 ++
src/lib/server/infra/rate-limit.ts | 59 +++
src/lib/server/infra/tokens.test.ts | 67 ++++
src/lib/server/infra/tokens.ts | 85 +++++
src/lib/server/notifications/links.ts | 47 +++
src/lib/server/notifications/settings.test.ts | 137 +++++++
src/lib/server/notifications/settings.ts | 130 +++++++
.../alerts/application/alert-engine.test.ts | 35 +-
.../alerts/application/alert-engine.ts | 160 +++++++-
.../alerts/application/alert.external.test.ts | 345 +++++++++++++++++
.../alerts/application/alert.service.ts | 116 +++++-
src/modules/alerts/application/types.ts | 23 +-
src/modules/alerts/domain/alert.domain.ts | 8 +
.../alerts/domain/sample-event.test.ts | 46 +++
src/modules/alerts/domain/sample-event.ts | 50 ++-
src/modules/alerts/index.ts | 92 ++++-
.../alert-mail.notifier.test.ts | 95 ++++-
.../infrastructure/alert-mail.notifier.ts | 144 +++----
.../alerts/infrastructure/event-summary.ts | 5 +-
.../auth/domain/role-permissions.data.ts | 2 +
.../external-recipient.service.test.ts | 322 ++++++++++++++++
.../application/external-recipient.service.ts | 351 ++++++++++++++++++
.../notification-settings.service.ts | 65 ++++
.../notifications/application/testing.ts | 64 ++++
.../domain/email-address.test.ts | 76 ++++
.../notifications/domain/email-address.ts | 66 ++++
.../domain/external-recipient.domain.ts | 176 +++++++++
.../domain/notification-settings.domain.ts | 13 +
src/modules/notifications/index.ts | 69 ++++
.../external-recipient-mail.notifier.ts | 48 +++
.../external-recipient.repository.ts | 71 ++++
.../repositories/in-memory.repositories.ts | 73 ++++
.../notification-settings.repository.ts | 60 +++
.../email/external-recipient-verify.html | 13 +
src/routes/+layout.server.ts | 5 +
src/routes/+layout.svelte | 5 +-
src/routes/api/alerts/[id]/test/+server.ts | 3 +-
src/routes/api/alerts/server.test.ts | 174 ++++++++-
src/routes/api/alerts/test/+server.ts | 3 +-
.../notifications/unsubscribe/+page.server.ts | 18 +
.../notifications/unsubscribe/+page.svelte | 8 +
.../notifications/verify/+page.server.ts | 18 +
src/routes/notifications/verify/+page.svelte | 8 +
.../settings/notifications/+page.server.ts | 42 +++
.../[org]/settings/notifications/+page.svelte | 189 ++++++++++
75 files changed, 4512 insertions(+), 227 deletions(-)
create mode 100644 src/lib/components/NotificationLinkPage.svelte
create mode 100644 src/lib/notifications/status.ts
create mode 100644 src/lib/notifications/types.ts
create mode 100644 src/lib/server/infra/notifications/email-parts.ts
create mode 100644 src/lib/server/infra/notifications/i18n.ts
create mode 100644 src/lib/server/infra/rate-limit.test.ts
create mode 100644 src/lib/server/infra/rate-limit.ts
create mode 100644 src/lib/server/infra/tokens.test.ts
create mode 100644 src/lib/server/infra/tokens.ts
create mode 100644 src/lib/server/notifications/links.ts
create mode 100644 src/lib/server/notifications/settings.test.ts
create mode 100644 src/lib/server/notifications/settings.ts
create mode 100644 src/modules/alerts/application/alert.external.test.ts
create mode 100644 src/modules/alerts/domain/sample-event.test.ts
create mode 100644 src/modules/notifications/application/external-recipient.service.test.ts
create mode 100644 src/modules/notifications/application/external-recipient.service.ts
create mode 100644 src/modules/notifications/application/notification-settings.service.ts
create mode 100644 src/modules/notifications/application/testing.ts
create mode 100644 src/modules/notifications/domain/email-address.test.ts
create mode 100644 src/modules/notifications/domain/email-address.ts
create mode 100644 src/modules/notifications/domain/external-recipient.domain.ts
create mode 100644 src/modules/notifications/domain/notification-settings.domain.ts
create mode 100644 src/modules/notifications/index.ts
create mode 100644 src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
create mode 100644 src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
create mode 100644 src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
create mode 100644 src/modules/notifications/infrastructure/repositories/notification-settings.repository.ts
create mode 100644 src/notifications/email/external-recipient-verify.html
create mode 100644 src/routes/notifications/unsubscribe/+page.server.ts
create mode 100644 src/routes/notifications/unsubscribe/+page.svelte
create mode 100644 src/routes/notifications/verify/+page.server.ts
create mode 100644 src/routes/notifications/verify/+page.svelte
create mode 100644 src/routes/org/[org]/settings/notifications/+page.server.ts
create mode 100644 src/routes/org/[org]/settings/notifications/+page.svelte
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 1d15a26b..d44e0e7a 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -70,7 +70,17 @@ La logica vive en `src/modules//` con `domain/`, `application/`, `infras
`index.ts` como composition root. El `domain/` contiene entidades (`*.domain.ts`) y datos
centralizados (`*.data.ts`) para constantes: permisos de roles, defaults de proyecto, pesos de
riesgo y mapeos de herramientas. Los modulos actuales son `auth`, `config`, `organization`,
-`projects`, `storage` y `code-report`. Las rutas deben importar desde el `index.ts` publico.
+`projects`, `storage`, `code-report`, `vault`, `audit`, `alerts` y `notifications`.
+
+**Destinatarios de email externo:** El módulo `notifications` gestiona acceso a personas sin
+cuenta GitOps (vendors, mailboxes). Cada dirección es un `ExternalRecipientEntity` con estados
+(`pending`, `verified`, `unsubscribed`, `blocked`). Las direcciones se confirman vía token HMAC
+(7 días, single-use, rate limited 3/h por dirección). Solo se envían a direcciones verificadas
+con dominio permitido (configurado en `/org//settings/notifications`). Las alertas omiten
+campos sensibles y links al app para externals. Rutas públicas sin sesión: `/notifications/verify`
+y `/notifications/unsubscribe` aceptan POST con tokens HMAC.
+
+Las rutas deben importar desde el `index.ts` publico.
GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos,
metadata de storage y code reports. Se configura con `GITDB_REPOSITORY_URL` (URLs HTTPS o SSH
@@ -85,34 +95,43 @@ CSRF Origin check de SvelteKit no dependa del header Host, previniendo bypass en
## RBAC y seguridad
-Los permisos usan `section:action` con scope global, de organizacion o de proyecto. Usar siempre
-`can()` o `isAdmin()` desde `$modules/auth`; `locals.user.role` es un objeto, no el string
-`admin`.
+Los permisos usan `::` (ej: `organization:projects:read`, `project:vault:secrets:all`)
+con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin()` desde `$modules/auth`;
+`locals.user.role` es un objeto, no el string `admin`.
+
+**Permisos de org:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`,
+`organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`,
+`organization:audit:read`, `organization:events:read`, `organization:alerts:read`,
+`organization:notifications:read` (leer destinatarios externos y dominios permitidos),
+`organization:notifications:update` (añadir direcciones externas, cambiar dominios).
**Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar
permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para
ocultar acciones que el usuario no puede realizar. El layout raíz (`+layout.server.ts`) calcula permisos
-granulares de lectura para settings de org (proyectos, usuarios, roles, configuración global, backups, servidor-keys, audit)
-y módulos de proyecto (vault, codereport, stateiac) combinándolos con lógica OR (`canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
-para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico.
+granulares de lectura para settings de org (proyectos, usuarios, roles, configuración, backups, servidor-keys,
+audit, eventos, alertas, notificaciones) y módulos de proyecto (vault, codereport, stateiac) combinándolos
+con lógica OR para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico.
Roles por defecto en `src/modules/auth/domain/role-permissions.data.ts`. Los permisos incluyen scope
-como prefijo (ej: `organization:projects:read`, `project:vault:secrets:all`) y se almacenan verbatim sin
-transformaciones. Recursos de módulos tienen sub-permisos granulares (ej: `project:vault:secrets:read`, `project:vault:environments:read`):
-- **GitOps Admin** (`cluster-admin`) — vault, openreport, stateiac (todos)
+como prefijo y se almacenan verbatim sin transformaciones. Módulos tienen sub-permisos granulares
+(ej: `project:vault:secrets:read`, `project:codereport:reports:read`):
+- **GitOps Admin** (`cluster-admin`) — acceso total a vault, openreport, stateiac
- **GitOps User** (`cluster-user`) — rol base sin permisos propios para acceso a nivel sistema
-- **Organization Admin** — todos los permisos de org (proyectos, usuarios, roles, configuración global, backups, server-access-keys, audit)
-- **Organization Developer** — solo read/create/update de proyectos
-- **Project Admin** — metadata/usuarios/roles/server-keys/audit plus todos los permisos de módulos (vault, codereport, stateiac)
-- **Project Developer/Viewer** — acceso granular a módulos con permisos diferenciados (solo lectura en Viewer)
-
-Los permisos de organización se propagan a sus proyectos solo cuando no hay un assignment explícito a nivel de
-proyecto. Un usuario con `organization:projects:read` puede satisfacer `project:project:read` en cualquier
-proyecto—pero si tiene un rol específico del proyecto, ese assignment es autoritario y los permisos de org no
-aplican (regla most-specific-wins). Permite delegación de autoridad granular con restricciones por-proyecto.
-
-`canManageOrganization()` controla acceso al area `/settings`, mientras que `canViewOrganization()` incluye
-tambien usuarios con acceso solo a proyectos bajo la organización (ven el overview pero no pueden acciones de org-scope).
+- **Organization Admin** — todos los permisos de org: proyectos, usuarios, roles, settings, backups,
+ server-keys, audit, eventos, alertas, notificaciones
+- **Organization Developer** — solo lectura/crear/actualizar proyectos
+- **Project Admin** — metadata/usuarios/roles/server-keys/audit/alertas/notificaciones; acceso total
+ a módulos (vault, codereport, stateiac)
+- **Project Developer** — lectura/crear/actualizar recursos; acceso granular a módulos; lee alertas
+- **Project Viewer** — solo lectura: metadata, alertas, módulos
+
+Los permisos de organización se propagan a sus proyectos solo cuando no hay assignment explícito a nivel de
+proyecto (regla most-specific-wins). `canManageOrganization()` controla acceso al area `/settings`, mientras
+que `canViewOrganization()` incluye usuarios con acceso solo a proyectos.
+
+**Rutas públicas de notificaciones:** `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con
+tokens HMAC (permitidas sin sesión en `hooks.server.ts`) para confirmar direcciones y unsubscribirse de alertas
+externas. Usan tokens stateless HMAC (signToken con `GITDB_ENCRYPTION_KEY`, TTL 90 días).
Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a
`roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a
diff --git a/CLAUDE.md b/CLAUDE.md
index 139df673..ca3d4170 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -101,7 +101,8 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data
and tool policy mappings.
Current modules include `auth`, `config`, `organization`, `projects`, `storage`,
-`code-report`, `vault`, `audit`, and `alerts`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
+`code-report`, `vault`, `audit`, `alerts`, and `notifications`. The `notifications` module handles
+external email recipient management (domains, verification tokens, unsubscribe tracking). Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
their `index.ts`, not internal layers.
GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage
@@ -117,7 +118,10 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are
`ORIGIN` environment variable pins the application's public origin (e.g., `http://localhost:3000`).
SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host
-header, preventing bypasses when running behind a proxy that rewrites Host headers.
+header, preventing bypasses when running behind a proxy that rewrites Host headers. It is also the
+origin of the absolute links in emails (`absoluteUrl()`); only under `vite dev` do those links use
+the origin of the requests the dev server receives instead (`rememberDevOrigin()` in
+`hooks.server.ts`), so they work on port 5173 whatever `ORIGIN` says.
## Domain events
@@ -199,8 +203,39 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- 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`
- (dry runs: never send, never touch the throttle). Project API keys only reach their project.
-
+ (dry runs that never touch the throttle; with `send: true`, `AlertEngine.sendTest()` also emails
+ the recipients a real event would reach, members filtered by cancan and verified externals only,
+ with a `[Test]` subject; needs SMTP and is limited to 5 per caller every 10 minutes, in memory.
+ It also registers the draft's new external addresses, so they get the confirmation email and
+ receive the next test once confirmed, before the alert is saved).
+ Project API keys only reach their project.
+
+- External email recipients (`$modules/notifications`, #99): `recipients.externalEmails` holds
+ normalized addresses outside GitOps. Each address is an `ExternalRecipientEntity` (GitDB
+ `external_recipients`) shared by every alert of the organization: `pending` → `verified` (the
+ owner clicked the confirmation link) → `unsubscribed`, or `blocked` when its domain leaves
+ `allowedExternalEmailDomains` (`notification_settings`, one row per organization, empty by
+ default = no externals; exact domain match, `*.example.com` for subdomains, punycode).
+ `AlertService` rejects not allowed or invalid addresses (`domain_not_allowed`,
+ `invalid_email`) and requires `:notifications:update` to **add** addresses
+ (`forbidden_external`; keeping or removing existing ones does not need it); after the save,
+ `register()` creates them as pending and emails `external-recipient-verify` directly through
+ `notify()` (token in the link: random, stored hashed, 7 days, single use, rate limited 3/h per
+ address and 30/h per organization, per process). The engine sends to `deliverable()` addresses
+ only: verified, allowed domain and with an unsubscribe link, so nothing goes to externals
+ without `ORIGIN`. They skip the cancan filter (no account) and never get system notifications.
+ Their email is the reduced `alert` template: no `sensitive` catalog fields, no links into the
+ app, an unsubscribe footer link and a `List-Unsubscribe` header. The unsubscribe link is a
+ stateless HMAC token (`signToken`, `GITDB_ENCRYPTION_KEY`, 90 days) made single use by
+ `unsubscribeVersion`. Public pages `/notifications/verify` and `/notifications/unsubscribe`
+ (allowed without session in `hooks.server.ts`) only act on POST, so mail scanners opening the
+ link change nothing. `List-Unsubscribe-Post` (RFC 8058 one-click) is not sent: providers POST
+ without an `Origin` header and SvelteKit's CSRF check would reject it.
+- `/org//settings/notifications` (`#lib/server/notifications/settings.ts`): allowed domains
+ (read with `organization:settings:read` or `organization:notifications:read`, changed with
+ `organization:settings:update` or `organization:notifications:update`) and the external recipients
+ status (`organization:notifications:read`, resend confirmation with `organization:notifications:update`).
+ Notification channels (#95) will live on this page too.
- UI: `/org//settings/alerts` and `/org//projects//settings/alerts` (list, `new`,
`[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`,
`test`, `toggle`, `delete`; everything works without JavaScript). Components live in
@@ -258,7 +293,7 @@ return { roles, canCreate };
The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and
passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions:
- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
-- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`
+- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`, `organization:notifications:read`
This ensures the UI only displays navigation items for sections the user has permission to view.
@@ -267,12 +302,14 @@ Permissions always include their scope as a prefix (e.g., `organization:projects
`project:vault:secrets:all`) and are stored verbatim—there is no scope-stripping transformation:
- **GitOps Admin** (`cluster-admin`) — grants vault, openreport, stateiac full access
- **GitOps User** (`cluster-user`) — no inherent permissions; base role for system-level access
-- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts
+- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts, notifications
- **Organization Developer** — read/create/update projects only
-- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
+- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts, notifications; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts
- **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
+`organization:notifications:read` and `organization:notifications:update` gate external email recipient management in settings.
+
Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module.
Organization-level permissions cascade into their projects only when no explicit project-level assignment exists
@@ -292,6 +329,11 @@ Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; `
resolves them into `locals.apiKey` and `cancanService.canApiKey()` confines a project key to its
own project.
+Unauthenticated public routes for external alert recipients: `/notifications/verify` and
+`/notifications/unsubscribe` accept POST requests with HMAC tokens (verifying confirmations and
+one-click unsubscribes). These are allowed without a session in `hooks.server.ts` and validate
+their tokens rather than checking permissions.
+
`locals.user.role` is a session role object, not the string `admin`. Use `isAdmin()` or the `can*`
helpers. Keep authorization tests beside changes to permission behavior.
diff --git a/README.md b/README.md
index 0edcac19..6752db2d 100644
--- a/README.md
+++ b/README.md
@@ -137,7 +137,8 @@ vulnerabilities*.
*greater than* `0`.
4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most.
5. **Test alert** shows whether an example event matches and who would get the email, without
- sending anything. Then **Create alert**.
+ sending anything. **Send test email** also emails those recipients with an example event and a
+ `[Test]` subject (external addresses only once confirmed). Then **Create alert**.
The same alert through the API (`gvs_` project keys only manage alerts of their own project):
@@ -163,6 +164,24 @@ 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.
+#### External email recipients
+
+Alerts can also email people without a GitOps account (a vendor, an on-call mailbox):
+
+1. In the organization's **Settings → Notifications**, list the allowed domains (needs
+ `organization:settings:update`). `partner.com` matches only that domain; use `*.partner.com`
+ for its subdomains. The list is empty by default, which means no external recipients.
+2. In the alert editor, add the addresses under **External emails** (needs
+ `organization:notifications:update` or `project:notifications:update`). The API takes them in
+ `recipients.externalEmails`.
+3. Each new address gets a confirmation email and receives nothing until its owner confirms. Every
+ alert email carries a one-click unsubscribe link.
+
+External recipients are not checked against GitOps permissions, so their emails leave out
+sensitive fields and links into the app. Removing a domain blocks its addresses without deleting
+them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and
+unsubscribe links can't be built and nothing is sent to external addresses.
+
### Email
Invitations, password resets, alerts and access notices are sent by SMTP:
diff --git a/src/hooks.server.ts b/src/hooks.server.ts
index b5555e6f..6315aa9e 100644
--- a/src/hooks.server.ts
+++ b/src/hooks.server.ts
@@ -6,13 +6,10 @@ import { projectService } from '#modules/projects';
import { registerAlertEngine } from '#modules/alerts';
import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap';
import { startGitDb } from '#lib/server/gitdb';
-import {
- getServerReadyState,
- markServerFailed,
- markServerReady,
-} from '#lib/server/server-ready';
+import { getServerReadyState, markServerFailed, markServerReady } from '#lib/server/server-ready';
import { renderStartingPage } from '#lib/server/starting-page';
import { runWithActor } from '#lib/server/request-context';
+import { rememberDevOrigin } from '#lib/server/infra/notifications';
import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger';
const startupLog = createLogger('startup');
@@ -60,6 +57,8 @@ const requestLogger: Handle = async ({ event, resolve }) => {
const authGuard: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname;
+ // dev only: email links use the port the dev server really answers on, whatever ORIGIN says
+ if (import.meta.env.DEV) rememberDevOrigin(event.url.origin);
const isApiRequest = pathname.startsWith('/api/');
if (pathname === '/health') {
@@ -115,9 +114,12 @@ const authGuard: Handle = async ({ event, resolve }) => {
return new Response(null, { status: 308, headers: { location } });
}
- // sign-in, sign-out, self-registration, password recovery, invitation acceptance and the Google
- // SSO round trip must work without (or with a broken) session; each route re-checks what it needs
+ // sign-in, sign-out, self-registration, password recovery, invitation acceptance, the Google
+ // SSO round trip and the links emailed to external alert recipients (who have no account) must
+ // work without (or with a broken) session; each route re-checks what it needs (its token)
if (
+ pathname === '/notifications/verify' ||
+ pathname === '/notifications/unsubscribe' ||
pathname === '/auth/login' ||
pathname === '/auth/sso/google/start' ||
pathname === '/auth/sso/google/callback' ||
diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts
index c38c820c..b01822f2 100644
--- a/src/lib/alerts/summary.ts
+++ b/src/lib/alerts/summary.ts
@@ -63,7 +63,7 @@ export function summarizeConditions(
/** "2 usuarios · Project Admin" */
export function summarizeRecipients(
- recipients: { userIds: string[]; roleIds: string[] },
+ recipients: { userIds: string[]; roleIds: string[]; externalEmails?: string[] },
users: AlertOption[],
roles: AlertOption[],
t: Translate,
@@ -71,6 +71,7 @@ export function summarizeRecipients(
const names = [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
+ ...(recipients.externalEmails ?? []),
];
return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients');
}
diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts
index c552527c..edb1243f 100644
--- a/src/lib/alerts/types.ts
+++ b/src/lib/alerts/types.ts
@@ -33,10 +33,22 @@ export type AlertDraft = {
eventType: string;
match: 'all' | 'any';
conditions: DraftCondition[];
- recipients: { userIds: string[]; roleIds: string[] };
+ recipients: { userIds: string[]; roleIds: string[]; externalEmails: string[] };
throttleMinutes: number;
};
+/** External email recipients as the editor needs them. */
+export type ExternalRecipientsEditorData = {
+ /** `:notifications:update`: needed to add addresses. */
+ canManage: boolean;
+ /** Allowed domains of the organization; empty = external recipients are off. */
+ allowedDomains: string[];
+ /** Status of the alert's current addresses (`pending`, `verified`…). */
+ statuses: Record;
+ /** Where the allowed domains are managed, when the user can open it. */
+ settingsPath: string | null;
+};
+
type Shared = {
basePath: string;
scope: AlertScope;
@@ -61,6 +73,7 @@ export type AlertListData = Shared & {
export type AlertEditorData = Shared & {
alertId: string | null;
draft: AlertDraft;
+ external: ExternalRecipientsEditorData;
canSave: boolean;
canDelete: boolean;
};
@@ -69,6 +82,9 @@ export type AlertTestView = {
matched: boolean;
recipients: Array<{ userId: string; username: string }>;
deniedCount: number;
+ external: Array<{ email: string; status: string; delivers: boolean }>;
+ /** Present when a real test email was sent. */
+ delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte
index 6296d268..3095f1ab 100644
--- a/src/lib/components/AppSidebar.svelte
+++ b/src/lib/components/AppSidebar.svelte
@@ -3,6 +3,7 @@
import {
Activity,
BellRing,
+ Mail,
BarChart3,
Building2,
ChevronDown,
@@ -50,6 +51,7 @@
export let canReadOrgAudit = false;
export let canReadOrgEvents = false;
export let canReadOrganizationAlerts = false;
+ export let canReadOrgNotifications = false;
export let canReadProjectInfo = false;
export let canReadProjectUsers = false;
export let canReadProjectRoles = false;
@@ -325,6 +327,12 @@
icon: BellRing,
visible: canReadOrganizationAlerts,
},
+ {
+ label: $_('sidebar.items.notifications'),
+ href: `/org/${organizationSlug}/settings/notifications`,
+ icon: Mail,
+ visible: canReadOrgNotifications,
+ },
]
.filter((item) => item.visible)
.map(({ visible, ...item }) => item);
@@ -401,14 +409,14 @@
),
) as Record;
- function isItemActive(href: string) {
- return currentPath.startsWith(href);
- }
+ // reactive declarations, not plain functions: the template calls them with `item` / `navModule`
+ // only, so a plain function would keep the active state of the first rendered page after a
+ // client-side navigation. Reassigning them when `currentPath` changes re-renders every call
+ $: isItemActive = (href: string) => currentPath.startsWith(href);
- function isModuleActive(navModule: NavModule) {
- if (navModule.base && currentPath.startsWith(navModule.base)) return true;
- return navModule.items.some((item) => isItemActive(item.href));
- }
+ $: isModuleActive = (navModule: NavModule) =>
+ (navModule.base ? currentPath.startsWith(navModule.base) : false) ||
+ navModule.items.some((item) => isItemActive(item.href));
function toggleModule(navModule: NavModule) {
openModules = { ...openModules, [navModule.name]: !moduleOpenState[navModule.name] };
diff --git a/src/lib/components/NotificationLinkPage.svelte b/src/lib/components/NotificationLinkPage.svelte
new file mode 100644
index 00000000..d658f498
--- /dev/null
+++ b/src/lib/components/NotificationLinkPage.svelte
@@ -0,0 +1,86 @@
+
+
+
+ {$_(`${base}.title`)} - GitOps
+
+
+
+
+
+
+
+
+ {#if kind === 'verify'}
+
+ {:else}
+
+ {/if}
+
+
{$_(`${base}.title`)}
+
+ {#if link.state === 'ready'}
+
+ {$_(`${base}.question`, {
+ values: { email: link.email, organization: link.organization },
+ })}
+
+
+ {:else if link.state === 'done'}
+
+ {$_(`${base}.done`, {
+ values: { email: link.email, organization: link.organization },
+ })}
+
+ {:else}
+
+ {$_(`notifications.link.${link.state}`)}
+
+ {/if}
+
+
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte
index f63a2e3d..e21278a9 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -2,8 +2,18 @@
import { untrack } from 'svelte';
import { enhance } from '$app/forms';
import type { SubmitFunction } from '$app/forms';
- import { ArrowLeft, FlaskConical, Info, MailWarning, Save, Trash2 } from '@lucide/svelte';
+ import {
+ ArrowLeft,
+ FlaskConical,
+ Info,
+ Send,
+ MailWarning,
+ Save,
+ ShieldAlert,
+ Trash2,
+ } from '@lucide/svelte';
import { _ } from '#lib/i18n';
+ import { statusBadgeClass } from '#lib/notifications/status';
import type {
AlertEditorData,
AlertFormResult,
@@ -29,7 +39,7 @@
let message = $state(initial.message);
let test = $state(initial.test);
let droppedConditions = $state(0);
- let busy = $state<'save' | 'test' | null>(null);
+ let busy = $state<'save' | 'test' | 'send' | null>(null);
let sampleProjectId = $state('');
let definition = $derived(data.catalog.find((entry) => entry.type === draft.eventType));
@@ -45,6 +55,26 @@
data.scope === 'organization' && definition?.scope === 'project',
);
let projects = $derived(data.referenceOptions.project ?? []);
+ let externalText = $state(untrack(() => draft.recipients.externalEmails.join('\n')));
+ let externalEnabled = $derived(
+ data.external.allowedDomains.length > 0 || draft.recipients.externalEmails.length > 0,
+ );
+ let externalErrors = $derived(
+ Object.entries(errors)
+ .filter(([key]) => /^recipients\.externalEmails\.\d+$/.test(key))
+ .map(([key, code]) => ({
+ email: draft.recipients.externalEmails[Number(key.split('.').pop())] ?? '',
+ code,
+ })),
+ );
+
+ function updateExternal(text: string) {
+ externalText = text;
+ draft.recipients.externalEmails = text
+ .split(/[\n,;]+/)
+ .map((value) => value.trim())
+ .filter(Boolean);
+ }
function compatible(entry: CatalogEntry | undefined, condition: DraftCondition) {
const field = entry?.fields.find((candidate) => candidate.key === condition.field);
@@ -64,17 +94,24 @@
return errors[key] ? $_(`alerts.errors.${errors[key]}`) : '';
}
- const submit: SubmitFunction = ({ action }) => {
+ // operation errors without field errors come as codes (`mail_not_configured`…)
+ const OPERATION_ERRORS = ['mail_not_configured', 'test_rate_limited'];
+
+ const submit: SubmitFunction = ({ action, submitter }) => {
+ const sending = submitter?.getAttribute('name') === 'send';
const intent = action.search.includes('test') ? 'test' : 'save';
- busy = intent;
+ busy = sending ? 'send' : intent;
message = '';
return async ({ result, update }) => {
busy = null;
if (result.type === 'failure') {
errors = (result.data?.errors as Record) ?? {};
+ const code = String(result.data?.error ?? '');
message = result.data?.errors
? $_('alerts.editor.fixErrors')
- : String(result.data?.error ?? '');
+ : OPERATION_ERRORS.includes(code)
+ ? $_(`alerts.errors.${code}`)
+ : code;
if (intent === 'test') test = null;
return;
}
@@ -302,6 +339,75 @@
{/if}
+
+
+ {$_('alerts.editor.externalEmails')}
+
+ {#if externalEnabled}
+
+
+ {$_('alerts.editor.externalNotice')}
+
+
+
+ {#if data.external.canManage}
+ {$_('alerts.editor.externalHelp', {
+ values: {
+ domains: data.external.allowedDomains.join(', ') || '—',
+ },
+ })}
+ {:else}
+ {$_('alerts.editor.externalReadonly')}
+ {/if}
+
+ {#if errors['recipients.externalEmails']}
+
+ {#if externalErrors.length > 0}
+
+ {#each externalErrors as failure (failure.email + failure.code)}
+ {failure.email}: {$_(`alerts.errors.${failure.code}`)}
+ {/each}
+
+ {:else}
+ {errorFor('recipients.externalEmails')}
+ {/if}
+
+ {/if}
+ {#if Object.keys(data.external.statuses).length > 0}
+
+ {#each Object.entries(data.external.statuses) as [email, status] (email)}
+
+ {email} · {$_(`notifications.status.${status}`)}
+
+ {/each}
+
+ {/if}
+ {:else}
+
+ {$_('alerts.editor.externalDisabled')}
+ {#if data.external.settingsPath}
+
+ {$_('alerts.editor.externalSettingsLink')}
+
+ {/if}
+
+ {/if}
+
+
{$_('alerts.editor.channels')}
@@ -394,12 +500,35 @@
{:else}
{$_('alerts.test.noRecipients')}
{/if}
+ {#if test.external.length > 0}
+
+ {#each test.external as recipient (recipient.email)}
+
+ {recipient.email}: {recipient.delivers
+ ? $_('alerts.test.externalDelivers')
+ : test.delivery && recipient.status === 'pending'
+ ? $_('alerts.test.externalVerificationSent')
+ : $_('alerts.test.externalSkipped', {
+ values: { status: $_(`notifications.status.${recipient.status}`) },
+ })}
+
+ {/each}
+
+ {/if}
{#if test.deniedCount > 0}
{$_('alerts.test.denied', { values: { count: test.deniedCount } })}
{/if}
- {$_('alerts.test.nothingSent')}
+ {#if test.delivery}
+
+ {$_('alerts.test.delivered', {
+ values: { sent: test.delivery.sent, failed: test.delivery.failed },
+ })}
+
+ {:else}
+ {$_('alerts.test.nothingSent')}
+ {/if}
{/if}
@@ -414,6 +543,19 @@
{$_('alerts.editor.test')}
+
+
+ {busy === 'send' ? $_('alerts.editor.sendingTest') : $_('alerts.editor.sendTest')}
+
/settings/notifications): external
+ // email recipients of alerts today, chat and webhook channels later (#82)
+ notifications: {
+ resource: 'notifications',
+ permissions: grantsFor('organization', 'notifications'),
+ },
},
},
project: {
@@ -96,6 +102,11 @@ const permissions = {
resource: 'alerts',
permissions: grantsFor('project', 'alerts'),
},
+ // notification delivery of one project: external email recipients of its alerts
+ notifications: {
+ resource: 'notifications',
+ permissions: grantsFor('project', 'notifications'),
+ },
modules: {
resource: 'modules',
sections: {
diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts
index 61cfbfc8..bf8a8f66 100644
--- a/src/lib/database/schemas.ts
+++ b/src/lib/database/schemas.ts
@@ -306,6 +306,46 @@ export const AlertEntity = entity('alerts', {
.$defaultFn(() => new Date().toISOString()),
});
+// notification delivery settings of one organization (#99), one row per organization;
+// `allowedExternalEmailDomains` empty = alerts cannot email addresses outside GitOps
+export const NotificationSettingsEntity = entity('notification_settings', {
+ id: uuid().primaryKey(),
+ organizationId: uuid().notNull(),
+ allowedExternalEmailDomains: json()
+ .notNull()
+ .$defaultFn(() => []),
+ createdAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ updatedAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+});
+
+// an email address outside GitOps that alerts of an organization may send to (#99), shared by
+// all its alerts. It only receives once `verified`; the verification token is stored hashed
+export const ExternalRecipientEntity = entity('external_recipients', {
+ id: uuid().primaryKey(),
+ organizationId: uuid().notNull(),
+ email: text().notNull(),
+ status: text().notNull().default('pending'),
+ verifiedAt: timestamp(),
+ unsubscribedAt: timestamp(),
+ blockedAt: timestamp(),
+ verificationTokenHash: text(),
+ verificationExpiresAt: timestamp(),
+ lastVerificationSentAt: timestamp(),
+ // bumped on unsubscribe: unsubscribe links issued before stop working (single use)
+ unsubscribeVersion: integer().notNull().default(0),
+ createdByUserId: uuid().notNull(),
+ createdAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ updatedAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+});
+
relations.for(ProjectEntity, ({ one, many }) => ({
roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }),
organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }),
diff --git a/src/lib/events/catalog/code-report.events.ts b/src/lib/events/catalog/code-report.events.ts
index be3cb18a..422f6d21 100644
--- a/src/lib/events/catalog/code-report.events.ts
+++ b/src/lib/events/catalog/code-report.events.ts
@@ -77,6 +77,17 @@ export const codeReportEvents: EventDefinitions<
> = {
[COMPLETED]: {
mailTemplate: 'alert-code-report-analysis',
+ samplePayload: {
+ analysisId: 'sample-analysis',
+ gitInfo: { repositoryUrl: null, branch: 'main', commit: '0123456789abcdef', version: null },
+ summary: { critical: 1, high: 2, medium: 3, low: 4, unknown: 0, total: 10, secrets: 0 },
+ policies: {
+ status: 'compliant',
+ totalViolations: 0,
+ blockingFailures: 0,
+ failedPolicyIds: [],
+ },
+ },
link: (context) => projectPath(context, `/code-report/history/${context.payload.analysisId}`),
mailSummary: ({ summary }) =>
summary.total === 0
diff --git a/src/lib/events/catalog/types.ts b/src/lib/events/catalog/types.ts
index d916e1e8..93ebcf12 100644
--- a/src/lib/events/catalog/types.ts
+++ b/src/lib/events/catalog/types.ts
@@ -61,6 +61,8 @@ type FieldCommon = {
options?: readonly { value: string; label: string }[];
/** For `reference` fields: the UI lists these entities in the alert's scope; the id is stored. */
reference?: FieldReference;
+ /** Left out of alert emails to external recipients (people without a GitOps account). */
+ sensitive?: boolean;
};
/**
@@ -100,6 +102,8 @@ export type EventDefinition = {
link?: (context: EventLinkContext) => string | null;
/** Short summary for the email subject (`3 critical, 5 high`); the event label otherwise. */
mailSummary?: (payload: DomainEventMap[K]) => EventMessage;
+ /** Realistic example payload for test emails; typed placeholders fill the rest of the fields. */
+ samplePayload?: Partial;
};
/** Definitions for a subset of events (one module's file). */
diff --git a/src/lib/events/catalog/vault.events.ts b/src/lib/events/catalog/vault.events.ts
index 79bbf064..d3081999 100644
--- a/src/lib/events/catalog/vault.events.ts
+++ b/src/lib/events/catalog/vault.events.ts
@@ -19,7 +19,14 @@ type EnvironmentEvent = typeof ENVIRONMENT_CREATED | typeof ENVIRONMENT_DELETED;
function secretFields(type: K) {
return [
- { key: 'key', label: fieldLabel(type, 'key'), type: 'string', operators: OPERATORS.string },
+ // secret names and paths describe the infrastructure: never sent outside GitOps
+ {
+ key: 'key',
+ label: fieldLabel(type, 'key'),
+ type: 'string',
+ operators: OPERATORS.string,
+ sensitive: true,
+ },
{
key: 'environmentIds',
label: fieldLabel(type, 'environmentIds'),
@@ -32,6 +39,7 @@ function secretFields(type: K) {
label: fieldLabel(type, 'folderPath'),
type: 'string',
operators: OPERATORS.string,
+ sensitive: true,
},
] as const;
}
@@ -106,6 +114,7 @@ export const vaultEvents: EventDefinitions = {
+ verified: 'border-emerald-200 bg-emerald-50 text-emerald-800',
+ pending: 'border-amber-200 bg-amber-50 text-amber-800',
+ unsubscribed: 'border-red-200 bg-red-50 text-red-700',
+ blocked: 'border-slate-300 bg-slate-100 text-slate-600',
+};
+
+export function statusBadgeClass(status: string): string {
+ return STATUS_BADGE[status] ?? 'border-slate-200 bg-slate-50 text-slate-600';
+}
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
new file mode 100644
index 00000000..cd358c49
--- /dev/null
+++ b/src/lib/notifications/types.ts
@@ -0,0 +1,4 @@
+/** What the public verify / unsubscribe pages show. The token itself is never echoed. */
+export type NotificationLinkState =
+ | { state: 'ready' | 'done'; email: string; organization: string }
+ | { state: 'invalid' | 'expired' };
diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts
index 128bc4bf..dddd9246 100644
--- a/src/lib/server/alerts/operations.ts
+++ b/src/lib/server/alerts/operations.ts
@@ -13,11 +13,14 @@ import {
alertEngine,
alertService,
buildSampleEvent,
+ isMailConfigured,
type AlertInput,
type AlertLocation,
type AlertRow,
} from '#modules/alerts';
import type { CatalogEntry } from '#lib/alerts/types';
+import type { AnyDomainEvent } from '#lib/server/events';
+import { RateLimiter } from '#lib/server/infra/rate-limit';
import { actorFor, callerCan, canManageAlerts, contextOf, type AlertLocals } from './access';
export type { CatalogEntry };
@@ -169,28 +172,68 @@ export async function deleteAlert(
/** `payload` overrides the invented sample; `sampleProjectId` picks the project of a project event
* for an organization alert. */
-export type AlertTestInput = { payload?: unknown; sampleProjectId?: unknown };
+export type AlertTestInput = {
+ payload?: unknown;
+ sampleProjectId?: unknown;
+ /** The alert being edited, when the draft comes from its editor. */
+ alertId?: unknown;
+ /** `true`: also email the alert's recipients about the example event. */
+ send?: unknown;
+};
+
+/** Real test emails per caller: enough to iterate on an alert, not to spam its recipients. */
+const TEST_SEND_LIMIT = { limit: 5, windowMs: 10 * 60 * 1000 };
+const TEST_LIMITER_KEY = Symbol.for('gitops.alerts.test-send-limiter');
+const testSendLimiter = ((globalThis as typeof globalThis & { [TEST_LIMITER_KEY]?: RateLimiter })[
+ TEST_LIMITER_KEY
+] ??= new RateLimiter(TEST_SEND_LIMIT));
export type AlertTestResult = {
matched: boolean;
recipients: Array<{ userId: string; username: string }>;
/** Selected users left out because they can't read the event. */
deniedCount: number;
+ /** External addresses, their status and whether they would get the email. */
+ external: Array<{ email: string; status: string; delivers: boolean }>;
+ /** Only when `send` was asked: emails really sent and failed. */
+ delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
/**
- * Evaluates an alert against an example event and tells who would receive it. Nothing is sent and
- * the throttle is not touched.
+ * Evaluates an alert against an example event and tells who would receive it. With `send: true`
+ * it also emails them (same rules as a real event, `[Test]` subject), rate limited per caller.
+ * The throttle is never touched.
*/
async function dryRun(
+ locals: AlertLocals,
alert: Pick<
AlertDomain,
- 'eventType' | 'scope' | 'conditions' | 'match' | 'recipients' | 'location' | 'appliesTo'
+ | 'id'
+ | 'name'
+ | 'description'
+ | 'organizationId'
+ | 'eventType'
+ | 'scope'
+ | 'conditions'
+ | 'match'
+ | 'recipients'
+ | 'location'
+ | 'appliesTo'
>,
input: AlertTestInput,
): Promise> {
if (!isEventType(alert.eventType)) return { ok: false, status: 400, error: 'Unknown event type' };
+ const send = input.send === true || input.send === 'true';
+ const actor = actorFor(locals);
+ if (send) {
+ if (!isMailConfigured()) {
+ return { ok: false, status: 409, error: 'mail_not_configured' };
+ }
+ if (!actor || !testSendLimiter.consume(actor.userId).allowed) {
+ return { ok: false, status: 429, error: 'test_rate_limited' };
+ }
+ }
const definition = getEventDefinition(alert.eventType) as EventDefinition;
const location = alert.location;
@@ -201,6 +244,8 @@ async function dryRun(
? (input.payload as Record)
: undefined;
const sample = buildSampleEvent(definition, alert, {
+ // a real email needs a full payload: summaries and templates read fields no condition sets
+ complete: send,
payload: payloadOverride,
projectId: requestedProjectId,
});
@@ -220,12 +265,30 @@ async function dryRun(
projectId = sample.projectId;
}
+ // sending a test asks unconfirmed external addresses to confirm (they never get alert content
+ // before that); once confirmed, the next test reaches them. Validation already required
+ // `:notifications:update` for addresses the alert didn't have
+ if (send && actor && alert.recipients.externalEmails.length > 0) {
+ await alertService.registerExternal(location, alert.recipients.externalEmails, actor);
+ }
+
const result = await alertEngine.dryRun(alert, {
type: alert.eventType,
payload: sample.payload as never,
scope: { organizationId: location.organizationId, projectId },
});
+ const delivery = send
+ ? await alertEngine.sendTest(alert, {
+ id: `test-${crypto.randomUUID()}`,
+ type: alert.eventType,
+ occurredAt: new Date().toISOString(),
+ actor: actor ? { kind: 'user', userId: actor.userId } : { kind: 'system' },
+ scope: { organizationId: location.organizationId, projectId },
+ payload: sample.payload,
+ } as AnyDomainEvent)
+ : undefined;
+
return {
ok: true,
status: 200,
@@ -233,6 +296,8 @@ async function dryRun(
matched: result.matched,
recipients: result.recipients.map(({ userId, username }) => ({ userId, username })),
deniedCount: result.denied.length,
+ external: result.external,
+ ...(delivery ? { delivery } : {}),
event: { type: alert.eventType, payload: sample.payload, projectId },
},
};
@@ -245,7 +310,7 @@ export async function testAlert(
): Promise> {
const loaded = await loadAuthorized(locals, id, 'update');
if (!loaded.ok) return loaded;
- return dryRun(loaded.data, input);
+ return dryRun(locals, loaded.data, input);
}
/** "Test alert" before saving: validates the draft and dry-runs it. */
@@ -260,10 +325,25 @@ export async function testDraftAlert(
if (!canWrite) return forbidden;
const actor = actorFor(locals);
if (!actor) return forbidden;
+ // testing an edited alert must not need `notifications:update` for the addresses it already has
+ const existing =
+ typeof input.alertId === 'string' && input.alertId
+ ? await alertService.get(input.alertId).catch(() => null)
+ : null;
+ const sameLocation =
+ existing &&
+ existing.organizationId === location.organizationId &&
+ existing.projectId === location.projectId;
+ const previousExternal = sameLocation ? existing.recipients.externalEmails : [];
try {
- const fields = await alertService.validate(location, input, actor);
- const draft = new AlertDomain({ id: 'draft', ...location, ...fields });
- return dryRun(draft, input);
+ const fields = await alertService.validate(location, input, actor, previousExternal);
+ // the stored id keeps the email's "manage the alert" link working
+ const draft = new AlertDomain({
+ id: sameLocation ? existing.id : 'draft',
+ ...location,
+ ...fields,
+ });
+ return dryRun(locals, draft, input);
} catch (error) {
return failure(error);
}
diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts
index 38938202..f3d31d52 100644
--- a/src/lib/server/alerts/page.ts
+++ b/src/lib/server/alerts/page.ts
@@ -6,6 +6,7 @@ import {
type AlertLocation,
type AlertRow,
} from '#modules/alerts';
+import { externalRecipientService, notificationSettingsService } from '#modules/notifications';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import {
@@ -22,7 +23,7 @@ import type {
AlertOption,
DraftCondition,
} from '#lib/alerts/types';
-import { canManageAlerts, type AlertLocals } from './access';
+import { callerCan, canManageAlerts, contextOf, type AlertLocals } from './access';
import {
createAlert,
deleteAlert,
@@ -154,7 +155,7 @@ function emptyDraft(eventType: string | null): AlertDraft {
eventType: eventType ?? '',
match: 'all',
conditions: [],
- recipients: { userIds: [], roleIds: [] },
+ recipients: { userIds: [], roleIds: [], externalEmails: [] },
throttleMinutes: 0,
};
}
@@ -171,11 +172,42 @@ function toDraft(alert: AlertRow): AlertDraft {
operator: condition.operator,
value: condition.value === undefined ? '' : condition.value,
})),
- recipients: { ...alert.recipients },
+ recipients: {
+ userIds: [...alert.recipients.userIds],
+ roleIds: [...alert.recipients.roleIds],
+ externalEmails: [...alert.recipients.externalEmails],
+ },
throttleMinutes: alert.throttleMinutes,
};
}
+async function externalRecipientsData(
+ locals: AlertLocals,
+ location: AlertLocation,
+ emails: string[],
+) {
+ const organizationContext = {
+ scope: 'organization' as const,
+ organizationId: location.organizationId,
+ };
+ const [canManage, settings, statuses, canOpenSettings, organization] = await Promise.all([
+ callerCan(locals, `${location.scope}:notifications:update`, contextOf(location)),
+ notificationSettingsService.get(location.organizationId).catch(() => null),
+ externalRecipientService
+ .statuses(location.organizationId, emails)
+ .catch(() => new Map()),
+ callerCan(locals, 'organization:notifications:read', organizationContext),
+ organizationService.getOrganization(location.organizationId).catch(() => null),
+ ]);
+ return {
+ canManage,
+ allowedDomains: settings?.allowedExternalEmailDomains ?? [],
+ statuses: Object.fromEntries(statuses),
+ settingsPath:
+ canOpenSettings && organization ? `/org/${organization.slug}/settings/notifications` : null,
+ };
+}
+
export async function loadAlertEditor(
locals: AlertLocals,
context: AlertPageContext,
@@ -199,9 +231,10 @@ export async function loadAlertEditor(
}
const catalog = await listCatalog(locals, location);
- const [references, recipients] = await Promise.all([
+ const [references, recipients, external] = await Promise.all([
referenceOptions(catalog, location),
recipientOptions(location),
+ externalRecipientsData(locals, location, alert?.recipients.externalEmails ?? []),
]);
const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null);
@@ -218,6 +251,7 @@ export async function loadAlertEditor(
referenceOptions: references,
users: recipients.users,
roles: recipients.roles,
+ external,
mailConfigured: isMailConfigured(),
canSave: alert ? allowed.canUpdate : allowed.canCreate,
canDelete: Boolean(alert) && allowed.canDelete,
@@ -261,6 +295,12 @@ export function parseAlertForm(form: FormData): AlertDraft {
recipients: {
userIds: form.getAll('userIds').map(String),
roleIds: form.getAll('roleIds').map(String),
+ // one address per line (or separated by commas) in a textarea; empty lines dropped
+ externalEmails: form
+ .getAll('externalEmails')
+ .flatMap((value) => String(value).split(/[\n,;]+/))
+ .map((value) => value.trim())
+ .filter(Boolean),
},
throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0,
};
@@ -335,6 +375,9 @@ export function alertActions(
const result = await testDraftAlert(event.locals, context.location, {
...toInput(draft),
sampleProjectId,
+ alertId: String(form.get('alertId') ?? '') || undefined,
+ // the "send test email" button posts `send=true`; "test alert" only dry-runs
+ send: form.get('send') === 'true',
});
if (!result.ok) {
return fail(result.status, { draft, error: result.error, errors: result.errors ?? {} });
diff --git a/src/lib/server/infra/notifications/config.test.ts b/src/lib/server/infra/notifications/config.test.ts
index 0ac5e014..9005a69f 100644
--- a/src/lib/server/infra/notifications/config.test.ts
+++ b/src/lib/server/infra/notifications/config.test.ts
@@ -1,5 +1,14 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest';
-import { formatSender, isSmtpConfigured, readSmtpConfig, requireSmtpConfig } from './config';
+import {
+ absoluteUrl,
+ formatSender,
+ isSmtpConfigured,
+ readPublicOrigin,
+ readSmtpConfig,
+ rememberDevOrigin,
+ requireSmtpConfig,
+ resetDevOrigin,
+} from './config';
const KEYS = [
'NOTIFICATION_SMTP_HOST',
@@ -121,3 +130,29 @@ describe('formatSender', () => {
expect(formatSender(requireSmtpConfig())).toBe('GitOps ');
});
});
+
+describe('public origin of email links', () => {
+ const previous = process.env.ORIGIN;
+
+ afterEach(() => {
+ resetDevOrigin();
+ if (previous === undefined) delete process.env.ORIGIN;
+ else process.env.ORIGIN = previous;
+ });
+
+ it('uses ORIGIN without a trailing slash', () => {
+ process.env.ORIGIN = 'http://localhost:3000/';
+ expect(readPublicOrigin()).toBe('http://localhost:3000');
+ expect(absoluteUrl('/notifications/verify?token=t')).toBe(
+ 'http://localhost:3000/notifications/verify?token=t',
+ );
+ });
+
+ it('prefers the origin the dev server is really served from', () => {
+ process.env.ORIGIN = 'http://localhost:3000';
+ rememberDevOrigin('http://localhost:5173');
+ expect(absoluteUrl('/notifications/verify?token=t')).toBe(
+ 'http://localhost:5173/notifications/verify?token=t',
+ );
+ });
+});
diff --git a/src/lib/server/infra/notifications/config.ts b/src/lib/server/infra/notifications/config.ts
index 4fabfa6e..1fd451c8 100644
--- a/src/lib/server/infra/notifications/config.ts
+++ b/src/lib/server/infra/notifications/config.ts
@@ -74,12 +74,34 @@ export function formatSender(config: SmtpConfig): string {
return config.fromName ? `${config.fromName} <${config.from}>` : config.from;
}
+const DEV_ORIGIN_KEY = Symbol.for('gitops.notifications.dev-origin');
+type GlobalWithDevOrigin = typeof globalThis & { [DEV_ORIGIN_KEY]?: string };
+
+/**
+ * Development only (`vite dev`): remembers the origin the app is really served from (e.g.
+ * `http://localhost:5173`), so email links work even when `ORIGIN` points at another port. Called
+ * by `hooks.server.ts` on every request; a no-op in production builds.
+ */
+export function rememberDevOrigin(origin: string): void {
+ if (!import.meta.env.DEV) return;
+ (globalThis as GlobalWithDevOrigin)[DEV_ORIGIN_KEY] = origin;
+}
+
+export function resetDevOrigin(): void {
+ delete (globalThis as GlobalWithDevOrigin)[DEV_ORIGIN_KEY];
+}
+
/**
* Public origin used for absolute links in emails (`ORIGIN`, e.g. `https://gitops.example.com`),
* without a trailing slash. `null` when unset or not an http(s) URL: emails then go without links.
+ * In development the origin of the requests the dev server receives wins; in production only
+ * `ORIGIN` counts, never the `Host` header (it would let a request put its own host in emails).
*/
export function readPublicOrigin(): string | null {
- const raw = value('ORIGIN');
+ const devOrigin = import.meta.env.DEV
+ ? (globalThis as GlobalWithDevOrigin)[DEV_ORIGIN_KEY]
+ : undefined;
+ const raw = devOrigin ?? value('ORIGIN');
if (!raw) return null;
try {
const url = new URL(raw);
diff --git a/src/lib/server/infra/notifications/email-parts.ts b/src/lib/server/infra/notifications/email-parts.ts
new file mode 100644
index 00000000..8963b702
--- /dev/null
+++ b/src/lib/server/infra/notifications/email-parts.ts
@@ -0,0 +1,21 @@
+import { renderTemplateString } from './template';
+
+// internally generated HTML snippets for `{{{ }}}` slots: every value goes through `{{ }}`
+
+/** Centered call-to-action button; empty without a URL (no `ORIGIN`). */
+export function emailButton(url: string | null, label: string): string {
+ if (!url) return '';
+ return renderTemplateString(
+ '{{ label }}
',
+ { url, label },
+ );
+}
+
+/** Grey side note; empty for an empty text. */
+export function emailNote(text: string): string {
+ if (!text) return '';
+ return renderTemplateString(
+ '{{ text }}
',
+ { text },
+ );
+}
diff --git a/src/lib/server/infra/notifications/i18n.ts b/src/lib/server/infra/notifications/i18n.ts
new file mode 100644
index 00000000..9704c06c
--- /dev/null
+++ b/src/lib/server/infra/notifications/i18n.ts
@@ -0,0 +1,32 @@
+import * as messages from '#lib/paraglide/messages.js';
+
+// `#lib/i18n` is client-oriented (stores, `$app/env`): server messages translate with paraglide
+export type MailLocale = 'es' | 'en';
+/** Language of a message when the recipient's is unknown. */
+export const DEFAULT_MAIL_LOCALE: MailLocale = 'en';
+
+type MessageFunction = (
+ values?: Record,
+ options?: { locale?: MailLocale },
+) => string;
+
+export type Translate = (key: string, values?: Record) => string;
+
+/** Server-side translation of an i18n key; unknown keys fall back to the key itself. */
+export function translateKey(
+ id: string,
+ values: Record = {},
+ locale: MailLocale = DEFAULT_MAIL_LOCALE,
+): string {
+ const message = (messages as Record)[id] as MessageFunction | undefined;
+ return message ? message(values, { locale }) : id;
+}
+
+export function mailLocale(value: string | null | undefined): MailLocale {
+ return value === 'es' || value === 'en' ? value : DEFAULT_MAIL_LOCALE;
+}
+
+/** `translateKey` bound to one locale. */
+export function translator(locale: MailLocale): Translate {
+ return (key, values) => translateKey(key, values, locale);
+}
diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts
index c703a27a..50fd0ea3 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -16,11 +16,22 @@ export {
absoluteUrl,
isSmtpConfigured,
readPublicOrigin,
+ rememberDevOrigin,
+ resetDevOrigin,
readSmtpConfig,
requireSmtpConfig,
type SmtpConfig,
} from './config';
export { withRetry, isRetryableMailError, type RetryOptions } from './retry';
+export {
+ DEFAULT_MAIL_LOCALE,
+ mailLocale,
+ translateKey,
+ translator,
+ type MailLocale,
+ type Translate,
+} from './i18n';
+export { emailButton, emailNote } from './email-parts';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
import { createLogger } from '#lib/server/logger';
@@ -29,7 +40,16 @@ import { notify as send } from './notify';
const QUEUE_KEY = Symbol.for('gitops.mail.queue');
const SHUTDOWN_KEY = Symbol.for('gitops.mail.shutdown');
-type GlobalWithQueue = typeof globalThis & { [QUEUE_KEY]?: Queue; [SHUTDOWN_KEY]?: boolean };
+const SEND_KEY = Symbol.for('gitops.mail.send');
+type GlobalWithQueue = typeof globalThis & {
+ [QUEUE_KEY]?: Queue;
+ [SHUTDOWN_KEY]?: boolean;
+ [SEND_KEY]?: typeof send;
+};
+
+// the queue outlives module reloads (dev HMR); it must send with the latest `notify`, whose
+// `instanceof Notification` check matches the classes the current code builds emails with
+(globalThis as GlobalWithQueue)[SEND_KEY] = send;
/**
* Process-wide queue for alert and system emails (3 at a time, 4 attempts with backoff). Kept on
@@ -37,7 +57,7 @@ type GlobalWithQueue = typeof globalThis & { [QUEUE_KEY]?: Queue; [SHUTDOWN_KEY]
* their links carry tokens and are sent directly.
*/
export const mailQueue: Queue = ((globalThis as GlobalWithQueue)[QUEUE_KEY] ??= new Queue({
- send: (notification) => send(notification),
+ send: (notification) => ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification),
concurrency: 3,
logger: createLogger('mail'),
}));
diff --git a/src/lib/server/infra/notifications/mail-notification.test.ts b/src/lib/server/infra/notifications/mail-notification.test.ts
index d5632a01..0ff1a5f5 100644
--- a/src/lib/server/infra/notifications/mail-notification.test.ts
+++ b/src/lib/server/infra/notifications/mail-notification.test.ts
@@ -72,3 +72,30 @@ describe('MailNotification', () => {
});
});
});
+
+describe('MailNotification headers', () => {
+ const base = { to: 'user@example.com', subject: 'Welcome', content: 'Hi
' };
+
+ it('keeps single-line headers', () => {
+ const notification = new MailNotification({
+ ...base,
+ headers: { 'List-Unsubscribe': '' },
+ });
+ expect(() => notification.validate()).not.toThrow();
+ expect(notification.headers).toEqual({
+ 'List-Unsubscribe': '',
+ });
+ });
+
+ it('rejects header injection', () => {
+ expect(() =>
+ new MailNotification({
+ ...base,
+ headers: { 'X-A': 'ok\r\nBcc: evil@example.com' },
+ }).validate(),
+ ).toThrow(/header is not valid/);
+ expect(() => new MailNotification({ ...base, headers: { 'X A': 'ok' } }).validate()).toThrow(
+ /header is not valid/,
+ );
+ });
+});
diff --git a/src/lib/server/infra/notifications/mail-notification.ts b/src/lib/server/infra/notifications/mail-notification.ts
index 41802961..a9587896 100644
--- a/src/lib/server/infra/notifications/mail-notification.ts
+++ b/src/lib/server/infra/notifications/mail-notification.ts
@@ -5,13 +5,18 @@ export type MailNotificationInput = {
subject: string;
/** HTML body, usually produced by `renderTemplate()`. */
content: string;
+ /** Extra headers (`List-Unsubscribe`…); values must be single-line. */
+ headers?: Record;
};
+const HEADER_NAME = /^[A-Za-z0-9-]+$/;
+
export class MailNotification extends Notification {
readonly channel: NotificationChannel = 'mail';
readonly to: string[];
readonly subject: string;
readonly content: string;
+ readonly headers: Record;
constructor(input: MailNotificationInput) {
super();
@@ -20,6 +25,7 @@ export class MailNotification extends Notification {
.filter(Boolean);
this.subject = input.subject?.trim() ?? '';
this.content = input.content ?? '';
+ this.headers = { ...input.headers };
}
validate(): void {
@@ -37,5 +43,11 @@ export class MailNotification extends Notification {
if (!this.content.trim()) {
throw new Error('MailNotification requires a content');
}
+ for (const [name, value] of Object.entries(this.headers)) {
+ // a line break would let a value inject further headers
+ if (!HEADER_NAME.test(name) || /[\r\n]/.test(value)) {
+ throw new Error(`MailNotification header is not valid: ${name}`);
+ }
+ }
}
}
diff --git a/src/lib/server/infra/notifications/mail-queue.test.ts b/src/lib/server/infra/notifications/mail-queue.test.ts
index 7b237430..d1c6d847 100644
--- a/src/lib/server/infra/notifications/mail-queue.test.ts
+++ b/src/lib/server/infra/notifications/mail-queue.test.ts
@@ -120,11 +120,13 @@ describe('MailQueue', () => {
const first = queue.enqueue(mail('ok@example.com'), { alertId: 'a1', eventId: 'e1' });
await vi.advanceTimersByTimeAsync(1000);
- await first;
+ await expect(first).resolves.toBe(true);
expect(send).toHaveBeenCalledTimes(2);
expect(log.error).not.toHaveBeenCalled();
- await queue.enqueue(mail('gone@example.com'), { alertId: 'a1', eventId: 'e2' });
+ await expect(
+ queue.enqueue(mail('gone@example.com'), { alertId: 'a1', eventId: 'e2' }),
+ ).resolves.toBe(false);
expect(send).toHaveBeenCalledTimes(3);
expect(log.error).toHaveBeenCalledTimes(1);
const [fields] = log.error.mock.calls[0];
diff --git a/src/lib/server/infra/notifications/mail-queue.ts b/src/lib/server/infra/notifications/mail-queue.ts
index 690d0a85..dfb112a8 100644
--- a/src/lib/server/infra/notifications/mail-queue.ts
+++ b/src/lib/server/infra/notifications/mail-queue.ts
@@ -9,7 +9,7 @@ export type MailContext = { alertId?: string; eventId?: string; kind?: string };
type Job = {
notification: MailNotification;
context: MailContext;
- done: () => void;
+ done: (sent: boolean) => void;
};
export type MailQueueOptions = {
@@ -44,9 +44,12 @@ export class MailQueue {
this.concurrency = Math.max(1, options.concurrency ?? 3);
}
- /** Queues one email; resolves once it was sent or definitively failed. */
- enqueue(notification: MailNotification, context: MailContext = {}): Promise {
- return new Promise((resolve) => {
+ /**
+ * Queues one email; resolves once it was sent (`true`) or definitively failed (`false`, already
+ * logged). It never rejects.
+ */
+ enqueue(notification: MailNotification, context: MailContext = {}): Promise {
+ return new Promise((resolve) => {
this.pending.push({ notification, context, done: resolve });
this.pump();
});
@@ -84,20 +87,25 @@ export class MailQueue {
while (this.active < this.concurrency && this.pending.length > 0) {
const job = this.pending.shift()!;
this.active += 1;
- void this.run(job).finally(() => {
- this.active -= 1;
- job.done();
- if (this.size === 0) {
- for (const resolve of [...this.idle]) resolve();
- this.idle.clear();
- } else {
- this.pump();
- }
- });
+ let sent = false;
+ void this.run(job)
+ .then((result) => {
+ sent = result;
+ })
+ .finally(() => {
+ this.active -= 1;
+ job.done(sent);
+ if (this.size === 0) {
+ for (const resolve of [...this.idle]) resolve();
+ this.idle.clear();
+ } else {
+ this.pump();
+ }
+ });
}
}
- private async run(job: Job): Promise {
+ private async run(job: Job): Promise {
const recipients = job.notification.to.map(recipientHash);
try {
await withRetry(() => this.options.send(job.notification), {
@@ -109,18 +117,28 @@ export class MailQueue {
'[mail] retrying email',
),
});
+ return true;
} catch (error) {
this.options.logger.error(
// only the error code: SMTP messages may quote the recipient address
{ ...job.context, recipients, code: errorCode(error) },
'[mail] email could not be sent',
);
+ return false;
}
}
}
+/**
+ * SMTP reply or network code; for other errors (a bug, an invalid email) the error's name. Never
+ * the message: SMTP and validation messages may quote the recipient address.
+ */
function errorCode(error: unknown): unknown {
if (!error || typeof error !== 'object') return undefined;
- const { code, responseCode } = error as { code?: unknown; responseCode?: unknown };
- return responseCode ?? code;
+ const { code, responseCode, name } = error as {
+ code?: unknown;
+ responseCode?: unknown;
+ name?: unknown;
+ };
+ return responseCode ?? code ?? name;
}
diff --git a/src/lib/server/infra/notifications/mail.transport.ts b/src/lib/server/infra/notifications/mail.transport.ts
index dc933e02..39c635c1 100644
--- a/src/lib/server/infra/notifications/mail.transport.ts
+++ b/src/lib/server/infra/notifications/mail.transport.ts
@@ -41,6 +41,7 @@ export const mailTransport: NotificationTransport = {
to: notification.to,
subject: notification.subject,
html: notification.content,
+ ...(Object.keys(notification.headers).length > 0 ? { headers: notification.headers } : {}),
});
},
};
diff --git a/src/lib/server/infra/rate-limit.test.ts b/src/lib/server/infra/rate-limit.test.ts
new file mode 100644
index 00000000..77ec4348
--- /dev/null
+++ b/src/lib/server/infra/rate-limit.test.ts
@@ -0,0 +1,27 @@
+import { describe, expect, it } from 'vitest';
+import { RateLimiter } from './rate-limit';
+
+describe('RateLimiter', () => {
+ it('allows `limit` attempts per window and key, then tells when to retry', () => {
+ let now = 0;
+ const limiter = new RateLimiter({ limit: 2, windowMs: 1000 }, () => now);
+
+ expect(limiter.consume('a')).toEqual({ allowed: true });
+ expect(limiter.consume('a')).toEqual({ allowed: true });
+ expect(limiter.consume('a')).toEqual({ allowed: false, retryAfterMs: 1000 });
+ expect(limiter.consume('b')).toEqual({ allowed: true });
+
+ now = 400;
+ expect(limiter.check('a')).toEqual({ allowed: false, retryAfterMs: 600 });
+
+ now = 1000;
+ expect(limiter.consume('a')).toEqual({ allowed: true });
+ });
+
+ it('does not count attempts when only checking', () => {
+ const limiter = new RateLimiter({ limit: 1, windowMs: 1000 }, () => 0);
+ limiter.check('a');
+ limiter.check('a');
+ expect(limiter.consume('a')).toEqual({ allowed: true });
+ });
+});
diff --git a/src/lib/server/infra/rate-limit.ts b/src/lib/server/infra/rate-limit.ts
new file mode 100644
index 00000000..36eccced
--- /dev/null
+++ b/src/lib/server/infra/rate-limit.ts
@@ -0,0 +1,59 @@
+export type RateLimitRule = {
+ /** Attempts allowed per window. */
+ limit: number;
+ windowMs: number;
+};
+
+export type RateLimitDecision = { allowed: true } | { allowed: false; retryAfterMs: number };
+
+/**
+ * In-memory fixed-window rate limiter keyed by an arbitrary string (an address, an
+ * organization…). Per process and cleared on restart: it slows abuse down, it is not an exact
+ * quota. Expired windows are pruned on use, so memory stays bounded by active keys.
+ */
+export class RateLimiter {
+ private readonly windows = new Map();
+
+ constructor(
+ private readonly rule: RateLimitRule,
+ private readonly now: () => number = () => Date.now(),
+ ) {}
+
+ /** What `consume(key)` would answer, without counting an attempt. */
+ check(key: string): RateLimitDecision {
+ const window = this.current(key);
+ if (window && window.count >= this.rule.limit) {
+ return { allowed: false, retryAfterMs: window.resetAt - this.now() };
+ }
+ return { allowed: true };
+ }
+
+ /** Counts one attempt for `key` when it is allowed. */
+ consume(key: string): RateLimitDecision {
+ const decision = this.check(key);
+ if (!decision.allowed) return decision;
+ const window = this.current(key);
+ if (window) window.count += 1;
+ else this.windows.set(key, { count: 1, resetAt: this.now() + this.rule.windowMs });
+ return decision;
+ }
+
+ reset(): void {
+ this.windows.clear();
+ }
+
+ private current(key: string) {
+ const now = this.now();
+ if (this.windows.size > 1000) {
+ for (const [candidate, window] of this.windows) {
+ if (window.resetAt <= now) this.windows.delete(candidate);
+ }
+ }
+ const window = this.windows.get(key);
+ if (window && window.resetAt <= now) {
+ this.windows.delete(key);
+ return undefined;
+ }
+ return window;
+ }
+}
diff --git a/src/lib/server/infra/tokens.test.ts b/src/lib/server/infra/tokens.test.ts
new file mode 100644
index 00000000..e3ac3170
--- /dev/null
+++ b/src/lib/server/infra/tokens.test.ts
@@ -0,0 +1,67 @@
+import { describe, expect, it } from 'vitest';
+import {
+ createOneTimeToken,
+ hashToken,
+ isTokenAlive,
+ signToken,
+ verifySignedToken,
+} from './tokens';
+
+const SECRET = 'test-secret';
+
+describe('one-time tokens', () => {
+ it('returns a random token, its SHA-256 hash and the expiry', () => {
+ const now = new Date('2026-11-24T10:00:00.000Z');
+ const first = createOneTimeToken(60_000, now);
+ const second = createOneTimeToken(60_000, now);
+
+ expect(first.token).not.toBe(second.token);
+ expect(first.hash).toBe(hashToken(first.token));
+ expect(first.hash).not.toContain(first.token);
+ expect(first.expiresAt).toBe('2026-11-24T10:01:00.000Z');
+ });
+
+ it('treats missing, broken and past expiries as expired', () => {
+ const now = Date.parse('2026-11-24T10:00:00.000Z');
+ expect(isTokenAlive('2026-11-24T10:00:01.000Z', now)).toBe(true);
+ expect(isTokenAlive('2026-11-24T10:00:00.000Z', now)).toBe(false);
+ expect(isTokenAlive(null, now)).toBe(false);
+ expect(isTokenAlive('not a date', now)).toBe(false);
+ });
+});
+
+describe('signed tokens', () => {
+ const now = Date.parse('2026-11-24T10:00:00.000Z');
+
+ it('round-trips the payload until it expires', () => {
+ const token = signToken(
+ 'unsubscribe',
+ { rid: 'r1', v: 2 },
+ { secret: SECRET, ttlMs: 60_000, now },
+ );
+
+ expect(verifySignedToken('unsubscribe', token, { secret: SECRET, now })).toMatchObject({
+ rid: 'r1',
+ v: 2,
+ });
+ expect(
+ verifySignedToken('unsubscribe', token, { secret: SECRET, now: now + 60_000 }),
+ ).toBeNull();
+ });
+
+ it('rejects tampered payloads, other purposes and other secrets', () => {
+ const token = signToken(
+ 'unsubscribe',
+ { rid: 'r1', v: 0 },
+ { secret: SECRET, ttlMs: 60_000, now },
+ );
+ const [version, , mac] = token.split('.');
+ const forged = `${version}.${Buffer.from(JSON.stringify({ rid: 'r2', v: 0, exp: 9e9 })).toString('base64url')}.${mac}`;
+
+ expect(verifySignedToken('unsubscribe', forged, { secret: SECRET, now })).toBeNull();
+ expect(verifySignedToken('verify', token, { secret: SECRET, now })).toBeNull();
+ expect(verifySignedToken('unsubscribe', token, { secret: 'other', now })).toBeNull();
+ expect(verifySignedToken('unsubscribe', 'garbage', { secret: SECRET, now })).toBeNull();
+ expect(verifySignedToken('unsubscribe', `${token}.extra`, { secret: SECRET, now })).toBeNull();
+ });
+});
diff --git a/src/lib/server/infra/tokens.ts b/src/lib/server/infra/tokens.ts
new file mode 100644
index 00000000..5d040d50
--- /dev/null
+++ b/src/lib/server/infra/tokens.ts
@@ -0,0 +1,85 @@
+import crypto from 'node:crypto';
+
+const TOKEN_BYTES = 32;
+
+/** SHA-256 of a token: what GitDB stores, so a leaked repository holds no usable link. */
+export function hashToken(token: string): string {
+ return crypto.createHash('sha256').update(token).digest('hex');
+}
+
+export type OneTimeToken = {
+ /** Goes in the link and nowhere else. */
+ token: string;
+ /** Stored instead of the token. */
+ hash: string;
+ expiresAt: string;
+};
+
+/**
+ * Random token for a single-use link (email verification, password reset…). The caller stores
+ * `hash` and `expiresAt`, looks the token up by `hashToken()`, and clears both once it is used.
+ */
+export function createOneTimeToken(ttlMs: number, now: Date = new Date()): OneTimeToken {
+ const token = crypto.randomBytes(TOKEN_BYTES).toString('base64url');
+ return {
+ token,
+ hash: hashToken(token),
+ expiresAt: new Date(now.getTime() + ttlMs).toISOString(),
+ };
+}
+
+/** Whether a stored expiry is still in the future; a missing or broken value counts as expired. */
+export function isTokenAlive(expiresAt: string | Date | null | undefined, now = Date.now()) {
+ if (!expiresAt) return false;
+ const time = expiresAt instanceof Date ? expiresAt.getTime() : Date.parse(expiresAt);
+ return Number.isFinite(time) && time > now;
+}
+
+const SIGNED_VERSION = 'v1';
+
+/**
+ * Stateless token `v1..` for links that are sent many times and must not
+ * cost a write each (unsubscribe links in every email). Nothing is stored: the HMAC (keyed per
+ * `purpose`) proves it was issued by this server, `exp` limits its life, and the caller makes it
+ * single-use by putting a counter in the payload that it bumps when the token is used.
+ */
+export function signToken(
+ purpose: string,
+ payload: Record,
+ options: { secret: string; ttlMs: number; now?: number },
+): string {
+ const exp = Math.floor(((options.now ?? Date.now()) + options.ttlMs) / 1000);
+ const body = Buffer.from(JSON.stringify({ ...payload, exp })).toString('base64url');
+ return `${SIGNED_VERSION}.${body}.${signature(purpose, body, options.secret)}`;
+}
+
+/** The payload of a valid, unexpired token issued for `purpose`; `null` otherwise. */
+export function verifySignedToken>(
+ purpose: string,
+ token: string,
+ options: { secret: string; now?: number },
+): (T & { exp: number }) | null {
+ const [version, body, mac, ...rest] = token.trim().split('.');
+ if (version !== SIGNED_VERSION || !body || !mac || rest.length > 0) return null;
+
+ const expected = Buffer.from(signature(purpose, body, options.secret), 'base64url');
+ const received = Buffer.from(mac, 'base64url');
+ if (expected.length !== received.length || !crypto.timingSafeEqual(expected, received)) {
+ return null;
+ }
+
+ try {
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
+ if (!payload || typeof payload !== 'object' || typeof payload.exp !== 'number') return null;
+ if (payload.exp * 1000 <= (options.now ?? Date.now())) return null;
+ return payload;
+ } catch {
+ return null;
+ }
+}
+
+function signature(purpose: string, body: string, secret: string): string {
+ // a key per purpose: a token minted for one kind of link is useless for another
+ const key = crypto.createHmac('sha256', secret).update(`gitops:token:${purpose}`).digest();
+ return crypto.createHmac('sha256', key).update(body).digest('base64url');
+}
diff --git a/src/lib/server/notifications/links.ts b/src/lib/server/notifications/links.ts
new file mode 100644
index 00000000..7d1b3de3
--- /dev/null
+++ b/src/lib/server/notifications/links.ts
@@ -0,0 +1,47 @@
+import { InvalidNotificationLinkError, externalRecipientService } from '#modules/notifications';
+import { organizationService } from '#modules/organization';
+
+import type { NotificationLinkState } from '#lib/notifications/types';
+
+export type { NotificationLinkState };
+
+type Action = 'verify' | 'unsubscribe';
+
+/** Response headers of both pages: the token is in the URL, keep it out of referrers and caches. */
+export const LINK_PAGE_HEADERS = { 'referrer-policy': 'no-referrer', 'cache-control': 'no-store' };
+
+async function organizationName(organizationId: string) {
+ const organization = await organizationService.getOrganization(organizationId).catch(() => null);
+ return organization?.name ?? 'GitOps';
+}
+
+async function run(action: Action, token: string, use: boolean): Promise {
+ try {
+ const recipient =
+ action === 'verify'
+ ? use
+ ? await externalRecipientService.verify(token)
+ : await externalRecipientService.inspectVerification(token)
+ : use
+ ? await externalRecipientService.unsubscribe(token)
+ : await externalRecipientService.inspectUnsubscribe(token);
+ return {
+ state: use ? 'done' : 'ready',
+ email: recipient.email,
+ organization: await organizationName(recipient.organizationId),
+ };
+ } catch (error) {
+ if (error instanceof InvalidNotificationLinkError) return { state: error.reason };
+ throw error;
+ }
+}
+
+/** GET: tells what the link would do, without using it (mail scanners open links). */
+export function inspectLink(action: Action, token: string) {
+ return run(action, token, false);
+}
+
+/** POST from the page's button: uses the link once. */
+export function useLink(action: Action, token: string) {
+ return run(action, token, true);
+}
diff --git a/src/lib/server/notifications/settings.test.ts b/src/lib/server/notifications/settings.test.ts
new file mode 100644
index 00000000..4d24f97d
--- /dev/null
+++ b/src/lib/server/notifications/settings.test.ts
@@ -0,0 +1,137 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// grants per session user in organization `org-1`
+const grants: Record = {};
+
+vi.mock('#modules/auth', () => ({
+ cancanService: {
+ canSessionUser: async (
+ user: { id?: string } | null,
+ permission: string,
+ context: { organizationId?: string },
+ ) =>
+ !!user?.id &&
+ context.organizationId === 'org-1' &&
+ (grants[user.id] ?? []).includes(permission),
+ canApiKey: async () => false,
+ },
+}));
+vi.mock('#modules/projects', () => ({ projectService: {} }));
+vi.mock('#modules/organization', () => ({ organizationService: {} }));
+vi.mock('#modules/alerts', () => ({ isMailConfigured: () => true }));
+
+vi.mock('#modules/notifications', async () => {
+ const { createNotificationsFixture } = await import('#modules/notifications/application/testing');
+ const domain = await import('#modules/notifications/domain/external-recipient.domain');
+ const fixture = createNotificationsFixture();
+ return {
+ ...domain,
+ fixture,
+ externalRecipientService: fixture.recipients,
+ notificationSettingsService: fixture.settings,
+ };
+});
+
+const notifications = (await import('#modules/notifications')) as unknown as {
+ fixture: ReturnType<
+ typeof import('#modules/notifications/application/testing').createNotificationsFixture
+ >;
+};
+const {
+ canOpenNotificationSettings,
+ loadNotificationSettings,
+ resendVerification,
+ saveAllowedDomains,
+} = await import('./settings');
+
+const ORG = 'org-1';
+const as = (id: string) => ({ user: { id } });
+
+describe('notification settings authorization', () => {
+ beforeEach(async () => {
+ for (const key of Object.keys(grants)) delete grants[key];
+ grants.admin = [
+ 'organization:settings:read',
+ 'organization:settings:update',
+ 'organization:notifications:read',
+ 'organization:notifications:update',
+ ];
+ grants.settingsEditor = ['organization:settings:read', 'organization:settings:update'];
+ grants.notificationsManager = [
+ 'organization:notifications:read',
+ 'organization:notifications:update',
+ ];
+ grants.viewer = ['organization:settings:read', 'organization:notifications:read'];
+ grants.developer = ['organization:projects:read'];
+
+ notifications.fixture.recipientRepository.rows = [];
+ // the fixture is shared: start every test with fresh rate-limit windows
+ notifications.fixture.advance(2 * 60 * 60 * 1000);
+ await notifications.fixture.settings.setAllowedDomains(ORG, ['partner.com']);
+ await notifications.fixture.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ });
+
+ it('opens the page with settings:read or notifications:read only', async () => {
+ expect(await canOpenNotificationSettings(as('viewer'), ORG)).toBe(true);
+ expect(await canOpenNotificationSettings(as('settingsEditor'), ORG)).toBe(true);
+ expect(await canOpenNotificationSettings(as('notificationsManager'), ORG)).toBe(true);
+ expect(await canOpenNotificationSettings(as('developer'), ORG)).toBe(false);
+ expect(await loadNotificationSettings(as('developer'), ORG)).toMatchObject({ status: 403 });
+ expect(await loadNotificationSettings({ user: null }, ORG)).toMatchObject({ status: 403 });
+ });
+
+ it('shows the external recipients only with notifications:read', async () => {
+ const editor = await loadNotificationSettings(as('settingsEditor'), ORG);
+ expect(editor).toMatchObject({
+ ok: true,
+ data: { allowedDomains: ['partner.com'], recipients: null, canEditDomains: true },
+ });
+
+ const manager = await loadNotificationSettings(as('notificationsManager'), ORG);
+ expect(manager.ok && manager.data.canEditDomains).toBe(false);
+ expect(manager.ok && manager.data.recipients?.map((recipient) => recipient.email)).toEqual([
+ 'ana@partner.com',
+ ]);
+ // the view never carries the token hash
+ expect(JSON.stringify(manager)).not.toContain('verificationTokenHash');
+ });
+
+ it('changes the allowed domains only with organization:settings:update', async () => {
+ for (const user of ['viewer', 'notificationsManager', 'developer']) {
+ expect(await saveAllowedDomains(as(user), ORG, 'evil.com')).toMatchObject({ status: 403 });
+ }
+ expect((await notifications.fixture.settings.get(ORG)).allowedExternalEmailDomains).toEqual([
+ 'partner.com',
+ ]);
+
+ const saved = await saveAllowedDomains(as('settingsEditor'), ORG, 'client.io');
+ expect(saved).toMatchObject({ ok: true, data: { allowedDomains: ['client.io'], blocked: 1 } });
+ expect(notifications.fixture.recipientRepository.rows[0].status).toBe('blocked');
+ });
+
+ it('reports invalid domains as validation errors', async () => {
+ expect(await saveAllowedDomains(as('admin'), ORG, 'partner.com\nnot a domain')).toMatchObject({
+ ok: false,
+ status: 400,
+ errors: { 'allowedExternalEmailDomains.1': 'invalid_domain' },
+ });
+ });
+
+ it('resends confirmations only with organization:notifications:update', async () => {
+ const [{ id }] = notifications.fixture.recipientRepository.rows;
+ for (const user of ['viewer', 'settingsEditor', 'developer']) {
+ expect(await resendVerification(as(user), ORG, id)).toMatchObject({ status: 403 });
+ }
+ expect(await resendVerification(as('notificationsManager'), ORG, id)).toMatchObject({
+ ok: true,
+ data: { email: 'ana@partner.com', status: 'pending' },
+ });
+ expect(await resendVerification(as('notificationsManager'), ORG, 'missing')).toMatchObject({
+ status: 404,
+ });
+ // another organization's grants don't reach this one
+ expect(await resendVerification(as('notificationsManager'), 'org-2', id)).toMatchObject({
+ status: 403,
+ });
+ });
+});
diff --git a/src/lib/server/notifications/settings.ts b/src/lib/server/notifications/settings.ts
new file mode 100644
index 00000000..a98a1900
--- /dev/null
+++ b/src/lib/server/notifications/settings.ts
@@ -0,0 +1,130 @@
+import {
+ ExternalRecipientNotFoundError,
+ ExternalRecipientStateError,
+ NotificationSettingsValidationError,
+ VerificationRateLimitedError,
+ externalRecipientService,
+ notificationSettingsService,
+ type ExternalRecipientView,
+} from '#modules/notifications';
+import { isMailConfigured } from '#modules/alerts';
+import { readPublicOrigin } from '#lib/server/infra/notifications';
+import { callerCan, type AlertLocals } from '#lib/server/alerts/access';
+
+/** Outcome of a settings operation; form actions map failures to `fail()`. */
+export type SettingsResult =
+ | { ok: true; data: T }
+ | { ok: false; status: number; error: string; errors?: Record };
+
+export type NotificationSettingsPage = {
+ allowedDomains: string[];
+ /** `null` when the caller can't read them (`organization:notifications:read`). */
+ recipients: ExternalRecipientView[] | null;
+ canEditDomains: boolean;
+ canManageRecipients: boolean;
+ mailConfigured: boolean;
+ originConfigured: boolean;
+};
+
+const forbidden = { ok: false as const, status: 403, error: 'Forbidden' };
+
+function permissions(locals: AlertLocals, organizationId: string) {
+ const context = { scope: 'organization' as const, organizationId };
+ return Promise.all([
+ callerCan(locals, 'organization:settings:read', context),
+ callerCan(locals, 'organization:settings:update', context),
+ callerCan(locals, 'organization:notifications:read', context),
+ callerCan(locals, 'organization:notifications:update', context),
+ ]).then(([settingsRead, settingsUpdate, notificationsRead, notificationsUpdate]) => ({
+ settingsRead,
+ settingsUpdate,
+ notificationsRead,
+ notificationsUpdate,
+ }));
+}
+
+/** Who may open `/org//settings/notifications`: the sidebar uses the same rule. */
+export async function canOpenNotificationSettings(locals: AlertLocals, organizationId: string) {
+ const allowed = await permissions(locals, organizationId);
+ return allowed.settingsRead || allowed.notificationsRead;
+}
+
+/**
+ * The page: allowed domains (read with `organization:settings:read` or
+ * `organization:notifications:read`, changed with `organization:settings:update`) and the
+ * external recipients (`organization:notifications:read`, resent with `…:update`).
+ */
+export async function loadNotificationSettings(
+ locals: AlertLocals,
+ organizationId: string,
+): Promise> {
+ const allowed = await permissions(locals, organizationId);
+ if (!allowed.settingsRead && !allowed.notificationsRead) return forbidden;
+ const [settings, recipients] = await Promise.all([
+ notificationSettingsService.get(organizationId),
+ allowed.notificationsRead ? externalRecipientService.list(organizationId) : null,
+ ]);
+ return {
+ ok: true,
+ data: {
+ allowedDomains: settings.allowedExternalEmailDomains,
+ recipients,
+ canEditDomains: allowed.settingsUpdate,
+ canManageRecipients: allowed.notificationsUpdate,
+ mailConfigured: isMailConfigured(),
+ originConfigured: Boolean(readPublicOrigin()),
+ },
+ };
+}
+
+export async function saveAllowedDomains(
+ locals: AlertLocals,
+ organizationId: string,
+ input: unknown,
+): Promise> {
+ const context = { scope: 'organization' as const, organizationId };
+ if (!(await callerCan(locals, 'organization:settings:update', context))) return forbidden;
+ try {
+ const result = await notificationSettingsService.setAllowedDomains(organizationId, input);
+ return {
+ ok: true,
+ data: {
+ allowedDomains: result.settings.allowedExternalEmailDomains,
+ blocked: result.blocked,
+ restored: result.restored,
+ },
+ };
+ } catch (error) {
+ if (error instanceof NotificationSettingsValidationError) {
+ return { ok: false, status: 400, error: 'Invalid settings', errors: error.errors };
+ }
+ throw error;
+ }
+}
+
+export async function resendVerification(
+ locals: AlertLocals,
+ organizationId: string,
+ recipientId: string,
+): Promise> {
+ const context = { scope: 'organization' as const, organizationId };
+ if (!(await callerCan(locals, 'organization:notifications:update', context))) return forbidden;
+ try {
+ const recipient = await externalRecipientService.resendVerification(
+ organizationId,
+ recipientId,
+ );
+ return { ok: true, data: recipient };
+ } catch (error) {
+ if (error instanceof ExternalRecipientNotFoundError) {
+ return { ok: false, status: 404, error: 'not_found' };
+ }
+ if (error instanceof ExternalRecipientStateError) {
+ return { ok: false, status: 409, error: 'invalid_status' };
+ }
+ if (error instanceof VerificationRateLimitedError) {
+ return { ok: false, status: 429, error: 'rate_limited' };
+ }
+ return { ok: false, status: 502, error: 'send_failed' };
+ }
+}
diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts
index bacd0a72..38905b46 100644
--- a/src/modules/alerts/application/alert-engine.test.ts
+++ b/src/modules/alerts/application/alert-engine.test.ts
@@ -109,7 +109,7 @@ function alertRow(overrides: Partial = {}): AlertRow {
eventType: 'code_report.analysis.completed',
match: 'all',
conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }],
- recipients: { userIds: [], roleIds: ['project-reporter'] },
+ recipients: { userIds: [], roleIds: ['project-reporter'], externalEmails: [] },
channels: ['mail'],
throttleMinutes: 0,
createdByUserId: 'author',
@@ -125,7 +125,8 @@ class RecordingNotifier implements AlertNotifierPort {
failFor = new Set();
async sendAlert(email: AlertEmail) {
- if (this.failFor.has(email.recipient.userId)) throw new Error('SMTP down');
+ const key = email.recipient.kind === 'member' ? email.recipient.userId : email.recipient.email;
+ if (this.failFor.has(key)) throw new Error('SMTP down');
this.alerts.push(email);
}
@@ -147,7 +148,12 @@ describe('AlertEngine', () => {
debug: ReturnType;
};
- const sentTo = () => notifier.alerts.map((email) => email.recipient.userId).sort();
+ const sentTo = () =>
+ notifier.alerts
+ .map((email) =>
+ email.recipient.kind === 'member' ? email.recipient.userId : email.recipient.email,
+ )
+ .sort();
beforeEach(() => {
repository = new InMemoryAlertRepository();
@@ -239,7 +245,9 @@ describe('AlertEngine', () => {
it('skips disabled users and users without an email', async () => {
repository.rows = [
- alertRow({ recipients: { userIds: ['carl', 'nomail', 'ana'], roleIds: [] } }),
+ alertRow({
+ recipients: { userIds: ['carl', 'nomail', 'ana'], roleIds: [], externalEmails: [] },
+ }),
];
await engine.handle(completed());
expect(sentTo()).toEqual(['ana']);
@@ -247,7 +255,9 @@ describe('AlertEngine', () => {
it('does not email recipients without the read permission, most-specific-wins included', async () => {
repository.rows = [
- alertRow({ recipients: { userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] } }),
+ alertRow({
+ recipients: { userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [], externalEmails: [] },
+ }),
];
await engine.handle(completed());
@@ -263,12 +273,16 @@ describe('AlertEngine', () => {
it('only fires alerts whose scope covers the event', async () => {
repository.rows = [
alertRow({ id: 'p1-alert' }),
- alertRow({ id: 'p2-alert', projectId: 'p2', recipients: { userIds: ['pia'], roleIds: [] } }),
+ alertRow({
+ id: 'p2-alert',
+ projectId: 'p2',
+ recipients: { userIds: ['pia'], roleIds: [], externalEmails: [] },
+ }),
alertRow({
id: 'org-alert',
scope: 'organization',
projectId: null,
- recipients: { userIds: ['eli'], roleIds: [] },
+ recipients: { userIds: ['eli'], roleIds: [], externalEmails: [] },
}),
alertRow({
id: 'other-org',
@@ -295,7 +309,10 @@ describe('AlertEngine', () => {
it('throttles an alert and reports the suppressed events in the next email', async () => {
repository.rows = [
- alertRow({ throttleMinutes: 30, recipients: { userIds: ['ana'], roleIds: [] } }),
+ alertRow({
+ throttleMinutes: 30,
+ recipients: { userIds: ['ana'], roleIds: [], externalEmails: [] },
+ }),
];
await engine.handle(completed({}, undefined, 'e1'));
@@ -480,7 +497,7 @@ describe('AlertEngine', () => {
scope: 'organization',
projectId: null,
conditions: [],
- recipients: { userIds: ['eli'], roleIds: [] },
+ recipients: { userIds: ['eli'], roleIds: [], externalEmails: [] },
}),
];
diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts
index 55054a6d..cb871bd4 100644
--- a/src/modules/alerts/application/alert-engine.ts
+++ b/src/modules/alerts/application/alert-engine.ts
@@ -1,4 +1,5 @@
import type { Logger } from 'pino';
+import { recipientHash } from '#lib/server/infra/notifications/mail-queue';
import { getEventDefinition, isEventType, type EventDefinition } from '#lib/events/catalog';
import type { AnyDomainEvent, EventBus, Unsubscribe } from '#lib/server/events';
import type { AlertDomain } from '../domain/alert.domain';
@@ -10,10 +11,22 @@ import {
import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository';
import { AlertThrottle } from './alert-throttle';
import { RecipientResolver, type Recipient } from './recipient-resolver';
-import { eventContext, type AlertDirectory, type ResolvedNames } from './types';
+import {
+ eventContext,
+ type AlertDirectory,
+ type ExternalRecipientsPort,
+ type ResolvedNames,
+} from './types';
+
+/**
+ * Who an alert email goes to: a member (filtered by cancan) or a verified external address,
+ * whose email carries an unsubscribe link and leaves out what only members may see.
+ */
+export type AlertEmailRecipient =
+ ({ kind: 'member' } & Recipient) | { kind: 'external'; email: string; unsubscribeUrl: string };
export type AlertEmail = {
- recipient: Recipient;
+ recipient: AlertEmailRecipient;
alert: Pick;
event: AnyDomainEvent;
definition: EventDefinition;
@@ -23,6 +36,15 @@ export type AlertEmail = {
names: ReadonlyMap;
/** Names and slugs of where the event happened, for the texts and the links. */
where: ResolvedNames;
+ /** Sent from the editor's "send test email" with an example event, not by a real event. */
+ test?: boolean;
+};
+
+/** What a test send reached. */
+export type AlertTestDelivery = {
+ /** Emails handed to the notifier (members and verified external addresses). */
+ sent: number;
+ failed: number;
};
export type SystemEmail = {
@@ -40,7 +62,9 @@ export interface AlertNotifierPort {
export type AlertEngineOptions = {
repository: Pick;
directory: AlertDirectory;
- recipients: RecipientResolver;
+ recipients: Pick;
+ /** Without it, the external addresses of alerts are ignored. */
+ externalRecipients?: Pick;
notifier: AlertNotifierPort;
throttle?: AlertThrottle;
logger: Pick;
@@ -56,6 +80,8 @@ export type AlertDryRun = {
recipients: Recipient[];
/** Selected users that would not get it because they can't read the event. */
denied: string[];
+ /** The alert's external addresses, their status and whether they would get it. */
+ external: Array<{ email: string; status: string; delivers: boolean }>;
};
const DEFAULT_CACHE_TTL_MS = 60_000;
@@ -132,14 +158,31 @@ export class AlertEngine {
const definition = getEventDefinition(event.type) as EventDefinition;
const matched = alert.appliesTo(event.scope) && matches(event, alert, definition);
const context = eventContext(event.scope);
- if (!context) return { matched, recipients: [], denied: [] };
+ if (!context) return { matched, recipients: [], denied: [], external: [] };
const resolved = await this.options.recipients.resolve(
alert.location,
alert.recipients,
definition.readPermission,
context,
);
- return { matched, ...resolved };
+ return { matched, ...resolved, external: await this.externalPreview(alert) };
+ }
+
+ private async externalPreview(alert: Pick) {
+ const emails = alert.recipients.externalEmails;
+ const port = this.options.externalRecipients;
+ if (!port || emails.length === 0) return [];
+ const organizationId = alert.location.organizationId;
+ const [statuses, deliverable] = await Promise.all([
+ port.statuses(organizationId, emails),
+ port.deliverable(organizationId, emails),
+ ]);
+ const delivering = new Set(deliverable.map((recipient) => recipient.email));
+ return emails.map((email) => ({
+ email,
+ status: statuses.get(email) ?? 'missing',
+ delivers: delivering.has(email),
+ }));
}
private async alertsFor(eventType: string): Promise {
@@ -168,6 +211,54 @@ export class AlertEngine {
return;
}
+ const delivery = await this.deliver(alert, event, definition, decision.suppressed, false);
+ log.info(
+ {
+ alertId: alert.id,
+ eventType: event.type,
+ eventId: event.id,
+ ...delivery,
+ previouslySuppressed: decision.suppressed,
+ },
+ '[alerts] alert fired',
+ );
+ }
+
+ /**
+ * Really emails the alert's recipients about `event` (an example built by the caller), with
+ * the same rules as a real event: members that can read it and verified external addresses.
+ * The throttle is neither checked nor touched.
+ */
+ async sendTest(
+ alert: Pick<
+ AlertDomain,
+ 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
+ >,
+ event: AnyDomainEvent,
+ ): Promise {
+ const definition = getEventDefinition(event.type) as EventDefinition;
+ const { sent, failed } = await this.deliver(alert, event, definition, 0, true);
+ this.options.logger.info(
+ { alertId: alert.id, eventType: event.type, sent, failed, test: true },
+ '[alerts] test email sent',
+ );
+ return { sent, failed };
+ }
+
+ private async deliver(
+ alert: Pick<
+ AlertDomain,
+ 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
+ >,
+ event: AnyDomainEvent,
+ definition: EventDefinition,
+ suppressed: number,
+ test: boolean,
+ ): Promise<{ recipients: number; externalRecipients: number; sent: number; failed: number }> {
+ const log = this.options.logger;
+ const context = eventContext(event.scope);
+ if (!context) return { recipients: 0, externalRecipients: 0, sent: 0, failed: 0 };
+
const { recipients, denied } = await this.options.recipients.resolve(
alert.location,
alert.recipients,
@@ -191,43 +282,72 @@ export class AlertEngine {
})
.catch(() => ({}));
+ // external addresses: no cancan (they have no account), only verified ones of an allowed
+ // domain, and system notifications never reach them (they only come from `fire`)
+ const external = await this.externalRecipientsOf(alert);
+
+ const targets: AlertEmailRecipient[] = [
+ ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })),
+ ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })),
+ ];
+
let sent = 0;
// one email per recipient: addresses are never shared, and a failure only affects one person
- for (const recipient of recipients) {
+ for (const recipient of targets) {
try {
await this.options.notifier.sendAlert({
recipient,
alert,
event,
definition,
- suppressed: decision.suppressed,
+ suppressed,
names,
where,
+ ...(test ? { test: true } : {}),
});
sent += 1;
} catch (error) {
log.warn(
- { err: error, alertId: alert.id, eventId: event.id, userId: recipient.userId },
+ {
+ err: error,
+ alertId: alert.id,
+ eventId: event.id,
+ ...(recipient.kind === 'member'
+ ? { userId: recipient.userId }
+ : { recipient: recipientHash(recipient.email) }),
+ },
'[alerts] email to recipient failed',
);
}
}
- log.info(
- {
- alertId: alert.id,
- eventType: event.type,
- eventId: event.id,
- recipients: recipients.length,
- sent,
- previouslySuppressed: decision.suppressed,
- },
- '[alerts] alert fired',
- );
+ return {
+ recipients: recipients.length,
+ externalRecipients: external.length,
+ sent,
+ failed: targets.length - sent,
+ };
+ }
+
+ private async externalRecipientsOf(
+ alert: Pick,
+ ) {
+ const port = this.options.externalRecipients;
+ const emails = alert.recipients.externalEmails;
+ if (!port || emails.length === 0) return [];
+ try {
+ return await port.deliverable(alert.organizationId, emails);
+ } catch (error) {
+ this.options.logger.warn(
+ { err: error, alertId: alert.id },
+ '[alerts] external recipients could not be resolved',
+ );
+ return [];
+ }
}
private async referenceNames(
- alert: AlertDomain,
+ alert: Pick,
definition: EventDefinition,
): Promise> {
const references = new Set(
diff --git a/src/modules/alerts/application/alert.external.test.ts b/src/modules/alerts/application/alert.external.test.ts
new file mode 100644
index 00000000..e42d6aa9
--- /dev/null
+++ b/src/modules/alerts/application/alert.external.test.ts
@@ -0,0 +1,345 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import type { AnyDomainEvent } from '#lib/server/events';
+import { createNotificationsFixture } from '#modules/notifications/application/testing';
+import { AlertValidationError, type AlertInput, type AlertLocation } from '../domain/alert.domain';
+import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository';
+import {
+ AlertEngine,
+ type AlertEmail,
+ type AlertNotifierPort,
+ type SystemEmail,
+} from './alert-engine';
+import { AlertService } from './alert.service';
+import { RecipientResolver } from './recipient-resolver';
+import { FakeAlertDirectory, actor } from './testing';
+
+const ORG = 'org-1';
+const orgLocation: AlertLocation = { scope: 'organization', organizationId: ORG, projectId: null };
+const projectLocation: AlertLocation = { scope: 'project', organizationId: ORG, projectId: 'p1' };
+
+const ALL_BUT_NOTIFICATIONS = [
+ 'project:codereport:reports:read',
+ 'organization:projects:read',
+ 'project:alerts:update',
+];
+
+function input(overrides: AlertInput = {}): AlertInput {
+ return {
+ name: 'Críticas',
+ eventType: 'code_report.analysis.completed',
+ conditions: [],
+ recipients: { userIds: [], roleIds: [], externalEmails: ['ana@partner.com'] },
+ ...overrides,
+ };
+}
+
+async function validationErrors(promise: Promise) {
+ const error = await promise.catch((caught) => caught);
+ expect(error).toBeInstanceOf(AlertValidationError);
+ return (error as AlertValidationError).errors;
+}
+
+function analysisEvent(): AnyDomainEvent {
+ return {
+ id: 'evt-1',
+ type: 'code_report.analysis.completed',
+ occurredAt: '2026-11-24T10:00:00.000Z',
+ actor: { kind: 'system' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: {
+ analysisId: 'a1',
+ serviceId: 'svc-1',
+ tool: 'trivy',
+ status: 'completed',
+ summary: { critical: 1, high: 0, medium: 0, low: 0, total: 1 },
+ },
+ } as unknown as AnyDomainEvent;
+}
+
+class RecordingNotifier implements AlertNotifierPort {
+ alerts: AlertEmail[] = [];
+ system: SystemEmail[] = [];
+ async sendAlert(email: AlertEmail) {
+ this.alerts.push(email);
+ }
+ async sendSystemNotification(email: SystemEmail) {
+ this.system.push(email);
+ }
+}
+
+describe('alerts with external email recipients', () => {
+ let notifications: ReturnType;
+ let repository: InMemoryAlertRepository;
+ let directory: FakeAlertDirectory;
+ let service: AlertService;
+
+ beforeEach(async () => {
+ notifications = createNotificationsFixture();
+ await notifications.settings.setAllowedDomains(ORG, ['partner.com']);
+ repository = new InMemoryAlertRepository();
+ directory = new FakeAlertDirectory();
+ directory.members = [
+ {
+ organizationId: ORG,
+ projectId: 'p1',
+ userId: 'u1',
+ username: 'ana',
+ email: 'ana@kettu.io',
+ disabled: false,
+ roleIds: [],
+ },
+ ];
+ let id = 0;
+ service = new AlertService(repository, directory, {
+ generateId: () => `alert-${++id}`,
+ externalRecipients: notifications.recipients,
+ });
+ });
+
+ describe('validation (API level, not only the UI)', () => {
+ it('saves allowed addresses normalized and sends their confirmation email', async () => {
+ const alert = await service.create(
+ projectLocation,
+ input({ recipients: { externalEmails: [' Ana@Partner.COM', 'ana@partner.com'] } }),
+ actor('admin'),
+ );
+
+ expect(alert.recipients).toEqual({
+ userIds: [],
+ roleIds: [],
+ externalEmails: ['ana@partner.com'],
+ });
+ expect(notifications.recipientRepository.rows).toMatchObject([
+ { email: 'ana@partner.com', status: 'pending', organizationId: ORG },
+ ]);
+ expect(notifications.notifier.sent).toHaveLength(1);
+ });
+
+ it('rejects addresses of a domain that is not allowed', async () => {
+ const errors = await validationErrors(
+ service.create(
+ projectLocation,
+ input({ recipients: { externalEmails: ['ok@partner.com', 'bob@evil.com', 'nope'] } }),
+ actor('admin'),
+ ),
+ );
+
+ expect(errors).toMatchObject({
+ 'recipients.externalEmails': 'domain_not_allowed',
+ 'recipients.externalEmails.1': 'domain_not_allowed',
+ 'recipients.externalEmails.2': 'invalid_email',
+ });
+ expect(repository.rows).toHaveLength(0);
+ expect(notifications.notifier.sent).toHaveLength(0);
+ });
+
+ it('rejects every external address while the organization allows no domain', async () => {
+ await notifications.settings.setAllowedDomains(ORG, []);
+ const errors = await validationErrors(service.create(orgLocation, input(), actor('admin')));
+ expect(errors['recipients.externalEmails']).toBe('domain_not_allowed');
+ });
+
+ it('needs :notifications:update to add external addresses', async () => {
+ const project = await validationErrors(
+ service.create(projectLocation, input(), actor('dev', ALL_BUT_NOTIFICATIONS)),
+ );
+ expect(project['recipients.externalEmails']).toBe('forbidden_external');
+
+ const organization = await validationErrors(
+ service.create(
+ orgLocation,
+ input(),
+ actor('dev', [...ALL_BUT_NOTIFICATIONS, 'project:notifications:update']),
+ ),
+ );
+ expect(organization['recipients.externalEmails']).toBe('forbidden_external');
+
+ await expect(
+ service.create(
+ projectLocation,
+ input(),
+ actor('admin', [...ALL_BUT_NOTIFICATIONS, 'project:notifications:update']),
+ ),
+ ).resolves.toBeDefined();
+ });
+
+ it('lets editors without the permission keep or remove existing addresses, not add new ones', async () => {
+ const alert = await service.create(projectLocation, input(), actor('admin'));
+ const editor = actor('dev', ALL_BUT_NOTIFICATIONS);
+
+ await expect(service.update(alert.id, { name: 'Renamed' }, editor)).resolves.toMatchObject({
+ recipients: { externalEmails: ['ana@partner.com'] },
+ });
+ const added = await validationErrors(
+ service.update(
+ alert.id,
+ { recipients: { externalEmails: ['ana@partner.com', 'eva@partner.com'] } },
+ editor,
+ ),
+ );
+ expect(added['recipients.externalEmails']).toBe('forbidden_external');
+ await expect(
+ service.update(alert.id, { recipients: { userIds: ['u1'], externalEmails: [] } }, editor),
+ ).resolves.toMatchObject({ recipients: { userIds: ['u1'], externalEmails: [] } });
+ });
+
+ it('accepts an alert whose only recipients are external', async () => {
+ await expect(service.create(orgLocation, input(), actor('admin'))).resolves.toBeDefined();
+ const errors = await validationErrors(
+ service.create(orgLocation, input({ recipients: { externalEmails: [] } }), actor('admin')),
+ );
+ expect(errors.recipients).toBe('required');
+ });
+
+ it('rejects external addresses when the module has no external recipients support', async () => {
+ const plain = new AlertService(repository, directory);
+ const errors = await validationErrors(plain.create(orgLocation, input(), actor('admin')));
+ expect(errors['recipients.externalEmails']).toBe('domain_not_allowed');
+ });
+ });
+
+ describe('engine', () => {
+ let notifier: RecordingNotifier;
+ let engine: AlertEngine;
+
+ beforeEach(() => {
+ notifier = new RecordingNotifier();
+ engine = new AlertEngine({
+ repository,
+ directory,
+ // members can't read the event: externals are not filtered by cancan
+ recipients: new RecipientResolver(directory, async () => false),
+ externalRecipients: notifications.recipients,
+ notifier,
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ });
+ });
+
+ async function verify(email: string) {
+ await notifications.recipients.verify(notifications.notifier.tokenFor(email));
+ }
+
+ it('emails verified external recipients only, each with its unsubscribe link', async () => {
+ await service.create(
+ projectLocation,
+ input({
+ recipients: {
+ userIds: ['u1'],
+ externalEmails: ['ana@partner.com', 'pending@partner.com'],
+ },
+ }),
+ actor('admin'),
+ );
+ await verify('ana@partner.com');
+
+ await engine.handle(analysisEvent());
+
+ expect(notifier.alerts).toHaveLength(1);
+ expect(notifier.alerts[0].recipient).toMatchObject({
+ kind: 'external',
+ email: 'ana@partner.com',
+ unsubscribeUrl: expect.stringContaining('/notifications/unsubscribe?token='),
+ });
+ });
+
+ it('stops emailing unsubscribed and blocked recipients', async () => {
+ await service.create(projectLocation, input(), actor('admin'));
+ await verify('ana@partner.com');
+ await engine.handle(analysisEvent());
+ expect(notifier.alerts).toHaveLength(1);
+
+ await notifications.settings.setAllowedDomains(ORG, ['other.com']);
+ await engine.handle(analysisEvent());
+ expect(notifier.alerts).toHaveLength(1);
+
+ await notifications.settings.setAllowedDomains(ORG, ['partner.com']);
+ const url = (notifier.alerts[0].recipient as { unsubscribeUrl: string }).unsubscribeUrl;
+ await notifications.recipients.unsubscribe(new URL(url).searchParams.get('token')!);
+ await engine.handle(analysisEvent());
+ expect(notifier.alerts).toHaveLength(1);
+ });
+
+ it('never sends system notifications to external recipients', async () => {
+ await service.create(projectLocation, input(), actor('admin'));
+ await verify('ana@partner.com');
+ directory.users = [{ userId: 'u1', username: 'ana', email: 'ana@kettu.io', disabled: false }];
+
+ await engine.handle({
+ id: 'evt-2',
+ type: 'access.granted',
+ occurredAt: '2026-11-24T10:00:00.000Z',
+ actor: { kind: 'user', userId: 'admin' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: { accessId: 'a1', userId: 'u1', roleId: 'r1', scope: 'project', status: 'active' },
+ } as unknown as AnyDomainEvent);
+
+ expect(notifier.system.map((email) => email.recipient.email)).toEqual(['ana@kettu.io']);
+ expect(notifier.alerts).toHaveLength(0);
+ });
+
+ it('sends a real test email to members and verified external addresses, never pending ones', async () => {
+ const alert = await service.create(
+ projectLocation,
+ input({
+ recipients: {
+ userIds: ['u1'],
+ externalEmails: ['ana@partner.com', 'pending@partner.com'],
+ },
+ }),
+ actor('admin'),
+ );
+ await verify('ana@partner.com');
+ // members pass the usual read check
+ engine = new AlertEngine({
+ repository,
+ directory,
+ recipients: new RecipientResolver(directory, async () => true),
+ externalRecipients: notifications.recipients,
+ notifier,
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ });
+
+ const delivery = await engine.sendTest(alert, analysisEvent());
+
+ expect(delivery).toEqual({ sent: 2, failed: 0 });
+ expect(notifier.alerts.map((email) => [email.recipient.kind, email.recipient.email])).toEqual(
+ [
+ ['member', 'ana@kettu.io'],
+ ['external', 'ana@partner.com'],
+ ],
+ );
+ expect(notifier.alerts.every((email) => email.test === true)).toBe(true);
+ });
+
+ it('does not touch the throttle when sending a test email', async () => {
+ const alert = await service.create(
+ projectLocation,
+ input({ throttleMinutes: 60 }),
+ actor('admin'),
+ );
+ await verify('ana@partner.com');
+
+ await engine.sendTest(alert, analysisEvent());
+ await engine.handle(analysisEvent());
+
+ expect(notifier.alerts.map((email) => email.test ?? false)).toEqual([true, false]);
+ });
+
+ it('tells in a dry run which external addresses would get the email', async () => {
+ const alert = await service.create(
+ projectLocation,
+ input({ recipients: { externalEmails: ['ana@partner.com', 'pending@partner.com'] } }),
+ actor('admin'),
+ );
+ await verify('ana@partner.com');
+
+ const result = await engine.dryRun(alert, analysisEvent());
+
+ expect(result.external).toEqual([
+ { email: 'ana@partner.com', status: 'verified', delivers: true },
+ { email: 'pending@partner.com', status: 'pending', delivers: false },
+ ]);
+ expect(notifier.alerts).toHaveLength(0);
+ });
+ });
+});
diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts
index 00e5e973..c266bf6b 100644
--- a/src/modules/alerts/application/alert.service.ts
+++ b/src/modules/alerts/application/alert.service.ts
@@ -27,6 +27,7 @@ import {
locationContext,
type AlertActor,
type AlertDirectory,
+ type ExternalRecipientsPort,
type ReferenceOption,
} from './types';
@@ -34,6 +35,8 @@ const MAX_NAME_LENGTH = 120;
const MAX_DESCRIPTION_LENGTH = 1000;
const MAX_CONDITIONS = 20;
const MAX_LIST_VALUES = 100;
+/** External addresses one alert may email. */
+export const MAX_EXTERNAL_EMAILS = 50;
const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']);
const LIST_OPERATORS = new Set(['in', 'not_in']);
@@ -43,6 +46,9 @@ export type AlertServiceOptions = {
generateId?: () => string;
/** Called after every successful write, so the engine drops its cached alerts. */
onChange?: () => void;
+ /** Without it, alerts can't have external email recipients. */
+ externalRecipients?: ExternalRecipientsPort;
+ logger?: { warn: (object: object, message: string) => void };
};
/** Ids the location's reference lists contain, loaded once per validation. */
@@ -58,6 +64,8 @@ export class AlertService {
private readonly now: () => Date;
private readonly generateId: () => string;
private readonly onChange: () => void;
+ private readonly externalRecipients: ExternalRecipientsPort | null;
+ private readonly logger: AlertServiceOptions['logger'];
constructor(
private readonly repository: AlertRepositoryPort,
@@ -67,6 +75,8 @@ export class AlertService {
this.now = options.now ?? (() => new Date());
this.generateId = options.generateId ?? (() => crypto.randomUUID());
this.onChange = options.onChange ?? (() => {});
+ this.externalRecipients = options.externalRecipients ?? null;
+ this.logger = options.logger;
}
async get(id: string): Promise {
@@ -109,11 +119,16 @@ export class AlertService {
});
}
- /** Validates `input` for `location` and returns the normalized fields, without saving. */
+ /**
+ * Validates `input` for `location` and returns the normalized fields, without saving.
+ * `previousExternalEmails` are the external addresses the alert already had: keeping them does
+ * not need `:notifications:update`, adding new ones does.
+ */
async validate(
location: AlertLocation,
input: AlertInput,
actor: AlertActor,
+ previousExternalEmails: readonly string[] = [],
): Promise {
const errors: AlertValidationErrors = {};
const references: ReferenceCache = new Map();
@@ -142,7 +157,13 @@ export class AlertService {
? await this.validateConditions(location, definition, input.conditions, errors, references)
: [];
- const recipients = await this.validateRecipients(location, input.recipients, errors);
+ const recipients = await this.validateRecipients(
+ location,
+ input.recipients,
+ actor,
+ previousExternalEmails,
+ errors,
+ );
const channels = this.validateChannels(input.channels, errors);
@@ -190,6 +211,7 @@ export class AlertService {
};
await this.repository.create(row);
this.onChange();
+ await this.registerExternal(location, fields.recipients.externalEmails, actor);
return new AlertDomain(row);
}
@@ -208,12 +230,39 @@ export class AlertService {
throttleMinutes: current.throttleMinutes,
...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)),
};
- const fields = await this.validate(current.location, merged, actor);
+ const fields = await this.validate(
+ current.location,
+ merged,
+ actor,
+ current.recipients.externalEmails,
+ );
await this.repository.update(id, fields);
this.onChange();
+ await this.registerExternal(current.location, fields.recipients.externalEmails, actor);
return new AlertDomain({ ...current.toJson(), ...fields, updatedAt: this.now().toISOString() });
}
+ /**
+ * New addresses become pending external recipients and get their confirmation email: after a
+ * save, and when a test email is sent from the editor (so the address can confirm before the
+ * alert is created). The addresses must have passed `validate()`; a failure is only logged.
+ */
+ async registerExternal(
+ location: AlertLocation,
+ emails: readonly string[],
+ actor: AlertActor,
+ ): Promise {
+ if (!this.externalRecipients || emails.length === 0) return;
+ try {
+ await this.externalRecipients.register(location.organizationId, emails, actor.userId);
+ } catch (error) {
+ this.logger?.warn(
+ { err: error, organizationId: location.organizationId },
+ '[alerts] external recipients could not be registered',
+ );
+ }
+ }
+
async delete(id: string): Promise {
await this.get(id);
await this.repository.delete(id);
@@ -395,6 +444,8 @@ export class AlertService {
private async validateRecipients(
location: AlertLocation,
value: unknown,
+ actor: AlertActor,
+ previousExternalEmails: readonly string[],
errors: AlertValidationErrors,
): Promise {
const raw = (value ?? {}) as Record;
@@ -404,10 +455,17 @@ export class AlertService {
: [];
const userIds = ids(raw.userIds);
const roleIds = ids(raw.roleIds);
+ const externalEmails = await this.validateExternalEmails(
+ location,
+ raw.externalEmails,
+ actor,
+ previousExternalEmails,
+ errors,
+ );
- if (userIds.length === 0 && roleIds.length === 0) {
- errors.recipients = 'required';
- return { userIds, roleIds };
+ if (userIds.length === 0 && roleIds.length === 0 && externalEmails.length === 0) {
+ if (!errors['recipients.externalEmails']) errors.recipients = 'required';
+ return { userIds, roleIds, externalEmails };
}
if (userIds.length > 0) {
@@ -419,7 +477,51 @@ export class AlertService {
if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role';
}
- return { userIds, roleIds };
+ return { userIds, roleIds, externalEmails };
+ }
+
+ /**
+ * External addresses: valid, inside the organization's allowed domains, and only added by
+ * someone with `:notifications:update` (they get the event without any cancan check).
+ */
+ private async validateExternalEmails(
+ location: AlertLocation,
+ value: unknown,
+ actor: AlertActor,
+ previous: readonly string[],
+ errors: AlertValidationErrors,
+ ): Promise {
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value)) {
+ errors['recipients.externalEmails'] = 'invalid';
+ return [];
+ }
+ const items = value.filter((item) => !(typeof item === 'string' && !item.trim()));
+ if (items.length === 0) return [];
+ if (items.length > MAX_EXTERNAL_EMAILS) {
+ errors['recipients.externalEmails'] = 'too_many';
+ return [];
+ }
+
+ let emails: string[] = [];
+ if (!this.externalRecipients) {
+ errors['recipients.externalEmails'] = 'domain_not_allowed';
+ } else {
+ const checked = await this.externalRecipients.check(location.organizationId, items);
+ emails = checked.emails;
+ const failures = Object.entries(checked.errors);
+ for (const [index, code] of failures) errors[`recipients.externalEmails.${index}`] = code;
+ if (failures.length > 0) errors['recipients.externalEmails'] = failures[0][1];
+ }
+
+ const known = new Set(previous);
+ if (emails.some((email) => !known.has(email))) {
+ const permission = `${location.scope}:notifications:update` as const;
+ if (!(await actor.canRead(permission, locationContext(location)))) {
+ errors['recipients.externalEmails'] = 'forbidden_external';
+ }
+ }
+ return emails;
}
private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] {
diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts
index 96d6d5f4..63999b00 100644
--- a/src/modules/alerts/application/types.ts
+++ b/src/modules/alerts/application/types.ts
@@ -59,7 +59,28 @@ export type ResolvedNames = {
role?: string;
};
-/** Who creates or edits an alert; `canRead` checks a grant in a context for that actor. */
+/** External email recipients as the alerts module sees them (`$modules/notifications`). */
+export interface ExternalRecipientsPort {
+ /** Normalized valid addresses, and ` ` → `invalid_email` | `domain_not_allowed`. */
+ check(
+ organizationId: string,
+ emails: readonly unknown[],
+ ): Promise<{ emails: string[]; errors: Record }>;
+ /** Creates the missing addresses as pending and sends their confirmation email. */
+ register(organizationId: string, emails: readonly string[], actorUserId: string): Promise;
+ /** The addresses that may get an email now, each with its unsubscribe link. */
+ deliverable(
+ organizationId: string,
+ emails: readonly string[],
+ ): Promise>;
+ /** `pending` | `verified` | `unsubscribed` | `blocked` | `missing` per address. */
+ statuses(organizationId: string, emails: readonly string[]): Promise>;
+}
+
+/**
+ * Who creates or edits an alert; `canRead` checks any grant in a context for that actor (named
+ * after its first use, the anti-escalation read check).
+ */
export type AlertActor = {
userId: string;
canRead(permission: PermissionGrant, context: PermissionContext): Promise;
diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts
index 4095ce55..1b2e648b 100644
--- a/src/modules/alerts/domain/alert.domain.ts
+++ b/src/modules/alerts/domain/alert.domain.ts
@@ -24,6 +24,12 @@ export type AlertCondition = {
export type AlertRecipients = {
userIds: string[];
roleIds: string[];
+ /**
+ * Addresses outside GitOps (normalized). They belong to the organization's external recipients
+ * (`$modules/notifications`) and only get emails once verified; the cancan filter does not
+ * apply to them.
+ */
+ externalEmails: string[];
};
/** Where an alert lives: an organization alert has no project. */
@@ -110,6 +116,7 @@ export class AlertDomain implements AlertRow {
this.recipients = {
userIds: stringArray(row.recipients?.userIds),
roleIds: stringArray(row.recipients?.roleIds),
+ externalEmails: stringArray(row.recipients?.externalEmails),
};
const channels = stringArray(row.channels).filter((channel): channel is AlertChannel =>
(ALERT_CHANNELS as readonly string[]).includes(channel),
@@ -153,6 +160,7 @@ export class AlertDomain implements AlertRow {
recipients: {
userIds: [...this.recipients.userIds],
roleIds: [...this.recipients.roleIds],
+ externalEmails: [...this.recipients.externalEmails],
},
channels: [...this.channels],
throttleMinutes: this.throttleMinutes,
diff --git a/src/modules/alerts/domain/sample-event.test.ts b/src/modules/alerts/domain/sample-event.test.ts
new file mode 100644
index 00000000..ab78f4c8
--- /dev/null
+++ b/src/modules/alerts/domain/sample-event.test.ts
@@ -0,0 +1,46 @@
+import { describe, expect, it } from 'vitest';
+import { getEventDefinition, type EventDefinition } from '#lib/events/catalog';
+import { buildSampleEvent } from './sample-event';
+
+const analysis = getEventDefinition('code_report.analysis.completed') as EventDefinition;
+
+describe('buildSampleEvent', () => {
+ it('only sets what the conditions need for a dry run', () => {
+ const sample = buildSampleEvent(analysis, {
+ scope: 'project',
+ conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }],
+ });
+ expect(sample.payload).toEqual({ summary: { critical: 1 } });
+ });
+
+ it('builds a complete payload for test emails, conditions still winning', () => {
+ const sample = buildSampleEvent(
+ analysis,
+ {
+ scope: 'project',
+ conditions: [{ field: 'summary.critical', operator: 'gt', value: 5 }],
+ },
+ { complete: true },
+ );
+
+ expect(sample.payload).toMatchObject({
+ analysisId: 'sample-analysis',
+ gitInfo: { branch: 'main' },
+ summary: { critical: 6, high: 2, total: 10 },
+ policies: { status: 'compliant' },
+ });
+ // enum fields get their first option; references are never invented
+ expect(typeof sample.payload.tool).toBe('string');
+ expect(sample.payload).not.toHaveProperty('serviceId');
+ });
+
+ it('fills typed placeholders for events without a sample payload', () => {
+ const definition = getEventDefinition('vault.secret.deleted') as EventDefinition;
+ const sample = buildSampleEvent(
+ definition,
+ { scope: 'project', conditions: [] },
+ { complete: true },
+ );
+ expect(sample.payload).toMatchObject({ key: 'example', folderPath: 'example' });
+ });
+});
diff --git a/src/modules/alerts/domain/sample-event.ts b/src/modules/alerts/domain/sample-event.ts
index a942d545..0d6f9eea 100644
--- a/src/modules/alerts/domain/sample-event.ts
+++ b/src/modules/alerts/domain/sample-event.ts
@@ -37,6 +37,35 @@ function satisfying(field: EventFieldDefinition, condition: AlertCondition): unk
}
}
+/** Placeholder for a field no condition sets, so templates and summaries have data to show. */
+function placeholder(field: EventFieldDefinition): unknown {
+ switch (field.type) {
+ case 'string':
+ return 'example';
+ case 'number':
+ return 0;
+ case 'boolean':
+ return false;
+ case 'enum':
+ return field.options?.[0]?.value;
+ case 'date':
+ return new Date().toISOString();
+ default:
+ // references must point at real entities: none is invented
+ return undefined;
+ }
+}
+
+function getPath(target: Record, path: string): unknown {
+ return path
+ .split('.')
+ .reduce(
+ (node, segment) =>
+ node && typeof node === 'object' ? (node as Record)[segment] : undefined,
+ target,
+ );
+}
+
function setPath(target: Record, path: string, value: unknown) {
const segments = path.split('.');
let node = target;
@@ -50,16 +79,33 @@ function setPath(target: Record, path: string, value: unknown)
/**
* Example event for "Test alert": a payload built so that, where possible, every condition holds
* (derived fields can't be forced). Values the caller passes win over the invented ones.
+ * `complete` (test emails) starts from the definition's `samplePayload` and fills every other
+ * catalog field with a typed placeholder, so the email has something to show.
*/
export function buildSampleEvent(
definition: EventDefinition,
alert: { scope: AlertScope; conditions: readonly AlertCondition[] },
- overrides: { payload?: Record; projectId?: string | null } = {},
+ overrides: {
+ payload?: Record;
+ projectId?: string | null;
+ complete?: boolean;
+ } = {},
): { payload: Record; projectId: string | null } {
const fields = listAlertFields(definition, alert.scope);
- const payload: Record = {};
+ const payload: Record = overrides.complete
+ ? structuredClone((definition.samplePayload ?? {}) as Record)
+ : {};
let projectId: string | null = null;
+ if (overrides.complete) {
+ for (const field of fields) {
+ if (field.derive || isScopeField(field)) continue;
+ if (getPath(payload, field.key as string) !== undefined) continue;
+ const value = placeholder(field);
+ if (value !== undefined) setPath(payload, field.key as string, value);
+ }
+ }
+
for (const condition of alert.conditions) {
const field = fields.find((candidate) => candidate.key === condition.field);
if (!field) continue;
diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts
index aff53c1a..3688a2a2 100644
--- a/src/modules/alerts/index.ts
+++ b/src/modules/alerts/index.ts
@@ -1,4 +1,4 @@
-import { eventBus } from '#lib/server/events';
+import { eventBus, type Unsubscribe } from '#lib/server/events';
import {
isSmtpConfigured,
mailQueue,
@@ -8,10 +8,11 @@ import {
import { createLogger } from '#lib/server/logger';
import { cancanService, roleService, userAccessService, apiKeysService } from '../auth';
import { codeReportSecurityPolicyService, codeReportService } from '../code-report';
+import { externalRecipientService } from '../notifications';
import { organizationService } from '../organization';
import { projectService } from '../projects';
import { vaultService } from '../vault';
-import { AlertEngine } from './application/alert-engine';
+import { AlertEngine, type AlertEngineOptions } from './application/alert-engine';
import { AlertService } from './application/alert.service';
import { AlertThrottle } from './application/alert-throttle';
import { RecipientResolver } from './application/recipient-resolver';
@@ -39,36 +40,93 @@ const recipientResolver = new RecipientResolver(alertDirectory, (userId, permiss
);
const ENGINE_KEY = Symbol.for('gitops.alerts.engine');
-type GlobalWithEngine = typeof globalThis & {
- [ENGINE_KEY]?: { engine: AlertEngine; attached: boolean };
+type EngineDependencies = Pick<
+ AlertEngineOptions,
+ 'repository' | 'directory' | 'recipients' | 'externalRecipients' | 'notifier'
+>;
+/** Bump when the way the engine is built changes, so a running dev server rebuilds it. */
+const ENGINE_WIRING = 2;
+
+type EngineSlot = {
+ engine: AlertEngine | null;
+ wiring?: number;
+ /** Kept apart from the engine so its windows survive an engine swap. */
+ throttle: AlertThrottle;
+ /** Bus subscription of the current engine. */
+ detach: Unsubscribe | null;
+ attached: boolean;
+ dependencies: EngineDependencies;
+};
+type GlobalWithEngine = typeof globalThis & { [ENGINE_KEY]?: EngineSlot };
+
+/** Calls go to whatever `get()` returns at call time. */
+function latest(get: () => T): T {
+ return new Proxy({} as T, {
+ get(_target, property) {
+ const target = get();
+ const value = Reflect.get(target, property);
+ return typeof value === 'function' ? value.bind(target) : value;
+ },
+ });
+}
+
+const dependencies: EngineDependencies = {
+ repository: alertRepository,
+ directory: alertDirectory,
+ recipients: recipientResolver,
+ externalRecipients: externalRecipientService,
+ notifier: new AlertMailNotifier(mailQueue),
};
// one engine per process: HMR re-evaluating this module must not subscribe a second one, and the
-// throttle windows must survive it
-const engineSlot = ((globalThis as GlobalWithEngine)[ENGINE_KEY] ??= {
- engine: new AlertEngine({
- repository: alertRepository,
- directory: alertDirectory,
- recipients: recipientResolver,
- notifier: new AlertMailNotifier(mailQueue),
- throttle: new AlertThrottle(),
+// throttle windows must survive it. Its collaborators are resolved on every call from the latest
+// evaluation: objects kept from an earlier one would run stale code and read a stale GitDB cache
+const engineSlot: EngineSlot = ((globalThis as GlobalWithEngine)[ENGINE_KEY] ??= {
+ engine: null,
+ throttle: new AlertThrottle(),
+ detach: null,
+ attached: false,
+ dependencies,
+});
+engineSlot.dependencies = dependencies;
+// slots created by an older version of this module lack it
+engineSlot.throttle ??= new AlertThrottle();
+
+function createEngine(): AlertEngine {
+ return new AlertEngine({
+ repository: latest(() => engineSlot.dependencies.repository),
+ directory: latest(() => engineSlot.dependencies.directory),
+ recipients: latest(() => engineSlot.dependencies.recipients),
+ externalRecipients: latest(() => engineSlot.dependencies.externalRecipients!),
+ notifier: latest(() => engineSlot.dependencies.notifier),
+ throttle: engineSlot.throttle,
logger: log,
// without SMTP there is nobody to tell: skip the work instead of logging a failure per event
deliveryEnabled: () => isMailConfigured(),
- }),
- attached: false,
-});
+ });
+}
+
+// in dev, a change to the engine's code (or to how it is wired) reloads it: swap the engine (same
+// throttle, same single bus subscription) instead of running stale code until a restart
+if (!(engineSlot.engine instanceof AlertEngine) || engineSlot.wiring !== ENGINE_WIRING) {
+ engineSlot.detach?.();
+ engineSlot.engine = createEngine();
+ engineSlot.wiring = ENGINE_WIRING;
+ engineSlot.detach = engineSlot.attached ? engineSlot.engine.attach(eventBus) : null;
+}
-export const alertEngine = engineSlot.engine;
+export const alertEngine: AlertEngine = engineSlot.engine;
export const alertService = new AlertService(alertRepository, alertDirectory, {
onChange: () => alertEngine.invalidate(),
+ externalRecipients: externalRecipientService,
+ logger: log,
});
/** Subscribes the alert engine to the bus once per process (`hooks.server.ts`). */
export function registerAlertEngine(): void {
if (engineSlot.attached) return;
- alertEngine.attach(eventBus);
+ engineSlot.detach = alertEngine.attach(eventBus);
registerMailShutdown();
engineSlot.attached = true;
log.info('[alerts] engine registered');
diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts
index 4c7bda84..d44ed75c 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts
@@ -48,7 +48,7 @@ function analysisEvent(): AnyDomainEvent {
function alertEmail(overrides: Partial = {}): AlertEmail {
return {
- recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com' },
+ recipient: { kind: 'member', 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,
@@ -181,6 +181,91 @@ describe('AlertMailNotifier', () => {
expect(html).toContain('in Kettu');
});
+ it('sends external recipients a reduced email with an unsubscribe link', async () => {
+ const unsubscribeUrl = `${ORIGIN}/notifications/unsubscribe?token=v1.abc.def`;
+ await notifier.sendAlert(
+ alertEmail({
+ recipient: { kind: 'external', email: 'ana@partner.com', unsubscribeUrl },
+ alert: { id: 'alert-2', name: 'Secretos borrados', description: null, scope: 'project' },
+ event: {
+ id: 'event-3',
+ type: 'vault.secret.deleted',
+ occurredAt: '2026-11-20T10:00:00.000Z',
+ actor: { kind: 'user', userId: 'u2' },
+ scope: { organizationId: 'org-1', projectId: 'p1' },
+ payload: {
+ secretId: 's1',
+ key: 'DB_PASSWORD',
+ folderId: null,
+ folderPath: '/payments',
+ environmentIds: ['env-prod'],
+ },
+ },
+ definition: getEventDefinition('vault.secret.deleted') as EventDefinition,
+ names: new Map([['env-prod', 'Production']]),
+ }),
+ );
+
+ const mail = sender.last;
+ expectClean(mail.content);
+ expect(mail.to).toEqual(['ana@partner.com']);
+ expect(mail.headers).toEqual({ 'List-Unsubscribe': `<${unsubscribeUrl}>` });
+ expect(mail.content).toContain('');
+ expect(mail.content).toContain('Production');
+ // sensitive catalog fields and the links into the app are left out
+ expect(mail.content).not.toContain('DB_PASSWORD');
+ expect(mail.content).not.toContain('/payments');
+ expect(mail.content).not.toContain(`${ORIGIN}/org/`);
+ expect(mail.content).toContain(`href="${unsubscribeUrl}"`);
+ expect(mail.content).toContain('Kettu added your address to the alert “Secretos borrados”');
+ expect(sender.sent[0].context).toMatchObject({ kind: 'alert_external' });
+ });
+
+ it('uses the generic template for external recipients of analysis alerts', async () => {
+ await notifier.sendAlert(
+ alertEmail({
+ recipient: {
+ kind: 'external',
+ email: 'ana@partner.com',
+ unsubscribeUrl: `${ORIGIN}/notifications/unsubscribe?token=t`,
+ },
+ }),
+ );
+ expect(sender.last.content).toContain('data-fields');
+ expect(sender.last.content).not.toContain('data-severities');
+ expect(sender.last.content).not.toContain('code-report/history');
+ });
+
+ it('throws when the queue gives up, so the engine counts the email as failed', async () => {
+ const failing = new AlertMailNotifier({ enqueue: async () => false });
+ await expect(failing.sendAlert(alertEmail())).rejects.toThrow('Email could not be sent');
+ });
+
+ it('still sends when the event payload lacks what the summary reads', async () => {
+ await notifier.sendAlert(alertEmail({ event: { ...analysisEvent(), payload: {} as never } }));
+ expect(sender.last.subject).toBe('[GitOps] Críticas en api-gateway: Analysis completed');
+ expectClean(sender.last.content);
+ });
+
+ it('marks test emails in the subject and the body', async () => {
+ await notifier.sendAlert(alertEmail({ test: true }));
+ expect(sender.last.subject).toBe(
+ '[Test] [GitOps] Críticas en api-gateway: 3 critical, 5 high (9 in total)',
+ );
+ expect(sender.last.content).toContain('This is a test email');
+ expect(sender.last.content).toContain(
+ `${ORIGIN}/org/kettu/projects/web/settings/alerts/alert-1`,
+ );
+
+ await notifier.sendAlert(
+ alertEmail({
+ test: true,
+ alert: { id: 'draft', name: 'Nueva', description: null, scope: 'project' },
+ }),
+ );
+ expect(sender.last.content).not.toContain('/settings/alerts/draft');
+ });
+
it('leaves the links out without ORIGIN', async () => {
delete process.env.ORIGIN;
await notifier.sendAlert(alertEmail());
@@ -191,7 +276,13 @@ describe('AlertMailNotifier', () => {
it('writes in the recipient language when known', async () => {
await notifier.sendAlert(
alertEmail({
- recipient: { userId: 'u1', username: 'ana', email: 'ana@example.com', locale: 'es' },
+ recipient: {
+ kind: 'member',
+ userId: 'u1',
+ username: 'ana',
+ email: 'ana@example.com',
+ locale: 'es',
+ },
}),
);
expect(sender.last.subject).toBe(
diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
index 8f7d1151..4fd344f1 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
@@ -1,56 +1,45 @@
import {
+ DEFAULT_MAIL_LOCALE,
MailNotification,
absoluteUrl,
+ emailButton as button,
+ emailNote as note,
+ mailLocale,
renderEmail,
renderTemplateString,
+ translateKey,
+ translator,
type MailContext,
+ type MailLocale,
+ type Translate,
} from '#lib/server/infra/notifications';
-import * as messages from '#lib/paraglide/messages.js';
import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog';
import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events';
import type { AlertEmail, AlertNotifierPort, SystemEmail } from '../application/alert-engine';
import { describeEventFields } from './event-summary';
-// `#lib/i18n` is client-oriented (stores, `$app/env`): emails translate with paraglide directly
-export type MailLocale = 'es' | 'en';
-/** Language of an email when the recipient's is unknown. */
-export const DEFAULT_MAIL_LOCALE: MailLocale = 'en';
-
-type MessageFunction = (
- values?: Record,
- options?: { locale?: MailLocale },
-) => string;
-
-type Translate = (key: string, values?: Record) => string;
-
-/** Server-side translation of an i18n key; unknown keys fall back to the key itself. */
-export function translateKey(
- id: string,
- values: Record = {},
- locale: MailLocale = DEFAULT_MAIL_LOCALE,
-): string {
- const message = (messages as Record)[id] as MessageFunction | undefined;
- return message ? message(values, { locale }) : id;
-}
-
-function localeOf(recipient: { locale?: string }): MailLocale {
- return recipient.locale === 'es' || recipient.locale === 'en'
- ? recipient.locale
- : DEFAULT_MAIL_LOCALE;
-}
+export { DEFAULT_MAIL_LOCALE, translateKey, type MailLocale };
/** Where emails go: the mail queue in production, a recorder in tests. */
export type MailSender = {
- enqueue(notification: MailNotification, context?: MailContext): Promise;
+ /** `false` (or a rejection) when the email could not be sent. */
+ enqueue(notification: MailNotification, context?: MailContext): Promise;
};
-// internally generated HTML: every value goes through `{{ }}` (escaped)
-function button(url: string | null, label: string): string {
- if (!url) return '';
- return renderTemplateString(
- '{{ label }}
',
- { url, label },
- );
+/** The queue gave up on an email (it already logged why). */
+export class MailNotSentError extends Error {
+ constructor() {
+ super('Email could not be sent');
+ this.name = 'MailNotSentError';
+ }
+}
+
+function safely(run: () => T): T | undefined {
+ try {
+ return run();
+ } catch {
+ return undefined;
+ }
}
function fieldsTable(rows: { label: string; value: string }[]): string {
@@ -66,14 +55,6 @@ function fieldsTable(rows: { label: string; value: string }[]): string {
return ``;
}
-function note(text: string): string {
- if (!text) return '';
- return renderTemplateString(
- '{{ text }}
',
- { text },
- );
-}
-
const SEVERITIES = [
{ key: 'critical', color: '#b91c1c', background: '#fee2e2' },
{ key: 'high', color: '#c2410c', background: '#ffedd5' },
@@ -90,8 +71,10 @@ export class AlertMailNotifier implements AlertNotifierPort {
constructor(private readonly sender: MailSender) {}
async sendAlert(email: AlertEmail): Promise {
- const locale = localeOf(email.recipient);
- const t: Translate = (key, values) => translateKey(key, values, locale);
+ const { recipient } = email;
+ const external = recipient.kind === 'external';
+ const locale = external ? DEFAULT_MAIL_LOCALE : mailLocale(recipient.locale);
+ const t: Translate = translator(locale);
const { event, where } = email;
const definition = email.definition as EventDefinition & {
link?: (context: unknown) => string | null;
@@ -99,16 +82,22 @@ export class AlertMailNotifier implements AlertNotifierPort {
};
const eventLabel = t(definition.label);
- const message = definition.mailSummary?.(event.payload);
+ // a definition callback that chokes on the payload must not cost the email
+ const message = safely(() => definition.mailSummary?.(event.payload));
const summary = message ? t(message.key, message.values) : eventLabel;
- const subject = t('alerts.email.alertSubject', { alert: email.alert.name, summary });
+ const baseSubject = t('alerts.email.alertSubject', { alert: email.alert.name, summary });
+ const subject = email.test
+ ? t('alerts.email.testSubject', { subject: baseSubject })
+ : baseSubject;
const resourcePath =
- definition.link?.({
- payload: event.payload,
- organizationSlug: where.organizationSlug ?? null,
- projectSlug: where.projectSlug ?? null,
- }) ?? null;
+ safely(() =>
+ definition.link?.({
+ payload: event.payload,
+ organizationSlug: where.organizationSlug ?? null,
+ projectSlug: where.projectSlug ?? null,
+ }),
+ ) ?? null;
const scopeName =
email.alert.scope === 'project' && where.project ? where.project : (where.organization ?? '');
@@ -118,12 +107,18 @@ export class AlertMailNotifier implements AlertNotifierPort {
intro:
email.alert.description ||
t('alerts.email.alertIntro', { event: eventLabel, where: where.project ?? scopeName }),
- suppressedNote:
- email.suppressed > 0 ? note(t('alerts.email.suppressed', { count: email.suppressed })) : '',
- actionButton: button(absoluteUrl(resourcePath), t('alerts.email.viewInApp')),
+ // the templates have no slot of their own for it: the test notice rides on this one
+ suppressedNote: email.test
+ ? note(t('alerts.email.testNote'))
+ : email.suppressed > 0
+ ? note(t('alerts.email.suppressed', { count: email.suppressed }))
+ : '',
+ // an external recipient has no account to open the resource with
+ actionButton: external ? '' : button(absoluteUrl(resourcePath), t('alerts.email.viewInApp')),
};
- const template = definition.mailTemplate ?? 'alert';
+ // the reduced version for external recipients: generic template, no sensitive fields
+ const template = external ? 'alert' : (definition.mailTemplate ?? 'alert');
const variables =
template === 'alert-code-report-analysis'
? { ...common, ...this.analysisVariables(email, t) }
@@ -137,7 +132,9 @@ export class AlertMailNotifier implements AlertNotifierPort {
...(where.project
? [{ label: t('alerts.email.project'), value: where.project }]
: []),
- ...describeEventFields(event, definition, email.names).map((field) => ({
+ ...describeEventFields(event, definition, email.names, {
+ omitSensitive: external,
+ }).map((field) => ({
label: t(field.label),
value: field.translate ? t(field.value) : field.value,
})),
@@ -147,19 +144,36 @@ export class AlertMailNotifier implements AlertNotifierPort {
const content = await renderEmail(template, variables, {
subject,
lang: locale,
- footer: t('alerts.email.footer', { alert: email.alert.name, where: scopeName }),
- footerLink: this.manageLink(email, t),
+ footer: external
+ ? t('alerts.email.externalFooter', {
+ alert: email.alert.name,
+ organization: where.organization ?? 'GitOps',
+ })
+ : t('alerts.email.footer', { alert: email.alert.name, where: scopeName }),
+ footerLink: external
+ ? { url: recipient.unsubscribeUrl, label: t('alerts.email.unsubscribe') }
+ : email.test && email.alert.id === 'draft'
+ ? null // an unsaved alert has nothing to manage yet
+ : this.manageLink(email, t),
});
- await this.sender.enqueue(
- new MailNotification({ to: email.recipient.email, subject, content }),
- { alertId: email.alert.id, eventId: event.id, kind: 'alert' },
+ const sent = await this.sender.enqueue(
+ new MailNotification({
+ to: recipient.email,
+ subject,
+ content,
+ // RFC 2369: mail clients show their own unsubscribe button
+ headers: external ? { 'List-Unsubscribe': `<${recipient.unsubscribeUrl}>` } : undefined,
+ }),
+ { alertId: email.alert.id, eventId: event.id, kind: external ? 'alert_external' : 'alert' },
);
+ // the engine counts it as failed
+ if (sent === false) throw new MailNotSentError();
}
async sendSystemNotification(email: SystemEmail): Promise {
- const locale = localeOf(email.recipient);
- const t: Translate = (key, values) => translateKey(key, values, locale);
+ const locale = mailLocale(email.recipient.locale);
+ const t: Translate = translator(locale);
const { names } = email;
const target = names.project
diff --git a/src/modules/alerts/infrastructure/event-summary.ts b/src/modules/alerts/infrastructure/event-summary.ts
index 697e37b0..24b8e79f 100644
--- a/src/modules/alerts/infrastructure/event-summary.ts
+++ b/src/modules/alerts/infrastructure/event-summary.ts
@@ -19,15 +19,18 @@ function safeValue(event: AnyDomainEvent, key: string): unknown {
/**
* The catalog fields of an event as label/value lines for an email. Reference ids are replaced by
- * the names in `names` when known; enum values and booleans become i18n keys.
+ * the names in `names` when known; enum values and booleans become i18n keys. `omitSensitive`
+ * leaves out fields marked `sensitive` (emails to external recipients).
*/
export function describeEventFields(
event: AnyDomainEvent,
definition: EventDefinition,
names: ReadonlyMap = new Map(),
+ options: { omitSensitive?: boolean } = {},
): EventFieldLine[] {
const lines: EventFieldLine[] = [];
for (const field of definition.fields) {
+ if (options.omitSensitive && field.sensitive) continue;
const value = safeValue(event, field.key as string);
if (value === undefined || value === null || value === '') continue;
if (Array.isArray(value) && value.length === 0) continue;
diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts
index d1344b4f..8a32daf0 100644
--- a/src/modules/auth/domain/role-permissions.data.ts
+++ b/src/modules/auth/domain/role-permissions.data.ts
@@ -18,6 +18,7 @@ export const ORGANIZATION_ADMIN_PERMISSIONS = [
'organization:audit:all',
'organization:events:all',
'organization:alerts:all',
+ 'organization:notifications:all',
];
export const ORGANIZATION_DEVELOPER_PERMISSIONS = [
@@ -33,6 +34,7 @@ export const PROJECT_ADMIN_PERMISSIONS = [
'project:server-keys:all',
'project:audit:all',
'project:alerts:all',
+ 'project:notifications:all',
'project:vault:secrets:all',
'project:vault:environments:all',
'project:vault:settings:all',
diff --git a/src/modules/notifications/application/external-recipient.service.test.ts b/src/modules/notifications/application/external-recipient.service.test.ts
new file mode 100644
index 00000000..5ff6ffc2
--- /dev/null
+++ b/src/modules/notifications/application/external-recipient.service.test.ts
@@ -0,0 +1,322 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import { hashToken } from '#lib/server/infra/tokens';
+import {
+ ExternalRecipientStateError,
+ InvalidNotificationLinkError,
+ NotificationSettingsValidationError,
+ VerificationRateLimitedError,
+} from '../domain/external-recipient.domain';
+import { UNSUBSCRIBE_TTL_MS, VERIFICATION_TTL_MS } from './external-recipient.service';
+import { createNotificationsFixture } from './testing';
+
+const ORG = 'org-1';
+const OTHER_ORG = 'org-2';
+const DAY = 24 * 60 * 60 * 1000;
+
+type Fixture = ReturnType;
+
+async function linkError(promise: Promise) {
+ const error = await promise.catch((caught) => caught);
+ expect(error).toBeInstanceOf(InvalidNotificationLinkError);
+ return (error as InvalidNotificationLinkError).reason;
+}
+
+function tokenOf(url: string) {
+ return new URL(url).searchParams.get('token')!;
+}
+
+describe('ExternalRecipientService', () => {
+ let f: Fixture;
+
+ beforeEach(async () => {
+ f = createNotificationsFixture();
+ await f.settings.setAllowedDomains(ORG, ['partner.com', '*.client.io']);
+ });
+
+ describe('check', () => {
+ it('normalizes valid addresses and reports invalid or not allowed ones by index', async () => {
+ const result = await f.recipients.check(ORG, [
+ 'Ana@Partner.com',
+ 'not-an-email',
+ 'bob@evil.com',
+ 'eva@eu.client.io',
+ 'ana@partner.com',
+ 'root@client.io',
+ ]);
+
+ expect(result.emails).toEqual(['ana@partner.com', 'eva@eu.client.io']);
+ expect(result.errors).toEqual({
+ 1: 'invalid_email',
+ 2: 'domain_not_allowed',
+ 5: 'domain_not_allowed',
+ });
+ });
+
+ it('allows no external address while the list is empty (the default)', async () => {
+ const result = await f.recipients.check(OTHER_ORG, ['ana@partner.com']);
+ expect(result).toEqual({ emails: [], errors: { 0: 'domain_not_allowed' } });
+ });
+ });
+
+ describe('verification', () => {
+ it('creates pending recipients and sends one confirmation link each, stored hashed', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com', 'ana@partner.com'], 'admin');
+
+ const [row] = f.recipientRepository.rows;
+ expect(f.recipientRepository.rows).toHaveLength(1);
+ expect(row).toMatchObject({ email: 'ana@partner.com', status: 'pending', verifiedAt: null });
+ expect(f.notifier.sent).toHaveLength(1);
+ const token = f.notifier.tokenFor('ana@partner.com');
+ expect(f.notifier.sent[0].verifyUrl).toMatch(
+ /^https:\/\/gitops\.example\.com\/notifications\/verify\?token=/,
+ );
+ expect(row.verificationTokenHash).toBe(hashToken(token));
+ expect(JSON.stringify(row)).not.toContain(token);
+ expect(row.verificationExpiresAt).toBe(
+ new Date(f.clock.now.getTime() + VERIFICATION_TTL_MS).toISOString(),
+ );
+ });
+
+ it('does not send again while the link is alive, nor to addresses outside the domains', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ await f.recipients.register(ORG, ['ana@partner.com', 'bob@evil.com'], 'admin');
+
+ expect(f.notifier.sent).toHaveLength(1);
+ expect(f.recipientRepository.rows.map((row) => row.email)).toEqual(['ana@partner.com']);
+ });
+
+ it('verifies once: the link stops working after use', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ const token = f.notifier.tokenFor('ana@partner.com');
+
+ expect(await f.recipients.inspectVerification(token)).toMatchObject({ status: 'pending' });
+ const verified = await f.recipients.verify(token);
+
+ expect(verified.status).toBe('verified');
+ expect(f.recipientRepository.rows[0]).toMatchObject({
+ status: 'verified',
+ verifiedAt: f.clock.now.toISOString(),
+ verificationTokenHash: null,
+ });
+ expect(await linkError(f.recipients.verify(token))).toBe('invalid');
+ });
+
+ it('rejects expired and unknown links', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ const token = f.notifier.tokenFor('ana@partner.com');
+
+ expect(await linkError(f.recipients.verify('made-up'))).toBe('invalid');
+ expect(await linkError(f.recipients.verify(''))).toBe('invalid');
+ f.advance(VERIFICATION_TTL_MS);
+ expect(await linkError(f.recipients.verify(token))).toBe('expired');
+ expect(f.recipientRepository.rows[0].status).toBe('pending');
+ });
+
+ it('sends a new link when an expired pending address is added again', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ const first = f.notifier.tokenFor('ana@partner.com');
+ f.advance(VERIFICATION_TTL_MS + 1);
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+
+ expect(f.notifier.sent).toHaveLength(2);
+ const second = f.notifier.tokenFor('ana@partner.com');
+ expect(await linkError(f.recipients.verify(first))).toBe('invalid');
+ expect((await f.recipients.verify(second)).status).toBe('verified');
+ });
+
+ it('rate limits confirmation emails per address and per organization', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ const [{ id }] = f.recipientRepository.rows;
+
+ await f.recipients.resendVerification(ORG, id);
+ await f.recipients.resendVerification(ORG, id);
+ const limited = await f.recipients.resendVerification(ORG, id).catch((error) => error);
+ expect(limited).toBeInstanceOf(VerificationRateLimitedError);
+ expect(f.notifier.sent).toHaveLength(3);
+
+ f.advance(60 * 60 * 1000);
+ await expect(f.recipients.resendVerification(ORG, id)).resolves.toMatchObject({
+ status: 'pending',
+ });
+
+ // 30 per organization and hour
+ const many = Array.from({ length: 40 }, (_, index) => `user${index}@partner.com`);
+ await f.recipients.register(ORG, many, 'admin');
+ expect(f.notifier.sent).toHaveLength(4 + 29);
+ expect(f.recipientRepository.rows.filter((row) => row.status === 'pending')).toHaveLength(41);
+ });
+
+ it('keeps the address pending when the email fails, and never throws on register', async () => {
+ f.notifier.fail = true;
+ await expect(
+ f.recipients.register(ORG, ['ana@partner.com'], 'admin'),
+ ).resolves.toBeUndefined();
+ expect(f.recipientRepository.rows[0].status).toBe('pending');
+ });
+
+ it('does not resend to verified recipients or to other organizations', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ await f.recipients.verify(f.notifier.tokenFor('ana@partner.com'));
+ const [{ id }] = f.recipientRepository.rows;
+
+ await expect(f.recipients.resendVerification(ORG, id)).rejects.toBeInstanceOf(
+ ExternalRecipientStateError,
+ );
+ await expect(f.recipients.resendVerification(OTHER_ORG, id)).rejects.toThrow(/not found/);
+ });
+
+ it('builds no link without ORIGIN, so nothing is sent', async () => {
+ f = createNotificationsFixture({ origin: null });
+ await f.settings.setAllowedDomains(ORG, ['partner.com']);
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+
+ expect(f.notifier.sent).toHaveLength(0);
+ expect(f.recipientRepository.rows[0]).toMatchObject({
+ status: 'pending',
+ verificationTokenHash: null,
+ });
+ });
+ });
+
+ describe('delivery and unsubscribe', () => {
+ async function verified(email: string) {
+ await f.recipients.register(ORG, [email], 'admin');
+ await f.recipients.verify(f.notifier.tokenFor(email));
+ }
+
+ it('only delivers to verified addresses of allowed domains, with an unsubscribe link', async () => {
+ await verified('ana@partner.com');
+ await f.recipients.register(ORG, ['pending@partner.com'], 'admin');
+
+ const deliverable = await f.recipients.deliverable(ORG, [
+ 'ana@partner.com',
+ 'pending@partner.com',
+ 'never-added@partner.com',
+ ]);
+
+ expect(deliverable.map((recipient) => recipient.email)).toEqual(['ana@partner.com']);
+ expect(deliverable[0].unsubscribeUrl).toMatch(
+ /^https:\/\/gitops\.example\.com\/notifications\/unsubscribe\?token=v1\./,
+ );
+ // another organization's alerts don't see it
+ expect(await f.recipients.deliverable(OTHER_ORG, ['ana@partner.com'])).toEqual([]);
+ });
+
+ it('unsubscribes once: the link is single use and the address stops receiving', async () => {
+ await verified('ana@partner.com');
+ const [{ unsubscribeUrl }] = await f.recipients.deliverable(ORG, ['ana@partner.com']);
+ const token = tokenOf(unsubscribeUrl);
+
+ expect((await f.recipients.inspectUnsubscribe(token)).email).toBe('ana@partner.com');
+ expect((await f.recipients.unsubscribe(token)).status).toBe('unsubscribed');
+ expect(await f.recipients.deliverable(ORG, ['ana@partner.com'])).toEqual([]);
+ expect(await linkError(f.recipients.unsubscribe(token))).toBe('invalid');
+ expect(f.recipientRepository.rows[0]).toMatchObject({
+ status: 'unsubscribed',
+ unsubscribedAt: f.clock.now.toISOString(),
+ unsubscribeVersion: 1,
+ });
+ });
+
+ it('lets an unsubscribed address resubscribe only through a new confirmation', async () => {
+ await verified('ana@partner.com');
+ const [{ unsubscribeUrl }] = await f.recipients.deliverable(ORG, ['ana@partner.com']);
+ await f.recipients.unsubscribe(tokenOf(unsubscribeUrl));
+ const [{ id }] = f.recipientRepository.rows;
+
+ // adding it to another alert does not resubscribe it
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ expect(f.recipientRepository.rows[0].status).toBe('unsubscribed');
+
+ await f.recipients.resendVerification(ORG, id);
+ await f.recipients.verify(f.notifier.tokenFor('ana@partner.com'));
+ const [again] = await f.recipients.deliverable(ORG, ['ana@partner.com']);
+ expect(again.unsubscribeUrl).not.toBe(unsubscribeUrl);
+ expect(await linkError(f.recipients.unsubscribe(tokenOf(unsubscribeUrl)))).toBe('invalid');
+ });
+
+ it('rejects expired and forged unsubscribe links', async () => {
+ await verified('ana@partner.com');
+ const [{ unsubscribeUrl }] = await f.recipients.deliverable(ORG, ['ana@partner.com']);
+ const token = tokenOf(unsubscribeUrl);
+
+ expect(await linkError(f.recipients.unsubscribe(`${token.slice(0, -2)}xx`))).toBe('invalid');
+ expect(await linkError(f.recipients.unsubscribe('v1.e30.abc'))).toBe('invalid');
+ f.advance(UNSUBSCRIBE_TTL_MS);
+ expect(await linkError(f.recipients.unsubscribe(token))).toBe('expired');
+ expect(f.recipientRepository.rows[0].status).toBe('verified');
+ });
+
+ it('sends nothing to external addresses without ORIGIN (no unsubscribe link)', async () => {
+ await verified('ana@partner.com');
+ const noOrigin = createNotificationsFixture({ origin: null });
+ noOrigin.recipientRepository.rows = structuredClone(f.recipientRepository.rows);
+ await noOrigin.settings.setAllowedDomains(ORG, ['partner.com']);
+
+ expect(await noOrigin.recipients.deliverable(ORG, ['ana@partner.com'])).toEqual([]);
+ });
+ });
+
+ describe('allowed domains', () => {
+ it('blocks the recipients of a removed domain without deleting them, and restores them', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com', 'eva@eu.client.io'], 'admin');
+ await f.recipients.verify(f.notifier.tokenFor('ana@partner.com'));
+
+ const removed = await f.settings.setAllowedDomains(ORG, ['*.client.io']);
+ expect(removed).toMatchObject({ blocked: 1, restored: 0 });
+ expect(f.recipientRepository.rows.map((row) => [row.email, row.status])).toEqual([
+ ['ana@partner.com', 'blocked'],
+ ['eva@eu.client.io', 'pending'],
+ ]);
+ expect(await f.recipients.deliverable(ORG, ['ana@partner.com'])).toEqual([]);
+
+ const restored = await f.settings.setAllowedDomains(ORG, 'partner.com\n*.client.io');
+ expect(restored).toMatchObject({ blocked: 0, restored: 1 });
+ expect(f.recipientRepository.rows[0]).toMatchObject({ status: 'verified', blockedAt: null });
+ expect(await f.recipients.deliverable(ORG, ['ana@partner.com'])).toHaveLength(1);
+ });
+
+ it('records the consent of a blocked address that confirms, but keeps it blocked', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ await f.settings.setAllowedDomains(ORG, []);
+ await f.recipients.verify(f.notifier.tokenFor('ana@partner.com'));
+
+ expect(f.recipientRepository.rows[0]).toMatchObject({ status: 'blocked' });
+ await f.settings.setAllowedDomains(ORG, ['partner.com']);
+ expect(f.recipientRepository.rows[0].status).toBe('verified');
+ });
+
+ it('normalizes, de-duplicates and validates the domain list', async () => {
+ const result = await f.settings.setAllowedDomains(ORG, [
+ ' Partner.COM ',
+ 'partner.com',
+ 'ÑANDÚ.es',
+ ]);
+ expect(result.settings.allowedExternalEmailDomains).toEqual([
+ 'partner.com',
+ 'xn--and-6ma2c.es',
+ ]);
+
+ const error = await f.settings
+ .setAllowedDomains(ORG, ['partner.com', 'http://evil', '*'])
+ .catch((caught) => caught);
+ expect(error).toBeInstanceOf(NotificationSettingsValidationError);
+ expect(error.errors).toEqual({
+ 'allowedExternalEmailDomains.1': 'invalid_domain',
+ 'allowedExternalEmailDomains.2': 'invalid_domain',
+ });
+ // nothing changed
+ expect((await f.settings.get(ORG)).allowedExternalEmailDomains).toEqual([
+ 'partner.com',
+ 'xn--and-6ma2c.es',
+ ]);
+ });
+
+ it('stamps blockedAt with the time the domain was removed', async () => {
+ await f.recipients.register(ORG, ['ana@partner.com'], 'admin');
+ f.advance(DAY);
+ await f.settings.setAllowedDomains(ORG, []);
+ expect(f.recipientRepository.rows[0].blockedAt).toBe(f.clock.now.toISOString());
+ });
+ });
+});
diff --git a/src/modules/notifications/application/external-recipient.service.ts b/src/modules/notifications/application/external-recipient.service.ts
new file mode 100644
index 00000000..808603a3
--- /dev/null
+++ b/src/modules/notifications/application/external-recipient.service.ts
@@ -0,0 +1,351 @@
+import { RateLimiter } from '#lib/server/infra/rate-limit';
+import {
+ createOneTimeToken,
+ hashToken,
+ isTokenAlive,
+ signToken,
+ verifySignedToken,
+} from '#lib/server/infra/tokens';
+import { emailDomain, isDomainAllowed, normalizeEmail } from '../domain/email-address';
+import {
+ ExternalRecipientDomain,
+ ExternalRecipientNotFoundError,
+ ExternalRecipientStateError,
+ InvalidNotificationLinkError,
+ VerificationRateLimitedError,
+ type ExternalEmailError,
+ type ExternalRecipientStatus,
+ type ExternalRecipientView,
+} from '../domain/external-recipient.domain';
+import type {
+ ExternalRecipientChanges,
+ ExternalRecipientRepositoryPort,
+} from '../infrastructure/repositories/external-recipient.repository';
+import type { NotificationSettingsRepositoryPort } from '../infrastructure/repositories/notification-settings.repository';
+
+export type VerificationEmail = {
+ email: string;
+ organizationId: string;
+ verifyUrl: string;
+ expiresAt: string;
+};
+
+export interface ExternalRecipientNotifierPort {
+ /** Sent right away, not through the mail queue: the link carries a token. */
+ sendVerification(email: VerificationEmail): Promise;
+}
+
+/** Public paths of the links; made absolute by `absoluteUrl` (`null` without `ORIGIN`). */
+export const VERIFY_PATH = '/notifications/verify';
+export const UNSUBSCRIBE_PATH = '/notifications/unsubscribe';
+
+const UNSUBSCRIBE_PURPOSE = 'notifications.unsubscribe';
+const DAY_MS = 24 * 60 * 60 * 1000;
+export const VERIFICATION_TTL_MS = 7 * DAY_MS;
+/** Life of the unsubscribe link of an email; an old email's link then shows "expired". */
+export const UNSUBSCRIBE_TTL_MS = 90 * DAY_MS;
+/** Addresses one alert (and one call) may carry. */
+export const MAX_EXTERNAL_EMAILS = 50;
+
+export type ExternalRecipientServiceOptions = {
+ /** HMAC secret of the unsubscribe links (`GITDB_ENCRYPTION_KEY`). */
+ secret: () => string;
+ /** Absolute URL of an app path, or `null` when `ORIGIN` is not set. */
+ absoluteUrl: (path: string) => string | null;
+ now?: () => Date;
+ generateId?: () => string;
+ /** Verification emails per address (any organization). */
+ perAddressLimiter?: RateLimiter;
+ /** Verification emails per organization. */
+ perOrganizationLimiter?: RateLimiter;
+ logger?: { warn: (object: object, message: string) => void };
+};
+
+export type DeliverableRecipient = { email: string; unsubscribeUrl: string };
+
+export type ExternalEmailCheck = {
+ /** The valid addresses, normalized and without duplicates. */
+ emails: string[];
+ /** `` → error code. */
+ errors: Record;
+};
+
+/**
+ * External email recipients of an organization's alerts: allowed-domain checks, the
+ * confirmation link (random token, stored hashed, 7 days, single use), the unsubscribe link
+ * (stateless HMAC token, single use through `unsubscribeVersion`) and the list of addresses an
+ * alert may actually email right now.
+ */
+export class ExternalRecipientService {
+ private readonly now: () => Date;
+ private readonly generateId: () => string;
+ private readonly perAddress: RateLimiter;
+ private readonly perOrganization: RateLimiter;
+
+ constructor(
+ private readonly repository: ExternalRecipientRepositoryPort,
+ private readonly settings: Pick,
+ private readonly notifier: ExternalRecipientNotifierPort,
+ private readonly options: ExternalRecipientServiceOptions,
+ ) {
+ this.now = options.now ?? (() => new Date());
+ this.generateId = options.generateId ?? (() => crypto.randomUUID());
+ const clock = () => this.now().getTime();
+ this.perAddress =
+ options.perAddressLimiter ?? new RateLimiter({ limit: 3, windowMs: 60 * 60 * 1000 }, clock);
+ this.perOrganization =
+ options.perOrganizationLimiter ??
+ new RateLimiter({ limit: 30, windowMs: 60 * 60 * 1000 }, clock);
+ }
+
+ /** Normalizes `emails` and tells which are invalid or outside the allowed domains. */
+ async check(organizationId: string, emails: readonly unknown[]): Promise {
+ const { allowedExternalEmailDomains: allowed } = await this.settings.get(organizationId);
+ const valid = new Set();
+ const errors: Record = {};
+ emails.forEach((raw, index) => {
+ const email = normalizeEmail(raw);
+ if (!email) errors[index] = 'invalid_email';
+ else if (!isDomainAllowed(emailDomain(email), allowed)) errors[index] = 'domain_not_allowed';
+ else valid.add(email);
+ });
+ return { emails: [...valid], errors };
+ }
+
+ async list(organizationId: string): Promise {
+ const recipients = await this.repository.listByOrganization(organizationId);
+ return recipients.map((recipient) => recipient.toView());
+ }
+
+ /** Status of each address in the organization (`missing` when it was never added). */
+ async statuses(
+ organizationId: string,
+ emails: readonly string[],
+ ): Promise> {
+ const recipients = await this.repository.listByOrganization(organizationId);
+ const byEmail = new Map(recipients.map((recipient) => [recipient.email, recipient.status]));
+ return new Map(emails.map((email) => [email, byEmail.get(email) ?? 'missing']));
+ }
+
+ /**
+ * Makes sure every address exists for the organization, creating the missing ones as
+ * `pending`, and sends the confirmation email to pending addresses without a live link. Call
+ * it after the alert using them was saved; addresses must have passed `check()`. A failed or
+ * rate-limited email leaves the address pending (it can be resent from the settings page)
+ * and never throws.
+ */
+ async register(organizationId: string, emails: readonly string[], actorUserId: string) {
+ const { allowedExternalEmailDomains: allowed } = await this.settings.get(organizationId);
+ for (const raw of emails) {
+ const email = normalizeEmail(raw);
+ if (!email || !isDomainAllowed(emailDomain(email), allowed)) continue;
+ let recipient = await this.repository.findByEmail(organizationId, email);
+ if (!recipient) {
+ const timestamp = this.now().toISOString();
+ const row = new ExternalRecipientDomain({
+ id: this.generateId(),
+ organizationId,
+ email,
+ status: 'pending',
+ unsubscribeVersion: 0,
+ createdByUserId: actorUserId,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ }).toJson();
+ await this.repository.create(row);
+ recipient = new ExternalRecipientDomain(row);
+ }
+ const linkAlive = isTokenAlive(recipient.verificationExpiresAt, this.now().getTime());
+ if (recipient.status !== 'pending' || linkAlive) {
+ continue;
+ }
+ await this.sendVerification(recipient).catch((error) => {
+ this.options.logger?.warn(
+ {
+ recipientId: recipient.id,
+ organizationId,
+ reason: error instanceof Error ? error.name : 'unknown',
+ },
+ '[notifications] verification email not sent',
+ );
+ });
+ }
+ }
+
+ /**
+ * Sends a new confirmation link to a `pending` or `unsubscribed` address (the owner has to
+ * click it again to resubscribe). Rate limited per address and per organization.
+ */
+ async resendVerification(organizationId: string, id: string): Promise {
+ const recipient = await this.repository.findById(id);
+ if (!recipient || recipient.organizationId !== organizationId) {
+ throw new ExternalRecipientNotFoundError(id);
+ }
+ if (recipient.status !== 'pending' && recipient.status !== 'unsubscribed') {
+ throw new ExternalRecipientStateError(recipient.status);
+ }
+ await this.sendVerification(recipient);
+ return (await this.repository.findById(id))!.toView();
+ }
+
+ /** What a confirmation link points at, without using it (the GET page). */
+ async inspectVerification(token: string): Promise {
+ const value = token.trim();
+ const recipient = value
+ ? await this.repository.findByVerificationTokenHash(hashToken(value))
+ : null;
+ if (!recipient) throw new InvalidNotificationLinkError('invalid');
+ if (!isTokenAlive(recipient.verificationExpiresAt, this.now().getTime())) {
+ throw new InvalidNotificationLinkError('expired');
+ }
+ return recipient;
+ }
+
+ /** Confirms the address. The link works once: its hash is cleared. */
+ async verify(token: string): Promise {
+ const recipient = await this.inspectVerification(token);
+ const timestamp = this.now().toISOString();
+ const changes: ExternalRecipientChanges = {
+ verifiedAt: timestamp,
+ unsubscribedAt: null,
+ verificationTokenHash: null,
+ verificationExpiresAt: null,
+ // a blocked address keeps waiting for its domain; the consent is recorded meanwhile
+ status: recipient.status === 'blocked' ? 'blocked' : 'verified',
+ };
+ await this.repository.update(recipient.id, changes);
+ return new ExternalRecipientDomain({ ...recipient.toJson(), ...changes });
+ }
+
+ /** Unsubscribe link for an email to `recipient`; `null` without `ORIGIN`. */
+ unsubscribeUrl(recipient: Pick) {
+ const token = signToken(
+ UNSUBSCRIBE_PURPOSE,
+ { rid: recipient.id, v: recipient.unsubscribeVersion },
+ { secret: this.options.secret(), ttlMs: UNSUBSCRIBE_TTL_MS, now: this.now().getTime() },
+ );
+ return this.options.absoluteUrl(`${UNSUBSCRIBE_PATH}?token=${encodeURIComponent(token)}`);
+ }
+
+ /** What an unsubscribe link points at, without using it (the GET page). */
+ async inspectUnsubscribe(token: string): Promise {
+ const payload = verifySignedToken<{ rid?: unknown; v?: unknown }>(UNSUBSCRIBE_PURPOSE, token, {
+ secret: this.options.secret(),
+ now: this.now().getTime(),
+ });
+ if (!payload) {
+ // tell an expired link apart only when the signature is ours
+ const stale = verifySignedToken(UNSUBSCRIBE_PURPOSE, token, {
+ secret: this.options.secret(),
+ now: 0,
+ });
+ throw new InvalidNotificationLinkError(stale ? 'expired' : 'invalid');
+ }
+ const recipient =
+ typeof payload.rid === 'string' ? await this.repository.findById(payload.rid) : null;
+ // the version moves on every unsubscribe: a used link no longer matches
+ if (!recipient || payload.v !== recipient.unsubscribeVersion) {
+ throw new InvalidNotificationLinkError('invalid');
+ }
+ return recipient;
+ }
+
+ async unsubscribe(token: string): Promise {
+ const recipient = await this.inspectUnsubscribe(token);
+ const changes: ExternalRecipientChanges = {
+ status: recipient.status === 'blocked' ? 'blocked' : 'unsubscribed',
+ unsubscribedAt: this.now().toISOString(),
+ unsubscribeVersion: recipient.unsubscribeVersion + 1,
+ verificationTokenHash: null,
+ verificationExpiresAt: null,
+ };
+ await this.repository.update(recipient.id, changes);
+ return new ExternalRecipientDomain({ ...recipient.toJson(), ...changes });
+ }
+
+ /**
+ * The addresses of `emails` an alert of the organization may email now: verified, with an
+ * allowed domain, and with an unsubscribe link (none are returned without `ORIGIN`).
+ */
+ async deliverable(
+ organizationId: string,
+ emails: readonly string[],
+ ): Promise {
+ if (emails.length === 0) return [];
+ const [{ allowedExternalEmailDomains: allowed }, recipients] = await Promise.all([
+ this.settings.get(organizationId),
+ this.repository.listByOrganization(organizationId),
+ ]);
+ const wanted = new Set(emails);
+ const result: DeliverableRecipient[] = [];
+ for (const recipient of recipients) {
+ if (!wanted.has(recipient.email) || !recipient.canReceive) continue;
+ if (!isDomainAllowed(emailDomain(recipient.email), allowed)) continue;
+ const unsubscribeUrl = this.unsubscribeUrl(recipient);
+ if (unsubscribeUrl) result.push({ email: recipient.email, unsubscribeUrl });
+ }
+ return result;
+ }
+
+ /**
+ * Blocks the addresses whose domain is no longer allowed and gives the others back the status
+ * they had before being blocked. Called whenever the allowed domains change.
+ */
+ async applyDomainPolicy(organizationId: string, allowed: readonly string[]) {
+ const recipients = await this.repository.listByOrganization(organizationId);
+ let blocked = 0;
+ let restored = 0;
+ for (const recipient of recipients) {
+ const isAllowed = isDomainAllowed(emailDomain(recipient.email), allowed);
+ if (!isAllowed && recipient.status !== 'blocked') {
+ await this.repository.update(recipient.id, {
+ status: 'blocked',
+ blockedAt: this.now().toISOString(),
+ });
+ blocked += 1;
+ } else if (isAllowed && recipient.status === 'blocked') {
+ await this.repository.update(recipient.id, {
+ status: recipient.unblockedStatus,
+ blockedAt: null,
+ });
+ restored += 1;
+ }
+ }
+ return { blocked, restored };
+ }
+
+ private async sendVerification(recipient: ExternalRecipientDomain): Promise {
+ const addressKey = recipient.email;
+ const organizationKey = recipient.organizationId;
+ const byAddress = this.perAddress.check(addressKey);
+ const byOrganization = this.perOrganization.check(organizationKey);
+ if (!byAddress.allowed || !byOrganization.allowed) {
+ const retryAfterMs = Math.max(
+ byAddress.allowed ? 0 : byAddress.retryAfterMs,
+ byOrganization.allowed ? 0 : byOrganization.retryAfterMs,
+ );
+ throw new VerificationRateLimitedError(retryAfterMs);
+ }
+
+ const link = createOneTimeToken(VERIFICATION_TTL_MS, this.now());
+ const verifyUrl = this.options.absoluteUrl(
+ `${VERIFY_PATH}?token=${encodeURIComponent(link.token)}`,
+ );
+ if (!verifyUrl) throw new Error('ORIGIN is not set: verification links cannot be built');
+
+ this.perAddress.consume(addressKey);
+ this.perOrganization.consume(organizationKey);
+ // a new link replaces the previous one, which stops working
+ await this.repository.update(recipient.id, {
+ verificationTokenHash: link.hash,
+ verificationExpiresAt: link.expiresAt,
+ lastVerificationSentAt: this.now().toISOString(),
+ });
+ await this.notifier.sendVerification({
+ email: recipient.email,
+ organizationId: recipient.organizationId,
+ verifyUrl,
+ expiresAt: link.expiresAt,
+ });
+ }
+}
diff --git a/src/modules/notifications/application/notification-settings.service.ts b/src/modules/notifications/application/notification-settings.service.ts
new file mode 100644
index 00000000..c8b0ff8f
--- /dev/null
+++ b/src/modules/notifications/application/notification-settings.service.ts
@@ -0,0 +1,65 @@
+import { normalizeDomainPattern } from '../domain/email-address';
+import { NotificationSettingsValidationError } from '../domain/external-recipient.domain';
+import {
+ MAX_ALLOWED_DOMAINS,
+ type NotificationSettings,
+} from '../domain/notification-settings.domain';
+import type { NotificationSettingsRepositoryPort } from '../infrastructure/repositories/notification-settings.repository';
+import type { ExternalRecipientService } from './external-recipient.service';
+
+export type AllowedDomainsUpdate = {
+ settings: NotificationSettings;
+ /** External recipients blocked because their domain was removed. */
+ blocked: number;
+ /** Blocked recipients restored because their domain is allowed again. */
+ restored: number;
+};
+
+/** A list, or text with one domain per line / separated by commas (the settings form). */
+function splitDomains(input: unknown): unknown[] | null {
+ if (Array.isArray(input)) return input;
+ if (typeof input === 'string') {
+ return input
+ .split(/[\s,;]+/)
+ .map((item) => item.trim())
+ .filter(Boolean);
+ }
+ return input === undefined || input === null ? [] : null;
+}
+
+/** Organization-wide notification settings (`/org//settings/notifications`). */
+export class NotificationSettingsService {
+ constructor(
+ private readonly repository: NotificationSettingsRepositoryPort,
+ private readonly recipients: Pick,
+ ) {}
+
+ get(organizationId: string): Promise {
+ return this.repository.get(organizationId);
+ }
+
+ /**
+ * Replaces the allowed external email domains (normalized, exact match, `*.` for subdomains)
+ * and blocks or restores the organization's external recipients accordingly.
+ */
+ async setAllowedDomains(organizationId: string, input: unknown): Promise {
+ const items = splitDomains(input);
+ const errors: Record = {};
+ const domains: string[] = [];
+ if (!items) {
+ errors.allowedExternalEmailDomains = 'invalid';
+ } else {
+ items.forEach((item, index) => {
+ const domain = normalizeDomainPattern(item);
+ if (!domain) errors[`allowedExternalEmailDomains.${index}`] = 'invalid_domain';
+ else if (!domains.includes(domain)) domains.push(domain);
+ });
+ if (domains.length > MAX_ALLOWED_DOMAINS) errors.allowedExternalEmailDomains = 'too_many';
+ }
+ if (Object.keys(errors).length > 0) throw new NotificationSettingsValidationError(errors);
+
+ const settings = await this.repository.setAllowedDomains(organizationId, domains);
+ const { blocked, restored } = await this.recipients.applyDomainPolicy(organizationId, domains);
+ return { settings, blocked, restored };
+ }
+}
diff --git a/src/modules/notifications/application/testing.ts b/src/modules/notifications/application/testing.ts
new file mode 100644
index 00000000..cc6c7fc1
--- /dev/null
+++ b/src/modules/notifications/application/testing.ts
@@ -0,0 +1,64 @@
+import { RateLimiter } from '#lib/server/infra/rate-limit';
+import {
+ InMemoryExternalRecipientRepository,
+ InMemoryNotificationSettingsRepository,
+} from '../infrastructure/repositories/in-memory.repositories';
+import {
+ ExternalRecipientService,
+ type ExternalRecipientNotifierPort,
+ type VerificationEmail,
+} from './external-recipient.service';
+import { NotificationSettingsService } from './notification-settings.service';
+
+export class RecordingVerificationNotifier implements ExternalRecipientNotifierPort {
+ sent: VerificationEmail[] = [];
+ fail = false;
+
+ async sendVerification(email: VerificationEmail) {
+ if (this.fail) throw new Error('SMTP down');
+ this.sent.push(email);
+ }
+
+ /** Token of the last confirmation link sent to `email`. */
+ tokenFor(email: string): string {
+ const last = [...this.sent].reverse().find((item) => item.email === email);
+ if (!last) throw new Error(`no verification sent to ${email}`);
+ return new URL(last.verifyUrl).searchParams.get('token')!;
+ }
+}
+
+/** The notifications module wired with in-memory repositories and a controllable clock. */
+export function createNotificationsFixture(options: { origin?: string | null } = {}) {
+ const clock = { now: new Date('2026-11-24T10:00:00.000Z') };
+ const origin = options.origin === undefined ? 'https://gitops.example.com' : options.origin;
+ const settingsRepository = new InMemoryNotificationSettingsRepository();
+ const recipientRepository = new InMemoryExternalRecipientRepository();
+ const notifier = new RecordingVerificationNotifier();
+ let id = 0;
+ const time = () => clock.now.getTime();
+ const recipients = new ExternalRecipientService(
+ recipientRepository,
+ settingsRepository,
+ notifier,
+ {
+ secret: () => 'test-encryption-key',
+ absoluteUrl: (path) => (origin ? `${origin}${path}` : null),
+ now: () => clock.now,
+ generateId: () => `recipient-${++id}`,
+ perAddressLimiter: new RateLimiter({ limit: 3, windowMs: 60 * 60 * 1000 }, time),
+ perOrganizationLimiter: new RateLimiter({ limit: 30, windowMs: 60 * 60 * 1000 }, time),
+ },
+ );
+ const settings = new NotificationSettingsService(settingsRepository, recipients);
+ return {
+ clock,
+ settingsRepository,
+ recipientRepository,
+ notifier,
+ recipients,
+ settings,
+ advance(ms: number) {
+ clock.now = new Date(clock.now.getTime() + ms);
+ },
+ };
+}
diff --git a/src/modules/notifications/domain/email-address.test.ts b/src/modules/notifications/domain/email-address.test.ts
new file mode 100644
index 00000000..893b9e7d
--- /dev/null
+++ b/src/modules/notifications/domain/email-address.test.ts
@@ -0,0 +1,76 @@
+import { describe, expect, it } from 'vitest';
+import {
+ domainMatches,
+ emailDomain,
+ isDomainAllowed,
+ normalizeDomain,
+ normalizeDomainPattern,
+ normalizeEmail,
+} from './email-address';
+
+describe('normalizeEmail', () => {
+ it('lower-cases and trims valid addresses', () => {
+ expect(normalizeEmail(' Ana.Lopez+alerts@Partner.COM ')).toBe('ana.lopez+alerts@partner.com');
+ });
+
+ it('converts internationalized domains to punycode', () => {
+ expect(normalizeEmail('pepe@ñandú.es')).toBe('pepe@xn--and-6ma2c.es');
+ });
+
+ it.each([
+ '',
+ 'no-at-sign',
+ '@partner.com',
+ 'ana@',
+ 'ana@localhost',
+ 'ana@127.0.0.1',
+ 'ana@partner..com',
+ 'ana..b@partner.com',
+ 'ana@-partner.com',
+ 'a b@partner.com',
+ 'ana@part ner.com',
+ ])('rejects %j', (value) => {
+ expect(normalizeEmail(value)).toBeNull();
+ });
+
+ it('rejects non-strings', () => {
+ expect(normalizeEmail(42)).toBeNull();
+ expect(normalizeEmail(null)).toBeNull();
+ });
+});
+
+describe('domain patterns', () => {
+ it('normalizes domains and wildcard patterns', () => {
+ expect(normalizeDomain('Partner.COM.')).toBe('partner.com');
+ expect(normalizeDomainPattern(' *.Partner.com ')).toBe('*.partner.com');
+ expect(normalizeDomainPattern('ÑANDÚ.es')).toBe('xn--and-6ma2c.es');
+ });
+
+ it.each(['', '*', '*.', 'http://partner.com', 'ana@partner.com', 'partner', '*.*.com'])(
+ 'rejects the pattern %j',
+ (value) => {
+ expect(normalizeDomainPattern(value)).toBeNull();
+ },
+ );
+
+ it('matches domains exactly, without implicit subdomains', () => {
+ expect(domainMatches('partner.com', 'partner.com')).toBe(true);
+ expect(domainMatches('eu.partner.com', 'partner.com')).toBe(false);
+ expect(domainMatches('evilpartner.com', 'partner.com')).toBe(false);
+ });
+
+ it('matches subdomains only with an explicit wildcard', () => {
+ expect(domainMatches('eu.partner.com', '*.partner.com')).toBe(true);
+ expect(domainMatches('a.eu.partner.com', '*.partner.com')).toBe(true);
+ expect(domainMatches('partner.com', '*.partner.com')).toBe(false);
+ expect(domainMatches('evilpartner.com', '*.partner.com')).toBe(false);
+ });
+
+ it('checks the domain of the address against the list', () => {
+ const email = normalizeEmail('ana@EU.partner.com')!;
+ expect(emailDomain(email)).toBe('eu.partner.com');
+ expect(isDomainAllowed(emailDomain(email), ['partner.com'])).toBe(false);
+ expect(isDomainAllowed(emailDomain(email), ['partner.com', '*.partner.com'])).toBe(true);
+ expect(isDomainAllowed(emailDomain(email), [])).toBe(false);
+ });
+});
diff --git a/src/modules/notifications/domain/email-address.ts b/src/modules/notifications/domain/email-address.ts
new file mode 100644
index 00000000..cb24ed4e
--- /dev/null
+++ b/src/modules/notifications/domain/email-address.ts
@@ -0,0 +1,66 @@
+import { domainToASCII } from 'node:url';
+
+const MAX_EMAIL_LENGTH = 254;
+const LOCAL_PART = /^[A-Za-z0-9.!#$%&'*+/=?^_`{|}~-]{1,64}$/;
+const LABEL = /^(?!-)[a-z0-9-]{1,63}(? 253) return null;
+ const labels = ascii.split('.');
+ // at least a name and a TLD, and no IP literals
+ if (labels.length < 2 || labels.every((label) => /^\d+$/.test(label))) return null;
+ return labels.every((label) => LABEL.test(label)) ? ascii : null;
+}
+
+/**
+ * `user@Example.COM` → `user@example.com` (domain normalized as in `normalizeDomain`, local part
+ * kept as typed but lower-cased so the same mailbox is stored once), or `null` when invalid.
+ */
+export function normalizeEmail(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim();
+ const at = trimmed.lastIndexOf('@');
+ if (at <= 0 || at === trimmed.length - 1) return null;
+ const local = trimmed.slice(0, at);
+ const domain = normalizeDomain(trimmed.slice(at + 1));
+ if (!domain || !LOCAL_PART.test(local) || local.startsWith('.') || local.endsWith('.')) {
+ return null;
+ }
+ if (local.includes('..')) return null;
+ const email = `${local.toLowerCase()}@${domain}`;
+ return email.length <= MAX_EMAIL_LENGTH ? email : null;
+}
+
+/** Domain of an already normalized address. */
+export function emailDomain(email: string): string {
+ return email.slice(email.lastIndexOf('@') + 1);
+}
+
+/**
+ * An allowed-domain entry: `empresa.com` (that domain only) or `*.empresa.com` (any subdomain,
+ * not `empresa.com` itself). Normalized like `normalizeDomain`; `null` when invalid.
+ */
+export function normalizeDomainPattern(value: unknown): string | null {
+ if (typeof value !== 'string') return null;
+ const trimmed = value.trim().toLowerCase();
+ if (trimmed.startsWith('*.')) {
+ const domain = normalizeDomain(trimmed.slice(2));
+ return domain ? `*.${domain}` : null;
+ }
+ return normalizeDomain(trimmed);
+}
+
+/** Exact match, or subdomain match for a `*.` pattern; there are no implicit subdomains. */
+export function domainMatches(domain: string, pattern: string): boolean {
+ if (pattern.startsWith('*.')) return domain.endsWith(pattern.slice(1));
+ return domain === pattern;
+}
+
+export function isDomainAllowed(domain: string, patterns: readonly string[]): boolean {
+ return patterns.some((pattern) => domainMatches(domain, pattern));
+}
diff --git a/src/modules/notifications/domain/external-recipient.domain.ts b/src/modules/notifications/domain/external-recipient.domain.ts
new file mode 100644
index 00000000..c13fb5ae
--- /dev/null
+++ b/src/modules/notifications/domain/external-recipient.domain.ts
@@ -0,0 +1,176 @@
+export const EXTERNAL_RECIPIENT_STATUSES = [
+ 'pending',
+ 'verified',
+ 'unsubscribed',
+ 'blocked',
+] as const;
+export type ExternalRecipientStatus = (typeof EXTERNAL_RECIPIENT_STATUSES)[number];
+
+export type ExternalRecipientRow = {
+ id: string;
+ organizationId: string;
+ email: string;
+ status: ExternalRecipientStatus;
+ verifiedAt: string | null;
+ unsubscribedAt: string | null;
+ blockedAt: string | null;
+ verificationTokenHash: string | null;
+ verificationExpiresAt: string | null;
+ lastVerificationSentAt: string | null;
+ unsubscribeVersion: number;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+};
+
+/** What the API and the pages may show: never the token hash. */
+export type ExternalRecipientView = Pick<
+ ExternalRecipientRow,
+ | 'id'
+ | 'email'
+ | 'status'
+ | 'verifiedAt'
+ | 'unsubscribedAt'
+ | 'blockedAt'
+ | 'lastVerificationSentAt'
+ | 'createdAt'
+>;
+
+function toIso(value: unknown): string | null {
+ if (value instanceof Date) return value.toISOString();
+ return typeof value === 'string' && value ? value : null;
+}
+
+/**
+ * An email address outside GitOps that alerts of one organization may send to. It is shared by
+ * the organization's alerts, so the address confirms once and one unsubscribe stops every alert
+ * of the organization.
+ *
+ * - `pending`: added, waiting for the owner to confirm the link.
+ * - `verified`: confirmed, receives alerts.
+ * - `unsubscribed`: the owner used an unsubscribe link.
+ * - `blocked`: its domain is no longer allowed by the organization.
+ *
+ * Only `verified` receives. Blocking keeps `verifiedAt` / `unsubscribedAt`, so allowing the domain
+ * again puts the address back where it was.
+ */
+export class ExternalRecipientDomain implements ExternalRecipientRow {
+ id: string;
+ organizationId: string;
+ email: string;
+ status: ExternalRecipientStatus;
+ verifiedAt: string | null;
+ unsubscribedAt: string | null;
+ blockedAt: string | null;
+ verificationTokenHash: string | null;
+ verificationExpiresAt: string | null;
+ lastVerificationSentAt: string | null;
+ unsubscribeVersion: number;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+
+ constructor(row: Record) {
+ this.id = row.id;
+ this.organizationId = row.organizationId;
+ this.email = row.email;
+ this.status = (EXTERNAL_RECIPIENT_STATUSES as readonly string[]).includes(row.status)
+ ? row.status
+ : 'pending';
+ this.verifiedAt = toIso(row.verifiedAt);
+ this.unsubscribedAt = toIso(row.unsubscribedAt);
+ this.blockedAt = toIso(row.blockedAt);
+ this.verificationTokenHash = row.verificationTokenHash ?? null;
+ this.verificationExpiresAt = toIso(row.verificationExpiresAt);
+ this.lastVerificationSentAt = toIso(row.lastVerificationSentAt);
+ this.unsubscribeVersion = Number.isInteger(Number(row.unsubscribeVersion))
+ ? Number(row.unsubscribeVersion)
+ : 0;
+ this.createdByUserId = row.createdByUserId;
+ this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString();
+ this.updatedAt = toIso(row.updatedAt) ?? this.createdAt;
+ }
+
+ get canReceive(): boolean {
+ return this.status === 'verified';
+ }
+
+ /** Status once its domain is allowed again: where it was before being blocked. */
+ get unblockedStatus(): ExternalRecipientStatus {
+ if (this.unsubscribedAt) return 'unsubscribed';
+ return this.verifiedAt ? 'verified' : 'pending';
+ }
+
+ toView(): ExternalRecipientView {
+ return {
+ id: this.id,
+ email: this.email,
+ status: this.status,
+ verifiedAt: this.verifiedAt,
+ unsubscribedAt: this.unsubscribedAt,
+ blockedAt: this.blockedAt,
+ lastVerificationSentAt: this.lastVerificationSentAt,
+ createdAt: this.createdAt,
+ };
+ }
+
+ toJson(): ExternalRecipientRow {
+ return {
+ id: this.id,
+ organizationId: this.organizationId,
+ email: this.email,
+ status: this.status,
+ verifiedAt: this.verifiedAt,
+ unsubscribedAt: this.unsubscribedAt,
+ blockedAt: this.blockedAt,
+ verificationTokenHash: this.verificationTokenHash,
+ verificationExpiresAt: this.verificationExpiresAt,
+ lastVerificationSentAt: this.lastVerificationSentAt,
+ unsubscribeVersion: this.unsubscribeVersion,
+ createdByUserId: this.createdByUserId,
+ createdAt: this.createdAt,
+ updatedAt: this.updatedAt,
+ };
+ }
+}
+
+/** Why an address can't be added; the alert editor maps them to `alerts.errors.`. */
+export type ExternalEmailError = 'invalid_email' | 'domain_not_allowed';
+
+export class NotificationSettingsValidationError extends Error {
+ constructor(readonly errors: Record) {
+ super(`Invalid notification settings: ${Object.keys(errors).join(', ')}`);
+ this.name = 'NotificationSettingsValidationError';
+ }
+}
+
+export class ExternalRecipientNotFoundError extends Error {
+ constructor(id: string) {
+ super(`External recipient not found: ${id}`);
+ this.name = 'ExternalRecipientNotFoundError';
+ }
+}
+
+/** The address is not in a status that allows the operation (resending to a verified one…). */
+export class ExternalRecipientStateError extends Error {
+ constructor(readonly status: ExternalRecipientStatus) {
+ super(`External recipient is ${status}`);
+ this.name = 'ExternalRecipientStateError';
+ }
+}
+
+/** Too many verification emails for the address or the organization; retry later. */
+export class VerificationRateLimitedError extends Error {
+ constructor(readonly retryAfterMs: number) {
+ super('Too many verification emails, try again later');
+ this.name = 'VerificationRateLimitedError';
+ }
+}
+
+/** A verification or unsubscribe link that is unknown, already used or expired. */
+export class InvalidNotificationLinkError extends Error {
+ constructor(readonly reason: 'invalid' | 'expired') {
+ super(`Notification link ${reason}`);
+ this.name = 'InvalidNotificationLinkError';
+ }
+}
diff --git a/src/modules/notifications/domain/notification-settings.domain.ts b/src/modules/notifications/domain/notification-settings.domain.ts
new file mode 100644
index 00000000..d73ba75d
--- /dev/null
+++ b/src/modules/notifications/domain/notification-settings.domain.ts
@@ -0,0 +1,13 @@
+/** Upper bound of the allowed-domain list; it is curated by hand. */
+export const MAX_ALLOWED_DOMAINS = 50;
+
+export type NotificationSettings = {
+ organizationId: string;
+ /** `empresa.com` or `*.empresa.com`, normalized; empty = no external recipients. */
+ allowedExternalEmailDomains: string[];
+ updatedAt: string | null;
+};
+
+export function defaultNotificationSettings(organizationId: string): NotificationSettings {
+ return { organizationId, allowedExternalEmailDomains: [], updatedAt: null };
+}
diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts
new file mode 100644
index 00000000..3586811b
--- /dev/null
+++ b/src/modules/notifications/index.ts
@@ -0,0 +1,69 @@
+import { absoluteUrl, notify } from '#lib/server/infra/notifications';
+import { RateLimiter } from '#lib/server/infra/rate-limit';
+import { createLogger } from '#lib/server/logger';
+import { passwordService } from '../auth';
+import { organizationService } from '../organization';
+import { ExternalRecipientService } from './application/external-recipient.service';
+import { NotificationSettingsService } from './application/notification-settings.service';
+import { ExternalRecipientMailNotifier } from './infrastructure/external-recipient-mail.notifier';
+import { ExternalRecipientRepository } from './infrastructure/repositories/external-recipient.repository';
+import { NotificationSettingsRepository } from './infrastructure/repositories/notification-settings.repository';
+
+const log = createLogger('notifications');
+
+const settingsRepository = new NotificationSettingsRepository();
+
+const LIMITERS_KEY = Symbol.for('gitops.notifications.verification-limiters');
+type Limiters = { perAddress: RateLimiter; perOrganization: RateLimiter };
+type GlobalWithLimiters = typeof globalThis & { [LIMITERS_KEY]?: Limiters };
+
+// only the rate limits live on `globalThis`, so they survive HMR. The service must not: kept
+// across a module reload, its repositories would read a stale GitDB client and cache
+const limiters = ((globalThis as GlobalWithLimiters)[LIMITERS_KEY] ??= {
+ perAddress: new RateLimiter({ limit: 3, windowMs: 60 * 60 * 1000 }),
+ perOrganization: new RateLimiter({ limit: 30, windowMs: 60 * 60 * 1000 }),
+});
+
+export const externalRecipientService = new ExternalRecipientService(
+ new ExternalRecipientRepository(),
+ settingsRepository,
+ new ExternalRecipientMailNotifier({
+ send: (notification) => notify(notification),
+ organizationName: async (id) =>
+ (await organizationService.getOrganization(id).catch(() => null))?.name ?? null,
+ }),
+ {
+ secret: () => passwordService.ensureEncryptionKey(),
+ absoluteUrl: (path) => absoluteUrl(path),
+ perAddressLimiter: limiters.perAddress,
+ perOrganizationLimiter: limiters.perOrganization,
+ logger: log,
+ },
+);
+
+export const notificationSettingsService = new NotificationSettingsService(
+ settingsRepository,
+ externalRecipientService,
+);
+
+export {
+ ExternalRecipientService,
+ MAX_EXTERNAL_EMAILS,
+ UNSUBSCRIBE_PATH,
+ VERIFY_PATH,
+ type DeliverableRecipient,
+ type ExternalEmailCheck,
+} from './application/external-recipient.service';
+export type { AllowedDomainsUpdate } from './application/notification-settings.service';
+export {
+ ExternalRecipientNotFoundError,
+ ExternalRecipientStateError,
+ InvalidNotificationLinkError,
+ NotificationSettingsValidationError,
+ VerificationRateLimitedError,
+ type ExternalEmailError,
+ type ExternalRecipientStatus,
+ type ExternalRecipientView,
+} from './domain/external-recipient.domain';
+export type { NotificationSettings } from './domain/notification-settings.domain';
+export { normalizeEmail } from './domain/email-address';
diff --git a/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts b/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
new file mode 100644
index 00000000..1f5c8398
--- /dev/null
+++ b/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
@@ -0,0 +1,48 @@
+import {
+ DEFAULT_MAIL_LOCALE,
+ MailNotification,
+ emailButton,
+ renderEmail,
+ translator,
+} from '#lib/server/infra/notifications';
+import type {
+ ExternalRecipientNotifierPort,
+ VerificationEmail,
+} from '../application/external-recipient.service';
+
+export type ExternalRecipientMailOptions = {
+ /** Sends one email now (`notify`): the link carries a token, so no queue and no bus. */
+ send: (notification: MailNotification) => Promise;
+ organizationName: (organizationId: string) => Promise;
+};
+
+/**
+ * Confirmation email for an external address (`external-recipient-verify`). The owner has no
+ * GitOps account, so the language is the default one (English).
+ */
+export class ExternalRecipientMailNotifier implements ExternalRecipientNotifierPort {
+ constructor(private readonly options: ExternalRecipientMailOptions) {}
+
+ async sendVerification(email: VerificationEmail): Promise {
+ const t = translator(DEFAULT_MAIL_LOCALE);
+ const organization =
+ (await this.options.organizationName(email.organizationId).catch(() => null)) ?? 'GitOps';
+ const subject = t('notifications.email.verify.subject', { organization });
+ const content = await renderEmail(
+ 'external-recipient-verify',
+ {
+ title: t('notifications.email.verify.title'),
+ intro: t('notifications.email.verify.intro', { organization, email: email.email }),
+ explanation: t('notifications.email.verify.explanation'),
+ actionButton: emailButton(email.verifyUrl, t('notifications.email.verify.action')),
+ expiry: t('notifications.email.verify.expiry', {
+ date: new Date(email.expiresAt).toUTCString(),
+ }),
+ ignore: t('notifications.email.verify.ignore'),
+ verifyUrl: email.verifyUrl,
+ },
+ { subject, lang: DEFAULT_MAIL_LOCALE, footer: t('notifications.email.verify.footer') },
+ );
+ await this.options.send(new MailNotification({ to: email.email, subject, content }));
+ }
+}
diff --git a/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts b/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
new file mode 100644
index 00000000..e5d34fca
--- /dev/null
+++ b/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
@@ -0,0 +1,71 @@
+import { ExternalRecipientEntity } from '#lib/database/schemas';
+import { Repository } from '#lib/server/infra/repository';
+import {
+ ExternalRecipientDomain,
+ type ExternalRecipientRow,
+} from '../../domain/external-recipient.domain';
+
+export type ExternalRecipientChanges = Partial<
+ Omit
+>;
+
+/** Persistence port; `InMemoryExternalRecipientRepository` implements it in tests. */
+export interface ExternalRecipientRepositoryPort {
+ findById(id: string): Promise;
+ findByEmail(organizationId: string, email: string): Promise;
+ findByVerificationTokenHash(hash: string): Promise;
+ listByOrganization(organizationId: string): Promise;
+ create(row: ExternalRecipientRow): Promise;
+ update(id: string, changes: ExternalRecipientChanges): Promise;
+}
+
+export class ExternalRecipientRepository
+ extends Repository
+ implements ExternalRecipientRepositoryPort
+{
+ async findById(id: string) {
+ const result = await this.db.select().from(ExternalRecipientEntity).where({ id }).limit(1);
+ const row = result.rows[0];
+ return row ? new ExternalRecipientDomain(row) : null;
+ }
+
+ async findByEmail(organizationId: string, email: string) {
+ const result = await this.db
+ .select()
+ .from(ExternalRecipientEntity)
+ .where({ organizationId, email })
+ .limit(1);
+ const row = result.rows[0];
+ return row ? new ExternalRecipientDomain(row) : null;
+ }
+
+ async findByVerificationTokenHash(hash: string) {
+ const result = await this.db
+ .select()
+ .from(ExternalRecipientEntity)
+ .where({ verificationTokenHash: hash })
+ .limit(1);
+ const row = result.rows[0];
+ return row ? new ExternalRecipientDomain(row) : null;
+ }
+
+ async listByOrganization(organizationId: string) {
+ const result = await this.db
+ .select()
+ .from(ExternalRecipientEntity)
+ .where({ organizationId })
+ .orderBy('createdAt', 'asc');
+ return result.rows.map((row: any) => new ExternalRecipientDomain(row));
+ }
+
+ async create(row: ExternalRecipientRow) {
+ await this.db.insert(ExternalRecipientEntity).values({ ...row });
+ }
+
+ async update(id: string, changes: ExternalRecipientChanges) {
+ await this.db
+ .update(ExternalRecipientEntity)
+ .set({ ...changes, updatedAt: new Date().toISOString() })
+ .where({ id });
+ }
+}
diff --git a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
new file mode 100644
index 00000000..99abd3d3
--- /dev/null
+++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
@@ -0,0 +1,73 @@
+import {
+ ExternalRecipientDomain,
+ type ExternalRecipientRow,
+} from '../../domain/external-recipient.domain';
+import {
+ defaultNotificationSettings,
+ type NotificationSettings,
+} from '../../domain/notification-settings.domain';
+import type {
+ ExternalRecipientChanges,
+ ExternalRecipientRepositoryPort,
+} from './external-recipient.repository';
+import type { NotificationSettingsRepositoryPort } from './notification-settings.repository';
+
+/** In-memory fakes for unit tests; they store copies so callers can't mutate the stored rows. */
+export class InMemoryNotificationSettingsRepository implements NotificationSettingsRepositoryPort {
+ settings = new Map();
+
+ async get(organizationId: string) {
+ const stored = this.settings.get(organizationId);
+ return stored ? structuredClone(stored) : defaultNotificationSettings(organizationId);
+ }
+
+ async setAllowedDomains(organizationId: string, domains: string[]) {
+ const settings = {
+ organizationId,
+ allowedExternalEmailDomains: [...domains],
+ updatedAt: new Date().toISOString(),
+ };
+ this.settings.set(organizationId, settings);
+ return structuredClone(settings);
+ }
+}
+
+export class InMemoryExternalRecipientRepository implements ExternalRecipientRepositoryPort {
+ rows: ExternalRecipientRow[] = [];
+
+ private copy(row: ExternalRecipientRow | undefined) {
+ return row ? new ExternalRecipientDomain(structuredClone(row)) : null;
+ }
+
+ async findById(id: string) {
+ return this.copy(this.rows.find((row) => row.id === id));
+ }
+
+ async findByEmail(organizationId: string, email: string) {
+ return this.copy(
+ this.rows.find((row) => row.organizationId === organizationId && row.email === email),
+ );
+ }
+
+ async findByVerificationTokenHash(hash: string) {
+ return this.copy(this.rows.find((row) => row.verificationTokenHash === hash));
+ }
+
+ async listByOrganization(organizationId: string) {
+ return this.rows
+ .filter((row) => row.organizationId === organizationId)
+ .map((row) => this.copy(row)!);
+ }
+
+ async create(row: ExternalRecipientRow) {
+ this.rows.push(structuredClone(row));
+ }
+
+ async update(id: string, changes: ExternalRecipientChanges) {
+ this.rows = this.rows.map((row) =>
+ row.id === id
+ ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() }
+ : row,
+ );
+ }
+}
diff --git a/src/modules/notifications/infrastructure/repositories/notification-settings.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-settings.repository.ts
new file mode 100644
index 00000000..b7137fdb
--- /dev/null
+++ b/src/modules/notifications/infrastructure/repositories/notification-settings.repository.ts
@@ -0,0 +1,60 @@
+import { NotificationSettingsEntity } from '#lib/database/schemas';
+import { Repository } from '#lib/server/infra/repository';
+import {
+ defaultNotificationSettings,
+ type NotificationSettings,
+} from '../../domain/notification-settings.domain';
+
+export interface NotificationSettingsRepositoryPort {
+ /** The organization's settings, or the defaults when none were saved. */
+ get(organizationId: string): Promise;
+ setAllowedDomains(organizationId: string, domains: string[]): Promise;
+}
+
+function toSettings(row: Record): NotificationSettings {
+ const domains = Array.isArray(row.allowedExternalEmailDomains)
+ ? row.allowedExternalEmailDomains.filter((item: unknown) => typeof item === 'string')
+ : [];
+ const updatedAt =
+ row.updatedAt instanceof Date ? row.updatedAt.toISOString() : (row.updatedAt ?? null);
+ return { organizationId: row.organizationId, allowedExternalEmailDomains: domains, updatedAt };
+}
+
+export class NotificationSettingsRepository
+ extends Repository
+ implements NotificationSettingsRepositoryPort
+{
+ private async find(organizationId: string) {
+ const result = await this.db
+ .select()
+ .from(NotificationSettingsEntity)
+ .where({ organizationId })
+ .limit(1);
+ return result.rows[0] ?? null;
+ }
+
+ async get(organizationId: string): Promise {
+ const row = await this.find(organizationId);
+ return row ? toSettings(row) : defaultNotificationSettings(organizationId);
+ }
+
+ async setAllowedDomains(organizationId: string, domains: string[]) {
+ const existing = await this.find(organizationId);
+ const timestamp = new Date().toISOString();
+ if (existing) {
+ await this.db
+ .update(NotificationSettingsEntity)
+ .set({ allowedExternalEmailDomains: domains, updatedAt: timestamp })
+ .where({ id: existing.id });
+ } else {
+ await this.db.insert(NotificationSettingsEntity).values({
+ id: crypto.randomUUID(),
+ organizationId,
+ allowedExternalEmailDomains: domains,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ });
+ }
+ return { organizationId, allowedExternalEmailDomains: domains, updatedAt: timestamp };
+ }
+}
diff --git a/src/notifications/email/external-recipient-verify.html b/src/notifications/email/external-recipient-verify.html
new file mode 100644
index 00000000..071c5674
--- /dev/null
+++ b/src/notifications/email/external-recipient-verify.html
@@ -0,0 +1,13 @@
+{{ title }}
+
+
{{ intro }}
+
{{ explanation }}
+
+{{{ actionButton }}}
+
diff --git a/src/routes/+layout.server.ts b/src/routes/+layout.server.ts
index fa0bb74e..793d7e23 100644
--- a/src/routes/+layout.server.ts
+++ b/src/routes/+layout.server.ts
@@ -60,6 +60,7 @@ export async function load({ locals, url }) {
canReadOrgAudit,
canReadOrgEvents,
canReadOrganizationAlerts,
+ canReadOrgNotificationSettings,
] = await Promise.all([
orgSectionPermission('organization:projects:read'),
orgSectionPermission('organization:users:read'),
@@ -70,7 +71,10 @@ export async function load({ locals, url }) {
orgSectionPermission('organization:audit:read'),
orgSectionPermission('organization:events:read'),
orgSectionPermission('organization:alerts:read'),
+ orgSectionPermission('organization:notifications:read'),
]);
+ // allowed domains are organization settings, external recipients are notifications
+ const canReadOrgNotifications = canReadOrgNotificationSettings || canReadOrgGlobal;
const currentProjectSlug = url.pathname.match(/\/projects\/([^/]+)/)?.[1] ?? null;
@@ -175,6 +179,7 @@ export async function load({ locals, url }) {
canReadOrgAudit,
canReadOrgEvents,
canReadOrganizationAlerts,
+ canReadOrgNotifications,
canReadProjectInfo,
canReadProjectUsers,
canReadProjectRoles,
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte
index 12c71bf3..7740ad20 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -16,7 +16,9 @@
setupI18n();
$: isBareLayout =
- $page?.url?.pathname?.startsWith('/auth/') || $page?.url?.pathname?.startsWith('/bootstrap');
+ $page?.url?.pathname?.startsWith('/auth/') ||
+ $page?.url?.pathname?.startsWith('/bootstrap') ||
+ $page?.url?.pathname?.startsWith('/notifications/');
onMount(() => {
sidebarCollapsed = localStorage.getItem('gitops-sidebar-collapsed') === '1';
@@ -66,6 +68,7 @@
canReadOrgAudit={data.canReadOrgAudit}
canReadOrgEvents={data.canReadOrgEvents}
canReadOrganizationAlerts={data.canReadOrganizationAlerts}
+ canReadOrgNotifications={data.canReadOrgNotifications}
canReadProjectInfo={data.canReadProjectInfo}
canReadProjectUsers={data.canReadProjectUsers}
canReadProjectRoles={data.canReadProjectRoles}
diff --git a/src/routes/api/alerts/[id]/test/+server.ts b/src/routes/api/alerts/[id]/test/+server.ts
index e817390d..313da302 100644
--- a/src/routes/api/alerts/[id]/test/+server.ts
+++ b/src/routes/api/alerts/[id]/test/+server.ts
@@ -1,7 +1,8 @@
import { readJson, toResponse } from '#lib/server/alerts/http';
import { testAlert } from '#lib/server/alerts/operations';
-// POST /api/alerts//test { payload?, sampleProjectId? }: dry run, nothing is sent
+// POST /api/alerts//test { payload?, sampleProjectId?, send? }: dry run; `send: true` also
+// emails the recipients that would get it ([Test] subject, rate limited per caller)
export async function POST({ params, request, locals }) {
const body = await readJson(request);
return toResponse(await testAlert(locals, params.id, body));
diff --git a/src/routes/api/alerts/server.test.ts b/src/routes/api/alerts/server.test.ts
index ed475185..7cbe438f 100644
--- a/src/routes/api/alerts/server.test.ts
+++ b/src/routes/api/alerts/server.test.ts
@@ -2,6 +2,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
type Grants = Record;
+const { sentEmails, mail } = vi.hoisted(() => ({
+ sentEmails: [] as unknown[],
+ mail: { configured: true },
+}));
+
// grants per caller and context key (`org:` / `project:`)
const grants: { users: Record; apiKeys: Record } = {
users: {},
@@ -56,6 +61,9 @@ vi.mock('#modules/alerts', async () => {
const { InMemoryAlertRepository } =
await import('#modules/alerts/infrastructure/repositories/in-memory-alert.repository');
const { buildSampleEvent } = await import('#modules/alerts/domain/sample-event');
+ const { createNotificationsFixture } = await import('#modules/notifications/application/testing');
+ const notifications = createNotificationsFixture();
+ await notifications.settings.setAllowedDomains('org-1', ['partner.com']);
const repository = new InMemoryAlertRepository();
const directory = new FakeAlertDirectory();
@@ -76,12 +84,19 @@ vi.mock('#modules/alerts', async () => {
let id = 0;
const alertService = new AlertService(repository, directory, {
generateId: () => `alert-${++id}`,
+ externalRecipients: notifications.recipients,
});
const alertEngine = new AlertEngine({
repository,
directory,
recipients: new RecipientResolver(directory, async () => true),
- notifier: { sendAlert: async () => {}, sendSystemNotification: async () => {} },
+ externalRecipients: notifications.recipients,
+ notifier: {
+ sendAlert: async (email: unknown) => {
+ sentEmails.push(email);
+ },
+ sendSystemNotification: async () => {},
+ },
logger: { info: () => {}, warn: () => {}, error: () => {}, debug: () => {} },
});
return {
@@ -91,6 +106,8 @@ vi.mock('#modules/alerts', async () => {
alertDirectory: directory,
buildSampleEvent,
repository,
+ notifications,
+ isMailConfigured: () => mail.configured,
};
});
@@ -99,6 +116,14 @@ const repository = (alerts as unknown as { repository: { rows: unknown[] } }).re
const collection = await import('./+server');
const item = await import('./[id]/+server');
const test = await import('./[id]/test/+server');
+const draftTest = await import('./test/+server');
+const notifications = (
+ alerts as unknown as {
+ notifications: ReturnType<
+ typeof import('#modules/notifications/application/testing').createNotificationsFixture
+ >;
+ }
+).notifications;
const ADMIN_GRANTS = [
'project:alerts:read',
@@ -141,7 +166,7 @@ describe('/api/alerts', () => {
beforeEach(() => {
repository.rows = [];
grants.users = {
- admin: { 'project:p1': ADMIN_GRANTS },
+ admin: { 'project:p1': [...ADMIN_GRANTS] },
viewer: { 'project:p1': ['project:alerts:read', 'project:codereport:reports:read'] },
// can manage alerts but not read code reports
vaultAdmin: { 'project:p1': ['project:alerts:create', 'project:vault:secrets:read'] },
@@ -191,6 +216,151 @@ describe('/api/alerts', () => {
});
});
+ describe('test emails', () => {
+ beforeEach(() => {
+ sentEmails.length = 0;
+ mail.configured = true;
+ });
+
+ it('only dry-runs unless send is true', async () => {
+ const created = await call(collection.POST, { locals: admin, body: guided });
+ const { id } = (await created.json()) as { id: string };
+
+ const dry = await call(test.POST, { locals: admin, params: { id }, body: {} });
+ expect(dry.status).toBe(200);
+ expect(await dry.json()).not.toHaveProperty('delivery');
+ expect(sentEmails).toHaveLength(0);
+
+ const sent = await call(test.POST, { locals: admin, params: { id }, body: { send: true } });
+ expect(sent.status).toBe(200);
+ await expect(sent.json()).resolves.toMatchObject({ delivery: { sent: 1, failed: 0 } });
+ expect(sentEmails).toEqual([
+ expect.objectContaining({
+ test: true,
+ alert: expect.objectContaining({ id }),
+ recipient: expect.objectContaining({ kind: 'member', userId: 'admin' }),
+ }),
+ ]);
+ });
+
+ it('refuses to send without SMTP and limits test emails per caller', async () => {
+ const created = await call(collection.POST, { locals: admin, body: guided });
+ const { id } = (await created.json()) as { id: string };
+
+ mail.configured = false;
+ const noSmtp = await call(test.POST, { locals: admin, params: { id }, body: { send: true } });
+ expect(noSmtp.status).toBe(409);
+ await expect(noSmtp.json()).resolves.toEqual({ error: 'mail_not_configured' });
+
+ mail.configured = true;
+ const caller = { user: { id: 'limited' } };
+ grants.users.limited = { 'project:p1': [...ADMIN_GRANTS] };
+ const statuses = [];
+ for (let attempt = 0; attempt < 6; attempt++) {
+ const response = await call(test.POST, {
+ locals: caller,
+ params: { id },
+ body: { send: true },
+ });
+ statuses.push(response.status);
+ }
+ expect(statuses).toEqual([200, 200, 200, 200, 200, 429]);
+ });
+
+ it('asks new external addresses of a draft to confirm, then sends them the test', async () => {
+ grants.users.admin['project:p1'].push('project:notifications:update');
+ const body = {
+ ...guided,
+ recipients: { externalEmails: ['draft-test@partner.com'] },
+ send: true,
+ };
+
+ const first = await call(draftTest.POST, { locals: admin, body });
+ expect(first.status).toBe(200);
+ await expect(first.json()).resolves.toMatchObject({
+ external: [{ email: 'draft-test@partner.com', status: 'pending', delivers: false }],
+ delivery: { sent: 0, failed: 0 },
+ });
+ // the confirmation email went out, the alert itself was not saved
+ expect(notifications.notifier.sent.map((email) => email.email)).toContain(
+ 'draft-test@partner.com',
+ );
+ expect(repository.rows).toHaveLength(0);
+ expect(sentEmails).toHaveLength(0);
+
+ await notifications.recipients.verify(
+ notifications.notifier.tokenFor('draft-test@partner.com'),
+ );
+ const second = await call(draftTest.POST, { locals: admin, body });
+ await expect(second.json()).resolves.toMatchObject({
+ external: [{ email: 'draft-test@partner.com', status: 'verified', delivers: true }],
+ delivery: { sent: 1, failed: 0 },
+ });
+ expect(sentEmails).toEqual([
+ expect.objectContaining({
+ test: true,
+ recipient: expect.objectContaining({ kind: 'external', email: 'draft-test@partner.com' }),
+ }),
+ ]);
+ });
+
+ it('still needs alert write permission', async () => {
+ const created = await call(collection.POST, { locals: admin, body: guided });
+ const { id } = (await created.json()) as { id: string };
+ const response = await call(test.POST, {
+ locals: viewer,
+ params: { id },
+ body: { send: true },
+ });
+ expect(response.status).toBe(403);
+ expect(sentEmails).toHaveLength(0);
+ });
+ });
+
+ describe('external email recipients', () => {
+ const external = (emails: string[]) => ({
+ ...guided,
+ recipients: { roleIds: ['r-admin'], externalEmails: emails },
+ });
+
+ it('rejects addresses outside the allowed domains', async () => {
+ grants.users.admin['project:p1'].push('project:notifications:update');
+ const response = await call(collection.POST, {
+ locals: admin,
+ body: external(['ana@partner.com', 'bob@evil.com']),
+ });
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toMatchObject({
+ errors: {
+ 'recipients.externalEmails': 'domain_not_allowed',
+ 'recipients.externalEmails.1': 'domain_not_allowed',
+ },
+ });
+ expect(repository.rows).toHaveLength(0);
+ });
+
+ it('needs project:notifications:update to add them', async () => {
+ const refused = await call(collection.POST, {
+ locals: admin,
+ body: external(['ana@partner.com']),
+ });
+ expect(refused.status).toBe(400);
+ await expect(refused.json()).resolves.toMatchObject({
+ errors: { 'recipients.externalEmails': 'forbidden_external' },
+ });
+
+ grants.users.admin['project:p1'].push('project:notifications:update');
+ const created = await call(collection.POST, {
+ locals: admin,
+ body: external(['Ana@Partner.com']),
+ });
+ expect(created.status).toBe(201);
+ await expect(created.json()).resolves.toMatchObject({
+ recipients: { externalEmails: ['ana@partner.com'] },
+ });
+ });
+ });
+
it('refuses an alert on events its author cannot read (anti-escalation)', async () => {
const response = await call(collection.POST, {
locals: { user: { id: 'vaultAdmin' } },
diff --git a/src/routes/api/alerts/test/+server.ts b/src/routes/api/alerts/test/+server.ts
index b7184e03..50716920 100644
--- a/src/routes/api/alerts/test/+server.ts
+++ b/src/routes/api/alerts/test/+server.ts
@@ -3,7 +3,8 @@ import { resolveLocation } from '#lib/server/alerts/access';
import { readJson, toResponse } from '#lib/server/alerts/http';
import { testDraftAlert } from '#lib/server/alerts/operations';
-// POST /api/alerts/test { organizationId | projectId, …alert, payload?, sampleProjectId? }: dry run of an unsaved alert
+// POST /api/alerts/test { organizationId | projectId, …alert, payload?, sampleProjectId?, send? }:
+// dry run of an unsaved alert; `send: true` also emails its recipients (see [id]/test)
export async function POST({ request, locals }) {
const body = await readJson(request);
const lookup = await resolveLocation({
diff --git a/src/routes/notifications/unsubscribe/+page.server.ts b/src/routes/notifications/unsubscribe/+page.server.ts
new file mode 100644
index 00000000..df184ae0
--- /dev/null
+++ b/src/routes/notifications/unsubscribe/+page.server.ts
@@ -0,0 +1,18 @@
+import { fail } from '@sveltejs/kit';
+import { LINK_PAGE_HEADERS, inspectLink, useLink } from '#lib/server/notifications/links';
+
+export async function load({ url, setHeaders }) {
+ setHeaders(LINK_PAGE_HEADERS);
+ const token = url.searchParams.get('token') ?? '';
+ return { token, link: await inspectLink('unsubscribe', token) };
+}
+
+export const actions = {
+ async default({ request }) {
+ const form = await request.formData();
+ const token = String(form.get('token') ?? '');
+ const link = await useLink('unsubscribe', token);
+ if (link.state !== 'done') return fail(400, { link });
+ return { link };
+ },
+};
diff --git a/src/routes/notifications/unsubscribe/+page.svelte b/src/routes/notifications/unsubscribe/+page.svelte
new file mode 100644
index 00000000..be12863d
--- /dev/null
+++ b/src/routes/notifications/unsubscribe/+page.svelte
@@ -0,0 +1,8 @@
+
+
+
diff --git a/src/routes/notifications/verify/+page.server.ts b/src/routes/notifications/verify/+page.server.ts
new file mode 100644
index 00000000..3c25c79f
--- /dev/null
+++ b/src/routes/notifications/verify/+page.server.ts
@@ -0,0 +1,18 @@
+import { fail } from '@sveltejs/kit';
+import { LINK_PAGE_HEADERS, inspectLink, useLink } from '#lib/server/notifications/links';
+
+export async function load({ url, setHeaders }) {
+ setHeaders(LINK_PAGE_HEADERS);
+ const token = url.searchParams.get('token') ?? '';
+ return { token, link: await inspectLink('verify', token) };
+}
+
+export const actions = {
+ async default({ request }) {
+ const form = await request.formData();
+ const token = String(form.get('token') ?? '');
+ const link = await useLink('verify', token);
+ if (link.state !== 'done') return fail(400, { link });
+ return { link };
+ },
+};
diff --git a/src/routes/notifications/verify/+page.svelte b/src/routes/notifications/verify/+page.svelte
new file mode 100644
index 00000000..a9d9be10
--- /dev/null
+++ b/src/routes/notifications/verify/+page.svelte
@@ -0,0 +1,8 @@
+
+
+
diff --git a/src/routes/org/[org]/settings/notifications/+page.server.ts b/src/routes/org/[org]/settings/notifications/+page.server.ts
new file mode 100644
index 00000000..62c5413e
--- /dev/null
+++ b/src/routes/org/[org]/settings/notifications/+page.server.ts
@@ -0,0 +1,42 @@
+import { error, fail } from '@sveltejs/kit';
+import { organizationService } from '#modules/organization';
+import {
+ loadNotificationSettings,
+ resendVerification,
+ saveAllowedDomains,
+} from '#lib/server/notifications/settings';
+
+export async function load({ parent, locals }) {
+ const { organization } = await parent();
+ const result = await loadNotificationSettings(locals, organization.id);
+ if (!result.ok) throw error(result.status, result.error);
+ return result.data;
+}
+
+export const actions = {
+ async domains({ request, locals, params }) {
+ const organization = await organizationOf(params.org);
+ const form = await request.formData();
+ const domains = String(form.get('allowedExternalEmailDomains') ?? '');
+ const result = await saveAllowedDomains(locals, organization.id, domains);
+ if (!result.ok) {
+ return fail(result.status, { domains, error: result.error, errors: result.errors ?? {} });
+ }
+ return { saved: true, blocked: result.data.blocked, restored: result.data.restored };
+ },
+
+ async resend({ request, locals, params }) {
+ const organization = await organizationOf(params.org);
+ const form = await request.formData();
+ const recipientId = String(form.get('recipientId') ?? '');
+ const result = await resendVerification(locals, organization.id, recipientId);
+ if (!result.ok) return fail(result.status, { recipientId, resendError: result.error });
+ return { resent: recipientId };
+ },
+};
+
+async function organizationOf(slug: string) {
+ const organization = await organizationService.tryFindBySlug(slug);
+ if (!organization) throw error(404, 'Organization not found');
+ return organization;
+}
diff --git a/src/routes/org/[org]/settings/notifications/+page.svelte b/src/routes/org/[org]/settings/notifications/+page.svelte
new file mode 100644
index 00000000..8dedef0a
--- /dev/null
+++ b/src/routes/org/[org]/settings/notifications/+page.svelte
@@ -0,0 +1,189 @@
+
+
+
+ {$_('notifications.settings.title')} - {$_('orgSettings.title')}
+
+
+
+
+ {$_('notifications.settings.title')}
+ {$_('notifications.settings.description')}
+
+
+ {#if !data.mailConfigured || !data.originConfigured}
+
+
+ {!data.mailConfigured
+ ? $_('notifications.settings.mailNotConfigured')
+ : $_('notifications.settings.originNotConfigured')}
+
+ {/if}
+
+
+
+
+
+
+ {$_('notifications.settings.domainsTitle')}
+
+
{$_('notifications.settings.domainsDescription')}
+
+
+
+
+
+
+ {#if data.recipients}
+
+
+
+
+ {$_('notifications.settings.recipientsTitle')}
+
+
+ {$_('notifications.settings.recipientsDescription')}
+
+
+
+ {#if form && 'resendError' in form && form.resendError}
+
+ {$_(`notifications.errors.${form.resendError}`)}
+
+ {:else if form && 'resent' in form && form.resent}
+
+ {$_('notifications.settings.resent')}
+
+ {/if}
+
+ {#if data.recipients.length === 0}
+
+ {$_('notifications.settings.recipientsEmpty')}
+
+ {:else}
+
+
+
+
+ {$_('notifications.settings.email')}
+ {$_('notifications.settings.status')}
+ {$_('notifications.settings.verifiedAt')}
+ {$_('notifications.settings.lastSent')}
+
+ {$_('notifications.settings.actions')}
+
+
+
+
+ {#each data.recipients as recipient (recipient.id)}
+
+ {recipient.email}
+
+
+ {$_(`notifications.status.${recipient.status}`)}
+
+
+ {formatDate(recipient.verifiedAt)}
+
+ {formatDate(recipient.lastVerificationSentAt)}
+
+
+ {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
+
+
+
+
+ {$_('notifications.settings.resend')}
+
+
+ {/if}
+
+
+ {/each}
+
+
+
+ {/if}
+
+ {/if}
+
From ac20a79d79040102d848938f6e89a4f36eb6032a Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Tue, 24 Nov 2026 10:41:53 +0100
Subject: [PATCH 2/2] Feat: Add alerts destination external email
---
.github/copilot-instructions.md | 10 ++++++++++
CLAUDE.md | 10 ++++++++--
src/lib/server/infra/notifications/index.ts | 10 ++--------
.../alerts/infrastructure/alert-mail.notifier.ts | 10 ++++++----
.../infrastructure/external-recipient-mail.notifier.ts | 9 ++-------
5 files changed, 28 insertions(+), 21 deletions(-)
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index d44e0e7a..c4273384 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -105,6 +105,10 @@ con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin
`organization:notifications:read` (leer destinatarios externos y dominios permitidos),
`organization:notifications:update` (añadir direcciones externas, cambiar dominios).
+**Permisos de proyecto:** `project:project:read`, `project:users:read`, `project:roles:read`,
+`project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`
+(leer destinatarios externos de alertas), `project:notifications:update` (añadir direcciones).
+
**Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar
permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para
ocultar acciones que el usuario no puede realizar. El layout raíz (`+layout.server.ts`) calcula permisos
@@ -152,6 +156,12 @@ normalizan errores. Ejecutar `bun run check`, `bun run lint`, `bun run test` y
## Comportamiento conocido
+**Imports de i18n desde notificaciones:** `#lib/server/infra/notifications/index.ts` no re-exporta
+funciones i18n (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`, etc.) porque estas cargan
+mensajes de Paraglide (requiere Vite), pero el index se importa desde `$modules/auth` que se
+ejecuta fuera de Vite en tests e2e. Importar estas funciones directamente desde
+`#lib/server/infra/notifications/i18n` en lugar del index principal.
+
**Startup y readiness del servidor:** El auth guard en `hooks.server.ts` verifica readiness via
`getServerReadyState()` antes de procesar cualquier request. Durante startup, los navegadores
reciben una página de landing "GitOps is starting" que se recarga automáticamente, mientras que
diff --git a/CLAUDE.md b/CLAUDE.md
index ca3d4170..83b8e83d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -292,7 +292,7 @@ return { roles, canCreate };
The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and
passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions:
-- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
+- **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, `project:notifications:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`)
- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`, `organization:notifications:read`
This ensures the UI only displays navigation items for sections the user has permission to view.
@@ -308,7 +308,7 @@ Permissions always include their scope as a prefix (e.g., `organization:projects
- **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts
- **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history
-`organization:notifications:read` and `organization:notifications:update` gate external email recipient management in settings.
+`organization:notifications:read` and `organization:notifications:update` gate external email recipient management at the organization level. At the project level, `project:notifications:read` and `project:notifications:update` control external recipients of project alerts (externals of alerts that scope to a project).
Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module.
@@ -358,6 +358,12 @@ commands change.
## Known behavior
+**i18n imports from notifications:** `#lib/server/infra/notifications/index.ts` does not re-export
+i18n functions (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`, etc.) despite using them internally.
+This is intentional: those functions load Paraglide messages (a Vite requirement), but the notifications
+index is imported by `$modules/auth` which runs outside Vite during e2e tests. When you need these
+functions, import them directly from `#lib/server/infra/notifications/i18n` instead of the main index.
+
**Server startup and readiness:** The auth guard in `hooks.server.ts` checks readiness via
`getServerReadyState()` before processing any request. During startup, browsers receive a
self-reloading "GitOps is starting" landing page, while API requests get a 503 response with
diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts
index 50fd0ea3..9fc2a7d0 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -23,14 +23,8 @@ export {
type SmtpConfig,
} from './config';
export { withRetry, isRetryableMailError, type RetryOptions } from './retry';
-export {
- DEFAULT_MAIL_LOCALE,
- mailLocale,
- translateKey,
- translator,
- type MailLocale,
- type Translate,
-} from './i18n';
+// `./i18n` is not re-exported on purpose: it loads the paraglide messages, and this entry point is
+// imported by `$modules/auth`, which also runs outside Vite (the e2e seed). Import it directly
export { emailButton, emailNote } from './email-parts';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
index 4fd344f1..1c744736 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
@@ -1,18 +1,20 @@
import {
- DEFAULT_MAIL_LOCALE,
MailNotification,
absoluteUrl,
emailButton as button,
emailNote as note,
- mailLocale,
renderEmail,
renderTemplateString,
+ type MailContext,
+} from '#lib/server/infra/notifications';
+import {
+ DEFAULT_MAIL_LOCALE,
+ mailLocale,
translateKey,
translator,
- type MailContext,
type MailLocale,
type Translate,
-} from '#lib/server/infra/notifications';
+} from '#lib/server/infra/notifications/i18n';
import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog';
import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events';
import type { AlertEmail, AlertNotifierPort, SystemEmail } from '../application/alert-engine';
diff --git a/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts b/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
index 1f5c8398..80521c23 100644
--- a/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
+++ b/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
@@ -1,10 +1,5 @@
-import {
- DEFAULT_MAIL_LOCALE,
- MailNotification,
- emailButton,
- renderEmail,
- translator,
-} from '#lib/server/infra/notifications';
+import { MailNotification, emailButton, renderEmail } from '#lib/server/infra/notifications';
+import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n';
import type {
ExternalRecipientNotifierPort,
VerificationEmail,