From 7d39a8cbebfde02140a90d08a7ad0a22e60fdf54 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Wed, 25 Nov 2026 10:55:00 +0100
Subject: [PATCH 1/3] Feat: Add alerts destination external email
---
.github/copilot-instructions.md | 23 +-
CLAUDE.md | 72 +++-
README.md | 21 +-
e2e/fixtures/seed.ts | 14 +-
e2e/specs/alerts.spec.ts | 40 ++
src/hooks.server.ts | 21 +-
src/lib/alerts/types.ts | 12 +
.../components/NotificationLinkPage.svelte | 65 ++++
src/lib/components/alerts/AlertEditor.svelte | 148 +++++++-
src/lib/components/alerts/AlertList.svelte | 61 ++-
.../alerts/AlertSettingsPanel.svelte | 251 +++++++++++++
src/lib/components/alerts/AlertWizard.svelte | 119 +++++-
src/lib/config/permissions.ts | 8 +
src/lib/database/schemas.ts | 35 ++
src/lib/events/catalog/code-report.events.ts | 11 +
src/lib/events/catalog/types.ts | 9 +-
src/lib/events/catalog/vault.events.ts | 10 +-
src/lib/i18n/locales/en.json | 104 +++++-
src/lib/i18n/locales/es.json | 104 +++++-
src/lib/notifications/status.ts | 10 +
src/lib/notifications/types.ts | 18 +
src/lib/server/alerts/operations.ts | 84 ++++-
src/lib/server/alerts/page.ts | 50 ++-
.../server/infra/notifications/config.test.ts | 37 +-
src/lib/server/infra/notifications/config.ts | 17 +-
.../server/infra/notifications/email-parts.ts | 21 ++
src/lib/server/infra/notifications/i18n.ts | 32 ++
src/lib/server/infra/notifications/index.ts | 14 +-
.../notifications/mail-notification.test.ts | 27 ++
.../infra/notifications/mail-notification.ts | 10 +
.../infra/notifications/mail-queue.test.ts | 6 +-
.../server/infra/notifications/mail-queue.ts | 44 ++-
.../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 | 123 ++++++
.../alerts/application/alert-engine.test.ts | 33 +-
.../alerts/application/alert-engine.ts | 147 +++++++-
.../alerts/application/alert.external.test.ts | 345 +++++++++++++++++
.../alerts/application/alert.service.test.ts | 7 +-
.../alerts/application/alert.service.ts | 96 ++++-
.../alerts/application/recipient-resolver.ts | 12 +-
src/modules/alerts/application/types.ts | 14 +-
.../alerts/domain/alert.domain.test.ts | 39 ++
src/modules/alerts/domain/alert.domain.ts | 10 +-
.../alerts/domain/sample-event.test.ts | 46 +++
src/modules/alerts/domain/sample-event.ts | 46 ++-
src/modules/alerts/index.ts | 82 +++-
.../alert-mail.notifier.test.ts | 94 ++++-
.../infrastructure/alert-mail.notifier.ts | 138 +++----
.../alerts/infrastructure/event-summary.ts | 2 +
.../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 | 43 +++
.../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.svelte | 5 +-
src/routes/api/alerts/[id]/test/+server.ts | 1 -
src/routes/api/alerts/server.test.ts | 173 ++++++++-
src/routes/api/alerts/test/+server.ts | 1 -
.../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/alerts/settings/+page.server.ts | 42 +++
.../settings/alerts/settings/+page.svelte | 33 ++
80 files changed, 4676 insertions(+), 250 deletions(-)
create mode 100644 src/lib/components/NotificationLinkPage.svelte
create mode 100644 src/lib/components/alerts/AlertSettingsPanel.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/alert.domain.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/alerts/settings/+page.server.ts
create mode 100644 src/routes/org/[org]/settings/alerts/settings/+page.svelte
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 1d15a26b..dda649ec 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -70,7 +70,7 @@ 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`, `monitoring` y `notifications`. 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
@@ -114,6 +114,21 @@ aplican (regla most-specific-wins). Permite delegación de autoridad granular co
`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).
+**Alertas y destinatarios externos:** `organization:alerts:read|update` y `project:alerts:read|update`
+gestionan alertas por eventos; `organization:notifications:read|update` y `project:notifications:update`
+gestionan destinatarios externos (personas sin cuenta GitOps: vendors, on-call mailboxes). El módulo
+`$modules/notifications` maneja dominios permitidos, verificación y desuscripción. En
+`/org//settings/alerts/settings`, los administradores listan dominios permitidos (ej: `partner.com`,
+`*.partner.com` para subdominos, normalizado a punycode); en alertas, se agregan addresses en `recipients.emails`.
+Cada dirección nueva es `pending` y genera email de confirmación (token aleatorio, hash almacenado, 7 días TTL,
+single use, rate limitado 3/h por address y 30/h por org). Solo addresses `verified` se entregan; estados:
+`pending` → `verified` → `unsubscribed`, o `blocked` si su dominio se quita de la lista permitida. Las rutas
+públicas `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens (no requieren sesión,
+no permiten GET para evitar que scanners abran URLs). Emails a externos usan template reducido (sin campos
+`sensitive`, sin links a la app) con footer de desuscripción y `List-Unsubscribe` HMAC stateless (90 días TTL).
+Sin `ORIGIN` no se envía nada. Infra: `src/lib/server/infra/tokens.ts` (HMAC con `GITDB_ENCRYPTION_KEY`) y
+`rate-limit.ts`.
+
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
`roleService.createDefaultProjectRoles()`. Ambas operaciones inicializan sus roles por defecto.
@@ -133,6 +148,12 @@ normalizan errores. Ejecutar `bun run check`, `bun run lint`, `bun run test` y
## Comportamiento conocido
+**i18n imports from notifications:** `#lib/server/infra/notifications/index.ts` no re-exporta
+los helpers i18n de email (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`…) porque cargan Paraglide
+(requiere Vite), y el index de notifications lo importan módulos que corren fuera de Vite (como `$modules/auth`
+en tests e2e). Importar estos helpers desde `#lib/server/infra/notifications/i18n`. Por la misma razón,
+`e2e/fixtures/seed.ts` siembra dominios permitidos vía `NotificationSettingsRepository`, no desde `$modules/notifications`.
+
**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 555c7f2d..c41e3e82 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -170,7 +170,9 @@ 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`, `alerts`, and `monitoring`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from
+`code-report`, `vault`, `audit`, `alerts`, `monitoring`, and `notifications`. The `notifications`
+module handles external email recipients of alerts (allowed 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
@@ -189,7 +191,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
@@ -271,8 +276,43 @@ 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.emails` 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`, also per address as `recipients.emails.`) 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 via
+ `src/lib/server/infra/rate-limit.ts` and `tokens.ts`). `RecipientResolver` only resolves members; the engine adds the `deliverable()`
+ addresses: 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` from `src/lib/server/infra/tokens.ts`, `GITDB_ENCRYPTION_KEY`, 90 days) made single use by
+ `unsubscribeVersion`. Public pages `/notifications/verify` and `/notifications/unsubscribe`
+ (allowed without session in `hooks.server.ts`, no app shell) 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.
+- Alert settings (`#lib/server/notifications/settings.ts`): allowed domains (read with
+ `organization:settings:read` or `organization:notifications:read`, changed with
+ `organization:settings:update`) and the external recipients status
+ (`organization:notifications:read`, resend confirmation with `organization:notifications:update`).
+ The "Settings" button of the alert lists (organization and project ones, no sidebar entry) opens
+ them in a modal (`AlertSettingsPanel`, data in `AlertListData.settings`) whose forms post to the
+ actions of `/org//settings/alerts/settings`, the same page browsers without JavaScript get.
+ The alert pages also get `data.external` (`ExternalRecipientsEditorData`: allowed domains, whether
+ the user may add addresses, statuses).
- 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
@@ -372,8 +412,8 @@ 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`
+- **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.
@@ -382,9 +422,9 @@ 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
@@ -407,6 +447,15 @@ 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.
+`organization:notifications:read` and `organization:notifications:update` gate external email
+recipients at the organization level; `project:notifications:update` lets project alerts add
+them. Existing roles are not migrated: enable them from the role editor.
+
+Unauthenticated public routes for external alert recipients: `/notifications/verify` and
+`/notifications/unsubscribe` accept POST requests with tokens (confirmations and unsubscribes).
+They 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.
@@ -431,6 +480,13 @@ commands change.
## Known behavior
+**i18n imports from notifications:** `#lib/server/infra/notifications/index.ts` does not re-export
+the email i18n helpers (`DEFAULT_MAIL_LOCALE`, `mailLocale`, `translator`…): they load Paraglide
+messages (a Vite requirement), and the notifications index is imported by `$modules/auth`, which
+runs outside Vite during e2e tests. Import them from `#lib/server/infra/notifications/i18n`. For
+the same reason `e2e/fixtures/seed.ts` seeds allowed domains through
+`NotificationSettingsRepository`, not `$modules/notifications`.
+
**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/README.md b/README.md
index ab72d5c8..f36d461a 100644
--- a/README.md
+++ b/README.md
@@ -139,7 +139,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):
@@ -165,6 +166,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 **Settings → Alerts**, click **Settings** and list the organization's 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, add the addresses next to users and roles (needs
+ `organization:notifications:update` or `project:notifications:update`). The API takes them in
+ `recipients.emails`.
+3. Each new address gets a confirmation email and receives nothing until its owner confirms. Every
+ alert email carries an 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.
+
### Monitoring
HTTP monitors check a URL (method, headers and body of your choice) every 60 seconds by default and
diff --git a/e2e/fixtures/seed.ts b/e2e/fixtures/seed.ts
index 3a1e065d..ef57e642 100644
--- a/e2e/fixtures/seed.ts
+++ b/e2e/fixtures/seed.ts
@@ -2,6 +2,7 @@ import { apiKeysService, roleService, userAccessService } from '#modules/auth';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { codeReportService } from '#modules/code-report';
+import { NotificationSettingsRepository } from '#modules/notifications/infrastructure/repositories/notification-settings.repository';
export const E2E_PASSWORD = 'E2ePassword!123';
@@ -110,6 +111,7 @@ export async function seedAll(): Promise {
slug: 'e2e-primary',
});
await roleService.createDefaultOrganizationRoles(primaryOrg.id);
+ await new NotificationSettingsRepository().setAllowedDomains(primaryOrg.id, ['example.com']);
const primaryOrgRoles = await roleService.listRoles('organization', primaryOrg.id);
const orgAdminRoleId = roleIdBySlug(primaryOrgRoles, 'org-admin');
const orgDeveloperRoleId = roleIdBySlug(primaryOrgRoles, 'org-developer');
@@ -192,7 +194,11 @@ export async function seedAll(): Promise {
],
});
const serverKeysNoDeleteUser = await bareUser('e2e-server-keys-no-delete');
- await assignProjectRole(primaryProject.id, serverKeysNoDeleteUser.userId, serverKeysNoDeleteRole.id);
+ await assignProjectRole(
+ primaryProject.id,
+ serverKeysNoDeleteUser.userId,
+ serverKeysNoDeleteRole.id,
+ );
const serverKeysNoUpdateRole = await roleService.createRole({
name: 'E2E Server Keys No Update',
@@ -202,7 +208,11 @@ export async function seedAll(): Promise {
permissions: ['project:project:read', 'project:server-keys:read', 'project:server-keys:create'],
});
const serverKeysNoUpdateUser = await bareUser('e2e-server-keys-no-update');
- await assignProjectRole(primaryProject.id, serverKeysNoUpdateUser.userId, serverKeysNoUpdateRole.id);
+ await assignProjectRole(
+ primaryProject.id,
+ serverKeysNoUpdateUser.userId,
+ serverKeysNoUpdateRole.id,
+ );
await apiKeysService.createProjectApiKey({
projectId: primaryProject.id,
diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index e1ed06ec..ce12308c 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -67,6 +67,7 @@ test.describe('project alerts', () => {
await page.getByRole('option', { name: 'Project Admin', exact: true }).click();
await targets.fill('oncall@example.com');
await targets.press('Enter');
+ await targets.press('Escape');
await wizard.getByRole('radio', { name: '1 hora' }).click();
await wizard.getByRole('button', { name: 'Siguiente' }).click();
@@ -77,6 +78,7 @@ test.describe('project alerts', () => {
await expect(result).toContainText('El evento de ejemplo cumple las condiciones.');
await expect(result).toContainText(seed.personas.projectAdmin.username);
await expect(result).toContainText('oncall@example.com');
+ await expect(result).toContainText('Sin añadir');
await expect(result).toContainText('no se ha enviado ningún email');
await wizard.getByRole('button', { name: 'Crear alerta' }).click();
@@ -215,11 +217,49 @@ test.describe('organization alerts', () => {
await expect(inherited.getByRole('link', { name: 'Editar' })).toHaveCount(0);
await expect(inherited.getByRole('switch')).toHaveCount(0);
});
+
+ test('the alert settings open in a modal from the list and save the allowed domains', async ({
+ page,
+ loginAs,
+ }) => {
+ await loginAs('orgAdmin');
+ await page.goto(orgAlertsUrl);
+ await page.waitForLoadState('networkidle');
+ await page.getByTestId('alert-settings').click();
+ const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
+ await expect(dialog).toBeVisible();
+ await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}$`));
+
+ const domains = dialog.getByLabel('Dominios (uno por línea)');
+ await expect(domains).toHaveValue('example.com');
+ await domains.fill('example.com\npartner.com');
+ await dialog.getByRole('button', { name: 'Guardar dominios' }).click();
+ await expect(page.getByRole('status').filter({ hasText: 'Dominios guardados' })).toBeVisible();
+ await expect(domains).toHaveValue('example.com\npartner.com');
+ });
+
+ test('project admins without organization access get no settings button', async ({
+ page,
+ loginAs,
+ }) => {
+ await loginAs('projectAdmin');
+ await page.goto(alertsUrl);
+ await expect(page.getByTestId('alert-settings')).toHaveCount(0);
+ });
});
test.describe('without JavaScript', () => {
test.use({ javaScriptEnabled: false });
+ test('the alert settings button opens the settings page', async ({ page, loginAs }) => {
+ await loginAs('orgAdmin');
+ await page.goto(orgAlertsUrl);
+ await page.getByTestId('alert-settings').click();
+ await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}/settings$`));
+ await expect(page.getByRole('heading', { name: 'Configuración de alertas' })).toBeVisible();
+ await expect(page.getByLabel('Dominios (uno por línea)')).toHaveValue(/example\.com/);
+ });
+
test('the editor still creates an alert through form actions', async ({ page, loginAs }) => {
await loginAs('projectAdmin');
await page.goto(`${alertsUrl}/new`);
diff --git a/src/hooks.server.ts b/src/hooks.server.ts
index 39cc2751..668d0697 100644
--- a/src/hooks.server.ts
+++ b/src/hooks.server.ts
@@ -5,16 +5,16 @@ import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import { registerAlertEngine } from '#modules/alerts';
import { getMonitoringConfig, startMonitoring } from '#modules/monitoring';
-import { isInternalMonitoringRequest, verifyWorkerRequest } from '#lib/server/monitoring/internal-auth';
+import {
+ isInternalMonitoringRequest,
+ verifyWorkerRequest,
+} from '#lib/server/monitoring/internal-auth';
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');
@@ -28,7 +28,9 @@ const serverReady = (async () => {
await refreshBootstrapState();
markServerReady();
// monitoring needs GitDB; if its repository or runtime can't start, the rest of the app still does
- startMonitoring().catch((error) => startupLog.error(error, '[startup] monitoring failed to start'));
+ startMonitoring().catch((error) =>
+ startupLog.error(error, '[startup] monitoring failed to start'),
+ );
})();
serverReady.catch((error) => {
@@ -64,6 +66,7 @@ const requestLogger: Handle = async ({ event, resolve }) => {
const authGuard: Handle = async ({ event, resolve }) => {
const pathname = event.url.pathname;
+ if (import.meta.env.DEV) rememberDevOrigin(event.url.origin);
const isApiRequest = pathname.startsWith('/api/');
if (pathname === '/health') {
@@ -127,9 +130,9 @@ const authGuard: Handle = async ({ event, resolve }) => {
return resolve(event);
}
- // 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
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/types.ts b/src/lib/alerts/types.ts
index 80803271..d06c0659 100644
--- a/src/lib/alerts/types.ts
+++ b/src/lib/alerts/types.ts
@@ -3,6 +3,7 @@
* components (`#lib/components/alerts`). Type-only: safe to import from the client.
*/
import type { EventDefinition, Operator } from '#lib/events/catalog';
+import type { NotificationSettingsPage } from '#lib/notifications/types';
import type {
AlertChannel,
AlertRecipients,
@@ -43,6 +44,13 @@ export type AlertDraft = {
throttleMinutes: number;
};
+export type ExternalRecipientsEditorData = {
+ canManage: boolean;
+ allowedDomains: string[];
+ statuses: Record;
+ settingsPath: string | null;
+};
+
type Shared = {
basePath: string;
scope: AlertScope;
@@ -57,9 +65,11 @@ type Shared = {
recipientRoles: AlertOption[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
+ external: ExternalRecipientsEditorData;
};
export type AlertListData = Shared & {
+ settings: NotificationSettingsPage | null;
alerts: AlertRow[];
/** Organization alerts that also fire for this project (project pages only). */
inherited: AlertRow[];
@@ -79,6 +89,8 @@ export type AlertTestView = {
matched: boolean;
recipients: Array<{ userId: string; username: string }>;
deniedCount: number;
+ external: Array<{ email: string; status: string; delivers: boolean }>;
+ delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
diff --git a/src/lib/components/NotificationLinkPage.svelte b/src/lib/components/NotificationLinkPage.svelte
new file mode 100644
index 00000000..27b6bc2d
--- /dev/null
+++ b/src/lib/components/NotificationLinkPage.svelte
@@ -0,0 +1,65 @@
+
+
+
+ {$_(`${base}.title`)} - GitOps
+
+
+
+ {#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 a19fc528..64929aed 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -9,10 +9,13 @@
LoaderCircle,
MailWarning,
Save,
+ Send,
+ ShieldAlert,
Trash2,
} from '@lucide/svelte';
import { Modal } from '#lib/components/ui';
import { _ } from '#lib/i18n';
+ import { statusBadgeClass } from '#lib/notifications/status';
import type {
AlertEditorData,
AlertFormResult,
@@ -42,7 +45,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 deleteOpen = $state(false);
@@ -74,21 +77,44 @@
test = null;
}
+ let externalEnabled = $derived(
+ data.external.allowedDomains.length > 0 || draft.recipients.emails.length > 0,
+ );
+ let externalErrors = $derived(
+ Object.entries(errors)
+ .filter(([key]) => /^recipients\.emails\.\d+$/.test(key))
+ .map(([key, code]) => ({
+ email: draft.recipients.emails[Number(key.split('.').pop())] ?? '',
+ code,
+ })),
+ );
+ function updateEmails(text: string) {
+ draft.recipients.emails = text
+ .split(/[\n,;]+/)
+ .map((value) => value.trim())
+ .filter(Boolean);
+ }
+
+ const OPERATION_ERRORS = ['mail_not_configured', 'test_rate_limited'];
+
function errorFor(key: string) {
return errors[key] ? $_(`alerts.errors.${errors[key]}`) : '';
}
- const submit: SubmitFunction = ({ action }) => {
+ const submit: SubmitFunction = ({ action, submitter }) => {
const intent = action.search.includes('test') ? 'test' : 'save';
- busy = intent;
+ busy = submitter?.getAttribute('name') === 'send' ? '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;
}
@@ -337,20 +363,68 @@
{/if}
-
-
+
{$_('alerts.editor.externalEmails')}
-
- {#if errors['recipients.emails']}
-
{errorFor('recipients.emails')}
+ {#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.emails']}
+
+ {#if externalErrors.length > 0}
+
+ {#each externalErrors as failure (failure.email + failure.code)}
+ {failure.email}: {$_(`alerts.errors.${failure.code}`)}
+ {/each}
+
+ {:else}
+ {errorFor('recipients.emails')}
+ {/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}
@@ -481,7 +555,30 @@
{$_('alerts.test.denied', { values: { count: test.deniedCount } })}
{/if}
-
{$_('alerts.test.nothingSent')}
+ {#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.delivery}
+
+ {$_('alerts.test.delivered', {
+ values: { sent: test.delivery.sent, failed: test.delivery.failed },
+ })}
+
+ {:else}
+
{$_('alerts.test.nothingSent')}
+ {/if}
{/if}
@@ -498,6 +595,21 @@
/>{/if}
{$_('alerts.editor.test')}
+
+ {#if busy === 'send'} {:else} {/if}
+ {busy === 'send' ? $_('alerts.editor.sendingTest') : $_('alerts.editor.sendTest')}
+
{#if busy === 'save'} {:else}(null);
let deleteOpen = $state(false);
let deleting = $state(false);
@@ -76,15 +85,27 @@
: $_('alerts.list.descriptionOrganization')}
- {#if data.canCreate && data.alerts.length > 0}
- openWizard(event, null)}
- >
- {$_('alerts.list.create')}
-
- {/if}
+
{#if !data.mailConfigured}
@@ -325,3 +346,25 @@
{#if data.canCreate || data.canUpdate}
{/if}
+
+{#if data.settings && data.external.settingsPath}
+
+ {#snippet icon()}
+
+ {/snippet}
+
+ {#snippet footer()}
+ (settingsOpen = false)}
+ >{$_('common.close')}
+ {/snippet}
+
+{/if}
diff --git a/src/lib/components/alerts/AlertSettingsPanel.svelte b/src/lib/components/alerts/AlertSettingsPanel.svelte
new file mode 100644
index 00000000..40db41c1
--- /dev/null
+++ b/src/lib/components/alerts/AlertSettingsPanel.svelte
@@ -0,0 +1,251 @@
+
+
+
+ {#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}
+
+ {$_(`notifications.errors.${form.resendError}`)}
+
+ {:else if 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')}
+
+
+
+ {#if busy === recipient.id} {:else} {/if}
+ {$_('notifications.settings.resend')}
+
+
+ {/if}
+
+
+ {/each}
+
+
+
+
+ {/if}
+
+ {/if}
+
diff --git a/src/lib/components/alerts/AlertWizard.svelte b/src/lib/components/alerts/AlertWizard.svelte
index c4adf6b9..9c8595e4 100644
--- a/src/lib/components/alerts/AlertWizard.svelte
+++ b/src/lib/components/alerts/AlertWizard.svelte
@@ -22,6 +22,8 @@
MessageSquare,
Save,
Search,
+ Send,
+ ShieldAlert,
User,
Users,
Webhook,
@@ -47,7 +49,9 @@
AlertTestView,
CatalogEntry,
DraftCondition,
+ ExternalRecipientsEditorData,
} from '#lib/alerts/types';
+ import { statusBadgeClass } from '#lib/notifications/status';
import ConditionBuilder from './ConditionBuilder.svelte';
import { DELIVERED_CHANNELS } from '#modules/alerts/domain/alert.domain';
@@ -59,6 +63,7 @@
recipientUsers: AlertOption[];
recipientRoles: AlertOption[];
mailConfigured: boolean;
+ external: ExternalRecipientsEditorData;
};
let {
@@ -77,7 +82,7 @@
let step = $state('event');
let errors = $state>({});
let message = $state('');
- let busy = $state<'save' | 'test' | null>(null);
+ let busy = $state<'save' | 'test' | 'send' | null>(null);
let test = $state(null);
let eventQuery = $state('');
let sampleProjectId = $state('');
@@ -231,13 +236,44 @@
if (kind === 'user') {
return { label: data.recipientUsers.find((user) => user.id === id)?.label ?? id, icon: User };
}
- return { label: id, icon: AtSign };
+ const status = data.external.statuses[id];
+ return {
+ label: status ? `${id} · ${$_(`notifications.status.${status}`)}` : id,
+ icon: AtSign,
+ };
}
+ const canAddExternal = $derived(
+ data.external.canManage && data.external.allowedDomains.length > 0,
+ );
+ function domainAllowed(email: string) {
+ const domain = email.split('@').pop() ?? '';
+ return data.external.allowedDomains.some((allowed) =>
+ allowed.startsWith('*.') ? domain.endsWith(allowed.slice(1)) : domain === allowed,
+ );
+ }
const parseEmail = (text: string) => {
const email = text.trim().toLowerCase();
- return EMAIL_PATTERN.test(email) ? `email:${email}` : null;
+ if (!canAddExternal || !EMAIL_PATTERN.test(email) || !domainAllowed(email)) return null;
+ return `email:${email}`;
};
+ const emailRejection = $derived(
+ !data.external.allowedDomains.length
+ ? $_('alerts.editor.externalDisabled')
+ : !data.external.canManage
+ ? $_('alerts.editor.externalReadonly')
+ : $_('alerts.editor.externalHelp', {
+ values: { domains: data.external.allowedDomains.join(', ') },
+ }),
+ );
+ const externalErrors = $derived(
+ Object.entries(errors)
+ .filter(([key]) => /^recipients\.emails\.\d+$/.test(key))
+ .map(([key, code]) => ({
+ email: draft.recipients.emails[Number(key.split('.').pop())] ?? '',
+ code,
+ })),
+ );
const parseSlack = (text: string) => {
const name = text.trim().toLowerCase().replace(/^#/, '');
return /^[a-z0-9][a-z0-9._-]{0,79}$/.test(name) ? `#${name}` : null;
@@ -292,9 +328,11 @@
}
// ---------- enviar ----------
- async function post(action: 'save' | 'test') {
+ const OPERATION_ERRORS = ['mail_not_configured', 'test_rate_limited'];
+
+ async function post(action: 'save' | 'test', send = false) {
if (!draft.name.trim() && definition) draft.name = $_(definition.label);
- busy = action;
+ busy = send ? 'send' : action;
message = '';
try {
const response = await fetch(`${data.basePath}?/${action}`, {
@@ -303,14 +341,18 @@
body: draftToFormData(draft, {
alertId: alert?.id,
sampleProjectId: action === 'test' ? sampleProjectId : null,
+ send: send ? 'true' : null,
}),
});
const result = deserialize(await response.text());
if (result.type === 'failure') {
errors = (result.data?.errors as Record) ?? {};
+ const code = String(result.data?.error ?? '');
message = Object.keys(errors).length
? $_('alerts.editor.fixErrors')
- : String(result.data?.error ?? $_('alerts.wizard.failed'));
+ : OPERATION_ERRORS.includes(code)
+ ? $_(`alerts.errors.${code}`)
+ : code || $_('alerts.wizard.failed');
if (action === 'test') test = null;
const first = STEPS.find((candidate) => stepErrors[candidate]);
if (first) step = first;
@@ -571,11 +613,33 @@
parse={parseEmail}
describe={describeMail}
placeholder={$_('alerts.wizard.mailPlaceholder')}
- invalidMessage={$_('alerts.errors.invalid_email')}
+ invalidMessage={emailRejection}
onchange={setMailValues}
/>
{/snippet}
+ {#if externalErrors.length > 0}
+
+ {#each externalErrors as failure (failure.email + failure.code)}
+ {failure.email}: {$_(`alerts.errors.${failure.code}`)}
+ {/each}
+
+ {/if}
+ {#if draft.recipients.emails.length > 0}
+
+
+ {$_('alerts.editor.externalNotice')}
+
+ {:else if !data.external.allowedDomains.length && data.external.settingsPath}
+
+ {$_('alerts.editor.externalDisabled')}
+ {$_('alerts.editor.externalSettingsLink')}
+
+ {/if}
{$_('alerts.editor.recipientsNotice')}
@@ -807,7 +871,33 @@
{$_('alerts.test.denied', { values: { count: test.deniedCount } })}
{/if}
- {$_('alerts.test.nothingSent')}
+ {#if test.external.length > 0}
+
+ {#each test.external as recipient (recipient.email)}
+
+ {$_(`notifications.status.${recipient.status}`)}
+ {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.delivery}
+
+ {$_('alerts.test.delivered', {
+ values: { sent: test.delivery.sent, failed: test.delivery.failed },
+ })}
+
+ {:else}
+ {$_('alerts.test.nothingSent')}
+ {/if}
{/if}
@@ -851,6 +941,19 @@
/>{/if}
{$_('alerts.editor.test')}
+ post('test', true)}
+ data-testid="alert-send-test"
+ >
+ {#if busy === 'send'} {:else} {/if}
+ {busy === 'send' ? $_('alerts.editor.sendingTest') : $_('alerts.editor.sendTest')}
+
new Date().toISOString()),
});
+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()),
+});
+
+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(),
+ 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 8adbb8b2..6ba4b9fe 100644
--- a/src/lib/events/catalog/types.ts
+++ b/src/lib/events/catalog/types.ts
@@ -33,12 +33,7 @@ export type FieldReference =
| 'monitor';
export type EventModule =
- | 'code_report'
- | 'vault'
- | 'projects'
- | 'organization'
- | 'access'
- | 'monitoring';
+ 'code_report' | 'vault' | 'projects' | 'organization' | 'access' | 'monitoring';
export type EventDefinitionScope = 'organization' | 'project';
@@ -68,6 +63,7 @@ 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;
+ sensitive?: boolean;
};
/**
@@ -107,6 +103,7 @@ 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;
+ 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..7b95fe80 100644
--- a/src/lib/events/catalog/vault.events.ts
+++ b/src/lib/events/catalog/vault.events.ts
@@ -19,7 +19,13 @@ type EnvironmentEvent = typeof ENVIRONMENT_CREATED | typeof ENVIRONMENT_DELETED;
function secretFields(type: K) {
return [
- { key: 'key', label: fieldLabel(type, 'key'), type: 'string', operators: OPERATORS.string },
+ {
+ key: 'key',
+ label: fieldLabel(type, 'key'),
+ type: 'string',
+ operators: OPERATORS.string,
+ sensitive: true,
+ },
{
key: 'environmentIds',
label: fieldLabel(type, 'environmentIds'),
@@ -32,6 +38,7 @@ function secretFields(type: K) {
label: fieldLabel(type, 'folderPath'),
type: 'string',
operators: OPERATORS.string,
+ sensitive: true,
},
] as const;
}
@@ -106,6 +113,7 @@ export const vaultEvents: EventDefinitions = {
+ verified: 'k-badge k-badge-ok',
+ pending: 'k-badge k-badge-warn',
+ unsubscribed: 'k-badge k-badge-danger',
+ blocked: 'k-badge',
+};
+
+export function statusBadgeClass(status: string): string {
+ return STATUS_BADGE[status] ?? 'k-badge';
+}
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
new file mode 100644
index 00000000..214982ce
--- /dev/null
+++ b/src/lib/notifications/types.ts
@@ -0,0 +1,18 @@
+import type { ExternalRecipientView } from '#modules/notifications/domain/external-recipient.domain';
+
+/** Alert settings of an organization (allowed domains and external recipients), as the page and
+ * the alert list's modal show them. */
+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;
+};
+
+/** 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..bf078436 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,62 @@ 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;
+ alertId?: unknown;
+ send?: unknown;
+};
+
+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: Array<{ email: string; status: string; delivers: boolean }>;
+ 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. The throttle is not
+ * 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 +238,7 @@ async function dryRun(
? (input.payload as Record)
: undefined;
const sample = buildSampleEvent(definition, alert, {
+ complete: send,
payload: payloadOverride,
projectId: requestedProjectId,
});
@@ -220,12 +258,27 @@ async function dryRun(
projectId = sample.projectId;
}
+ if (send && actor && alert.recipients.emails.length > 0) {
+ await alertService.registerExternal(location, alert.recipients.emails, 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 +286,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 +300,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 +315,23 @@ export async function testDraftAlert(
if (!canWrite) return forbidden;
const actor = actorFor(locals);
if (!actor) return forbidden;
+ 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.emails : [];
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);
+ 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 830fbcee..10b2f899 100644
--- a/src/lib/server/alerts/page.ts
+++ b/src/lib/server/alerts/page.ts
@@ -11,6 +11,7 @@ import {
emptyRecipients,
type AlertChannel,
} from '#modules/alerts/domain/alert.domain';
+import { externalRecipientService, notificationSettingsService } from '#modules/notifications';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import {
@@ -26,8 +27,13 @@ import type {
AlertListData,
AlertOption,
DraftCondition,
+ ExternalRecipientsEditorData,
} from '#lib/alerts/types';
-import { canManageAlerts, type AlertLocals } from './access';
+import {
+ canOpenNotificationSettings,
+ loadNotificationSettings,
+} from '#lib/server/notifications/settings';
+import { callerCan, canManageAlerts, contextOf, type AlertLocals } from './access';
import {
createAlert,
deleteAlert,
@@ -99,6 +105,29 @@ async function recipientOptions(location: AlertLocation) {
};
}
+async function externalRecipientsData(
+ locals: AlertLocals,
+ location: AlertLocation,
+ emails: string[],
+): Promise {
+ 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, [...new Set(emails)])
+ .catch(() => new Map()),
+ canOpenNotificationSettings(locals, location.organizationId),
+ organizationService.getOrganization(location.organizationId).catch(() => null),
+ ]);
+ return {
+ canManage,
+ allowedDomains: settings?.allowedExternalEmailDomains ?? [],
+ statuses: Object.fromEntries(statuses),
+ settingsPath:
+ canOpenSettings && organization ? `/org/${organization.slug}/settings/alerts/settings` : null,
+ };
+}
+
export async function loadAlertList(
locals: AlertLocals,
context: AlertPageContext,
@@ -121,10 +150,15 @@ export async function loadAlertList(
scope: 'organization',
projectId: null,
};
- const [references, own, organizationRecipients] = await Promise.all([
+ const [references, own, organizationRecipients, external] = await Promise.all([
referenceOptions([...catalog, ...inheritedCatalog], organizationLocation),
recipientOptions(location),
location.scope === 'project' ? recipientOptions(organizationLocation) : null,
+ externalRecipientsData(
+ locals,
+ location,
+ listed.data.alerts.flatMap((alert) => alert.recipients.emails ?? []),
+ ),
]);
// names for the recipients of the location's alerts and of the inherited organization ones
const merge = (a: AlertOption[], b: AlertOption[] = []) => [
@@ -151,6 +185,12 @@ export async function loadAlertList(
recipientUsers: own.users,
recipientRoles: own.roles,
mailConfigured: isMailConfigured(),
+ external,
+ settings: external.settingsPath
+ ? await loadNotificationSettings(locals, location.organizationId).then((result) =>
+ result.ok ? result.data : null,
+ )
+ : null,
canCreate: allowed.canCreate,
canUpdate: allowed.canUpdate,
canDelete: allowed.canDelete,
@@ -212,9 +252,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.emails ?? []),
]);
const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null);
@@ -234,6 +275,7 @@ export async function loadAlertEditor(
recipientUsers: recipients.users,
recipientRoles: recipients.roles,
mailConfigured: isMailConfigured(),
+ external,
canSave: alert ? allowed.canUpdate : allowed.canCreate,
canDelete: Boolean(alert) && allowed.canDelete,
};
@@ -374,6 +416,8 @@ export function alertActions(
const result = await testDraftAlert(event.locals, context.location, {
...toInput(draft),
sampleProjectId,
+ alertId: String(form.get('alertId') ?? '') || undefined,
+ 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..3342fe5e 100644
--- a/src/lib/server/infra/notifications/config.ts
+++ b/src/lib/server/infra/notifications/config.ts
@@ -74,12 +74,27 @@ 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 };
+
+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.
*/
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..155e2aa5 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -16,11 +16,14 @@ export {
absoluteUrl,
isSmtpConfigured,
readPublicOrigin,
+ rememberDevOrigin,
+ resetDevOrigin,
readSmtpConfig,
requireSmtpConfig,
type SmtpConfig,
} from './config';
export { withRetry, isRetryableMailError, type RetryOptions } from './retry';
+export { emailButton, emailNote } from './email-parts';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
import { createLogger } from '#lib/server/logger';
@@ -29,7 +32,14 @@ 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;
+};
+
+(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 +47,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..85251250 100644
--- a/src/lib/server/infra/notifications/mail-notification.ts
+++ b/src/lib/server/infra/notifications/mail-notification.ts
@@ -5,13 +5,17 @@ export type MailNotificationInput = {
subject: string;
/** HTML body, usually produced by `renderTemplate()`. */
content: string;
+ 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 +24,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 +42,10 @@ 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)) {
+ 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..2a2f2b7f 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,8 @@ 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) => {
+ enqueue(notification: MailNotification, context: MailContext = {}): Promise {
+ return new Promise((resolve) => {
this.pending.push({ notification, context, done: resolve });
this.pump();
});
@@ -84,20 +83,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 +113,24 @@ 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;
}
}
}
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..0481150d
--- /dev/null
+++ b/src/lib/server/notifications/settings.ts
@@ -0,0 +1,123 @@
+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';
+import type { NotificationSettingsPage } from '#lib/notifications/types';
+
+export type { NotificationSettingsPage };
+
+/** 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 };
+
+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/alerts/settings` (the alert list links to it). */
+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 52c09f93..d3861945 100644
--- a/src/modules/alerts/application/alert-engine.test.ts
+++ b/src/modules/alerts/application/alert-engine.test.ts
@@ -126,7 +126,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);
}
@@ -148,7 +149,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();
@@ -240,13 +246,15 @@ describe('AlertEngine', () => {
it('skips disabled users and users without an email', async () => {
repository.rows = [
- alertRow({ recipients: { ...emptyRecipients(), userIds: ['carl', 'nomail', 'ana'], roleIds: [] } }),
+ alertRow({
+ recipients: { ...emptyRecipients(), userIds: ['carl', 'nomail', 'ana'], roleIds: [] },
+ }),
];
await engine.handle(completed());
expect(sentTo()).toEqual(['ana']);
});
- it('also emails external addresses, once each', async () => {
+ it('never emails external addresses that are not verified external recipients', async () => {
repository.rows = [
alertRow({
recipients: {
@@ -257,12 +265,14 @@ describe('AlertEngine', () => {
}),
];
await engine.handle(completed());
- expect(sentTo()).toEqual(['ana', 'email:oncall@example.com']);
+ expect(sentTo()).toEqual(['ana']);
});
it('does not email recipients without the read permission, most-specific-wins included', async () => {
repository.rows = [
- alertRow({ recipients: { ...emptyRecipients(), userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] } }),
+ alertRow({
+ recipients: { ...emptyRecipients(), userIds: ['ana', 'dora', 'eli', 'fran'], roleIds: [] },
+ }),
];
await engine.handle(completed());
@@ -278,7 +288,11 @@ 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: { ...emptyRecipients(), userIds: ['pia'], roleIds: [] } }),
+ alertRow({
+ id: 'p2-alert',
+ projectId: 'p2',
+ recipients: { ...emptyRecipients(), userIds: ['pia'], roleIds: [] },
+ }),
alertRow({
id: 'org-alert',
scope: 'organization',
@@ -310,7 +324,10 @@ describe('AlertEngine', () => {
it('throttles an alert and reports the suppressed events in the next email', async () => {
repository.rows = [
- alertRow({ throttleMinutes: 30, recipients: { ...emptyRecipients(), userIds: ['ana'], roleIds: [] } }),
+ alertRow({
+ throttleMinutes: 30,
+ recipients: { ...emptyRecipients(), userIds: ['ana'], roleIds: [] },
+ }),
];
await engine.handle(completed({}, undefined, 'e1'));
diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts
index 2abd25d3..5fe48983 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 { DELIVERED_CHANNELS, type AlertDomain } from '../domain/alert.domain';
@@ -10,10 +11,18 @@ 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';
+
+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 +32,12 @@ export type AlertEmail = {
names: ReadonlyMap;
/** Names and slugs of where the event happened, for the texts and the links. */
where: ResolvedNames;
+ test?: boolean;
+};
+
+export type AlertTestDelivery = {
+ sent: number;
+ failed: number;
};
export type SystemEmail = {
@@ -40,7 +55,8 @@ export interface AlertNotifierPort {
export type AlertEngineOptions = {
repository: Pick;
directory: AlertDirectory;
- recipients: RecipientResolver;
+ recipients: Pick;
+ externalRecipients?: Pick;
notifier: AlertNotifierPort;
throttle?: AlertThrottle;
logger: Pick;
@@ -56,6 +72,7 @@ export type AlertDryRun = {
recipients: Recipient[];
/** Selected users that would not get it because they can't read the event. */
denied: string[];
+ external: Array<{ email: string; status: string; delivers: boolean }>;
};
const DEFAULT_CACHE_TTL_MS = 60_000;
@@ -132,14 +149,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.emails;
+ 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 {
@@ -176,6 +210,49 @@ 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',
+ );
+ }
+
+ 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,
@@ -199,43 +276,73 @@ export class AlertEngine {
})
.catch(() => ({}));
+ const memberEmails = new Set(recipients.map((recipient) => recipient.email.toLowerCase()));
+ const external = (await this.externalRecipientsOf(alert)).filter(
+ (recipient) => !memberEmails.has(recipient.email.toLowerCase()),
+ );
+
+ 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.emails;
+ 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..4fa69fb6
--- /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: [], emails: ['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: { emails: [' Ana@Partner.COM', 'ana@partner.com'] } }),
+ actor('admin'),
+ );
+
+ expect(alert.recipients).toMatchObject({
+ userIds: [],
+ roleIds: [],
+ emails: ['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: { emails: ['ok@partner.com', 'bob@evil.com', 'nope'] } }),
+ actor('admin'),
+ ),
+ );
+
+ expect(errors).toMatchObject({
+ 'recipients.emails': 'domain_not_allowed',
+ 'recipients.emails.1': 'domain_not_allowed',
+ 'recipients.emails.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.emails']).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.emails']).toBe('forbidden_external');
+
+ const organization = await validationErrors(
+ service.create(
+ orgLocation,
+ input(),
+ actor('dev', [...ALL_BUT_NOTIFICATIONS, 'project:notifications:update']),
+ ),
+ );
+ expect(organization['recipients.emails']).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: { emails: ['ana@partner.com'] },
+ });
+ const added = await validationErrors(
+ service.update(
+ alert.id,
+ { recipients: { emails: ['ana@partner.com', 'eva@partner.com'] } },
+ editor,
+ ),
+ );
+ expect(added['recipients.emails']).toBe('forbidden_external');
+ await expect(
+ service.update(alert.id, { recipients: { userIds: ['u1'], emails: [] } }, editor),
+ ).resolves.toMatchObject({ recipients: { userIds: ['u1'], emails: [] } });
+ });
+
+ 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: { emails: [] } }), 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.emails']).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'],
+ emails: ['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'],
+ emails: ['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: { emails: ['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.test.ts b/src/modules/alerts/application/alert.service.test.ts
index c52b9219..52d087d3 100644
--- a/src/modules/alerts/application/alert.service.test.ts
+++ b/src/modules/alerts/application/alert.service.test.ts
@@ -1,4 +1,5 @@
import { beforeEach, describe, expect, it, vi, type Mock } from 'vitest';
+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 { AlertService } from './alert.service';
@@ -35,7 +36,9 @@ describe('AlertService', () => {
let onChange: Mock<() => void>;
let service: AlertService;
- beforeEach(() => {
+ beforeEach(async () => {
+ const notifications = createNotificationsFixture();
+ await notifications.settings.setAllowedDomains(ORG, ['example.com']);
repository = new InMemoryAlertRepository();
directory = new FakeAlertDirectory();
directory.members = [
@@ -77,6 +80,7 @@ describe('AlertService', () => {
generateId: () => 'alert-1',
now: () => new Date('2026-11-20T10:00:00.000Z'),
onChange,
+ externalRecipients: notifications.recipients,
});
});
@@ -317,6 +321,7 @@ describe('AlertService', () => {
);
expect(errors).toEqual({
'recipients.emails': 'invalid_email',
+ 'recipients.emails.0': 'invalid_email',
'recipients.slackChannels': 'invalid_slack_channel',
'recipients.googleChatSpaces': 'required',
'recipients.webhookUrls': 'invalid_url',
diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts
index 3fbb51a5..2dc72706 100644
--- a/src/modules/alerts/application/alert.service.ts
+++ b/src/modules/alerts/application/alert.service.ts
@@ -28,6 +28,7 @@ import {
locationContext,
type AlertActor,
type AlertDirectory,
+ type ExternalRecipientsPort,
type ReferenceOption,
} from './types';
@@ -36,8 +37,8 @@ const MAX_DESCRIPTION_LENGTH = 1000;
const MAX_CONDITIONS = 20;
const MAX_LIST_VALUES = 100;
const MAX_TARGETS = 50;
+export const MAX_EXTERNAL_EMAILS = MAX_TARGETS;
-const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
const SLACK_CHANNEL_PATTERN = /^#[a-z0-9][a-z0-9._-]{0,79}$/;
const MAX_SPACE_LENGTH = 128;
@@ -49,6 +50,8 @@ export type AlertServiceOptions = {
generateId?: () => string;
/** Called after every successful write, so the engine drops its cached alerts. */
onChange?: () => void;
+ externalRecipients?: ExternalRecipientsPort;
+ logger?: { warn: (object: object, message: string) => void };
};
/** Ids the location's reference lists contain, loaded once per validation. */
@@ -64,6 +67,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,
@@ -73,6 +78,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 {
@@ -115,11 +122,11 @@ export class AlertService {
});
}
- /** Validates `input` for `location` and returns the normalized fields, without saving. */
async validate(
location: AlertLocation,
input: AlertInput,
actor: AlertActor,
+ previousEmails: readonly string[] = [],
): Promise {
const errors: AlertValidationErrors = {};
const references: ReferenceCache = new Map();
@@ -150,7 +157,14 @@ export class AlertService {
const channels = this.validateChannels(input.channels, errors);
- const recipients = await this.validateRecipients(location, input.recipients, channels, errors);
+ const recipients = await this.validateRecipients(
+ location,
+ input.recipients,
+ channels,
+ actor,
+ previousEmails,
+ errors,
+ );
const throttleMinutes = Number(input.throttleMinutes ?? 0);
if (
@@ -196,6 +210,7 @@ export class AlertService {
};
await this.repository.create(row);
this.onChange();
+ await this.registerExternal(location, fields.recipients.emails, actor);
return new AlertDomain(row);
}
@@ -214,12 +229,29 @@ 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.emails);
await this.repository.update(id, fields);
this.onChange();
+ await this.registerExternal(current.location, fields.recipients.emails, actor);
return new AlertDomain({ ...current.toJson(), ...fields, updatedAt: this.now().toISOString() });
}
+ 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);
@@ -406,6 +438,8 @@ export class AlertService {
location: AlertLocation,
value: unknown,
channels: AlertChannel[],
+ actor: AlertActor,
+ previousEmails: readonly string[],
errors: AlertValidationErrors,
): Promise {
const raw = (value ?? {}) as Record;
@@ -428,10 +462,16 @@ export class AlertService {
if (channels.includes('mail')) {
recipients.userIds = list('userIds');
recipients.roleIds = list('roleIds');
- recipients.emails = list('emails', (item) => item.trim().toLowerCase());
+ recipients.emails = await this.validateEmails(
+ location,
+ raw.emails,
+ actor,
+ previousEmails,
+ errors,
+ );
const { userIds, roleIds, emails } = recipients;
if (userIds.length === 0 && roleIds.length === 0 && emails.length === 0) {
- errors.recipients = 'required';
+ if (!errors['recipients.emails']) errors.recipients = 'required';
}
if (userIds.length > 0) {
const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId));
@@ -441,10 +481,6 @@ export class AlertService {
const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id));
if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role';
}
- if (emails.some((email) => !EMAIL_PATTERN.test(email))) {
- errors['recipients.emails'] = 'invalid_email';
- }
- tooMany('emails', emails);
}
if (channels.includes('slack')) {
@@ -481,6 +517,46 @@ export class AlertService {
return recipients;
}
+ private async validateEmails(
+ location: AlertLocation,
+ value: unknown,
+ actor: AlertActor,
+ previous: readonly string[],
+ errors: AlertValidationErrors,
+ ): Promise {
+ if (value === undefined || value === null) return [];
+ if (!Array.isArray(value)) {
+ errors['recipients.emails'] = '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.emails'] = 'too_many';
+ return [];
+ }
+
+ let emails: string[] = [];
+ if (!this.externalRecipients) {
+ errors['recipients.emails'] = '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.emails.${index}`] = code;
+ if (failures.length > 0) errors['recipients.emails'] = 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.emails'] = 'forbidden_external';
+ }
+ }
+ return emails;
+ }
+
private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] {
if (value === undefined || value === null) return ['mail'];
const list = Array.isArray(value) ? value : [value];
diff --git a/src/modules/alerts/application/recipient-resolver.ts b/src/modules/alerts/application/recipient-resolver.ts
index 85c0038b..f14db3dc 100644
--- a/src/modules/alerts/application/recipient-resolver.ts
+++ b/src/modules/alerts/application/recipient-resolver.ts
@@ -18,8 +18,7 @@ export type ResolvedRecipients = {
* Turns an alert's users and roles into the people that get the email: the selected users plus
* every member holding one of the roles, restricted to current members of the alert's location
* that are enabled and have an email, and finally to those allowed to read the event
- * (`readPermission` checked where the event happened, most-specific-wins included). External
- * addresses (`emails`) are appended as they are.
+ * (`readPermission` checked where the event happened, most-specific-wins included).
*/
export class RecipientResolver {
constructor(
@@ -57,15 +56,6 @@ export class RecipientResolver {
else denied.push(candidate.userId);
}
- // addresses outside the platform: the alert's author chose them explicitly and could read the
- // event when saving it (anti-escalation check), so they are not permission-filtered
- const known = new Set(recipients.map((recipient) => recipient.email.toLowerCase()));
- for (const email of selection.emails ?? []) {
- if (known.has(email.toLowerCase())) continue;
- known.add(email.toLowerCase());
- recipients.push({ userId: `email:${email}`, username: email, email });
- }
-
return { recipients, denied };
}
}
diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts
index 96d6d5f4..cb4b4bc4 100644
--- a/src/modules/alerts/application/types.ts
+++ b/src/modules/alerts/application/types.ts
@@ -59,7 +59,19 @@ export type ResolvedNames = {
role?: string;
};
-/** Who creates or edits an alert; `canRead` checks a grant in a context for that actor. */
+export interface ExternalRecipientsPort {
+ check(
+ organizationId: string,
+ emails: readonly unknown[],
+ ): Promise<{ emails: string[]; errors: Record }>;
+ register(organizationId: string, emails: readonly string[], actorUserId: string): Promise;
+ deliverable(
+ organizationId: string,
+ emails: readonly string[],
+ ): Promise>;
+ statuses(organizationId: string, emails: readonly string[]): Promise>;
+}
+
export type AlertActor = {
userId: string;
canRead(permission: PermissionGrant, context: PermissionContext): Promise;
diff --git a/src/modules/alerts/domain/alert.domain.test.ts b/src/modules/alerts/domain/alert.domain.test.ts
new file mode 100644
index 00000000..c30aab0b
--- /dev/null
+++ b/src/modules/alerts/domain/alert.domain.test.ts
@@ -0,0 +1,39 @@
+import { describe, expect, it } from 'vitest';
+import { AlertDomain, type AlertRow } from './alert.domain';
+
+const row = (recipients: Record) =>
+ ({
+ id: 'a1',
+ organizationId: 'org-1',
+ projectId: null,
+ scope: 'organization',
+ name: 'Legacy',
+ description: null,
+ enabled: true,
+ eventType: 'code_report.analysis.completed',
+ match: 'all',
+ conditions: [],
+ recipients,
+ channels: ['mail'],
+ throttleMinutes: 0,
+ createdByUserId: 'u1',
+ createdAt: '2026-11-24T00:00:00.000Z',
+ updatedAt: '2026-11-24T00:00:00.000Z',
+ }) as unknown as AlertRow;
+
+describe('AlertDomain', () => {
+ it('reads the external addresses saved by the first version of #99 (`externalEmails`)', () => {
+ const alert = new AlertDomain(
+ row({ userIds: [], roleIds: [], externalEmails: ['ana@partner.com'] }),
+ );
+ expect(alert.recipients.emails).toEqual(['ana@partner.com']);
+ expect(alert.toJson().recipients).not.toHaveProperty('externalEmails');
+ });
+
+ it('merges both fields without duplicates', () => {
+ const alert = new AlertDomain(
+ row({ emails: ['ana@partner.com'], externalEmails: ['ana@partner.com', 'eva@partner.com'] }),
+ );
+ expect(alert.recipients.emails).toEqual(['ana@partner.com', 'eva@partner.com']);
+ });
+});
diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts
index c78c06ae..06473dab 100644
--- a/src/modules/alerts/domain/alert.domain.ts
+++ b/src/modules/alerts/domain/alert.domain.ts
@@ -33,7 +33,6 @@ export type AlertRecipients = {
userIds: string[];
/** mail: every member holding one of these roles */
roleIds: string[];
- /** mail: addresses outside the platform */
emails: string[];
/** slack: channel names, stored with their `#` */
slackChannels: string[];
@@ -138,7 +137,14 @@ export class AlertDomain implements AlertRow {
this.recipients = {
userIds: stringArray(row.recipients?.userIds),
roleIds: stringArray(row.recipients?.roleIds),
- emails: stringArray(row.recipients?.emails),
+ emails: [
+ ...new Set([
+ ...stringArray(row.recipients?.emails),
+ ...stringArray(
+ (row.recipients as { externalEmails?: unknown } | undefined)?.externalEmails,
+ ),
+ ]),
+ ],
slackChannels: stringArray(row.recipients?.slackChannels),
googleChatSpaces: stringArray(row.recipients?.googleChatSpaces),
webhookUrls: stringArray(row.recipients?.webhookUrls),
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..2938d521 100644
--- a/src/modules/alerts/domain/sample-event.ts
+++ b/src/modules/alerts/domain/sample-event.ts
@@ -37,6 +37,33 @@ function satisfying(field: EventFieldDefinition, condition: AlertCondition): unk
}
}
+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:
+ 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;
@@ -54,12 +81,27 @@ function setPath(target: Record, path: string, value: unknown)
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 17e71a77..c090eec8 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,11 +8,12 @@ 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 { monitorService } from '../monitoring';
-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';
@@ -41,36 +42,85 @@ 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'
+>;
+const ENGINE_WIRING = 2;
+
+type EngineSlot = {
+ engine: AlertEngine | null;
+ wiring?: number;
+ throttle: AlertThrottle;
+ detach: Unsubscribe | null;
+ attached: boolean;
+ dependencies: EngineDependencies;
+};
+type GlobalWithEngine = typeof globalThis & { [ENGINE_KEY]?: EngineSlot };
+
+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(),
+const engineSlot: EngineSlot = ((globalThis as GlobalWithEngine)[ENGINE_KEY] ??= {
+ engine: null,
+ throttle: new AlertThrottle(),
+ detach: null,
+ attached: false,
+ dependencies,
+});
+engineSlot.dependencies = dependencies;
+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,
-});
+ });
+}
+
+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..921c2a7a 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,90 @@ 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');
+ 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 +275,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..33eccac7 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
@@ -1,56 +1,45 @@
import {
MailNotification,
absoluteUrl,
+ emailButton as button,
+ emailNote as note,
renderEmail,
renderTemplateString,
type MailContext,
} from '#lib/server/infra/notifications';
-import * as messages from '#lib/paraglide/messages.js';
+import {
+ DEFAULT_MAIL_LOCALE,
+ mailLocale,
+ translateKey,
+ translator,
+ type MailLocale,
+ type Translate,
+} 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';
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;
+ 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 },
- );
+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,21 @@ export class AlertMailNotifier implements AlertNotifierPort {
};
const eventLabel = t(definition.label);
- const message = definition.mailSummary?.(event.payload);
+ 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 +106,15 @@ 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')),
+ suppressedNote: email.test
+ ? note(t('alerts.email.testNote'))
+ : email.suppressed > 0
+ ? note(t('alerts.email.suppressed', { count: email.suppressed }))
+ : '',
+ actionButton: external ? '' : button(absoluteUrl(resourcePath), t('alerts.email.viewInApp')),
};
- const template = definition.mailTemplate ?? 'alert';
+ const template = external ? 'alert' : (definition.mailTemplate ?? 'alert');
const variables =
template === 'alert-code-report-analysis'
? { ...common, ...this.analysisVariables(email, t) }
@@ -137,7 +128,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 +140,34 @@ 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
+ : 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,
+ headers: external ? { 'List-Unsubscribe': `<${recipient.unsubscribeUrl}>` } : undefined,
+ }),
+ { alertId: email.alert.id, eventId: event.id, kind: external ? 'alert_external' : 'alert' },
);
+ 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..34e3b524 100644
--- a/src/modules/alerts/infrastructure/event-summary.ts
+++ b/src/modules/alerts/infrastructure/event-summary.ts
@@ -25,9 +25,11 @@ 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 1eed3680..40a25a73 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..78473a93
--- /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/alerts/settings`). */
+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..80521c23
--- /dev/null
+++ b/src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts
@@ -0,0 +1,43 @@
+import { MailNotification, emailButton, renderEmail } from '#lib/server/infra/notifications';
+import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n';
+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.svelte b/src/routes/+layout.svelte
index ed527f91..ec021b24 100644
--- a/src/routes/+layout.svelte
+++ b/src/routes/+layout.svelte
@@ -40,7 +40,10 @@
const pathname = $derived(page.url.pathname);
const isBareLayout = $derived(
- pathname.startsWith('/auth/') || pathname.startsWith('/bootstrap') || pathname === '/brand',
+ pathname.startsWith('/auth/') ||
+ pathname.startsWith('/bootstrap') ||
+ pathname.startsWith('/notifications/') ||
+ pathname === '/brand',
);
// el menú móvil se cierra al navegar
diff --git a/src/routes/api/alerts/[id]/test/+server.ts b/src/routes/api/alerts/[id]/test/+server.ts
index e817390d..df6f2ae9 100644
--- a/src/routes/api/alerts/[id]/test/+server.ts
+++ b/src/routes/api/alerts/[id]/test/+server.ts
@@ -1,7 +1,6 @@
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
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..0620fe24 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,150 @@ 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: { emails: ['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 },
+ });
+ 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'], emails: 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.emails': 'domain_not_allowed',
+ 'recipients.emails.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.emails': '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: { emails: ['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..af3be756 100644
--- a/src/routes/api/alerts/test/+server.ts
+++ b/src/routes/api/alerts/test/+server.ts
@@ -3,7 +3,6 @@ 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
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/alerts/settings/+page.server.ts b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
new file mode 100644
index 00000000..62c5413e
--- /dev/null
+++ b/src/routes/org/[org]/settings/alerts/settings/+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/alerts/settings/+page.svelte b/src/routes/org/[org]/settings/alerts/settings/+page.svelte
new file mode 100644
index 00000000..fa350f83
--- /dev/null
+++ b/src/routes/org/[org]/settings/alerts/settings/+page.svelte
@@ -0,0 +1,33 @@
+
+
+
+ {$_('notifications.settings.title')} - {$_('orgSettings.title')}
+
+
+
From 77c73f380d1c626bb42df773cc642015e71a0fdf Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Wed, 25 Nov 2026 12:03:16 +0100
Subject: [PATCH 2/3] Feat: Add alerts destination external email
---
.github/copilot-instructions.md | 6 +-
CLAUDE.md | 4 +-
README.md | 4 +-
.../alerts/AlertSettingsPanel.svelte | 144 +++++++++++++++---
src/lib/i18n/locales/en.json | 6 +-
src/lib/i18n/locales/es.json | 6 +-
src/lib/server/notifications/settings.test.ts | 33 +++-
src/lib/server/notifications/settings.ts | 24 ++-
.../alerts/application/alert.service.test.ts | 25 +++
.../alerts/application/alert.service.ts | 16 ++
.../external-recipient.service.test.ts | 24 +++
.../application/external-recipient.service.ts | 13 ++
.../external-recipient.repository.ts | 5 +
.../repositories/in-memory.repositories.ts | 4 +
.../settings/alerts/settings/+page.server.ts | 10 ++
15 files changed, 295 insertions(+), 29 deletions(-)
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index dda649ec..26919822 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -122,8 +122,10 @@ gestionan destinatarios externos (personas sin cuenta GitOps: vendors, on-call m
`*.partner.com` para subdominos, normalizado a punycode); en alertas, se agregan addresses en `recipients.emails`.
Cada dirección nueva es `pending` y genera email de confirmación (token aleatorio, hash almacenado, 7 días TTL,
single use, rate limitado 3/h por address y 30/h por org). Solo addresses `verified` se entregan; estados:
-`pending` → `verified` → `unsubscribed`, o `blocked` si su dominio se quita de la lista permitida. Las rutas
-públicas `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens (no requieren sesión,
+`pending` → `verified` → `unsubscribed`, o `blocked` si su dominio se quita de la lista permitida. Una dirección
+`pending` agregada por error puede quitarse desde Settings antes de confirmar: su enlace de confirmación se anula
+y se quita de todas las alertas de la organización (`alertService.removeEmail()`). Las rutas públicas
+`/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens (no requieren sesión,
no permiten GET para evitar que scanners abran URLs). Emails a externos usan template reducido (sin campos
`sensitive`, sin links a la app) con footer de desuscripción y `List-Unsubscribe` HMAC stateless (90 días TTL).
Sin `ORIGIN` no se envía nada. Infra: `src/lib/server/infra/tokens.ts` (HMAC con `GITDB_ENCRYPTION_KEY`) y
diff --git a/CLAUDE.md b/CLAUDE.md
index c41e3e82..b196040d 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -307,7 +307,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- Alert settings (`#lib/server/notifications/settings.ts`): allowed domains (read with
`organization:settings:read` or `organization:notifications:read`, changed with
`organization:settings:update`) and the external recipients status
- (`organization:notifications:read`, resend confirmation with `organization:notifications:update`).
+ (`organization:notifications:read`; resend a confirmation, or remove a `pending` address added by
+ mistake, with `organization:notifications:update`: removing deletes the recipient, so its link
+ stops working, and `alertService.removeEmail()` drops it from every alert of the organization).
The "Settings" button of the alert lists (organization and project ones, no sidebar entry) opens
them in a modal (`AlertSettingsPanel`, data in `AlertListData.settings`) whose forms post to the
actions of `/org//settings/alerts/settings`, the same page browsers without JavaScript get.
diff --git a/README.md b/README.md
index f36d461a..0d4e8265 100644
--- a/README.md
+++ b/README.md
@@ -177,7 +177,9 @@ Alerts can also email people without a GitOps account (a vendor, an on-call mail
`organization:notifications:update` or `project:notifications:update`). The API takes them in
`recipients.emails`.
3. Each new address gets a confirmation email and receives nothing until its owner confirms. Every
- alert email carries an unsubscribe link.
+ alert email carries an unsubscribe link. An address added by mistake can be removed from
+ **Settings** while it is still pending: its confirmation link stops working and it is taken out
+ of every alert.
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
diff --git a/src/lib/components/alerts/AlertSettingsPanel.svelte b/src/lib/components/alerts/AlertSettingsPanel.svelte
index 40db41c1..dc527b8d 100644
--- a/src/lib/components/alerts/AlertSettingsPanel.svelte
+++ b/src/lib/components/alerts/AlertSettingsPanel.svelte
@@ -2,8 +2,17 @@
import { enhance } from '$app/forms';
import type { SubmitFunction } from '$app/forms';
import { invalidateAll } from '$app/navigation';
- import { Globe, LoaderCircle, MailCheck, MailWarning, RefreshCw, Save } from '@lucide/svelte';
- import { toast } from '#lib/components/ui';
+ import {
+ Globe,
+ LoaderCircle,
+ MailCheck,
+ MailWarning,
+ RefreshCw,
+ Save,
+ Trash2,
+ } from '@lucide/svelte';
+ import { Modal, toast } from '#lib/components/ui';
+ import type { ExternalRecipientView } from '#modules/notifications/domain/external-recipient.domain';
import { _ } from '#lib/i18n';
import { statusBadgeClass } from '#lib/notifications/status';
import type { NotificationSettingsPage } from '#lib/notifications/types';
@@ -19,6 +28,8 @@
restored?: number;
resendError?: string;
resent?: string;
+ removeError?: string;
+ removed?: string;
} | null;
};
let { data, action, form = null }: Props = $props();
@@ -82,6 +93,33 @@
}
};
};
+
+ let removeTarget = $state(null);
+ let removeOpen = $state(false);
+
+ function askRemove(event: MouseEvent, recipient: ExternalRecipientView) {
+ event.preventDefault();
+ removeTarget = recipient;
+ removeOpen = true;
+ }
+
+ const remove: SubmitFunction = () => {
+ busy = 'remove';
+ return async ({ result }) => {
+ busy = null;
+ removeOpen = false;
+ if (result.type === 'success') {
+ toast.success(
+ $_('notifications.settings.removed', { values: { email: String(result.data?.removed) } }),
+ );
+ await invalidateAll();
+ } else if (result.type === 'failure' && result.data?.removeError) {
+ toast.error($_(`notifications.errors.${result.data.removeError}`));
+ } else {
+ toast.error($_('alerts.wizard.failed'));
+ }
+ };
+ };
@@ -176,6 +214,14 @@
{:else if form?.resent}
{$_('notifications.settings.resent')}
+ {:else if form?.removeError}
+
+ {$_(`notifications.errors.${form.removeError}`)}
+
+ {:else if form?.removed}
+
+ {$_('notifications.settings.removed', { values: { email: form.removed } })}
+
{/if}
{#if data.recipients.length === 0}
@@ -218,26 +264,45 @@
{formatDate(recipient.lastVerificationSentAt)}
-
- {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
-
-
-
+
+ {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
+
- {#if busy === recipient.id} {:else} {/if}
- {$_('notifications.settings.resend')}
-
-
- {/if}
+
+
+ {#if busy === recipient.id} {:else} {/if}
+
+
+ {/if}
+ {#if data.canManageRecipients && recipient.status === 'pending'}
+
+
+ askRemove(event, recipient)}
+ data-testid="remove-recipient"
+ >
+
+
+
+ {/if}
+
{/each}
@@ -249,3 +314,40 @@
{/if}
+
+{#if data.canManageRecipients}
+
+ {#snippet icon()}
+
+ {/snippet}
+
+
+
+ {#snippet footer()}
+ (removeOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'remove'} {/if}
+ {$_('notifications.settings.remove')}
+
+ {/snippet}
+
+{/if}
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index cb6f3cc9..538e1891 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -2099,7 +2099,11 @@
"resend": "Resend confirmation",
"resent": "Confirmation email sent again.",
"back": "Back to alerts",
- "domainsSavedTitle": "Domains saved"
+ "domainsSavedTitle": "Domains saved",
+ "remove": "Remove",
+ "removeTitle": "Remove this recipient?",
+ "removeDescription": "{email} hasn't confirmed yet. Its confirmation link will stop working and it will be removed from every alert of the organization.",
+ "removed": "{email} removed"
},
"errors": {
"invalid": "The value is not valid.",
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index 1fcb48dc..00e62ceb 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -2099,7 +2099,11 @@
"resend": "Reenviar confirmación",
"resent": "Email de confirmación reenviado.",
"back": "Volver a alertas",
- "domainsSavedTitle": "Dominios guardados"
+ "domainsSavedTitle": "Dominios guardados",
+ "remove": "Quitar",
+ "removeTitle": "¿Quitar este destinatario?",
+ "removeDescription": "{email} todavía no ha confirmado. Se anulará su enlace de confirmación y se quitará de todas las alertas de la organización.",
+ "removed": "{email} quitado"
},
"errors": {
"invalid": "El valor no es válido.",
diff --git a/src/lib/server/notifications/settings.test.ts b/src/lib/server/notifications/settings.test.ts
index 4d24f97d..91b2dda5 100644
--- a/src/lib/server/notifications/settings.test.ts
+++ b/src/lib/server/notifications/settings.test.ts
@@ -18,7 +18,16 @@ vi.mock('#modules/auth', () => ({
}));
vi.mock('#modules/projects', () => ({ projectService: {} }));
vi.mock('#modules/organization', () => ({ organizationService: {} }));
-vi.mock('#modules/alerts', () => ({ isMailConfigured: () => true }));
+const removedFromAlerts: Array<{ organizationId: string; email: string }> = [];
+vi.mock('#modules/alerts', () => ({
+ isMailConfigured: () => true,
+ alertService: {
+ removeEmail: async (organizationId: string, email: string) => {
+ removedFromAlerts.push({ organizationId, email });
+ return 2;
+ },
+ },
+}));
vi.mock('#modules/notifications', async () => {
const { createNotificationsFixture } = await import('#modules/notifications/application/testing');
@@ -40,6 +49,7 @@ const notifications = (await import('#modules/notifications')) as unknown as {
const {
canOpenNotificationSettings,
loadNotificationSettings,
+ removeExternalRecipient,
resendVerification,
saveAllowedDomains,
} = await import('./settings');
@@ -134,4 +144,25 @@ describe('notification settings authorization', () => {
status: 403,
});
});
+
+ it('removes pending recipients, and from the alerts, only with organization:notifications:update', async () => {
+ removedFromAlerts.length = 0;
+ const [{ id }] = notifications.fixture.recipientRepository.rows;
+ for (const user of ['viewer', 'settingsEditor', 'developer']) {
+ expect(await removeExternalRecipient(as(user), ORG, id)).toMatchObject({ status: 403 });
+ }
+ expect(await removeExternalRecipient(as('notificationsManager'), 'org-2', id)).toMatchObject({
+ status: 403,
+ });
+ expect(removedFromAlerts).toEqual([]);
+
+ expect(await removeExternalRecipient(as('notificationsManager'), ORG, id)).toEqual({
+ ok: true,
+ data: { email: 'ana@partner.com', alerts: 2 },
+ });
+ expect(removedFromAlerts).toEqual([{ organizationId: ORG, email: 'ana@partner.com' }]);
+ expect(await removeExternalRecipient(as('notificationsManager'), ORG, id)).toMatchObject({
+ status: 404,
+ });
+ });
});
diff --git a/src/lib/server/notifications/settings.ts b/src/lib/server/notifications/settings.ts
index 0481150d..ec85bebc 100644
--- a/src/lib/server/notifications/settings.ts
+++ b/src/lib/server/notifications/settings.ts
@@ -7,7 +7,7 @@ import {
notificationSettingsService,
type ExternalRecipientView,
} from '#modules/notifications';
-import { isMailConfigured } from '#modules/alerts';
+import { alertService, isMailConfigured } from '#modules/alerts';
import { readPublicOrigin } from '#lib/server/infra/notifications';
import { callerCan, type AlertLocals } from '#lib/server/alerts/access';
import type { NotificationSettingsPage } from '#lib/notifications/types';
@@ -95,6 +95,28 @@ export async function saveAllowedDomains(
}
}
+export async function removeExternalRecipient(
+ 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 removed = await externalRecipientService.remove(organizationId, recipientId);
+ const alerts = await alertService.removeEmail(organizationId, removed.email);
+ return { ok: true, data: { email: removed.email, alerts } };
+ } 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' };
+ }
+ throw error;
+ }
+}
+
export async function resendVerification(
locals: AlertLocals,
organizationId: string,
diff --git a/src/modules/alerts/application/alert.service.test.ts b/src/modules/alerts/application/alert.service.test.ts
index 52d087d3..248dbcca 100644
--- a/src/modules/alerts/application/alert.service.test.ts
+++ b/src/modules/alerts/application/alert.service.test.ts
@@ -339,6 +339,31 @@ describe('AlertService', () => {
});
describe('recipients', () => {
+ it('removes an external address from every alert of the organization', async () => {
+ const alert = await service.create(
+ projectLocation,
+ guidedExample({ recipients: { emails: ['typo@example.com', 'ops@example.com'] } }),
+ actor(),
+ );
+ repository.rows.push(
+ {
+ ...alert.toJson(),
+ id: 'alert-2',
+ recipients: { ...alert.recipients, emails: ['typo@example.com'] },
+ },
+ { ...alert.toJson(), id: 'other-org', organizationId: 'org-2' },
+ );
+ onChange.mockClear();
+
+ expect(await service.removeEmail(ORG, 'typo@example.com')).toBe(2);
+ const emails = (id: string) =>
+ repository.rows.find((row) => row.id === id)?.recipients.emails;
+ expect(emails('alert-1')).toEqual(['ops@example.com']);
+ expect(emails('alert-2')).toEqual([]);
+ expect(emails('other-org')).toEqual(['typo@example.com', 'ops@example.com']);
+ expect(onChange).toHaveBeenCalledTimes(1);
+ });
+
it('rejects users and roles outside the location', async () => {
const errors = await validationErrors(
service.create(
diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts
index 2dc72706..5377baba 100644
--- a/src/modules/alerts/application/alert.service.ts
+++ b/src/modules/alerts/application/alert.service.ts
@@ -252,6 +252,22 @@ export class AlertService {
}
}
+ /** Drops `email` from every alert of the organization (and of its projects) that has it. */
+ async removeEmail(organizationId: string, email: string): Promise {
+ const alerts = await this.repository.listByOrganization(organizationId);
+ const affected = alerts.filter((alert) => alert.recipients.emails.includes(email));
+ for (const alert of affected) {
+ await this.repository.update(alert.id, {
+ recipients: {
+ ...alert.recipients,
+ emails: alert.recipients.emails.filter((candidate) => candidate !== email),
+ },
+ });
+ }
+ if (affected.length > 0) this.onChange();
+ return affected.length;
+ }
+
async delete(id: string): Promise {
await this.get(id);
await this.repository.delete(id);
diff --git a/src/modules/notifications/application/external-recipient.service.test.ts b/src/modules/notifications/application/external-recipient.service.test.ts
index 5ff6ffc2..5c75e0c8 100644
--- a/src/modules/notifications/application/external-recipient.service.test.ts
+++ b/src/modules/notifications/application/external-recipient.service.test.ts
@@ -165,6 +165,30 @@ describe('ExternalRecipientService', () => {
await expect(f.recipients.resendVerification(OTHER_ORG, id)).rejects.toThrow(/not found/);
});
+ it('removes a pending address: its confirmation link stops working', async () => {
+ await f.recipients.register(ORG, ['typo@partner.com'], 'admin');
+ const token = f.notifier.tokenFor('typo@partner.com');
+ const [{ id }] = f.recipientRepository.rows;
+
+ await expect(f.recipients.remove(OTHER_ORG, id)).rejects.toThrow(/not found/);
+ await expect(f.recipients.remove(ORG, id)).resolves.toMatchObject({
+ email: 'typo@partner.com',
+ status: 'pending',
+ });
+ expect(f.recipientRepository.rows).toEqual([]);
+ await expect(f.recipients.verify(token)).rejects.toBeInstanceOf(InvalidNotificationLinkError);
+ });
+
+ it('only removes pending addresses', 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.remove(ORG, id)).rejects.toBeInstanceOf(
+ ExternalRecipientStateError,
+ );
+ expect(f.recipientRepository.rows).toHaveLength(1);
+ });
+
it('builds no link without ORIGIN, so nothing is sent', async () => {
f = createNotificationsFixture({ origin: null });
await f.settings.setAllowedDomains(ORG, ['partner.com']);
diff --git a/src/modules/notifications/application/external-recipient.service.ts b/src/modules/notifications/application/external-recipient.service.ts
index 808603a3..295b55a3 100644
--- a/src/modules/notifications/application/external-recipient.service.ts
+++ b/src/modules/notifications/application/external-recipient.service.ts
@@ -188,6 +188,19 @@ export class ExternalRecipientService {
return (await this.repository.findById(id))!.toView();
}
+ /** Deletes a `pending` address (added by mistake): its confirmation link stops working. */
+ async remove(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') {
+ throw new ExternalRecipientStateError(recipient.status);
+ }
+ await this.repository.delete(id);
+ return recipient.toView();
+ }
+
/** What a confirmation link points at, without using it (the GET page). */
async inspectVerification(token: string): Promise {
const value = token.trim();
diff --git a/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts b/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
index e5d34fca..acdf2e0d 100644
--- a/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
+++ b/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts
@@ -17,6 +17,7 @@ export interface ExternalRecipientRepositoryPort {
listByOrganization(organizationId: string): Promise;
create(row: ExternalRecipientRow): Promise;
update(id: string, changes: ExternalRecipientChanges): Promise;
+ delete(id: string): Promise;
}
export class ExternalRecipientRepository
@@ -68,4 +69,8 @@ export class ExternalRecipientRepository
.set({ ...changes, updatedAt: new Date().toISOString() })
.where({ id });
}
+
+ async delete(id: string) {
+ await this.db.delete(ExternalRecipientEntity).where({ id });
+ }
}
diff --git a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
index 99abd3d3..7531ab89 100644
--- a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
+++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
@@ -70,4 +70,8 @@ export class InMemoryExternalRecipientRepository implements ExternalRecipientRep
: row,
);
}
+
+ async delete(id: string) {
+ this.rows = this.rows.filter((row) => row.id !== id);
+ }
}
diff --git a/src/routes/org/[org]/settings/alerts/settings/+page.server.ts b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
index 62c5413e..221be30e 100644
--- a/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
+++ b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
@@ -2,6 +2,7 @@ import { error, fail } from '@sveltejs/kit';
import { organizationService } from '#modules/organization';
import {
loadNotificationSettings,
+ removeExternalRecipient,
resendVerification,
saveAllowedDomains,
} from '#lib/server/notifications/settings';
@@ -33,6 +34,15 @@ export const actions = {
if (!result.ok) return fail(result.status, { recipientId, resendError: result.error });
return { resent: recipientId };
},
+
+ async remove({ request, locals, params }) {
+ const organization = await organizationOf(params.org);
+ const form = await request.formData();
+ const recipientId = String(form.get('recipientId') ?? '');
+ const result = await removeExternalRecipient(locals, organization.id, recipientId);
+ if (!result.ok) return fail(result.status, { recipientId, removeError: result.error });
+ return { removed: result.data.email, removedFromAlerts: result.data.alerts };
+ },
};
async function organizationOf(slug: string) {
From 99333403e286a9efaca73856b5549ffba42f79b1 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Wed, 25 Nov 2026 15:13:09 +0100
Subject: [PATCH 3/3] Feat: Add base for canals
---
.github/copilot-instructions.md | 28 +-
CLAUDE.md | 64 ++-
README.md | 15 +
e2e/specs/alerts.spec.ts | 28 +-
src/lib/alerts/draft.ts | 9 +-
src/lib/alerts/summary.ts | 26 +-
src/lib/alerts/types.ts | 16 +-
src/lib/components/alerts/AlertEditor.svelte | 96 ++--
src/lib/components/alerts/AlertList.svelte | 35 +-
.../alerts/AlertSettingsPanel.svelte | 422 ++++++++-------
src/lib/components/alerts/AlertWizard.svelte | 473 +++++++++--------
src/lib/components/audit-summary.ts | 12 +-
.../notifications/ChannelsSection.svelte | 481 ++++++++++++++++++
src/lib/database/schemas.ts | 20 +
src/lib/i18n/locales/en.json | 85 +++-
src/lib/i18n/locales/es.json | 85 +++-
src/lib/notifications/types.ts | 37 ++
src/lib/server/alerts/operations.ts | 9 +-
src/lib/server/alerts/page.ts | 71 ++-
.../server/infra/http/webhook-request.test.ts | 125 +++++
src/lib/server/infra/http/webhook-request.ts | 149 ++++++
.../infra/notifications/chat-notification.ts | 99 ++++
.../server/infra/notifications/chat-types.ts | 7 +
.../infra/notifications/delivery-queue.ts | 140 +++++
src/lib/server/infra/notifications/index.ts | 20 +-
.../server/infra/notifications/mail-queue.ts | 115 +----
.../infra/notifications/notification.ts | 2 +-
src/lib/server/infra/notifications/retry.ts | 7 +-
src/lib/server/notifications/channels-page.ts | 106 ++++
src/lib/server/notifications/channels.ts | 175 +++++++
.../alerts/application/alert-engine.test.ts | 1 +
.../alerts/application/alert-engine.ts | 165 ++++--
.../alerts/application/alert.channels.test.ts | 359 +++++++++++++
.../alerts/application/alert.service.test.ts | 51 +-
.../alerts/application/alert.service.ts | 183 ++++---
src/modules/alerts/application/types.ts | 20 +
src/modules/alerts/domain/alert.domain.ts | 46 +-
src/modules/alerts/index.ts | 39 +-
.../infrastructure/alert-channel-message.ts | 52 ++
.../infrastructure/alert-mail.notifier.ts | 29 +-
.../alerts/infrastructure/event-summary.ts | 42 +-
.../notification-channel.service.test.ts | 240 +++++++++
.../notification-channel.service.ts | 333 ++++++++++++
.../notifications/application/testing.ts | 83 +++
.../domain/notification-channel.domain.ts | 131 +++++
src/modules/notifications/index.ts | 68 ++-
.../infrastructure/channel-test-message.ts | 28 +
.../crypto/channel-cipher.test.ts | 35 ++
.../infrastructure/crypto/channel-cipher.ts | 66 +++
.../repositories/in-memory.repositories.ts | 42 ++
.../notification-channel.repository.ts | 55 ++
.../api/notification-channels/+server.ts | 33 ++
.../api/notification-channels/[id]/+server.ts | 23 +
.../[id]/test/+server.ts | 7 +
.../api/notification-channels/server.test.ts | 260 ++++++++++
.../settings/alerts/settings/+page.server.ts | 22 +
.../settings/alerts/settings/+page.svelte | 39 ++
.../settings/alerts/settings/+page.server.ts | 19 +-
.../settings/alerts/settings/+page.svelte | 7 +-
59 files changed, 4532 insertions(+), 903 deletions(-)
create mode 100644 src/lib/components/notifications/ChannelsSection.svelte
create mode 100644 src/lib/server/infra/http/webhook-request.test.ts
create mode 100644 src/lib/server/infra/http/webhook-request.ts
create mode 100644 src/lib/server/infra/notifications/chat-notification.ts
create mode 100644 src/lib/server/infra/notifications/chat-types.ts
create mode 100644 src/lib/server/infra/notifications/delivery-queue.ts
create mode 100644 src/lib/server/notifications/channels-page.ts
create mode 100644 src/lib/server/notifications/channels.ts
create mode 100644 src/modules/alerts/application/alert.channels.test.ts
create mode 100644 src/modules/alerts/infrastructure/alert-channel-message.ts
create mode 100644 src/modules/notifications/application/notification-channel.service.test.ts
create mode 100644 src/modules/notifications/application/notification-channel.service.ts
create mode 100644 src/modules/notifications/domain/notification-channel.domain.ts
create mode 100644 src/modules/notifications/infrastructure/channel-test-message.ts
create mode 100644 src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts
create mode 100644 src/modules/notifications/infrastructure/crypto/channel-cipher.ts
create mode 100644 src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
create mode 100644 src/routes/api/notification-channels/+server.ts
create mode 100644 src/routes/api/notification-channels/[id]/+server.ts
create mode 100644 src/routes/api/notification-channels/[id]/test/+server.ts
create mode 100644 src/routes/api/notification-channels/server.test.ts
create mode 100644 src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.server.ts
create mode 100644 src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.svelte
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 26919822..1701f9be 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -114,22 +114,18 @@ aplican (regla most-specific-wins). Permite delegación de autoridad granular co
`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).
-**Alertas y destinatarios externos:** `organization:alerts:read|update` y `project:alerts:read|update`
-gestionan alertas por eventos; `organization:notifications:read|update` y `project:notifications:update`
-gestionan destinatarios externos (personas sin cuenta GitOps: vendors, on-call mailboxes). El módulo
-`$modules/notifications` maneja dominios permitidos, verificación y desuscripción. En
-`/org//settings/alerts/settings`, los administradores listan dominios permitidos (ej: `partner.com`,
-`*.partner.com` para subdominos, normalizado a punycode); en alertas, se agregan addresses en `recipients.emails`.
-Cada dirección nueva es `pending` y genera email de confirmación (token aleatorio, hash almacenado, 7 días TTL,
-single use, rate limitado 3/h por address y 30/h por org). Solo addresses `verified` se entregan; estados:
-`pending` → `verified` → `unsubscribed`, o `blocked` si su dominio se quita de la lista permitida. Una dirección
-`pending` agregada por error puede quitarse desde Settings antes de confirmar: su enlace de confirmación se anula
-y se quita de todas las alertas de la organización (`alertService.removeEmail()`). Las rutas públicas
-`/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens (no requieren sesión,
-no permiten GET para evitar que scanners abran URLs). Emails a externos usan template reducido (sin campos
-`sensitive`, sin links a la app) con footer de desuscripción y `List-Unsubscribe` HMAC stateless (90 días TTL).
-Sin `ORIGIN` no se envía nada. Infra: `src/lib/server/infra/tokens.ts` (HMAC con `GITDB_ENCRYPTION_KEY`) y
-`rate-limit.ts`.
+**Alertas, destinatarios externos y canales de notificación:** `organization:alerts:read|update` y
+`project:alerts:read|update` gestionan alertas por eventos; `organization:notifications:read|update`
+y `project:notifications:update` gestionan destinatarios externos y canales. El módulo
+`$modules/notifications` maneja dominios permitidos, canales de notificación (webhook, Slack, Google Chat),
+verificación y desuscripción. En `/org//settings/alerts/settings`, administradores configuran dominios
+permitidos y canales (`NotificationChannelEntity` en GitDB). Alertas guardan `recipients` (usuarios, roles,
+emails externos) y `channelIds` (referencias a canales, no destinatarios individuales). Canales de organización
+se usan en alertas de org y proyecto; canales de proyecto solo en sus alertas. URLs de webhook se encriptan
+con `GITDB_ENCRYPTION_KEY` (AES-GCM por channel id). Emails externos: `pending` → `verified` → `unsubscribed`
+o `blocked` si dominio se quita; template reducido sin campos `sensitive` ni links; `List-Unsubscribe` HMAC
+(90 días). Canales: un mensaje por canal en paralelo, fallo de canal nunca afecta email. Rutas públicas
+`/notifications/verify` y `/notifications/unsubscribe` aceptan POST (no GET). Sin `ORIGIN` no se envía nada.
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 b196040d..eb807dd1 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -121,10 +121,8 @@ session like any other page. Check it there before inventing a new style.
a `Modal` (`role="alertdialog"`), and deleting a top-level entity asks to type its name.
- Floating panels (`DropdownMenu`, `Select`, `TagInput` suggestions) render in `` through
`floating` in `ui/overlay.ts`, so no `overflow` (tables, modal bodies) clips them.
-- Alerts: one alert notifies several channels (`mail`, `slack`, `google_chat`, `webhook`), one
- message each; targets live in `recipients` (`userIds`/`roleIds`/`emails`, `slackChannels`,
- `googleChatSpaces`, `webhookUrls`). Only `mail` is delivered (`DELIVERED_CHANNELS`); the rest are
- stored and validated. Create/edit happens in `AlertWizard` (modal); the `/new` and `/[id]` pages
+- Alerts: email targets live in `recipients` (`userIds`/`roleIds`/`emails`) and chat or webhook
+ targets in `channelIds` (notification channels); `channels` is derived on save. Create/edit happens in `AlertWizard` (modal); the `/new` and `/[id]` pages
keep the no-JS editor (`AlertEditor`), so new alert fields must be added to both.
- `toast.*` is client-only (module state): call it from event handlers, never during SSR.
- Tokens: `bg-ink-950…500`, `brand-50…900`, text `text-fg|fg-muted|fg-subtle`, status
@@ -239,12 +237,15 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(`scope: 'organization'`, covers every project of it) or a project. `conditions`
(`{ field, operator, value }`) use the catalog fields, combined with `match: 'all' | 'any'`; an
empty list always matches. Organization alerts on project events also get a `projectId` field
- (`listAlertFields`, value taken from the event scope).
+ (`listAlertFields`, value taken from the event scope). Email recipients are in `recipients`
+ (users, roles, external emails); chat and webhook targets are in `channelIds` (references to
+ `NotificationChannelEntity`), not in recipients (a channel delivers to its configured destination,
+ not to individual recipients).
- `AlertService` validates every write against the catalog and the location and throws
`AlertValidationError` with field-level codes (`conditions.0.operator: 'invalid_operator'`):
alertable event compatible with the scope, operators of the field, typed values, references and
- recipients (users, roles) inside the location, and **anti-escalation** (the author must hold the
- event's `readPermission`).
+ recipients (users, roles, emails) inside the location, channels in the location, and
+ **anti-escalation** (the author must hold the event's `readPermission`).
- `AlertEngine` subscribes to `'*'` once per process (`registerAlertEngine()` in `hooks.server.ts`,
HMR-safe). Per event: fixed system notifications first (`system-notifications.data.ts`: access
granted/updated/revoked to the affected user, new personal API keys to their owner, never to the
@@ -272,7 +273,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
recipient hash, never the content or the address. `registerMailShutdown()` drains it on
`sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their
tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the
- engine skips events (debug log), warns once at startup and the alert pages show a banner.
+ engine skips emails and system notifications (debug log) but still posts to channels, warns once
+ at startup and the alert pages show a banner. `MailQueue` is a `DeliveryQueue`
+ (`#lib/server/infra/notifications/delivery-queue.ts`), the generic queue channels reuse.
- 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`
@@ -310,11 +313,46 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(`organization:notifications:read`; resend a confirmation, or remove a `pending` address added by
mistake, with `organization:notifications:update`: removing deletes the recipient, so its link
stops working, and `alertService.removeEmail()` drops it from every alert of the organization).
- The "Settings" button of the alert lists (organization and project ones, no sidebar entry) opens
- them in a modal (`AlertSettingsPanel`, data in `AlertListData.settings`) whose forms post to the
- actions of `/org//settings/alerts/settings`, the same page browsers without JavaScript get.
- The alert pages also get `data.external` (`ExternalRecipientsEditorData`: allowed domains, whether
- the user may add addresses, statuses).
+ The "Settings" button of the alert lists (no sidebar entry) opens them in a modal
+ (`AlertSettingsPanel`) together with the location's notification channels; its forms post to the
+ actions of `/settings` (`/org//settings/alerts/settings` or
+ `/org//projects//settings/alerts/settings`), the same pages browsers without
+ JavaScript get. Project settings only hold channels (domains are the organization's). The alert
+ pages also get `data.external` (`ExternalRecipientsEditorData`), `data.channels` (channel options
+ the location's alerts may use), `data.channelsSection` and `data.configPath` (for the settings modal).
+- Notification channels (`$modules/notifications`): `NotificationChannelEntity` (GitDB
+ `notification_channels`), owned by an organization (usable by alerts of the organization and of
+ all its projects) or a project (only its alerts). `type` is `webhook`, `slack` or `google-chat`;
+ a type is available only once its transport is registered with `registerChatTransport()`
+ (`#lib/server/infra/notifications/chat-notification.ts`). This base registers none: each
+ transport (webhook, Slack, Google Chat) activates its own, and tests use `FakeChatTransport`.
+ A `ChatTransport` implements `send()` and `validateDestination()`, the anti-SSRF check
+ (`validateWebhookUrl()`: https, no credentials, no IP literal, default port, allowed host and
+ path) run before saving and again before every send. The destination (`webhookUrl`) is
+ encrypted with `GITDB_ENCRYPTION_KEY` (`channel-cipher.ts`, AES-GCM bound to the channel id)
+ and only ever leaves the server masked (`https://hooks.slack.com/…/••••1a2b`); changing it
+ means typing it again. `enabled` flag can disable delivery without deleting the channel.
+- Channel delivery: alerts store `channelIds` (references to `NotificationChannelEntity`). Adding
+ a channel needs `:notifications:update` (`forbidden_channel`), and a channel must be
+ usable from the alert's location (`unknown_channel`). The engine emails each recipient and
+ posts **one message per channel** in parallel; a failing channel never affects the emails or
+ the other channels, and system notifications never go to channels. The message is a
+ provider-neutral `ChannelMessage` (`buildAlertChannelMessage()`: default language, no
+ `sensitive` fields, "View in GitOps" link, throttled count); transports format it. Deliveries
+ go through the process-wide `channelQueue` (concurrency 3; `postJson()` from
+ `#lib/server/infra/http/webhook-request.ts` with a 5 s timeout and no redirects; `withRetry`
+ only on network errors, 429 honoring `Retry-After`, and 5xx). A permanent failure (4xx,
+ invalid or undecryptable destination, type without transport) sets `lastError`; a success
+ clears it. `lastDeliveryAt` is only refreshed hourly, since each write is a commit. Logs carry
+ the channel id and type, never the URL nor the message.
+- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first with
+ `:notifications:read|create|update|delete`; a channel the caller can't read is a 404).
+ Routes: `GET|POST /api/notification-channels` (`organizationId` or `projectId`),
+ `GET|PATCH|DELETE /api/notification-channels/[id]` and `POST /api/notification-channels/[id]/test`
+ (posts a test even to a disabled channel). Form actions for the settings pages live in
+ `#lib/server/notifications/channels-page.ts`; the UI is `ChannelsSection`
+ (`#lib/components/notifications/`), and the alert editors pick channels from `data.channels`
+ (the alert's draft has `channelIds: string[]`, not direct recipients by channel type).
- 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
diff --git a/README.md b/README.md
index 0d4e8265..a6a7f565 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,21 @@ sensitive fields and links into the app. Removing a domain blocks its addresses
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.
+#### Notification channels
+
+Alerts can also post to chat channels and webhooks. In **Settings → Alerts**, click **Settings** to
+manage the channels of the organization (usable by every alert of the organization and its
+projects) or of a project (only its alerts). Each channel has a name and the webhook URL its
+provider gives you; the URL is stored encrypted and only ever shown masked. **Send test message**
+posts an example to check it works. Then pick the channels in the alert, next to its email
+recipients: each firing sends one message per channel, and a failing channel never stops the
+emails or the other channels.
+
+Adding channels to an alert needs `organization:notifications:update` or
+`project:notifications:update`: people reading a channel may have no access to the resource.
+Messages leave out sensitive fields. Channel types become available as their transports land
+(generic webhooks, Slack and Google Chat); until then the settings say no type is available yet.
+
### Monitoring
HTTP monitors check a URL (method, headers and body of your choice) every 60 seconds by default and
diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index ce12308c..1976df06 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -95,7 +95,7 @@ test.describe('project alerts', () => {
await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
});
- test('only email can be enabled and the alert is edited in the same wizard', async ({
+ test('without channels only email can be picked and the alert is edited in the same wizard', async ({
page,
loginAs,
}) => {
@@ -108,12 +108,13 @@ test.describe('project alerts', () => {
await expect(wizard.getByLabel('Nombre', { exact: true })).toHaveValue(GUIDED_NAME);
await wizard.getByRole('button', { name: /Destinos/ }).click();
- // Slack, Google Chat and Webhook have no notifier yet: shown as "soon" and not selectable
- for (const channel of [/^Slack/, /^Google Chat/, /^Webhook/]) {
- const card = wizard.getByRole('checkbox', { name: channel });
- await expect(card).toBeDisabled();
- await expect(card).toContainText('Próximamente');
- await expect(card).toHaveAttribute('aria-checked', 'false');
+ const channels = wizard.getByTestId('alert-channels');
+ await expect(channels.getByRole('checkbox', { name: /^Email/ })).toBeEnabled();
+ for (const type of ['slack', 'google-chat', 'webhook']) {
+ const card = channels.locator(`[data-channel-type="${type}"]`);
+ await expect(card.getByRole('checkbox')).toBeDisabled();
+ await expect(card).toContainText('No configurado');
+ await expect(card.getByRole('link', { name: 'Configurar' })).toBeVisible();
}
const targets = wizard.getByLabel('Destinatarios');
@@ -238,12 +239,23 @@ test.describe('organization alerts', () => {
await expect(domains).toHaveValue('example.com\npartner.com');
});
- test('project admins without organization access get no settings button', async ({
+ test('project admins manage the project channels, not the organization domains', async ({
page,
loginAs,
}) => {
await loginAs('projectAdmin');
await page.goto(alertsUrl);
+ await page.waitForLoadState('networkidle');
+ await page.getByTestId('alert-settings').click();
+ const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
+ await expect(dialog.getByTestId('notification-channels')).toBeVisible();
+ await expect(dialog.getByTestId('channel-types-unavailable')).toBeVisible();
+ await expect(dialog.getByLabel('Dominios (uno por línea)')).toHaveCount(0);
+ });
+
+ test('a project viewer gets no settings button', async ({ page, loginAs }) => {
+ await loginAs('projectViewer');
+ await page.goto(alertsUrl);
await expect(page.getByTestId('alert-settings')).toHaveCount(0);
});
});
diff --git a/src/lib/alerts/draft.ts b/src/lib/alerts/draft.ts
index 7f5eee50..a8fc7e55 100644
--- a/src/lib/alerts/draft.ts
+++ b/src/lib/alerts/draft.ts
@@ -13,8 +13,8 @@ export function emptyDraft(): AlertDraft {
eventType: '',
match: 'all',
conditions: [],
- channels: ['mail'],
recipients: emptyRecipients(),
+ channelIds: [],
throttleMinutes: 0,
};
}
@@ -36,7 +36,6 @@ export function draftFromAlert(alert: AlertRow): AlertDraft {
? [...condition.value]
: condition.value,
})),
- channels: [...alert.channels],
// copia de cada lista: `alert` puede ser un proxy reactivo (no admite structuredClone)
recipients: Object.fromEntries(
Object.entries({ ...emptyRecipients(), ...alert.recipients }).map(([key, list]) => [
@@ -44,6 +43,7 @@ export function draftFromAlert(alert: AlertRow): AlertDraft {
[...list],
]),
) as AlertDraft['recipients'],
+ channelIds: [...(alert.channelIds ?? [])],
throttleMinutes: alert.throttleMinutes,
};
}
@@ -60,14 +60,11 @@ export function draftToFormData(
form.set('eventType', draft.eventType);
form.set('match', draft.match);
form.set('throttleMinutes', String(draft.throttleMinutes));
- for (const channel of draft.channels) form.append('channels', channel);
const lists = {
userIds: draft.recipients.userIds,
roleIds: draft.recipients.roleIds,
emails: draft.recipients.emails,
- slackChannels: draft.recipients.slackChannels,
- googleChatSpaces: draft.recipients.googleChatSpaces,
- webhookUrls: draft.recipients.webhookUrls,
+ channelIds: draft.channelIds,
};
for (const [name, values] of Object.entries(lists)) {
for (const value of values) form.append(name, value);
diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts
index b143106e..75d6e05c 100644
--- a/src/lib/alerts/summary.ts
+++ b/src/lib/alerts/summary.ts
@@ -67,29 +67,31 @@ export function summarizeRecipients(
users: AlertOption[],
roles: AlertOption[],
t: Translate,
+ channels: { ids: string[]; options: Array<{ id: string; name: string }> } = {
+ ids: [],
+ options: [],
+ },
): string {
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.emails ?? []),
+ ...channels.ids.map((id) => channels.options.find((option) => option.id === id)?.name ?? id),
];
return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients');
}
-/** Targets of one channel, ready to print: names for mail, `#canal` for Slack, spaces, URLs. */
export function channelTargets(
channel: string,
- recipients: {
- userIds: string[];
- roleIds: string[];
- emails?: string[];
- slackChannels?: string[];
- googleChatSpaces?: string[];
- webhookUrls?: string[];
+ alert: {
+ recipients: { userIds: string[]; roleIds: string[]; emails?: string[] };
+ channelIds?: string[];
},
users: AlertOption[],
roles: AlertOption[],
+ channels: Array<{ id: string; name: string; type: string }> = [],
): string[] {
+ const { recipients } = alert;
if (channel === 'mail') {
return [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
@@ -97,8 +99,8 @@ export function channelTargets(
...(recipients.emails ?? []),
];
}
- if (channel === 'slack') return recipients.slackChannels ?? [];
- if (channel === 'google_chat') return recipients.googleChatSpaces ?? [];
- if (channel === 'webhook') return recipients.webhookUrls ?? [];
- return [];
+ return (alert.channelIds ?? [])
+ .map((id) => channels.find((option) => option.id === id))
+ .filter((option) => option?.type === channel)
+ .map((option) => option!.name);
}
diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts
index d06c0659..acfc4fd5 100644
--- a/src/lib/alerts/types.ts
+++ b/src/lib/alerts/types.ts
@@ -3,7 +3,7 @@
* components (`#lib/components/alerts`). Type-only: safe to import from the client.
*/
import type { EventDefinition, Operator } from '#lib/events/catalog';
-import type { NotificationSettingsPage } from '#lib/notifications/types';
+import type { ChannelsSectionData, NotificationSettingsPage } from '#lib/notifications/types';
import type {
AlertChannel,
AlertRecipients,
@@ -39,11 +39,19 @@ export type AlertDraft = {
eventType: string;
match: 'all' | 'any';
conditions: DraftCondition[];
- channels: AlertChannel[];
recipients: AlertRecipients;
+ channelIds: string[];
throttleMinutes: number;
};
+export type AlertChannelOption = {
+ id: string;
+ name: string;
+ type: string;
+ scope: 'organization' | 'project';
+ enabled: boolean;
+};
+
export type ExternalRecipientsEditorData = {
canManage: boolean;
allowedDomains: string[];
@@ -63,6 +71,7 @@ type Shared = {
* organization ones, only to name the recipients of inherited alerts). */
recipientUsers: AlertOption[];
recipientRoles: AlertOption[];
+ channels: AlertChannelOption[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
external: ExternalRecipientsEditorData;
@@ -70,6 +79,8 @@ type Shared = {
export type AlertListData = Shared & {
settings: NotificationSettingsPage | null;
+ channelsSection: ChannelsSectionData | null;
+ configPath: string | null;
alerts: AlertRow[];
/** Organization alerts that also fire for this project (project pages only). */
inherited: AlertRow[];
@@ -90,6 +101,7 @@ export type AlertTestView = {
recipients: Array<{ userId: string; username: string }>;
deniedCount: number;
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte
index 64929aed..a196090d 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -23,7 +23,6 @@
DraftCondition,
} from '#lib/alerts/types';
import ConditionBuilder from './ConditionBuilder.svelte';
- import { DELIVERED_CHANNELS } from '#modules/alerts/domain/alert.domain';
import OptionPicker from './OptionPicker.svelte';
type Props = { data: AlertEditorData; form: AlertFormResult };
@@ -39,8 +38,6 @@
}));
let draft = $state(initial.draft);
// canales sin envío todavía: solo se pueden mantener (o quitar) si la alerta ya los tenía
- const initialChannels: string[] = [...initial.draft.channels];
- const isSoon = (channel: string) => !(DELIVERED_CHANNELS as readonly string[]).includes(channel);
let errors = $state>(initial.errors);
let message = $state(initial.message);
let test = $state(initial.test);
@@ -428,47 +425,67 @@
{/if}
-
+
{$_('alerts.editor.channels')}
- {#each [{ key: 'mail', list: null }, { key: 'slack', list: 'slackChannels' }, { key: 'google_chat', list: 'googleChatSpaces' }, { key: 'webhook', list: 'webhookUrls' }] as const as channel (channel.key)}
-
+
{$_('alerts.editor.channelsHelp')}
+ {#if data.channels.length === 0}
+
+ {$_('alerts.editor.noChannels')}
+ {#if data.external.settingsPath}
+
+ {$_('alerts.editor.channelsSettingsLink')}
+
+ {/if}
+
+ {:else}
+ {#each data.channels as channel (channel.id)}
+ {@const selected = draft.channelIds.includes(channel.id)}
{
+ draft.channelIds = event.currentTarget.checked
+ ? [...draft.channelIds, channel.id]
+ : draft.channelIds.filter((id) => id !== channel.id);
+ }}
/>
- {$_(`alerts.channels.${channel.key}`)}
- {#if isSoon(channel.key)}
- {$_('alerts.channels.soon')}
+ {$_(`notifications.channels.types.${channel.type}`)}
+
+ {#if channel.scope === 'organization' && data.scope === 'project'}
+ {$_('alerts.editor.channelFromOrganization')}
{/if}
-
- {#if channel.list && (!isSoon(channel.key) || initialChannels.includes(channel.key))}
-
- {#if errors[`recipients.${channel.list}`]}
-
- {errorFor(`recipients.${channel.list}`)}
-
+ {#if !channel.enabled}
+
{$_('notifications.channels.disabled')}
{/if}
+
+ {#if selected && !data.canSave}
+
{/if}
-
- {/each}
- {#if errors.channels}
- {errorFor('channels')}
+ {/each}
+ {#if draft.channelIds.length > 0}
+
+
+ {$_('alerts.editor.channelsNotice')}
+
+ {/if}
+ {#if !data.external.canManage}
+ {$_('alerts.editor.channelsReadonly')}
+ {/if}
+ {/if}
+ {#if errors.channelIds}
+ {errorFor('channelIds')}
{/if}
@@ -555,6 +572,17 @@
{$_('alerts.test.denied', { values: { count: test.deniedCount } })}
{/if}
+ {#if test.channels?.length > 0}
+
+ {#each test.channels as channel (channel.id)}
+
+ {channel.name}: {channel.delivers
+ ? $_('alerts.test.channelDelivers')
+ : $_('alerts.test.channelSkipped')}
+
+ {/each}
+
+ {/if}
{#if test.external.length > 0}
{#each test.external as recipient (recipient.email)}
diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte
index 350800b0..027ef62c 100644
--- a/src/lib/components/alerts/AlertList.svelte
+++ b/src/lib/components/alerts/AlertList.svelte
@@ -51,7 +51,12 @@
const examples = ['alerts.list.example1', 'alerts.list.example2', 'alerts.list.example3'];
- const channelIcons = { mail: Mail, slack: Hash, google_chat: MessageSquare, webhook: Webhook };
+ const channelIcons = {
+ mail: Mail,
+ slack: Hash,
+ 'google-chat': MessageSquare,
+ webhook: Webhook,
+ };
// el asistente: "Crear alerta" y "Editar" lo abren; sus enlaces siguen funcionando sin JS
let wizardOpen = $state(false);
@@ -65,7 +70,7 @@
let settingsOpen = $state(false);
function openSettings(event: MouseEvent) {
- if (!data.settings || event.metaKey || event.ctrlKey || event.shiftKey) return;
+ if (!data.configPath || event.metaKey || event.ctrlKey || event.shiftKey) return;
event.preventDefault();
settingsOpen = true;
}
@@ -86,9 +91,9 @@
- {#if data.external.settingsPath}
+ {#if data.configPath}
{channelTargets(channel, alert.recipients, data.users, data.roles).join(
+ >{channelTargets(channel, alert, data.users, data.roles, data.channels).join(
', ',
) || $_('alerts.summary.noRecipients')}
@@ -344,15 +349,22 @@
{#if data.canCreate || data.canUpdate}
-
+ (settingsOpen = true)}
+ />
{/if}
-{#if data.settings && data.external.settingsPath}
+{#if data.configPath}
{#snippet icon()}
{/snippet}
-
+
{#snippet footer()}
(settingsOpen = false)}
>{$_('common.close')} ;
- saved?: boolean;
- blocked?: number;
- restored?: number;
- resendError?: string;
- resent?: string;
- removeError?: string;
- removed?: string;
- } | null;
+ form?:
+ | ({
+ domains?: string;
+ errors?: Record;
+ saved?: boolean;
+ blocked?: number;
+ restored?: number;
+ resendError?: string;
+ resent?: string;
+ removeError?: string;
+ removed?: string;
+ } & NonNullable)
+ | null;
};
- let { data, action, form = null }: Props = $props();
+ let {
+ data,
+ channels = null,
+ organizationSettingsPath = null,
+ action,
+ form = null,
+ }: Props = $props();
let domainError = $state('');
const formDomainError = $derived(
@@ -43,7 +58,7 @@
let busy = $state<'domains' | string | null>(null);
let domainsText = $derived(
- typeof form?.domains === 'string' ? form.domains : data.allowedDomains.join('\n'),
+ typeof form?.domains === 'string' ? form.domains : (data?.allowedDomains ?? []).join('\n'),
);
function formatDate(value: string | null) {
@@ -123,199 +138,216 @@
- {#if !data.mailConfigured || !data.originConfigured}
-
-
- {!data.mailConfigured
- ? $_('notifications.settings.mailNotConfigured')
- : $_('notifications.settings.originNotConfigured')}
-
- {/if}
+ {#if data}
+ {#if !data.mailConfigured || !data.originConfigured}
+
+
+ {!data.mailConfigured
+ ? $_('notifications.settings.mailNotConfigured')
+ : $_('notifications.settings.originNotConfigured')}
+
+ {/if}
-
-
-
-
-
-
-
- {$_('notifications.settings.domainsTitle')}
-
-
- {$_('notifications.settings.domainsDescription')}
-
+
+
+
+
+
+
+
+ {$_('notifications.settings.domainsTitle')}
+
+
+ {$_('notifications.settings.domainsDescription')}
+
+
-
-
-
-
- {$_('notifications.settings.domainsLabel')}
-
-
-
- {$_('notifications.settings.domainsHelp')}
-
- {#if domainError || formDomainError}
-
- {domainError || formDomainError}
-
- {:else if form?.saved}
-
- {$_('notifications.settings.domainsSaved', {
- values: { blocked: form.blocked ?? 0, restored: form.restored ?? 0 },
- })}
+
+
+
+ {$_('notifications.settings.domainsLabel')}
+
+
+
+ {$_('notifications.settings.domainsHelp')}
+ {#if domainError || formDomainError}
+
+ {domainError || formDomainError}
+
+ {:else if form?.saved}
+
+ {$_('notifications.settings.domainsSaved', {
+ values: { blocked: form.blocked ?? 0, restored: form.restored ?? 0 },
+ })}
+
+ {/if}
+
+ {#if data.canEditDomains}
+
+ {#if busy === 'domains'} {:else} {/if}
+ {$_('notifications.settings.saveDomains')}
+
+ {:else}
+ {$_('notifications.settings.domainsReadonly')}
{/if}
-
- {#if data.canEditDomains}
-
- {#if busy === 'domains'} {:else} {/if}
- {$_('notifications.settings.saveDomains')}
-
- {:else}
- {$_('notifications.settings.domainsReadonly')}
- {/if}
-
-
+
+
- {#if data.recipients}
-
-
-
-
- {$_('notifications.settings.recipientsTitle')}
-
-
- {$_('notifications.settings.recipientsDescription')}
-
-
+ {#if data.recipients}
+
+
+
+
+ {$_('notifications.settings.recipientsTitle')}
+
+
+ {$_('notifications.settings.recipientsDescription')}
+
+
- {#if form?.resendError}
-
- {$_(`notifications.errors.${form.resendError}`)}
-
- {:else if form?.resent}
- {$_('notifications.settings.resent')}
- {:else if form?.removeError}
-
- {$_(`notifications.errors.${form.removeError}`)}
-
- {:else if form?.removed}
-
- {$_('notifications.settings.removed', { values: { email: form.removed } })}
-
- {/if}
+ {#if form?.resendError}
+
+ {$_(`notifications.errors.${form.resendError}`)}
+
+ {:else if form?.resent}
+ {$_('notifications.settings.resent')}
+ {:else if form?.removeError}
+
+ {$_(`notifications.errors.${form.removeError}`)}
+
+ {:else if form?.removed}
+
+ {$_('notifications.settings.removed', { values: { email: form.removed } })}
+
+ {/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')}
-
-
-
- {#if busy === recipient.id} {:else} {/if}
-
-
- {/if}
- {#if data.canManageRecipients && recipient.status === 'pending'}
-
-
- askRemove(event, recipient)}
- data-testid="remove-recipient"
- >
-
-
-
- {/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}
-
-
+
+
+ {#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')}
+
+
+
+ {#if busy === recipient.id} {:else} {/if}
+
+
+ {/if}
+ {#if data.canManageRecipients && recipient.status === 'pending'}
+
+
+ askRemove(event, recipient)}
+ data-testid="remove-recipient"
+ >
+
+
+
+ {/if}
+
+
+
+ {/each}
+
+
+
-
- {/if}
-
+ {/if}
+
+ {/if}
+ {:else if organizationSettingsPath}
+
+ {$_('notifications.settings.organizationDomains')}
+ {$_('notifications.settings.organizationDomainsLink')}
+
+ {/if}
+
+ {#if channels}
+
{/if}
-{#if data.canManageRecipients}
+{#if data?.canManageRecipients}
void;
+ } = $props();
const STEPS = ['event', 'conditions', 'channels', 'review'] as const;
type Step = (typeof STEPS)[number];
@@ -87,6 +95,7 @@
let eventQuery = $state('');
let sampleProjectId = $state('');
let droppedConditions = $state(0);
+ let mailOn = $state(true);
// cada apertura empieza de cero (o desde la alerta que se edita)
let wasOpen = false;
@@ -100,6 +109,12 @@
eventQuery = '';
sampleProjectId = '';
droppedConditions = 0;
+ mailOn =
+ !alert ||
+ draft.recipients.userIds.length +
+ draft.recipients.roleIds.length +
+ draft.recipients.emails.length >
+ 0;
}
wasOpen = open;
});
@@ -139,53 +154,77 @@
delete errors.eventType;
}
- // ---------- paso 3: canales ----------
- type ChannelMeta = {
- key: AlertChannel;
- icon: typeof Mail;
- label: string;
- description: string;
+ const channelIcons: Record = {
+ mail: Mail,
+ slack: Hash,
+ 'google-chat': MessageSquare,
+ webhook: Webhook,
};
- const channelMeta: ChannelMeta[] = $derived([
- {
- key: 'mail',
- icon: Mail,
- label: $_('alerts.channels.mail'),
- description: $_('alerts.wizard.mailDescription'),
- },
- {
- key: 'slack',
- icon: Hash,
+
+ const CHANNEL_TYPES = ['mail', 'slack', 'google-chat', 'webhook'] as const;
+ type ChannelType = (typeof CHANNEL_TYPES)[number];
+ const typeMeta = $derived({
+ mail: { label: $_('alerts.channels.mail'), description: $_('alerts.wizard.mailDescription') },
+ slack: {
label: $_('alerts.channels.slack'),
description: $_('alerts.wizard.slackDescription'),
},
- {
- key: 'google_chat',
- icon: MessageSquare,
+ 'google-chat': {
label: $_('alerts.channels.google_chat'),
description: $_('alerts.wizard.googleChatDescription'),
},
- {
- key: 'webhook',
- icon: Webhook,
+ webhook: {
label: $_('alerts.channels.webhook'),
description: $_('alerts.wizard.webhookDescription'),
},
- ]);
+ } satisfies Record);
+
+ const channelsOf = (type: ChannelType) =>
+ data.channels.filter((channel) => channel.type === type);
+
+ function typeOn(type: ChannelType) {
+ if (type === 'mail') return mailOn;
+ return channelsOf(type).some((channel) => draft.channelIds.includes(channel.id));
+ }
- // canales sin envío todavía: no se pueden activar (sí desactivar si una alerta ya los tenía)
- const isSoon = (channel: AlertChannel) => !DELIVERED_CHANNELS.includes(channel);
-
- function toggleChannel(channel: AlertChannel) {
- if (isSoon(channel) && !draft.channels.includes(channel)) return;
- draft.channels = draft.channels.includes(channel)
- ? draft.channels.filter((item) => item !== channel)
- : [...draft.channels, channel].sort(
- (a, b) =>
- channelMeta.findIndex((meta) => meta.key === a) -
- channelMeta.findIndex((meta) => meta.key === b),
+ function toggleType(type: ChannelType) {
+ if (type === 'mail') {
+ mailOn = !mailOn;
+ if (!mailOn) {
+ draft.recipients.userIds = [];
+ draft.recipients.roleIds = [];
+ draft.recipients.emails = [];
+ }
+ } else {
+ const ids = channelsOf(type).map((channel) => channel.id);
+ if (typeOn(type)) {
+ draft.channelIds = draft.channelIds.filter((id) => !ids.includes(id));
+ } else if (data.external.canManage) {
+ const enabled = channelsOf(type).filter((channel) => channel.enabled);
+ const picked = (enabled.length > 0 ? enabled : channelsOf(type)).map(
+ (channel) => channel.id,
);
- delete errors.channels;
+ draft.channelIds = [...draft.channelIds, ...picked];
+ }
+ }
+ delete errors.channelIds;
+ delete errors.recipients;
+ }
+
+ function toggleChannel(channel: AlertChannelOption) {
+ const on = draft.channelIds.includes(channel.id);
+ if (!on && !data.external.canManage) return;
+ draft.channelIds = on
+ ? draft.channelIds.filter((id) => id !== channel.id)
+ : [...draft.channelIds, channel.id];
+ delete errors.channelIds;
+ delete errors.recipients;
+ }
+
+ function configure(event: MouseEvent) {
+ if (!onConfigure || event.metaKey || event.ctrlKey || event.shiftKey) return;
+ event.preventDefault();
+ onConfigure();
}
// destinatarios de email como etiquetas: `role:`, `user:`, `email:`
@@ -274,38 +313,25 @@
code,
})),
);
- const parseSlack = (text: string) => {
- const name = text.trim().toLowerCase().replace(/^#/, '');
- return /^[a-z0-9][a-z0-9._-]{0,79}$/.test(name) ? `#${name}` : null;
- };
- const parseSpace = (text: string) => (text.trim() ? text.trim().slice(0, 128) : null);
- const parseUrl = (text: string) => {
- try {
- const url = new URL(text.trim());
- return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null;
- } catch {
- return null;
- }
- };
-
- function targetsOf(channel: AlertChannel): number {
- return channelTargets(channel, draft.recipients, data.recipientUsers, data.recipientRoles)
- .length;
- }
-
// ---------- validación por paso (lo mínimo para avanzar; el servidor valida todo) ----------
const stepReady = $derived({
event: Boolean(draft.eventType),
conditions: true,
channels:
- draft.channels.length > 0 && draft.channels.every((channel) => targetsOf(channel) > 0),
+ (mailOn
+ ? draft.recipients.userIds.length +
+ draft.recipients.roleIds.length +
+ draft.recipients.emails.length
+ : 0) +
+ draft.channelIds.length >
+ 0,
review: true,
} satisfies Record);
const stepOfError = (key: string): Step => {
if (key === 'eventType') return 'event';
if (key.startsWith('conditions') || key === 'match') return 'conditions';
- if (key.startsWith('recipients') || key === 'channels' || key === 'throttleMinutes') {
+ if (key.startsWith('recipients') || key === 'channelIds' || key === 'throttleMinutes') {
return 'channels';
}
return 'review';
@@ -532,180 +558,191 @@
{:else if step === 'channels'}
-
+
{$_('alerts.wizard.channelsTitle')}
-
{$_('alerts.wizard.channelsHelp')}
+
{$_('alerts.wizard.channelsHelp')}
- {#each channelMeta as meta (meta.key)}
- {@const on = draft.channels.includes(meta.key)}
- {@const soon = isSoon(meta.key) && !on}
-
toggleChannel(meta.key)}
+ data-channel-type={type}
>
- toggleType(type)}
>
- {meta.label}
- {meta.description}
- {#if soon}
- {$_('alerts.channels.soon')}
- {:else}
+ {typeMeta[type].label}
+
+ {configured ? typeMeta[type].description : $_('alerts.wizard.notConfigured')}
+
+
+ {#if configured}
{#if on} {/if}
+ {:else}
+
{$_('alerts.wizard.notConfigured')}
+ {#if data.configPath}
+
+ {$_('alerts.wizard.configure')}
+
+ {/if}
{/if}
-
+
{/each}
- {#if errorFor('channels')}
-
{errorFor('channels')}
+ {#if errorFor('channelIds')}
+
{errorFor('channelIds')}
{/if}
- {#each channelMeta.filter((meta) => draft.channels.includes(meta.key)) as meta (meta.key)}
+ {#if mailOn}
- {meta.label}
+ {$_('alerts.channels.mail')}
- {#if meta.key === 'mail'}
- {#if !data.mailConfigured}
-
- {$_(
- 'alerts.mailDisabled',
- )}
-
- {/if}
-
- {#snippet children(control)}
-
- {/snippet}
-
- {#if externalErrors.length > 0}
-
- {#each externalErrors as failure (failure.email + failure.code)}
- {failure.email}: {$_(`alerts.errors.${failure.code}`)}
- {/each}
-
- {/if}
- {#if draft.recipients.emails.length > 0}
-
-
- {$_('alerts.editor.externalNotice')}
-
- {:else if !data.external.allowedDomains.length && data.external.settingsPath}
-
- {$_('alerts.editor.externalDisabled')}
- {$_('alerts.editor.externalSettingsLink')}
-
- {/if}
-
- {$_('alerts.editor.recipientsNotice')}
+ {$_(
+ 'alerts.mailDisabled',
+ )}
- {:else if meta.key === 'slack'}
-
- {#snippet children(control)}
- ({ label: value, icon: Hash })}
- placeholder="#alertas"
- invalidMessage={$_('alerts.errors.invalid_slack_channel')}
- />
- {/snippet}
-
- {:else if meta.key === 'google_chat'}
-
- {#snippet children(control)}
- ({ label: value, icon: MessageSquare })}
- placeholder={$_('alerts.wizard.googleChatPlaceholder')}
- />
- {/snippet}
-
- {:else}
-
+ {#snippet children(control)}
+
+ {/snippet}
+
+ {#if externalErrors.length > 0}
+
+ {#each externalErrors as failure (failure.email + failure.code)}
+ {failure.email}: {$_(`alerts.errors.${failure.code}`)}
+ {/each}
+
+ {/if}
+ {#if draft.recipients.emails.length > 0}
+
- {#snippet children(control)}
- ({ label: value, icon: Webhook })}
- placeholder="https://hooks.example.com/gitops"
- invalidMessage={$_('alerts.errors.invalid_url')}
- />
- {/snippet}
-
+
+ {$_('alerts.editor.externalNotice')}
+
+ {:else if !data.external.allowedDomains.length && data.external.settingsPath}
+
+ {$_('alerts.editor.externalDisabled')}
+ {$_('alerts.editor.externalSettingsLink')}
+
{/if}
+
+ {$_('alerts.editor.recipientsNotice')}
+
+
+ {/if}
+
+ {#each CHANNEL_TYPES.filter((type) => type !== 'mail' && typeOn(type)) as type (type)}
+ {@const Icon = channelIcons[type]}
+
{/each}
+ {#if draft.channelIds.length > 0}
+
+
+ {$_('alerts.editor.channelsNotice')}
+
+ {/if}
+ {#if !data.external.canManage && data.channels.length > 0}
+
{$_('alerts.editor.channelsReadonly')}
+ {/if}
+
{$_('alerts.wizard.throttle')}
@@ -822,17 +859,29 @@
{$_('alerts.wizard.step.channels')}
- {#each channelMeta.filter( (meta) => draft.channels.includes(meta.key) ) as meta (meta.key)}
+ {#if channelTargets('mail', draft, data.recipientUsers, data.recipientRoles).length > 0}
-
+
- {meta.label}:
+ {$_('alerts.channels.mail')}:
{channelTargets(
- meta.key,
- draft.recipients,
+ 'mail',
+ draft,
data.recipientUsers,
data.recipientRoles,
- ).join(', ') || '—'}
+ ).join(', ')}
+
+
+ {/if}
+ {#each data.channels.filter( (channel) => draft.channelIds.includes(channel.id) ) as channel (channel.id)}
+ {@const Icon = channelIcons[channel.type] ?? Webhook}
+
+
+
+ {$_(`notifications.channels.types.${channel.type}`)}:
+ {channel.name}
{/each}
@@ -944,7 +993,7 @@
post('test', true)}
data-testid="alert-send-test"
diff --git a/src/lib/components/audit-summary.ts b/src/lib/components/audit-summary.ts
index 2960d4d3..32c5b32f 100644
--- a/src/lib/components/audit-summary.ts
+++ b/src/lib/components/audit-summary.ts
@@ -3,7 +3,12 @@
export type EntityRowChange =
| { type: 'added'; row: Record }
| { type: 'removed'; row: Record }
- | { type: 'modified'; before: Record; after: Record; changedFields: string[] };
+ | {
+ type: 'modified';
+ before: Record;
+ after: Record;
+ changedFields: string[];
+ };
export type FieldValue =
| { kind: 'text'; text: string }
@@ -103,7 +108,10 @@ export function classifyValue(value: unknown): FieldValue {
if (isFlagsObject(value)) {
return {
kind: 'flags',
- flags: Object.entries(value).map(([key, entry]) => ({ label: humanizeField(key), value: Boolean(entry) })),
+ flags: Object.entries(value).map(([key, entry]) => ({
+ label: humanizeField(key),
+ value: Boolean(entry),
+ })),
};
}
return { kind: 'json', json: value };
diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte
new file mode 100644
index 00000000..cb4cb702
--- /dev/null
+++ b/src/lib/components/notifications/ChannelsSection.svelte
@@ -0,0 +1,481 @@
+
+
+
+
+
+
+ {$_('notifications.channels.title')}
+
+
+ {data.scope === 'project'
+ ? $_('notifications.channels.descriptionProject')
+ : $_('notifications.channels.descriptionOrganization')}
+
+
+
+
+
+ {$_('notifications.channels.privacyNotice')}
+
+
+ {#if form?.channelTest}
+
+ {form.channelTest.sent
+ ? $_('notifications.channels.testSent')
+ : $_('notifications.channels.testFailed', {
+ values: { reason: form.channelTest.error ?? '—' },
+ })}
+
+ {:else if form?.channelError && form.channelForm !== 'create' && !form.channelErrors}
+
+ {errorMessage(form.channelError)}
+
+ {/if}
+
+ {#if data.channels.length === 0}
+
+ {$_('notifications.channels.empty')}
+
+ {:else}
+
+ {#each data.channels as channel (channel.id)}
+ {@const Icon = typeIcons[channel.type] ?? Webhook}
+
+
+
+
+ {channel.name}
+
+ {$_(`notifications.channels.types.${channel.type}`)}
+
+ {#if !channel.enabled}
+
+ {$_('notifications.channels.disabled')}
+
+ {/if}
+ {#if !channel.available}
+
+ {$_('notifications.channels.unavailable')}
+
+ {/if}
+
+
+ {channel.destinationMasked}
+
+
+ {$_('notifications.channels.lastDelivery', {
+ values: { date: formatDate(channel.lastDeliveryAt) },
+ })}
+
+ {#if channel.lastError}
+
+ {$_('notifications.channels.lastError', { values: { error: channel.lastError } })}
+
+ {/if}
+
+
+
+ {#if data.canUpdate}
+
+
+
+ {#if busy === `test:${channel.id}`} {:else} {/if}
+
+
+
+
+
+
+
+
+
+
openEdit(event, channel)}
+ >
+
+
+ {/if}
+ {#if data.canDelete}
+
+
+ openDelete(event, channel)}
+ >
+
+
+
+ {/if}
+
+
+ {/each}
+
+ {/if}
+
+ {#if data.inherited.length > 0}
+
+
+ {$_('notifications.channels.inheritedTitle')}
+
+
{$_('notifications.channels.inheritedDescription')}
+
+ {#each data.inherited as channel (channel.id)}
+ {@const Icon = typeIcons[channel.type] ?? Webhook}
+
+ {channel.name}
+ {#if !channel.enabled}
+ · {$_('notifications.channels.disabled')}
+ {/if}
+
+ {/each}
+
+
+ {/if}
+
+ {#if data.canCreate}
+
+
+
+ {$_('notifications.channels.create')}
+
+ {#if data.availableTypes.length === 0}
+
+ {$_('notifications.channels.noTypes')}
+
+ {:else}
+ {@const errors = { ...formCreateErrors, ...createErrors }}
+
+
+
{$_('notifications.channels.type')}
+
+ {#each data.availableTypes as type (type)}
+ {$_(`notifications.channels.types.${type}`)}
+ {/each}
+
+ {#if errors.type}
+ {errorText(errors, 'type')}
+
{/if}
+
+
+
{$_('notifications.channels.name')}
+
+ {#if errors.name}
+ {errorText(errors, 'name')}
+
{/if}
+
+
+
{$_('notifications.channels.destination')}
+
+ {#if errors.destination}
+
{errorText(errors, 'destination')}
+ {/if}
+
+
+
+ {#if busy === 'create'} {:else} {/if}
+ {$_('notifications.channels.create')}
+
+
+
+ {/if}
+
+ {/if}
+
+
+{#if data.canUpdate}
+
+
+
+
+
{$_('notifications.channels.name')}
+
+ {#if editErrors.name}
+ {errorText(editErrors, 'name')}
+
{/if}
+
+
+
{$_('notifications.channels.newDestination')}
+
+ {#if editErrors.destination}
+ {errorText(editErrors, 'destination')}
+
{/if}
+
+
+ {#snippet footer()}
+ (editOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'edit'} {/if}
+ {$_('notifications.channels.save')}
+
+ {/snippet}
+
+{/if}
+
+{#if data.canDelete}
+
+ {#snippet icon()}
+
+ {/snippet}
+
+
+
+ {#snippet footer()}
+ (deleteOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'delete'} {/if}
+ {$_('notifications.channels.delete')}
+
+ {/snippet}
+
+{/if}
diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts
index dda5f7d1..a9e5f5ad 100644
--- a/src/lib/database/schemas.ts
+++ b/src/lib/database/schemas.ts
@@ -431,6 +431,26 @@ export const ExternalRecipientEntity = entity('external_recipients', {
.$defaultFn(() => new Date().toISOString()),
});
+export const NotificationChannelEntity = entity('notification_channels', {
+ id: uuid().primaryKey(),
+ type: text().notNull(),
+ name: text().notNull(),
+ scope: text().notNull(),
+ organizationId: uuid().notNull(),
+ projectId: uuid().$defaultFn(() => null),
+ webhookUrl: text().notNull(),
+ enabled: bool().notNull().default(true),
+ createdByUserId: uuid().notNull(),
+ createdAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ updatedAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ lastDeliveryAt: timestamp(),
+ lastError: text(),
+});
+
relations.for(ProjectEntity, ({ one, many }) => ({
roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }),
organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }),
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index 538e1891..5b41899d 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -1721,7 +1721,9 @@
"domain_not_allowed": "The domain is not allowed for external recipients.",
"forbidden_external": "You are not allowed to add external recipients.",
"mail_not_configured": "SMTP is not configured: the test email can't be sent.",
- "test_rate_limited": "You sent too many test emails. Wait a few minutes."
+ "test_rate_limited": "You sent too many test emails. Wait a few minutes.",
+ "unknown_channel": "Some channel does not exist or can't be used from here.",
+ "forbidden_channel": "You are not allowed to add channels to the alert."
},
"channels": {
"mail": "Email",
@@ -1816,7 +1818,13 @@
"externalStatus": "Status of the external emails",
"sendTest": "Send test email",
"sendingTest": "Sending…",
- "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed)."
+ "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed).",
+ "channelsHelp": "The email goes to the recipients above. You can also post the alert to chat channels or webhooks: one message per channel.",
+ "noChannels": "There are no channels for this scope.",
+ "channelsSettingsLink": "Configure channels",
+ "channelFromOrganization": "(from the organization)",
+ "channelsNotice": "A channel is read by people who may not be allowed to see this event. The message leaves out sensitive fields.",
+ "channelsReadonly": "Only people who manage notifications can add channels."
},
"test": {
"matched": "The example event matches the conditions.",
@@ -1828,7 +1836,9 @@
"externalDelivers": "would get it",
"externalSkipped": "would not get it ({status})",
"delivered": "Test email sent: {sent} sent, {failed} failed.",
- "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again."
+ "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again.",
+ "channelDelivers": "would get the message",
+ "channelSkipped": "would not get it (disabled or deleted)"
},
"mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent.",
"wizard": {
@@ -1875,7 +1885,9 @@
"skipConditions": "No conditions",
"created": "Alert created",
"saved": "Alert saved",
- "failed": "Could not complete it. Try again."
+ "failed": "Could not complete it. Try again.",
+ "notConfigured": "Not configured",
+ "configure": "Configure"
}
},
"monitoring": {
@@ -2103,7 +2115,11 @@
"remove": "Remove",
"removeTitle": "Remove this recipient?",
"removeDescription": "{email} hasn't confirmed yet. Its confirmation link will stop working and it will be removed from every alert of the organization.",
- "removed": "{email} removed"
+ "removed": "{email} removed",
+ "projectDescription": "Chat channels and webhooks this project's alerts can use.",
+ "descriptionProject": "This project's chat channels and webhooks.",
+ "organizationDomains": "Allowed domains and external recipients are managed in the organization.",
+ "organizationDomainsLink": "Open organization settings"
},
"errors": {
"invalid": "The value is not valid.",
@@ -2113,7 +2129,18 @@
"invalid_status": "This recipient does not need a confirmation.",
"rate_limited": "Too many confirmation emails were sent. Try again later.",
"send_failed": "The confirmation email could not be sent.",
- "Forbidden": "You are not allowed to do this."
+ "Forbidden": "You are not allowed to do this.",
+ "required": "This field is required.",
+ "too_long": "It is too long.",
+ "invalid_type": "Invalid channel type.",
+ "type_unavailable": "This channel type is not available yet.",
+ "invalid_url": "The URL is not valid.",
+ "not_https": "The URL must use https.",
+ "credentials": "The URL can't include a user or a password.",
+ "ip_address": "The URL can't point to an IP address.",
+ "port": "The URL can't use another port.",
+ "host_not_allowed": "That domain is not allowed for this channel type.",
+ "path_not_allowed": "The URL path does not match this channel type."
},
"link": {
"invalid": "This link is not valid or has already been used.",
@@ -2142,6 +2169,52 @@
"ignore": "If you did not expect this email, ignore it: you will not get anything.",
"footer": "You receive this email because someone in a GitOps organization added your address to an alert."
}
+ },
+ "channels": {
+ "title": "Channels",
+ "descriptionOrganization": "Chat channels and webhooks the alerts of the organization and its projects can post to.",
+ "descriptionProject": "Channels only this project's alerts can use.",
+ "privacyNotice": "A channel is read by people who may have no GitOps account or permissions. The channel URL is stored encrypted and never shown in full again.",
+ "empty": "No channels yet.",
+ "types": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
+ },
+ "disabled": "Disabled",
+ "unavailable": "Type not available",
+ "lastDelivery": "Last delivery: {date}",
+ "lastError": "Last error: {error}",
+ "test": "Send test message",
+ "testSent": "Test message sent.",
+ "testFailed": "The test message could not be sent ({reason}).",
+ "enable": "Enable",
+ "disable": "Disable",
+ "delete": "Delete",
+ "confirmDelete": "Delete this channel? Alerts using it will stop posting to it.",
+ "edit": "Edit",
+ "name": "Name",
+ "newDestination": "New URL (empty keeps the current one)",
+ "save": "Save",
+ "inheritedTitle": "Organization channels",
+ "inheritedDescription": "This project's alerts can also use these channels. They are managed from the organization settings.",
+ "create": "Add channel",
+ "noTypes": "No channel type is available yet.",
+ "type": "Type",
+ "destination": "Webhook URL",
+ "testMessage": {
+ "title": "GitOps test message for {channel}",
+ "summary": "This channel will get the alerts of {where}.",
+ "event": "Test message",
+ "channel": "Channel",
+ "open": "Open in GitOps"
+ },
+ "created": "Channel added",
+ "saved": "Channel saved",
+ "deleted": "Channel deleted",
+ "disabledToast": "Channel disabled",
+ "enabledToast": "Channel enabled",
+ "deleteTitle": "Delete the channel?"
}
}
}
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index 00e62ceb..dd4ed300 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -1721,7 +1721,9 @@
"domain_not_allowed": "El dominio no está permitido para destinatarios externos.",
"forbidden_external": "No tienes permiso para añadir destinatarios externos.",
"mail_not_configured": "El SMTP no está configurado: no se puede enviar el email de prueba.",
- "test_rate_limited": "Has enviado demasiados emails de prueba. Espera unos minutos."
+ "test_rate_limited": "Has enviado demasiados emails de prueba. Espera unos minutos.",
+ "unknown_channel": "Algún canal no existe o no se puede usar desde aquí.",
+ "forbidden_channel": "No tienes permiso para añadir canales a la alerta."
},
"channels": {
"mail": "Email",
@@ -1816,7 +1818,13 @@
"externalStatus": "Estado de los emails externos",
"sendTest": "Enviar email de prueba",
"sendingTest": "Enviando…",
- "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados)."
+ "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados).",
+ "channelsHelp": "El email llega a los destinatarios de arriba. Además, puedes publicar la alerta en canales de chat o webhooks: un mensaje por canal.",
+ "noChannels": "No hay canales configurados para este ámbito.",
+ "channelsSettingsLink": "Configurar canales",
+ "channelFromOrganization": "(de la organización)",
+ "channelsNotice": "Un canal lo lee gente que puede no tener permiso para ver este evento. El mensaje no incluye los campos sensibles.",
+ "channelsReadonly": "Solo quien puede gestionar las notificaciones puede añadir canales."
},
"test": {
"matched": "El evento de ejemplo cumple las condiciones.",
@@ -1828,7 +1836,9 @@
"externalDelivers": "lo recibiría",
"externalSkipped": "no lo recibiría ({status})",
"delivered": "Email de prueba enviado: {sent} enviados, {failed} fallidos.",
- "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba."
+ "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba.",
+ "channelDelivers": "recibiría el mensaje",
+ "channelSkipped": "no lo recibiría (deshabilitado o eliminado)"
},
"mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán.",
"wizard": {
@@ -1875,7 +1885,9 @@
"skipConditions": "Sin condiciones",
"created": "Alerta creada",
"saved": "Alerta guardada",
- "failed": "No se pudo completar. Inténtalo de nuevo."
+ "failed": "No se pudo completar. Inténtalo de nuevo.",
+ "notConfigured": "No configurado",
+ "configure": "Configurar"
}
},
"monitoring": {
@@ -2103,7 +2115,11 @@
"remove": "Quitar",
"removeTitle": "¿Quitar este destinatario?",
"removeDescription": "{email} todavía no ha confirmado. Se anulará su enlace de confirmación y se quitará de todas las alertas de la organización.",
- "removed": "{email} quitado"
+ "removed": "{email} quitado",
+ "projectDescription": "Canales de chat y webhooks que pueden usar las alertas de este proyecto.",
+ "descriptionProject": "Canales de chat y webhooks de este proyecto.",
+ "organizationDomains": "Los dominios permitidos y los destinatarios externos se gestionan en la organización.",
+ "organizationDomainsLink": "Abrir configuración de la organización"
},
"errors": {
"invalid": "El valor no es válido.",
@@ -2113,7 +2129,18 @@
"invalid_status": "Este destinatario no necesita confirmación.",
"rate_limited": "Se han enviado demasiados emails de confirmación. Inténtalo más tarde.",
"send_failed": "No se ha podido enviar el email de confirmación.",
- "Forbidden": "No tienes permiso para hacer esto."
+ "Forbidden": "No tienes permiso para hacer esto.",
+ "required": "Este campo es obligatorio.",
+ "too_long": "Es demasiado largo.",
+ "invalid_type": "Tipo de canal no válido.",
+ "type_unavailable": "Este tipo de canal todavía no está disponible.",
+ "invalid_url": "La URL no es válida.",
+ "not_https": "La URL debe usar https.",
+ "credentials": "La URL no puede incluir usuario ni contraseña.",
+ "ip_address": "La URL no puede apuntar a una dirección IP.",
+ "port": "La URL no puede usar otro puerto.",
+ "host_not_allowed": "Ese dominio no está permitido para este tipo de canal.",
+ "path_not_allowed": "La ruta de la URL no corresponde a este tipo de canal."
},
"link": {
"invalid": "Este enlace no es válido o ya se ha usado.",
@@ -2142,6 +2169,52 @@
"ignore": "Si no esperabas este email, ignóralo: no recibirás nada.",
"footer": "Recibes este email porque alguien de una organización de GitOps añadió tu dirección a una alerta."
}
+ },
+ "channels": {
+ "title": "Canales",
+ "descriptionOrganization": "Canales de chat y webhooks donde las alertas de la organización y de sus proyectos pueden publicar.",
+ "descriptionProject": "Canales que solo pueden usar las alertas de este proyecto.",
+ "privacyNotice": "Un canal lo lee gente que puede no tener cuenta ni permisos en GitOps. La URL del canal se guarda cifrada y nunca se vuelve a mostrar completa.",
+ "empty": "Todavía no hay canales.",
+ "types": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
+ },
+ "disabled": "Deshabilitado",
+ "unavailable": "Tipo no disponible",
+ "lastDelivery": "Último envío: {date}",
+ "lastError": "Último error: {error}",
+ "test": "Enviar mensaje de prueba",
+ "testSent": "Mensaje de prueba enviado.",
+ "testFailed": "No se ha podido enviar el mensaje de prueba ({reason}).",
+ "enable": "Habilitar",
+ "disable": "Deshabilitar",
+ "delete": "Eliminar",
+ "confirmDelete": "¿Eliminar este canal? Las alertas que lo usan dejarán de publicar en él.",
+ "edit": "Editar",
+ "name": "Nombre",
+ "newDestination": "Nueva URL (vacío para mantener la actual)",
+ "save": "Guardar",
+ "inheritedTitle": "Canales de la organización",
+ "inheritedDescription": "Las alertas de este proyecto también pueden usar estos canales. Se gestionan desde los ajustes de la organización.",
+ "create": "Añadir canal",
+ "noTypes": "Todavía no hay ningún tipo de canal disponible.",
+ "type": "Tipo",
+ "destination": "URL del webhook",
+ "testMessage": {
+ "title": "Mensaje de prueba de GitOps para {channel}",
+ "summary": "Este canal recibirá las alertas de {where}.",
+ "event": "Mensaje de prueba",
+ "channel": "Canal",
+ "open": "Abrir en GitOps"
+ },
+ "created": "Canal añadido",
+ "saved": "Canal guardado",
+ "deleted": "Canal eliminado",
+ "disabledToast": "Canal deshabilitado",
+ "enabledToast": "Canal habilitado",
+ "deleteTitle": "¿Eliminar el canal?"
}
}
}
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
index 214982ce..a3f6c64c 100644
--- a/src/lib/notifications/types.ts
+++ b/src/lib/notifications/types.ts
@@ -16,3 +16,40 @@ export type NotificationSettingsPage = {
export type NotificationLinkState =
| { state: 'ready' | 'done'; email: string; organization: string }
| { state: 'invalid' | 'expired' };
+
+export type ChannelView = {
+ id: string;
+ type: string;
+ name: string;
+ scope: 'organization' | 'project';
+ organizationId: string;
+ projectId: string | null;
+ enabled: boolean;
+ destinationMasked: string;
+ available: boolean;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+ lastDeliveryAt: string | null;
+ lastError: string | null;
+};
+
+export type ChannelsSectionData = {
+ scope: 'organization' | 'project';
+ channels: ChannelView[];
+ inherited: ChannelView[];
+ availableTypes: string[];
+ canCreate: boolean;
+ canUpdate: boolean;
+ canDelete: boolean;
+};
+
+export type ChannelsFormResult = {
+ channelForm?: string;
+ channelDraft?: { type: string; name: string };
+ channelError?: string;
+ channelErrors?: Record;
+ channelSaved?: string;
+ channelDeleted?: string;
+ channelTest?: { channelId: string; sent: boolean; error: string | null };
+} | null;
diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts
index bf078436..25218693 100644
--- a/src/lib/server/alerts/operations.ts
+++ b/src/lib/server/alerts/operations.ts
@@ -191,6 +191,7 @@ export type AlertTestResult = {
/** Selected users left out because they can't read the event. */
deniedCount: number;
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
@@ -212,6 +213,7 @@ async function dryRun(
| 'conditions'
| 'match'
| 'recipients'
+ | 'channelIds'
| 'location'
| 'appliesTo'
>,
@@ -287,6 +289,7 @@ async function dryRun(
recipients: result.recipients.map(({ userId, username }) => ({ userId, username })),
deniedCount: result.denied.length,
external: result.external,
+ channels: result.channels,
...(delivery ? { delivery } : {}),
event: { type: alert.eventType, payload: sample.payload, projectId },
},
@@ -323,9 +326,11 @@ export async function testDraftAlert(
existing &&
existing.organizationId === location.organizationId &&
existing.projectId === location.projectId;
- const previousExternal = sameLocation ? existing.recipients.emails : [];
+ const previous = sameLocation
+ ? { emails: existing.recipients.emails, channelIds: existing.channelIds }
+ : {};
try {
- const fields = await alertService.validate(location, input, actor, previousExternal);
+ const fields = await alertService.validate(location, input, actor, previous);
const draft = new AlertDomain({
id: sameLocation ? existing.id : 'draft',
...location,
diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts
index 10b2f899..06529f40 100644
--- a/src/lib/server/alerts/page.ts
+++ b/src/lib/server/alerts/page.ts
@@ -6,12 +6,12 @@ import {
type AlertLocation,
type AlertRow,
} from '#modules/alerts';
+import { emptyRecipients } from '#modules/alerts/domain/alert.domain';
import {
- ALERT_CHANNELS,
- emptyRecipients,
- type AlertChannel,
-} from '#modules/alerts/domain/alert.domain';
-import { externalRecipientService, notificationSettingsService } from '#modules/notifications';
+ externalRecipientService,
+ notificationChannelService,
+ notificationSettingsService,
+} from '#modules/notifications';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import {
@@ -24,6 +24,7 @@ import {
import type {
AlertDraft,
AlertEditorData,
+ AlertChannelOption,
AlertListData,
AlertOption,
DraftCondition,
@@ -33,6 +34,7 @@ import {
canOpenNotificationSettings,
loadNotificationSettings,
} from '#lib/server/notifications/settings';
+import { loadChannelsSection } from '#lib/server/notifications/channels-page';
import { callerCan, canManageAlerts, contextOf, type AlertLocals } from './access';
import {
createAlert,
@@ -87,6 +89,17 @@ async function referenceOptions(
);
}
+async function channelOptions(location: AlertLocation): Promise {
+ const channels = await notificationChannelService.listUsable(location).catch(() => []);
+ return channels.map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ }));
+}
+
async function recipientOptions(location: AlertLocation) {
const [members, roles] = await Promise.all([
alertDirectory.listMembers(location).catch(() => []),
@@ -150,7 +163,7 @@ export async function loadAlertList(
scope: 'organization',
projectId: null,
};
- const [references, own, organizationRecipients, external] = await Promise.all([
+ const [references, own, organizationRecipients, external, channels] = await Promise.all([
referenceOptions([...catalog, ...inheritedCatalog], organizationLocation),
recipientOptions(location),
location.scope === 'project' ? recipientOptions(organizationLocation) : null,
@@ -159,6 +172,7 @@ export async function loadAlertList(
location,
listed.data.alerts.flatMap((alert) => alert.recipients.emails ?? []),
),
+ channelOptions(location),
]);
// names for the recipients of the location's alerts and of the inherited organization ones
const merge = (a: AlertOption[], b: AlertOption[] = []) => [
@@ -169,6 +183,14 @@ export async function loadAlertList(
users: merge(own.users, organizationRecipients?.users),
roles: merge(own.roles, organizationRecipients?.roles),
};
+ const [settings, channelsSection] = await Promise.all([
+ location.scope === 'organization' && external.settingsPath
+ ? loadNotificationSettings(locals, location.organizationId).then((result) =>
+ result.ok ? result.data : null,
+ )
+ : null,
+ loadChannelsSection(locals, location).catch(() => null),
+ ]);
return {
basePath: context.basePath,
@@ -184,13 +206,12 @@ export async function loadAlertList(
roles: recipients.roles,
recipientUsers: own.users,
recipientRoles: own.roles,
+ channels,
mailConfigured: isMailConfigured(),
external,
- settings: external.settingsPath
- ? await loadNotificationSettings(locals, location.organizationId).then((result) =>
- result.ok ? result.data : null,
- )
- : null,
+ settings,
+ channelsSection,
+ configPath: settings || channelsSection ? `${context.basePath}/settings` : null,
canCreate: allowed.canCreate,
canUpdate: allowed.canUpdate,
canDelete: allowed.canDelete,
@@ -205,8 +226,8 @@ function emptyDraft(eventType: string | null): AlertDraft {
eventType: eventType ?? '',
match: 'all',
conditions: [],
- channels: ['mail'],
recipients: emptyRecipients(),
+ channelIds: [],
throttleMinutes: 0,
};
}
@@ -223,8 +244,12 @@ function toDraft(alert: AlertRow): AlertDraft {
operator: condition.operator,
value: condition.value === undefined ? '' : condition.value,
})),
- channels: [...alert.channels],
- recipients: { ...emptyRecipients(), ...alert.recipients },
+ recipients: {
+ userIds: [...alert.recipients.userIds],
+ roleIds: [...alert.recipients.roleIds],
+ emails: [...alert.recipients.emails],
+ },
+ channelIds: [...alert.channelIds],
throttleMinutes: alert.throttleMinutes,
};
}
@@ -252,10 +277,11 @@ export async function loadAlertEditor(
}
const catalog = await listCatalog(locals, location);
- const [references, recipients, external] = await Promise.all([
+ const [references, recipients, external, channels] = await Promise.all([
referenceOptions(catalog, location),
recipientOptions(location),
externalRecipientsData(locals, location, alert?.recipients.emails ?? []),
+ channelOptions(location),
]);
const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null);
@@ -274,6 +300,7 @@ export async function loadAlertEditor(
roles: recipients.roles,
recipientUsers: recipients.users,
recipientRoles: recipients.roles,
+ channels,
mailConfigured: isMailConfigured(),
external,
canSave: alert ? allowed.canUpdate : allowed.canCreate,
@@ -325,24 +352,12 @@ export function parseAlertForm(form: FormData): AlertDraft {
eventType: String(form.get('eventType') ?? ''),
match: form.get('match') === 'any' ? 'any' : 'all',
conditions,
- channels: (() => {
- const channels = form
- .getAll('channels')
- .map(String)
- .filter((channel): channel is AlertChannel =>
- (ALERT_CHANNELS as readonly string[]).includes(channel),
- );
- // the editor always posts at least `mail`; older clients post nothing
- return channels.length > 0 ? [...new Set(channels)] : ['mail'];
- })(),
recipients: {
userIds: form.getAll('userIds').map(String),
roleIds: form.getAll('roleIds').map(String),
emails: listField(form, 'emails'),
- slackChannels: listField(form, 'slackChannels'),
- googleChatSpaces: listField(form, 'googleChatSpaces'),
- webhookUrls: listField(form, 'webhookUrls'),
},
+ channelIds: form.getAll('channelIds').map(String).filter(Boolean),
throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0,
};
}
diff --git a/src/lib/server/infra/http/webhook-request.test.ts b/src/lib/server/infra/http/webhook-request.test.ts
new file mode 100644
index 00000000..f268ae8d
--- /dev/null
+++ b/src/lib/server/infra/http/webhook-request.test.ts
@@ -0,0 +1,125 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { withRetry } from '../notifications/retry';
+import {
+ WebhookDeliveryError,
+ isRetryableWebhookError,
+ postJson,
+ validateWebhookUrl,
+ webhookRetryAfter,
+} from './webhook-request';
+
+const rule = { hosts: ['hooks.slack.com'], pathPrefix: '/services/' };
+
+describe('validateWebhookUrl (anti-SSRF)', () => {
+ it('accepts an https URL of an allowed host and path', () => {
+ const result = validateWebhookUrl('https://hooks.slack.com/services/T0/B0/abc', rule);
+ expect(result).toMatchObject({ ok: true });
+ });
+
+ it.each([
+ ['http://hooks.slack.com/services/T0', 'not_https'],
+ ['https://user:pass@hooks.slack.com/services/T0', 'credentials'],
+ ['https://127.0.0.1/services/T0', 'ip_address'],
+ ['https://[::1]/services/T0', 'ip_address'],
+ ['https://169.254.169.254/services/T0', 'ip_address'],
+ ['https://hooks.slack.com:8443/services/T0', 'port'],
+ ['https://evil.com/services/T0', 'host_not_allowed'],
+ ['https://hooks.slack.com.evil.com/services/T0', 'host_not_allowed'],
+ ['https://hooks.slack.com/other/T0', 'path_not_allowed'],
+ ['javascript:alert(1)', 'not_https'],
+ ['not a url', 'invalid_url'],
+ ['', 'invalid_url'],
+ ])('rejects %s', (url, error) => {
+ expect(validateWebhookUrl(url, rule)).toEqual({ ok: false, error });
+ });
+});
+
+function response(status: number, headers: Record = {}) {
+ return new Response(status === 204 ? null : 'secret body', { status, headers });
+}
+
+describe('postJson', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('posts JSON without following redirects and accepts any 2xx', async () => {
+ const fetch = vi.fn(async () => response(204));
+ await postJson('https://hooks.slack.com/services/x', { text: 'hi' }, { fetch });
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://hooks.slack.com/services/x',
+ expect.objectContaining({
+ method: 'POST',
+ redirect: 'manual',
+ body: '{"text":"hi"}',
+ headers: expect.objectContaining({ 'content-type': 'application/json' }),
+ }),
+ );
+ });
+
+ it('treats 429 and 5xx as retryable, honoring Retry-After', async () => {
+ const tooMany = await postJson(
+ 'https://h/x',
+ {},
+ {
+ fetch: async () => response(429, { 'retry-after': '7' }),
+ },
+ ).catch((error) => error);
+ expect(tooMany).toBeInstanceOf(WebhookDeliveryError);
+ expect(tooMany).toMatchObject({ status: 429, retryable: true, retryAfterMs: 7000 });
+
+ const down = await postJson('https://h/x', {}, { fetch: async () => response(503) }).catch(
+ (error) => error,
+ );
+ expect(down).toMatchObject({ status: 503, retryable: true });
+ });
+
+ it('treats other 4xx and redirects as permanent', async () => {
+ for (const status of [400, 403, 404, 410, 301, 302]) {
+ const error = await postJson(
+ 'https://h/x',
+ {},
+ { fetch: async () => response(status) },
+ ).catch((caught) => caught);
+ expect(error).toMatchObject({ status, retryable: false });
+ expect(error.summary).toBe(`HTTP ${status}`);
+ // the response body never ends up in the error
+ expect(String(error.message)).not.toContain('secret body');
+ }
+ });
+
+ it('times out after 5 s and calls it retryable', async () => {
+ vi.useFakeTimers();
+ const fetch = vi.fn(
+ (_url: string, init?: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
+ }),
+ );
+ const pending = postJson('https://h/x', {}, { fetch: fetch as never }).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await pending).toMatchObject({ status: null, retryable: true, reason: 'timeout' });
+ });
+
+ it('retries with withRetry only what may succeed later', async () => {
+ const sleep = vi.fn(async (_ms: number) => {});
+ const statuses = [429, 503, 200];
+ const fetch = vi.fn(async () => response(statuses.shift()!, { 'retry-after': '2' }));
+ await withRetry(() => postJson('https://h/x', {}, { fetch }), {
+ isRetryable: isRetryableWebhookError,
+ retryAfterMs: webhookRetryAfter,
+ sleep,
+ random: () => 0.5,
+ });
+ expect(fetch).toHaveBeenCalledTimes(3);
+ // 429 waits its Retry-After, 503 the regular backoff (4 s for the second retry)
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([2000, 4000]);
+
+ const gone = vi.fn(async () => response(404));
+ await expect(
+ withRetry(() => postJson('https://h/x', {}, { fetch: gone }), {
+ isRetryable: isRetryableWebhookError,
+ sleep,
+ }),
+ ).rejects.toMatchObject({ status: 404 });
+ expect(gone).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/lib/server/infra/http/webhook-request.ts b/src/lib/server/infra/http/webhook-request.ts
new file mode 100644
index 00000000..66292d4b
--- /dev/null
+++ b/src/lib/server/infra/http/webhook-request.ts
@@ -0,0 +1,149 @@
+import { isIP } from 'node:net';
+
+/** Why a webhook URL is refused; the UI maps them to `notifications.errors.`. */
+export type WebhookUrlError =
+ | 'invalid_url'
+ | 'not_https'
+ | 'credentials'
+ | 'ip_address'
+ | 'port'
+ | 'host_not_allowed'
+ | 'path_not_allowed';
+
+export type WebhookUrlRule = {
+ /** Exact host names the URL may point at (`hooks.slack.com`). */
+ hosts: readonly string[];
+ /** Required path prefix (`/services/`). */
+ pathPrefix?: string;
+};
+
+const MAX_URL_LENGTH = 2048;
+
+/**
+ * Anti-SSRF check of a webhook URL whose provider is known: `https` only, no credentials, no IP
+ * literal, the default port, an allowed host and path. Run it before saving **and** before every
+ * send (the stored value could have been changed in GitDB by hand).
+ */
+export function validateWebhookUrl(
+ raw: unknown,
+ rule: WebhookUrlRule,
+): { ok: true; url: URL } | { ok: false; error: WebhookUrlError } {
+ if (typeof raw !== 'string' || !raw.trim() || raw.length > MAX_URL_LENGTH) {
+ return { ok: false, error: 'invalid_url' };
+ }
+ let url: URL;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ return { ok: false, error: 'invalid_url' };
+ }
+ if (url.protocol !== 'https:') return { ok: false, error: 'not_https' };
+ if (url.username || url.password) return { ok: false, error: 'credentials' };
+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();
+ if (isIP(host)) return { ok: false, error: 'ip_address' };
+ if (url.port && url.port !== '443') return { ok: false, error: 'port' };
+ if (!rule.hosts.includes(host)) return { ok: false, error: 'host_not_allowed' };
+ if (rule.pathPrefix && !url.pathname.startsWith(rule.pathPrefix)) {
+ return { ok: false, error: 'path_not_allowed' };
+ }
+ return { ok: true, url };
+}
+
+/** A webhook delivery that failed; `retryable` tells whether trying again may help. */
+export class WebhookDeliveryError extends Error {
+ constructor(
+ /** HTTP status, or `null` for network errors and timeouts. */
+ readonly status: number | null,
+ readonly retryable: boolean,
+ /** `Retry-After` of a 429, in ms. */
+ readonly retryAfterMs: number | null = null,
+ readonly reason: 'timeout' | 'network' | 'redirect' | 'http' = 'http',
+ ) {
+ super(
+ status === null ? `Webhook delivery failed (${reason})` : `Webhook answered HTTP ${status}`,
+ );
+ this.name = 'WebhookDeliveryError';
+ }
+
+ /** Short description for `lastError` and the logs: never the URL nor the response body. */
+ get summary(): string {
+ if (this.status !== null) return `HTTP ${this.status}`;
+ return this.reason;
+ }
+}
+
+export const WEBHOOK_TIMEOUT_MS = 5_000;
+/** Longest `Retry-After` honored; longer waits fall back to the regular backoff. */
+const MAX_RETRY_AFTER_MS = 60_000;
+
+function parseRetryAfter(value: string | null, now: number): number | null {
+ if (!value) return null;
+ const seconds = Number(value);
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now;
+ if (!Number.isFinite(ms) || ms < 0) return null;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+export type PostJsonOptions = {
+ timeoutMs?: number;
+ headers?: Record;
+ fetch?: typeof fetch;
+ now?: () => number;
+};
+
+/**
+ * POSTs `body` as JSON. Any 2xx is a success; the response body is discarded. Redirects are not
+ * followed (they would bypass the URL check). Throws `WebhookDeliveryError`: retryable for network
+ * errors, timeouts, 429 (with its `Retry-After`) and 5xx; permanent for 3xx and other 4xx.
+ */
+export async function postJson(
+ url: string,
+ body: unknown,
+ options: PostJsonOptions = {},
+): Promise {
+ const send = options.fetch ?? fetch;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? WEBHOOK_TIMEOUT_MS);
+ let response: Response;
+ try {
+ response = await send(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...options.headers },
+ body: JSON.stringify(body),
+ redirect: 'manual',
+ signal: controller.signal,
+ });
+ } catch {
+ throw new WebhookDeliveryError(
+ null,
+ true,
+ null,
+ controller.signal.aborted ? 'timeout' : 'network',
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+ // nothing of the answer is kept: it is not ours to log
+ await response.body?.cancel().catch(() => {});
+
+ const { status } = response;
+ if (status >= 200 && status < 300) return;
+ if (status >= 300 && status < 400)
+ throw new WebhookDeliveryError(status, false, null, 'redirect');
+ if (status === 429) {
+ const retryAfter = parseRetryAfter(
+ response.headers.get('retry-after'),
+ (options.now ?? Date.now)(),
+ );
+ throw new WebhookDeliveryError(status, true, retryAfter);
+ }
+ throw new WebhookDeliveryError(status, status >= 500);
+}
+
+export function isRetryableWebhookError(error: unknown): boolean {
+ return error instanceof WebhookDeliveryError && error.retryable;
+}
+
+export function webhookRetryAfter(error: unknown): number | null {
+ return error instanceof WebhookDeliveryError ? error.retryAfterMs : null;
+}
diff --git a/src/lib/server/infra/notifications/chat-notification.ts b/src/lib/server/infra/notifications/chat-notification.ts
new file mode 100644
index 00000000..9a82ab7e
--- /dev/null
+++ b/src/lib/server/infra/notifications/chat-notification.ts
@@ -0,0 +1,99 @@
+import { Notification } from './notification';
+import type { NotificationTransport } from './transport';
+import { registerTransport } from './notify';
+import type { WebhookUrlError } from '../http/webhook-request';
+
+import { CHAT_CHANNEL_TYPES, type ChatChannelType } from './chat-types';
+
+export { CHAT_CHANNEL_TYPES, isChatChannelType, type ChatChannelType } from './chat-types';
+
+/**
+ * Provider-neutral content of a channel message; each transport turns it into its own format
+ * (Block Kit, Cards v2, signed JSON). Texts are already translated and plain: transports escape
+ * them for their format.
+ */
+export type ChannelMessage = {
+ /** The alert's name, or the channel's for a test message. */
+ title: string;
+ /** One line: `3 critical, 5 high` or the event label. */
+ summary: string;
+ /** Translated event label (`Analysis completed`). */
+ eventLabel: string;
+ /** Catalog fields as label/value, sensitive ones left out. */
+ fields: Array<{ label: string; value: string }>;
+ /** Absolute link to the resource in GitOps (`ORIGIN`), when there is one. */
+ link: { url: string; label: string } | null;
+ /** Matching events skipped by the throttle since the previous message. */
+ suppressed: number;
+ /** Plain-text fallback (mobile notifications, clients without rich formatting). */
+ text: string;
+ /** A test from the UI, not a real event. */
+ test: boolean;
+ /** Raw event data for formats that carry it (generic webhooks); absent for test messages. */
+ event?: { id: string; type: string; occurredAt: string; scope: Record };
+ alert?: { id: string; name: string };
+};
+
+export type ChatNotificationInput = {
+ channel: ChatChannelType;
+ /** Destination URL in clear: only ever held in memory, right before sending. */
+ destination: string;
+ message: ChannelMessage;
+};
+
+export class ChatNotification extends Notification {
+ readonly channel: ChatChannelType;
+ readonly destination: string;
+ readonly message: ChannelMessage;
+
+ constructor(input: ChatNotificationInput) {
+ super();
+ this.channel = input.channel;
+ this.destination = input.destination;
+ this.message = input.message;
+ }
+
+ validate(): void {
+ if (!this.destination) throw new Error('ChatNotification requires a destination');
+ if (!this.message.title.trim()) throw new Error('ChatNotification requires a title');
+ }
+}
+
+/**
+ * Transport of one chat channel type. `validateDestination` is the anti-SSRF check of the
+ * provider's URL, run before saving a channel and again before every send.
+ */
+export interface ChatTransport extends NotificationTransport {
+ validateDestination(raw: unknown): { ok: true; url: URL } | { ok: false; error: WebhookUrlError };
+}
+
+const CHAT_TRANSPORTS_KEY = Symbol.for('gitops.notifications.chat-transports');
+type GlobalWithChatTransports = typeof globalThis & {
+ [CHAT_TRANSPORTS_KEY]?: Map;
+};
+
+function registry(): Map {
+ return ((globalThis as GlobalWithChatTransports)[CHAT_TRANSPORTS_KEY] ??= new Map());
+}
+
+/**
+ * Activates a channel type: its channels can then be created and receive messages. Each
+ * transport sub-task (#96 webhook, #97 Slack, #98 Google Chat) registers its own.
+ */
+export function registerChatTransport(type: ChatChannelType, transport: ChatTransport): void {
+ registry().set(type, transport);
+ registerTransport(type, transport as NotificationTransport);
+}
+
+export function getChatTransport(type: ChatChannelType): ChatTransport | null {
+ return registry().get(type) ?? null;
+}
+
+/** Channel types with a registered transport, in catalog order. */
+export function availableChatTypes(): ChatChannelType[] {
+ return CHAT_CHANNEL_TYPES.filter((type) => registry().has(type));
+}
+
+export function resetChatTransports(): void {
+ registry().clear();
+}
diff --git a/src/lib/server/infra/notifications/chat-types.ts b/src/lib/server/infra/notifications/chat-types.ts
new file mode 100644
index 00000000..680be4fe
--- /dev/null
+++ b/src/lib/server/infra/notifications/chat-types.ts
@@ -0,0 +1,7 @@
+/** Channel types that post a message to a destination URL (`notification_channels.type`). */
+export const CHAT_CHANNEL_TYPES = ['webhook', 'slack', 'google-chat'] as const;
+export type ChatChannelType = (typeof CHAT_CHANNEL_TYPES)[number];
+
+export function isChatChannelType(value: unknown): value is ChatChannelType {
+ return (CHAT_CHANNEL_TYPES as readonly unknown[]).includes(value);
+}
diff --git a/src/lib/server/infra/notifications/delivery-queue.ts b/src/lib/server/infra/notifications/delivery-queue.ts
new file mode 100644
index 00000000..84e902e8
--- /dev/null
+++ b/src/lib/server/infra/notifications/delivery-queue.ts
@@ -0,0 +1,140 @@
+import type { Logger } from 'pino';
+import { withRetry, type RetryOptions } from './retry';
+
+type Job = {
+ item: T;
+ context: Record;
+ done: (sent: boolean) => void;
+};
+
+export type DeliveryQueueOptions = {
+ /** Delivers one item; a rejection is retried when `retry.isRetryable` allows it. */
+ send: (item: T) => Promise;
+ /** Deliveries in flight at the same time; a burst waits in the queue. */
+ concurrency?: number;
+ retry?: RetryOptions;
+ logger: Pick;
+ /** Log prefix and noun: `[mail]` / `email`, `[channels]` / `message`. */
+ label: { prefix: string; noun: string; plural: string };
+ /** Extra log fields for an item; never its content nor a secret destination. */
+ describe?: (item: T) => Record;
+ /** Short code of a definitive failure for the logs (never a message: it may quote secrets). */
+ errorCode?: (error: unknown) => unknown;
+ /** Called once per item after its last attempt. */
+ onSettled?: (item: T, outcome: { sent: true } | { sent: false; error: unknown }) => void;
+};
+
+/**
+ * In-process delivery queue with limited concurrency and retries (`withRetry`). Each job is one
+ * delivery; a definitive failure is logged and dropped, never thrown at the caller. Per process:
+ * pending jobs are lost on a crash, and `drain()` flushes them on shutdown.
+ */
+export class DeliveryQueue {
+ private readonly pending: Job[] = [];
+ private active = 0;
+ private readonly idle = new Set<() => void>();
+ private readonly concurrency: number;
+
+ constructor(protected readonly options: DeliveryQueueOptions) {
+ this.concurrency = Math.max(1, options.concurrency ?? 3);
+ }
+
+ /**
+ * Queues one delivery; resolves once it succeeded (`true`) or definitively failed (`false`,
+ * already logged). It never rejects.
+ */
+ enqueue(item: T, context: Record = {}): Promise {
+ return new Promise((resolve) => {
+ this.pending.push({ item, context, done: resolve });
+ this.pump();
+ });
+ }
+
+ /** Deliveries waiting or in flight. */
+ get size(): number {
+ return this.pending.length + this.active;
+ }
+
+ /**
+ * Resolves when the queue is empty, or after `timeoutMs` with what is left (`true` when
+ * everything was delivered).
+ */
+ drain(timeoutMs = 10_000): Promise {
+ if (this.size === 0) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ const onIdle = () => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ const timer = setTimeout(() => {
+ this.idle.delete(onIdle);
+ const { prefix, plural } = this.options.label;
+ this.options.logger.warn(
+ { remaining: this.size },
+ `${prefix} shutdown timeout: ${plural} left unsent`,
+ );
+ resolve(false);
+ }, timeoutMs);
+ this.idle.add(onIdle);
+ });
+ }
+
+ private pump(): void {
+ while (this.active < this.concurrency && this.pending.length > 0) {
+ const job = this.pending.shift()!;
+ this.active += 1;
+ 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 {
+ const { prefix, noun } = this.options.label;
+ const fields = { ...job.context, ...this.options.describe?.(job.item) };
+ const code = this.options.errorCode ?? defaultErrorCode;
+ try {
+ await withRetry(() => this.options.send(job.item), {
+ ...this.options.retry,
+ onRetry: (error, attempt, delayMs) =>
+ this.options.logger.debug(
+ { ...fields, attempt, delayMs, code: code(error) },
+ `${prefix} retrying ${noun}`,
+ ),
+ });
+ this.options.onSettled?.(job.item, { sent: true });
+ return true;
+ } catch (error) {
+ this.options.logger.error(
+ { ...fields, code: code(error) },
+ `${prefix} ${noun} could not be sent`,
+ );
+ this.options.onSettled?.(job.item, { sent: false, error });
+ return false;
+ }
+ }
+}
+
+/** The error's code, HTTP/SMTP status or name; never its message. */
+export function defaultErrorCode(error: unknown): unknown {
+ if (!error || typeof error !== 'object') return undefined;
+ const { code, responseCode, status, name } = error as {
+ code?: unknown;
+ responseCode?: unknown;
+ status?: unknown;
+ name?: unknown;
+ };
+ return responseCode ?? status ?? code ?? name;
+}
diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts
index 155e2aa5..cbd16c74 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -24,6 +24,20 @@ export {
} from './config';
export { withRetry, isRetryableMailError, type RetryOptions } from './retry';
export { emailButton, emailNote } from './email-parts';
+export {
+ CHAT_CHANNEL_TYPES,
+ ChatNotification,
+ availableChatTypes,
+ getChatTransport,
+ isChatChannelType,
+ registerChatTransport,
+ resetChatTransports,
+ type ChannelMessage,
+ type ChatChannelType,
+ type ChatNotificationInput,
+ type ChatTransport,
+} from './chat-notification';
+export { DeliveryQueue, defaultErrorCode, type DeliveryQueueOptions } from './delivery-queue';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
import { createLogger } from '#lib/server/logger';
@@ -41,13 +55,17 @@ type GlobalWithQueue = typeof globalThis & {
(globalThis as GlobalWithQueue)[SEND_KEY] = send;
+export function sendWithLatestNotify(notification: Parameters[0]): Promise {
+ return ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification);
+}
+
/**
* Process-wide queue for alert and system emails (3 at a time, 4 attempts with backoff). Kept on
* `globalThis` so HMR doesn't create a second one. Invitations and password resets don't use it:
* their links carry tokens and are sent directly.
*/
export const mailQueue: Queue = ((globalThis as GlobalWithQueue)[QUEUE_KEY] ??= new Queue({
- send: (notification) => ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification),
+ send: (notification) => sendWithLatestNotify(notification),
concurrency: 3,
logger: createLogger('mail'),
}));
diff --git a/src/lib/server/infra/notifications/mail-queue.ts b/src/lib/server/infra/notifications/mail-queue.ts
index 2a2f2b7f..2fdc7da7 100644
--- a/src/lib/server/infra/notifications/mail-queue.ts
+++ b/src/lib/server/infra/notifications/mail-queue.ts
@@ -1,17 +1,12 @@
import crypto from 'node:crypto';
import type { Logger } from 'pino';
+import { DeliveryQueue } from './delivery-queue';
import type { MailNotification } from './mail-notification';
-import { isRetryableMailError, withRetry, type RetryOptions } from './retry';
+import { isRetryableMailError, type RetryOptions } from './retry';
/** What the logs may say about an email: never its content or the address in clear. */
export type MailContext = { alertId?: string; eventId?: string; kind?: string };
-type Job = {
- notification: MailNotification;
- context: MailContext;
- done: (sent: boolean) => void;
-};
-
export type MailQueueOptions = {
send: (notification: MailNotification) => Promise;
/** Emails sent at the same time; a burst of events waits in the queue. */
@@ -34,103 +29,19 @@ export function recipientHash(address: string): string {
* is one email; a definitive failure is logged and dropped, never thrown at the caller. Per
* process: pending emails are lost on a crash, and `drain()` flushes them on shutdown.
*/
-export class MailQueue {
- private readonly pending: Job[] = [];
- private active = 0;
- private readonly idle = new Set<() => void>();
- private readonly concurrency: number;
-
- constructor(private readonly options: MailQueueOptions) {
- this.concurrency = Math.max(1, options.concurrency ?? 3);
- }
-
- enqueue(notification: MailNotification, context: MailContext = {}): Promise {
- return new Promise((resolve) => {
- this.pending.push({ notification, context, done: resolve });
- this.pump();
- });
- }
-
- /** Emails waiting or being sent. */
- get size(): number {
- return this.pending.length + this.active;
- }
-
- /**
- * Resolves when the queue is empty, or after `timeoutMs` with what is left (`true` when
- * everything was sent).
- */
- drain(timeoutMs = 10_000): Promise {
- if (this.size === 0) return Promise.resolve(true);
- return new Promise((resolve) => {
- const onIdle = () => {
- clearTimeout(timer);
- resolve(true);
- };
- const timer = setTimeout(() => {
- this.idle.delete(onIdle);
- this.options.logger.warn(
- { remaining: this.size },
- '[mail] shutdown timeout: emails left unsent',
- );
- resolve(false);
- }, timeoutMs);
- this.idle.add(onIdle);
+export class MailQueue extends DeliveryQueue {
+ constructor(options: MailQueueOptions) {
+ super({
+ send: options.send,
+ concurrency: options.concurrency,
+ retry: { isRetryable: isRetryableMailError, ...options.retry },
+ logger: options.logger,
+ label: { prefix: '[mail]', noun: 'email', plural: 'emails' },
+ describe: (notification) => ({ recipients: notification.to.map(recipientHash) }),
});
}
- private pump(): void {
- while (this.active < this.concurrency && this.pending.length > 0) {
- const job = this.pending.shift()!;
- this.active += 1;
- 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 {
- const recipients = job.notification.to.map(recipientHash);
- try {
- await withRetry(() => this.options.send(job.notification), {
- isRetryable: isRetryableMailError,
- ...this.options.retry,
- onRetry: (error, attempt, delayMs) =>
- this.options.logger.debug(
- { ...job.context, recipients, attempt, delayMs, code: errorCode(error) },
- '[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;
- }
+ enqueue(notification: MailNotification, context: MailContext = {}): Promise {
+ return super.enqueue(notification, context);
}
}
-
-function errorCode(error: unknown): unknown {
- if (!error || typeof error !== 'object') return undefined;
- const { code, responseCode, name } = error as {
- code?: unknown;
- responseCode?: unknown;
- name?: unknown;
- };
- return responseCode ?? code ?? name;
-}
diff --git a/src/lib/server/infra/notifications/notification.ts b/src/lib/server/infra/notifications/notification.ts
index 1244b065..eee81eef 100644
--- a/src/lib/server/infra/notifications/notification.ts
+++ b/src/lib/server/infra/notifications/notification.ts
@@ -1,4 +1,4 @@
-export type NotificationChannel = 'mail' | 'slack';
+export type NotificationChannel = 'mail' | 'slack' | 'google-chat' | 'webhook';
export abstract class Notification {
abstract readonly channel: NotificationChannel;
diff --git a/src/lib/server/infra/notifications/retry.ts b/src/lib/server/infra/notifications/retry.ts
index 48ac0607..ad36bff2 100644
--- a/src/lib/server/infra/notifications/retry.ts
+++ b/src/lib/server/infra/notifications/retry.ts
@@ -7,6 +7,7 @@ export type RetryOptions = {
/** ± fraction of each delay added at random, so retries of a burst don't line up. */
jitter?: number;
isRetryable?: (error: unknown) => boolean;
+ retryAfterMs?: (error: unknown) => number | null | undefined;
sleep?: (ms: number) => Promise;
random?: () => number;
onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
@@ -33,7 +34,11 @@ export async function withRetry(fn: () => Promise, options: RetryOptions =
} catch (error) {
if (attempt >= attempts || !isRetryable(error)) throw error;
const delay = baseDelayMs * factor ** (attempt - 1);
- const delayMs = Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1))));
+ const requested = options.retryAfterMs?.(error);
+ const delayMs =
+ typeof requested === 'number' && requested >= 0
+ ? Math.round(requested)
+ : Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1))));
options.onRetry?.(error, attempt, delayMs);
await sleep(delayMs);
}
diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts
new file mode 100644
index 00000000..4dea0869
--- /dev/null
+++ b/src/lib/server/notifications/channels-page.ts
@@ -0,0 +1,106 @@
+import { fail } from '@sveltejs/kit';
+import type { ChannelLocation } from '#modules/notifications';
+import type { AlertLocals } from '#lib/server/alerts/access';
+import type { ChannelsSectionData } from '#lib/notifications/types';
+import {
+ canManageChannels,
+ createChannel,
+ deleteChannel,
+ listChannels,
+ testChannel,
+ updateChannel,
+} from './channels';
+
+/** The channels section of a notifications page; `null` without `:notifications:read`. */
+export async function loadChannelsSection(
+ locals: AlertLocals,
+ location: ChannelLocation,
+): Promise {
+ const listed = await listChannels(locals, location);
+ if (!listed.ok) return null;
+ const [canCreate, canUpdate, canDelete] = await Promise.all([
+ canManageChannels(locals, location, 'create'),
+ canManageChannels(locals, location, 'update'),
+ canManageChannels(locals, location, 'delete'),
+ ]);
+ return { ...listed.data, scope: location.scope, canCreate, canUpdate, canDelete };
+}
+
+type ActionEvent = { request: Request; params: Record; locals: AlertLocals };
+
+/** Form actions of the channels section, shared by the organization and project pages. */
+export function channelActions(resolve: (event: ActionEvent) => Promise) {
+ return {
+ async createChannel(event: ActionEvent) {
+ const location = await resolve(event);
+ const form = await event.request.formData();
+ const input = {
+ type: String(form.get('type') ?? ''),
+ name: String(form.get('name') ?? ''),
+ destination: String(form.get('destination') ?? ''),
+ enabled: true,
+ };
+ const result = await createChannel(event.locals, location, input);
+ if (!result.ok) {
+ // the destination is never echoed back: it has to be typed again
+ return fail(result.status, {
+ channelForm: 'create',
+ channelDraft: { type: input.type, name: input.name },
+ channelError: result.error,
+ channelErrors: result.errors ?? {},
+ });
+ }
+ return { channelSaved: result.data.id };
+ },
+
+ async updateChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await updateChannel(event.locals, channelId, {
+ name: String(form.get('name') ?? ''),
+ destination: String(form.get('destination') ?? ''),
+ });
+ if (!result.ok) {
+ return fail(result.status, {
+ channelForm: channelId,
+ channelError: result.error,
+ channelErrors: result.errors ?? {},
+ });
+ }
+ return { channelSaved: channelId };
+ },
+
+ async toggleChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await updateChannel(event.locals, channelId, {
+ enabled: form.get('enabled') === 'true',
+ });
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelSaved: channelId };
+ },
+
+ async deleteChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await deleteChannel(event.locals, channelId);
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelDeleted: channelId };
+ },
+
+ async testChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await testChannel(event.locals, channelId);
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelTest: { channelId, ...result.data } };
+ },
+ };
+}
diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts
new file mode 100644
index 00000000..a8be8b0b
--- /dev/null
+++ b/src/lib/server/notifications/channels.ts
@@ -0,0 +1,175 @@
+import {
+ NotificationChannelNotFoundError,
+ NotificationChannelValidationError,
+ buildChannelTestMessage,
+ notificationChannelService,
+ type ChannelInput,
+ type ChannelLocation,
+ type NotificationChannelView,
+} from '#modules/notifications';
+import { organizationService } from '#modules/organization';
+import { projectService } from '#modules/projects';
+import { absoluteUrl, type ChatChannelType } from '#lib/server/infra/notifications';
+import { actorFor, callerCan, contextOf, type AlertLocals } from '#lib/server/alerts/access';
+
+export type ChannelAction = 'read' | 'create' | 'update' | 'delete';
+
+/** Outcome of a channel operation, mapped to JSON by the API and to `fail()` by form actions. */
+export type ChannelResult =
+ | { ok: true; status: number; data: T }
+ | { ok: false; status: number; error: string; errors?: Record };
+
+const forbidden = { ok: false as const, status: 403, error: 'Forbidden' };
+const notFound = { ok: false as const, status: 404, error: 'Channel not found' };
+
+/** `:notifications:` in the channel's (or the page's) location. */
+export function canManageChannels(
+ locals: AlertLocals,
+ location: ChannelLocation,
+ action: ChannelAction,
+): Promise {
+ return callerCan(locals, `${location.scope}:notifications:${action}`, contextOf(location));
+}
+
+function failure(error: unknown): ChannelResult {
+ if (error instanceof NotificationChannelValidationError) {
+ return { ok: false, status: 400, error: 'Invalid channel', errors: error.errors };
+ }
+ if (error instanceof NotificationChannelNotFoundError) return notFound;
+ throw error;
+}
+
+async function loadAuthorized(locals: AlertLocals, id: string, action: ChannelAction) {
+ const channel = await notificationChannelService.get(id).catch(() => null);
+ if (!channel) return notFound;
+ // a channel the caller can't read is indistinguishable from a missing one
+ if (!(await canManageChannels(locals, channel.location, 'read'))) return notFound;
+ if (action !== 'read' && !(await canManageChannels(locals, channel.location, action))) {
+ return forbidden;
+ }
+ return { ok: true as const, status: 200, data: channel };
+}
+
+export type ChannelList = {
+ channels: NotificationChannelView[];
+ /** Organization channels a project's alerts can also use (project locations only). */
+ inherited: NotificationChannelView[];
+ /** Types that can be created now (a transport is registered for them). */
+ availableTypes: ChatChannelType[];
+};
+
+export async function listChannels(
+ locals: AlertLocals,
+ location: ChannelLocation,
+): Promise> {
+ if (!(await canManageChannels(locals, location, 'read'))) return forbidden;
+ const own = await notificationChannelService.list(location);
+ const inherited =
+ location.scope === 'project'
+ ? await notificationChannelService.list({
+ organizationId: location.organizationId,
+ projectId: null,
+ })
+ : [];
+ return {
+ ok: true,
+ status: 200,
+ data: {
+ channels: own.map((channel) => notificationChannelService.toView(channel)),
+ inherited: inherited.map((channel) => notificationChannelService.toView(channel)),
+ availableTypes: notificationChannelService.availableTypes(),
+ },
+ };
+}
+
+export async function getChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'read');
+ return loaded.ok
+ ? { ok: true, status: 200, data: notificationChannelService.toView(loaded.data) }
+ : loaded;
+}
+
+export async function createChannel(
+ locals: AlertLocals,
+ location: ChannelLocation,
+ input: ChannelInput,
+): Promise> {
+ if (!(await canManageChannels(locals, location, 'create'))) return forbidden;
+ const actor = actorFor(locals);
+ if (!actor) return forbidden;
+ try {
+ const channel = await notificationChannelService.create(location, input, actor.userId);
+ return { ok: true, status: 201, data: notificationChannelService.toView(channel) };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+export async function updateChannel(
+ locals: AlertLocals,
+ id: string,
+ input: ChannelInput,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'update');
+ if (!loaded.ok) return loaded;
+ try {
+ // the type can't change: a different provider is a different channel
+ const { type: _type, ...changes } = input;
+ void _type;
+ const channel = await notificationChannelService.update(id, changes);
+ return { ok: true, status: 200, data: notificationChannelService.toView(channel) };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+export async function deleteChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'delete');
+ if (!loaded.ok) return loaded;
+ try {
+ await notificationChannelService.delete(id);
+ return { ok: true, status: 200, data: { id } };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+/** Names and settings path of a channel's location, for the test message. */
+async function describeLocation(location: ChannelLocation) {
+ const organization = await organizationService
+ .getOrganization(location.organizationId)
+ .catch(() => null);
+ const project = location.projectId
+ ? await projectService.getProject(location.projectId).catch(() => null)
+ : null;
+ const where = project?.name ?? organization?.name ?? 'GitOps';
+ const path =
+ organization && project
+ ? `/org/${organization.slug}/projects/${project.slug}/settings/notifications`
+ : organization
+ ? `/org/${organization.slug}/settings/notifications`
+ : null;
+ return { where, link: absoluteUrl(path) };
+}
+
+/** "Send test message": posts a test to the channel, even a disabled one, and tells the result. */
+export async function testChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'update');
+ if (!loaded.ok) return loaded;
+ const channel = loaded.data;
+ const { where, link } = await describeLocation(channel.location);
+ const result = await notificationChannelService.test(
+ id,
+ buildChannelTestMessage({ channelName: channel.name, where, link }),
+ );
+ return { ok: true, status: 200, data: result };
+}
diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts
index d3861945..c60eaff4 100644
--- a/src/modules/alerts/application/alert-engine.test.ts
+++ b/src/modules/alerts/application/alert-engine.test.ts
@@ -112,6 +112,7 @@ function alertRow(overrides: Partial = {}): AlertRow {
conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }],
recipients: { ...emptyRecipients(), userIds: [], roleIds: ['project-reporter'] },
channels: ['mail'],
+ channelIds: [],
throttleMinutes: 0,
createdByUserId: 'author',
createdAt: TIMESTAMP,
diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts
index 5fe48983..463b42dd 100644
--- a/src/modules/alerts/application/alert-engine.ts
+++ b/src/modules/alerts/application/alert-engine.ts
@@ -2,7 +2,7 @@ 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 { DELIVERED_CHANNELS, type AlertDomain } from '../domain/alert.domain';
+import type { AlertDomain } from '../domain/alert.domain';
import { matches } from '../domain/condition-evaluator';
import {
getSystemNotification,
@@ -11,10 +11,12 @@ import {
import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository';
import { AlertThrottle } from './alert-throttle';
import { RecipientResolver, type Recipient } from './recipient-resolver';
+import type { ChannelMessage } from '#lib/server/infra/notifications/chat-notification';
import {
eventContext,
type AlertDirectory,
type ExternalRecipientsPort,
+ type NotificationChannelsPort,
type ResolvedNames,
} from './types';
@@ -40,6 +42,18 @@ export type AlertTestDelivery = {
failed: number;
};
+type AlertToDeliver = Pick<
+ AlertDomain,
+ | 'id'
+ | 'name'
+ | 'description'
+ | 'scope'
+ | 'organizationId'
+ | 'location'
+ | 'recipients'
+ | 'channelIds'
+>;
+
export type SystemEmail = {
recipient: Recipient;
kind: SystemNotificationKind;
@@ -63,8 +77,9 @@ export type AlertEngineOptions = {
/** How long alerts of one event type stay cached; GitDB sync changes show up after this. */
cacheTtlMs?: number;
now?: () => number;
- /** `false` when no email can be sent (SMTP not configured): events are then ignored. */
deliveryEnabled?: () => boolean;
+ channels?: NotificationChannelsPort;
+ channelMessage?: (input: Omit) => ChannelMessage;
};
export type AlertDryRun = {
@@ -73,6 +88,7 @@ export type AlertDryRun = {
/** Selected users that would not get it because they can't read the event. */
denied: string[];
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
};
const DEFAULT_CACHE_TTL_MS = 60_000;
@@ -105,7 +121,7 @@ export class AlertEngine {
async handle(event: AnyDomainEvent): Promise {
if (!isEventType(event.type)) return;
- if (this.options.deliveryEnabled && !this.options.deliveryEnabled()) {
+ if (!this.mailEnabled() && !this.options.channels) {
this.options.logger.debug(
{ eventType: event.type, eventId: event.id },
'[alerts] email is not configured, event skipped',
@@ -114,13 +130,18 @@ export class AlertEngine {
}
const definition = getEventDefinition(event.type) as EventDefinition;
- // system notifications first: they don't depend on anyone configuring an alert
- await this.sendSystemNotification(event).catch((error) =>
- this.options.logger.error(
- { err: error, eventType: event.type, eventId: event.id },
- '[alerts] system notification failed',
- ),
- );
+ if (!this.mailEnabled()) {
+ this.options.logger.debug(
+ { eventType: event.type, eventId: event.id },
+ '[alerts] email is not configured, emails skipped',
+ );
+ } else
+ await this.sendSystemNotification(event).catch((error) =>
+ this.options.logger.error(
+ { err: error, eventType: event.type, eventId: event.id },
+ '[alerts] system notification failed',
+ ),
+ );
if (!definition.alertable) return;
@@ -143,20 +164,49 @@ export class AlertEngine {
async dryRun(
alert: Pick & {
appliesTo: AlertDomain['appliesTo'];
+ channelIds?: string[];
},
event: Pick,
): Promise {
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: [], external: [] };
+ if (!context) return { matched, recipients: [], denied: [], external: [], channels: [] };
const resolved = await this.options.recipients.resolve(
alert.location,
alert.recipients,
definition.readPermission,
context,
);
- return { matched, ...resolved, external: await this.externalPreview(alert) };
+ return {
+ matched,
+ ...resolved,
+ external: await this.externalPreview(alert),
+ channels: await this.channelPreview(alert),
+ };
+ }
+
+ private mailEnabled(): boolean {
+ return !this.options.deliveryEnabled || this.options.deliveryEnabled();
+ }
+
+ private async channelPreview(alert: {
+ location: AlertDomain['location'];
+ channelIds?: string[];
+ }) {
+ const port = this.options.channels;
+ const ids = alert.channelIds ?? [];
+ if (!port || ids.length === 0) return [];
+ const usable = await port.listUsable(alert.location).catch(() => []);
+ return ids.map((id) => {
+ const channel = usable.find((candidate) => candidate.id === id);
+ return {
+ id,
+ name: channel?.name ?? id,
+ type: channel?.type ?? 'unknown',
+ delivers: Boolean(channel?.enabled),
+ };
+ });
}
private async externalPreview(alert: Pick) {
@@ -193,14 +243,6 @@ export class AlertEngine {
const context = eventContext(event.scope);
if (!context) return;
- const pending = alert.channels.filter((channel) => !DELIVERED_CHANNELS.includes(channel));
- if (pending.length > 0) {
- log.debug(
- { alertId: alert.id, channels: pending },
- '[alerts] channels without a notifier yet are skipped',
- );
- }
-
const decision = this.throttle.acquire(alert.id, alert.throttleMinutes);
if (!decision.send) {
log.info(
@@ -223,13 +265,7 @@ export class AlertEngine {
);
}
- async sendTest(
- alert: Pick<
- AlertDomain,
- 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
- >,
- event: AnyDomainEvent,
- ): Promise {
+ async sendTest(alert: AlertToDeliver, 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(
@@ -240,18 +276,24 @@ export class AlertEngine {
}
private async deliver(
- alert: Pick<
- AlertDomain,
- 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
- >,
+ alert: AlertToDeliver,
event: AnyDomainEvent,
definition: EventDefinition,
suppressed: number,
test: boolean,
- ): Promise<{ recipients: number; externalRecipients: number; sent: number; failed: number }> {
+ ): Promise<{
+ recipients: number;
+ externalRecipients: number;
+ channels: 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 };
+ if (!context) {
+ return { recipients: 0, externalRecipients: 0, channels: 0, sent: 0, failed: 0 };
+ }
+ const mail = this.mailEnabled();
const { recipients, denied } = await this.options.recipients.resolve(
alert.location,
@@ -277,14 +319,18 @@ export class AlertEngine {
.catch(() => ({}));
const memberEmails = new Set(recipients.map((recipient) => recipient.email.toLowerCase()));
- const external = (await this.externalRecipientsOf(alert)).filter(
- (recipient) => !memberEmails.has(recipient.email.toLowerCase()),
- );
-
- const targets: AlertEmailRecipient[] = [
- ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })),
- ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })),
- ];
+ const external = mail
+ ? (await this.externalRecipientsOf(alert)).filter(
+ (recipient) => !memberEmails.has(recipient.email.toLowerCase()),
+ )
+ : [];
+
+ const targets: AlertEmailRecipient[] = mail
+ ? [
+ ...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
@@ -316,11 +362,44 @@ export class AlertEngine {
}
}
+ const channelIds = alert.channelIds ?? [];
+ let channelsSent = 0;
+ if (channelIds.length > 0 && this.options.channels && this.options.channelMessage) {
+ const message = this.options.channelMessage({
+ alert,
+ event,
+ definition,
+ suppressed,
+ names,
+ where,
+ ...(test ? { test: true } : {}),
+ });
+ const results = await Promise.all(
+ channelIds.map((channelId) =>
+ this.options
+ .channels!.deliver(channelId, message, {
+ alertId: alert.id,
+ eventId: event.id,
+ kind: test ? 'alert_test' : 'alert',
+ })
+ .catch((error) => {
+ log.warn(
+ { err: error, alertId: alert.id, eventId: event.id, channelId },
+ '[alerts] channel message failed',
+ );
+ return false;
+ }),
+ ),
+ );
+ channelsSent = results.filter(Boolean).length;
+ }
+
return {
recipients: recipients.length,
externalRecipients: external.length,
- sent,
- failed: targets.length - sent,
+ channels: channelIds.length,
+ sent: sent + channelsSent,
+ failed: targets.length - sent + (channelIds.length - channelsSent),
};
}
diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts
new file mode 100644
index 00000000..a85d4ee1
--- /dev/null
+++ b/src/modules/alerts/application/alert.channels.test.ts
@@ -0,0 +1,359 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getEventDefinition, type EventDefinition } from '#lib/events/catalog';
+import type { AnyDomainEvent } from '#lib/server/events';
+import { createChannelsFixture } from '#modules/notifications/application/testing';
+import {
+ AlertDomain,
+ AlertValidationError,
+ type AlertInput,
+ type AlertLocation,
+} from '../domain/alert.domain';
+import { buildAlertChannelMessage } from '../infrastructure/alert-channel-message';
+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 { AlertThrottle } from './alert-throttle';
+import { RecipientResolver } from './recipient-resolver';
+import { FakeAlertDirectory, actor } from './testing';
+import type { NotificationChannelsPort } from './types';
+
+const ORG = 'org-1';
+const orgLocation: AlertLocation = { scope: 'organization', organizationId: ORG, projectId: null };
+const p1: AlertLocation = { scope: 'project', organizationId: ORG, projectId: 'p1' };
+const HOOK = 'https://hooks.example.com/hook/T0/B0/xyz';
+const WITHOUT_NOTIFICATIONS = ['project:codereport:reports:read', 'organization:projects:read'];
+
+function input(overrides: AlertInput = {}): AlertInput {
+ return {
+ name: 'Críticas',
+ eventType: 'code_report.analysis.completed',
+ recipients: { userIds: ['u1'] },
+ ...overrides,
+ };
+}
+
+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',
+ gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null },
+ summary: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0, total: 1, secrets: 0 },
+ policies: {
+ status: 'compliant',
+ totalViolations: 0,
+ blockingFailures: 0,
+ failedPolicyIds: [],
+ },
+ },
+ } as unknown as AnyDomainEvent;
+}
+
+async function validationErrors(promise: Promise) {
+ const error = await promise.catch((caught) => caught);
+ expect(error).toBeInstanceOf(AlertValidationError);
+ return (error as AlertValidationError).errors;
+}
+
+class RecordingNotifier implements AlertNotifierPort {
+ alerts: AlertEmail[] = [];
+ system: SystemEmail[] = [];
+ fail = false;
+ async sendAlert(email: AlertEmail) {
+ if (this.fail) throw new Error('SMTP down');
+ this.alerts.push(email);
+ }
+ async sendSystemNotification(email: SystemEmail) {
+ this.system.push(email);
+ }
+}
+
+describe('alerts with notification channels', () => {
+ let channels: ReturnType;
+ let port: NotificationChannelsPort;
+ let repository: InMemoryAlertRepository;
+ let directory: FakeAlertDirectory;
+ let service: AlertService;
+ let orgChannel: string;
+ let p1Channel: string;
+ let p2Channel: string;
+
+ beforeEach(async () => {
+ channels = createChannelsFixture();
+ port = {
+ listUsable: async (location) =>
+ (await channels.service.listUsable(location)).map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ })),
+ deliver: (id, message, context) => channels.service.deliver(id, message, context),
+ };
+ orgChannel = (
+ await channels.service.create(
+ orgLocation,
+ { type: 'slack', name: '#org', destination: HOOK },
+ 'a',
+ )
+ ).id;
+ p1Channel = (
+ await channels.service.create(p1, { type: 'slack', name: '#p1', destination: HOOK }, 'a')
+ ).id;
+ p2Channel = (
+ await channels.service.create(
+ { ...p1, projectId: 'p2' },
+ { type: 'slack', name: '#p2', destination: HOOK },
+ 'a',
+ )
+ ).id;
+
+ 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}`,
+ channels: port,
+ });
+ });
+
+ describe('validation', () => {
+ it('accepts the project and organization channels a project alert may use', async () => {
+ const alert = await service.create(
+ p1,
+ input({ channelIds: [p1Channel, orgChannel, p1Channel] }),
+ actor('admin'),
+ );
+ expect(alert.channelIds).toEqual([p1Channel, orgChannel]);
+ expect(alert.channels).toEqual(['mail', 'slack']);
+ });
+
+ it('rejects channels of another project or another location', async () => {
+ expect(
+ (
+ await validationErrors(
+ service.create(p1, input({ channelIds: [p2Channel] }), actor('admin')),
+ )
+ ).channelIds,
+ ).toBe('unknown_channel');
+ // an organization alert can't use a project channel either
+ expect(
+ (
+ await validationErrors(
+ service.create(orgLocation, input({ channelIds: [p1Channel] }), actor('admin')),
+ )
+ ).channelIds,
+ ).toBe('unknown_channel');
+ });
+
+ it('needs