From b72af36ed7e8ed6aef439f72833f4b04d3f17d8b Mon Sep 17 00:00:00 2001 From: "Liam Verdejo (ES)" Date: Tue, 24 Nov 2026 10:28:20 +0100 Subject: [PATCH 1/2] Feat: Add alerts destination external email --- .github/copilot-instructions.md | 63 ++-- CLAUDE.md | 56 ++- README.md | 21 +- src/hooks.server.ts | 16 +- src/lib/alerts/summary.ts | 3 +- src/lib/alerts/types.ts | 18 +- src/lib/components/AppSidebar.svelte | 22 +- .../components/NotificationLinkPage.svelte | 86 +++++ src/lib/components/alerts/AlertEditor.svelte | 154 +++++++- src/lib/config/permissions.ts | 11 + src/lib/database/schemas.ts | 40 ++ src/lib/events/catalog/code-report.events.ts | 11 + src/lib/events/catalog/types.ts | 4 + src/lib/events/catalog/vault.events.ts | 11 +- src/lib/i18n/locales/en.json | 104 +++++- src/lib/i18n/locales/es.json | 104 +++++- src/lib/notifications/status.ts | 15 + src/lib/notifications/types.ts | 4 + src/lib/server/alerts/operations.ts | 96 ++++- src/lib/server/alerts/page.ts | 51 ++- .../server/infra/notifications/config.test.ts | 37 +- src/lib/server/infra/notifications/config.ts | 24 +- .../server/infra/notifications/email-parts.ts | 21 ++ src/lib/server/infra/notifications/i18n.ts | 32 ++ src/lib/server/infra/notifications/index.ts | 24 +- .../notifications/mail-notification.test.ts | 27 ++ .../infra/notifications/mail-notification.ts | 12 + .../infra/notifications/mail-queue.test.ts | 6 +- .../server/infra/notifications/mail-queue.ts | 52 ++- .../infra/notifications/mail.transport.ts | 1 + src/lib/server/infra/rate-limit.test.ts | 27 ++ src/lib/server/infra/rate-limit.ts | 59 +++ src/lib/server/infra/tokens.test.ts | 67 ++++ src/lib/server/infra/tokens.ts | 85 +++++ src/lib/server/notifications/links.ts | 47 +++ src/lib/server/notifications/settings.test.ts | 137 +++++++ src/lib/server/notifications/settings.ts | 130 +++++++ .../alerts/application/alert-engine.test.ts | 35 +- .../alerts/application/alert-engine.ts | 160 +++++++- .../alerts/application/alert.external.test.ts | 345 +++++++++++++++++ .../alerts/application/alert.service.ts | 116 +++++- src/modules/alerts/application/types.ts | 23 +- src/modules/alerts/domain/alert.domain.ts | 8 + .../alerts/domain/sample-event.test.ts | 46 +++ src/modules/alerts/domain/sample-event.ts | 50 ++- src/modules/alerts/index.ts | 92 ++++- .../alert-mail.notifier.test.ts | 95 ++++- .../infrastructure/alert-mail.notifier.ts | 144 +++---- .../alerts/infrastructure/event-summary.ts | 5 +- .../auth/domain/role-permissions.data.ts | 2 + .../external-recipient.service.test.ts | 322 ++++++++++++++++ .../application/external-recipient.service.ts | 351 ++++++++++++++++++ .../notification-settings.service.ts | 65 ++++ .../notifications/application/testing.ts | 64 ++++ .../domain/email-address.test.ts | 76 ++++ .../notifications/domain/email-address.ts | 66 ++++ .../domain/external-recipient.domain.ts | 176 +++++++++ .../domain/notification-settings.domain.ts | 13 + src/modules/notifications/index.ts | 69 ++++ .../external-recipient-mail.notifier.ts | 48 +++ .../external-recipient.repository.ts | 71 ++++ .../repositories/in-memory.repositories.ts | 73 ++++ .../notification-settings.repository.ts | 60 +++ .../email/external-recipient-verify.html | 13 + src/routes/+layout.server.ts | 5 + src/routes/+layout.svelte | 5 +- src/routes/api/alerts/[id]/test/+server.ts | 3 +- src/routes/api/alerts/server.test.ts | 174 ++++++++- src/routes/api/alerts/test/+server.ts | 3 +- .../notifications/unsubscribe/+page.server.ts | 18 + .../notifications/unsubscribe/+page.svelte | 8 + .../notifications/verify/+page.server.ts | 18 + src/routes/notifications/verify/+page.svelte | 8 + .../settings/notifications/+page.server.ts | 42 +++ .../[org]/settings/notifications/+page.svelte | 189 ++++++++++ 75 files changed, 4512 insertions(+), 227 deletions(-) create mode 100644 src/lib/components/NotificationLinkPage.svelte create mode 100644 src/lib/notifications/status.ts create mode 100644 src/lib/notifications/types.ts create mode 100644 src/lib/server/infra/notifications/email-parts.ts create mode 100644 src/lib/server/infra/notifications/i18n.ts create mode 100644 src/lib/server/infra/rate-limit.test.ts create mode 100644 src/lib/server/infra/rate-limit.ts create mode 100644 src/lib/server/infra/tokens.test.ts create mode 100644 src/lib/server/infra/tokens.ts create mode 100644 src/lib/server/notifications/links.ts create mode 100644 src/lib/server/notifications/settings.test.ts create mode 100644 src/lib/server/notifications/settings.ts create mode 100644 src/modules/alerts/application/alert.external.test.ts create mode 100644 src/modules/alerts/domain/sample-event.test.ts create mode 100644 src/modules/notifications/application/external-recipient.service.test.ts create mode 100644 src/modules/notifications/application/external-recipient.service.ts create mode 100644 src/modules/notifications/application/notification-settings.service.ts create mode 100644 src/modules/notifications/application/testing.ts create mode 100644 src/modules/notifications/domain/email-address.test.ts create mode 100644 src/modules/notifications/domain/email-address.ts create mode 100644 src/modules/notifications/domain/external-recipient.domain.ts create mode 100644 src/modules/notifications/domain/notification-settings.domain.ts create mode 100644 src/modules/notifications/index.ts create mode 100644 src/modules/notifications/infrastructure/external-recipient-mail.notifier.ts create mode 100644 src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts create mode 100644 src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts create mode 100644 src/modules/notifications/infrastructure/repositories/notification-settings.repository.ts create mode 100644 src/notifications/email/external-recipient-verify.html create mode 100644 src/routes/notifications/unsubscribe/+page.server.ts create mode 100644 src/routes/notifications/unsubscribe/+page.svelte create mode 100644 src/routes/notifications/verify/+page.server.ts create mode 100644 src/routes/notifications/verify/+page.svelte create mode 100644 src/routes/org/[org]/settings/notifications/+page.server.ts create mode 100644 src/routes/org/[org]/settings/notifications/+page.svelte diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 1d15a26b..d44e0e7a 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -70,7 +70,17 @@ La logica vive en `src/modules//` con `domain/`, `application/`, `infras `index.ts` como composition root. El `domain/` contiene entidades (`*.domain.ts`) y datos centralizados (`*.data.ts`) para constantes: permisos de roles, defaults de proyecto, pesos de riesgo y mapeos de herramientas. Los modulos actuales son `auth`, `config`, `organization`, -`projects`, `storage` y `code-report`. Las rutas deben importar desde el `index.ts` publico. +`projects`, `storage`, `code-report`, `vault`, `audit`, `alerts` y `notifications`. + +**Destinatarios de email externo:** El módulo `notifications` gestiona acceso a personas sin +cuenta GitOps (vendors, mailboxes). Cada dirección es un `ExternalRecipientEntity` con estados +(`pending`, `verified`, `unsubscribed`, `blocked`). Las direcciones se confirman vía token HMAC +(7 días, single-use, rate limited 3/h por dirección). Solo se envían a direcciones verificadas +con dominio permitido (configurado en `/org//settings/notifications`). Las alertas omiten +campos sensibles y links al app para externals. Rutas públicas sin sesión: `/notifications/verify` +y `/notifications/unsubscribe` aceptan POST con tokens HMAC. + +Las rutas deben importar desde el `index.ts` publico. GitDB es la unica fuente de verdad para usuarios, roles, API keys, organizaciones, proyectos, metadata de storage y code reports. Se configura con `GITDB_REPOSITORY_URL` (URLs HTTPS o SSH @@ -85,34 +95,43 @@ CSRF Origin check de SvelteKit no dependa del header Host, previniendo bypass en ## RBAC y seguridad -Los permisos usan `section:action` con scope global, de organizacion o de proyecto. Usar siempre -`can()` o `isAdmin()` desde `$modules/auth`; `locals.user.role` es un objeto, no el string -`admin`. +Los permisos usan `::` (ej: `organization:projects:read`, `project:vault:secrets:all`) +con scope `cluster`, `organization` o `project`. Usar siempre `can()` o `isAdmin()` desde `$modules/auth`; +`locals.user.role` es un objeto, no el string `admin`. + +**Permisos de org:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, +`organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, +`organization:audit:read`, `organization:events:read`, `organization:alerts:read`, +`organization:notifications:read` (leer destinatarios externos y dominios permitidos), +`organization:notifications:update` (añadir direcciones externas, cambiar dominios). **Gating de permisos en UI:** En loaders de rutas, usar `cancanService.canSessionUser()` para verificar permisos específicos y pasarlos a componentes como props (`canCreate`, `canUpdate`, `canDelete`) para ocultar acciones que el usuario no puede realizar. El layout raíz (`+layout.server.ts`) calcula permisos -granulares de lectura para settings de org (proyectos, usuarios, roles, configuración global, backups, servidor-keys, audit) -y módulos de proyecto (vault, codereport, stateiac) combinándolos con lógica OR (`canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`) -para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico. +granulares de lectura para settings de org (proyectos, usuarios, roles, configuración, backups, servidor-keys, +audit, eventos, alertas, notificaciones) y módulos de proyecto (vault, codereport, stateiac) combinándolos +con lógica OR para obtener flags de lectura de alto nivel que se filtran en AppSidebar según acceso específico. Roles por defecto en `src/modules/auth/domain/role-permissions.data.ts`. Los permisos incluyen scope -como prefijo (ej: `organization:projects:read`, `project:vault:secrets:all`) y se almacenan verbatim sin -transformaciones. Recursos de módulos tienen sub-permisos granulares (ej: `project:vault:secrets:read`, `project:vault:environments:read`): -- **GitOps Admin** (`cluster-admin`) — vault, openreport, stateiac (todos) +como prefijo y se almacenan verbatim sin transformaciones. Módulos tienen sub-permisos granulares +(ej: `project:vault:secrets:read`, `project:codereport:reports:read`): +- **GitOps Admin** (`cluster-admin`) — acceso total a vault, openreport, stateiac - **GitOps User** (`cluster-user`) — rol base sin permisos propios para acceso a nivel sistema -- **Organization Admin** — todos los permisos de org (proyectos, usuarios, roles, configuración global, backups, server-access-keys, audit) -- **Organization Developer** — solo read/create/update de proyectos -- **Project Admin** — metadata/usuarios/roles/server-keys/audit plus todos los permisos de módulos (vault, codereport, stateiac) -- **Project Developer/Viewer** — acceso granular a módulos con permisos diferenciados (solo lectura en Viewer) - -Los permisos de organización se propagan a sus proyectos solo cuando no hay un assignment explícito a nivel de -proyecto. Un usuario con `organization:projects:read` puede satisfacer `project:project:read` en cualquier -proyecto—pero si tiene un rol específico del proyecto, ese assignment es autoritario y los permisos de org no -aplican (regla most-specific-wins). Permite delegación de autoridad granular con restricciones por-proyecto. - -`canManageOrganization()` controla acceso al area `/settings`, mientras que `canViewOrganization()` incluye -tambien usuarios con acceso solo a proyectos bajo la organización (ven el overview pero no pueden acciones de org-scope). +- **Organization Admin** — todos los permisos de org: proyectos, usuarios, roles, settings, backups, + server-keys, audit, eventos, alertas, notificaciones +- **Organization Developer** — solo lectura/crear/actualizar proyectos +- **Project Admin** — metadata/usuarios/roles/server-keys/audit/alertas/notificaciones; acceso total + a módulos (vault, codereport, stateiac) +- **Project Developer** — lectura/crear/actualizar recursos; acceso granular a módulos; lee alertas +- **Project Viewer** — solo lectura: metadata, alertas, módulos + +Los permisos de organización se propagan a sus proyectos solo cuando no hay assignment explícito a nivel de +proyecto (regla most-specific-wins). `canManageOrganization()` controla acceso al area `/settings`, mientras +que `canViewOrganization()` incluye usuarios con acceso solo a proyectos. + +**Rutas públicas de notificaciones:** `/notifications/verify` y `/notifications/unsubscribe` aceptan POST con +tokens HMAC (permitidas sin sesión en `hooks.server.ts`) para confirmar direcciones y unsubscribirse de alertas +externas. Usan tokens stateless HMAC (signToken con `GITDB_ENCRYPTION_KEY`, TTL 90 días). Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a `roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a diff --git a/CLAUDE.md b/CLAUDE.md index 139df673..ca3d4170 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -101,7 +101,8 @@ Domain layers include entity classes (e.g., `*.domain.ts`) and centralized data and tool policy mappings. Current modules include `auth`, `config`, `organization`, `projects`, `storage`, -`code-report`, `vault`, `audit`, and `alerts`. Shared infrastructure lives in `src/lib/`. Routes should import module APIs from +`code-report`, `vault`, `audit`, `alerts`, and `notifications`. The `notifications` module handles +external email recipient management (domains, verification tokens, unsubscribe tracking). Shared infrastructure lives in `src/lib/`. Routes should import module APIs from their `index.ts`, not internal layers. GitDB is the single source of truth. Users, roles, API keys, organizations, projects, storage @@ -117,7 +118,10 @@ Bitbucket, and GitLab; in production, ensure SSH authentication credentials are `ORIGIN` environment variable pins the application's public origin (e.g., `http://localhost:3000`). SvelteKit's CSRF Origin check depends on this value instead of deriving it from the incoming Host -header, preventing bypasses when running behind a proxy that rewrites Host headers. +header, preventing bypasses when running behind a proxy that rewrites Host headers. It is also the +origin of the absolute links in emails (`absoluteUrl()`); only under `vite dev` do those links use +the origin of the requests the dev server receives instead (`rememberDevOrigin()` in +`hooks.server.ts`), so they work on port 5173 whatever `ORIGIN` says. ## Domain events @@ -199,8 +203,39 @@ in `docs/adr/0001-event-bus-and-alerts.md`. - HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`, `GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test` - (dry runs: never send, never touch the throttle). Project API keys only reach their project. - + (dry runs that never touch the throttle; with `send: true`, `AlertEngine.sendTest()` also emails + the recipients a real event would reach, members filtered by cancan and verified externals only, + with a `[Test]` subject; needs SMTP and is limited to 5 per caller every 10 minutes, in memory. + It also registers the draft's new external addresses, so they get the confirmation email and + receive the next test once confirmed, before the alert is saved). + Project API keys only reach their project. + +- External email recipients (`$modules/notifications`, #99): `recipients.externalEmails` holds + normalized addresses outside GitOps. Each address is an `ExternalRecipientEntity` (GitDB + `external_recipients`) shared by every alert of the organization: `pending` → `verified` (the + owner clicked the confirmation link) → `unsubscribed`, or `blocked` when its domain leaves + `allowedExternalEmailDomains` (`notification_settings`, one row per organization, empty by + default = no externals; exact domain match, `*.example.com` for subdomains, punycode). + `AlertService` rejects not allowed or invalid addresses (`domain_not_allowed`, + `invalid_email`) and requires `:notifications:update` to **add** addresses + (`forbidden_external`; keeping or removing existing ones does not need it); after the save, + `register()` creates them as pending and emails `external-recipient-verify` directly through + `notify()` (token in the link: random, stored hashed, 7 days, single use, rate limited 3/h per + address and 30/h per organization, per process). The engine sends to `deliverable()` addresses + only: verified, allowed domain and with an unsubscribe link, so nothing goes to externals + without `ORIGIN`. They skip the cancan filter (no account) and never get system notifications. + Their email is the reduced `alert` template: no `sensitive` catalog fields, no links into the + app, an unsubscribe footer link and a `List-Unsubscribe` header. The unsubscribe link is a + stateless HMAC token (`signToken`, `GITDB_ENCRYPTION_KEY`, 90 days) made single use by + `unsubscribeVersion`. Public pages `/notifications/verify` and `/notifications/unsubscribe` + (allowed without session in `hooks.server.ts`) only act on POST, so mail scanners opening the + link change nothing. `List-Unsubscribe-Post` (RFC 8058 one-click) is not sent: providers POST + without an `Origin` header and SvelteKit's CSRF check would reject it. +- `/org//settings/notifications` (`#lib/server/notifications/settings.ts`): allowed domains + (read with `organization:settings:read` or `organization:notifications:read`, changed with + `organization:settings:update` or `organization:notifications:update`) and the external recipients + status (`organization:notifications:read`, resend confirmation with `organization:notifications:update`). + Notification channels (#95) will live on this page too. - UI: `/org//settings/alerts` and `/org//projects//settings/alerts` (list, `new`, `[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`, `test`, `toggle`, `delete`; everything works without JavaScript). Components live in @@ -258,7 +293,7 @@ return { roles, canCreate }; The root layout (`+layout.server.ts`) calculates granular read permissions for each settings section and passes them to the AppSidebar component, which filters sidebar items based on specific resource permissions: - **Project level:** `project:project:read`, `project:users:read`, `project:roles:read`, `project:server-keys:read`, `project:audit:read`, `project:alerts:read`, plus module-specific permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. High-level read flags combine granular permissions with OR logic (e.g., `canReadProjectVault = canReadProjectVaultSecrets || canReadProjectVaultEnvironments`) -- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read` +- **Organization level:** `organization:projects:read`, `organization:users:read`, `organization:roles:read`, `organization:settings:read`, `organization:backups:read`, `organization:server-keys:read`, `organization:audit:read`, `organization:events:read`, `organization:alerts:read`, `organization:notifications:read` This ensures the UI only displays navigation items for sections the user has permission to view. @@ -267,12 +302,14 @@ Permissions always include their scope as a prefix (e.g., `organization:projects `project:vault:secrets:all`) and are stored verbatim—there is no scope-stripping transformation: - **GitOps Admin** (`cluster-admin`) — grants vault, openreport, stateiac full access - **GitOps User** (`cluster-user`) — no inherent permissions; base role for system-level access -- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts +- **Organization Admin** — all org-level permissions: projects, users, roles, settings, backups, server-keys, audit, events, alerts, notifications - **Organization Developer** — read/create/update projects only -- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history +- **Project Admin** — all project-level permissions: project metadata, users, roles, server-keys, audit, alerts, notifications; plus all module permissions: vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history - **Project Developer** — read/create/update project resources; no deletion or admin; granular module access; reads alerts - **Project Viewer** — read-only: project metadata, alerts, all modules, vault secrets/environments, codereport reports/dependencies/vulnerabilities, stateiac stacks/states/history +`organization:notifications:read` and `organization:notifications:update` gate external email recipient management in settings. + Module resources have granular sub-permissions: `project:vault:secrets:read`, `project:vault:environments:read`, `project:codereport:reports:read`, `project:codereport:dependencies:read`, `project:codereport:vulnerabilities:read`, `project:stateiac:stacks:read`, `project:stateiac:states:read`, `project:stateiac:history:read`. These allow fine-grained access control within each module. Organization-level permissions cascade into their projects only when no explicit project-level assignment exists @@ -292,6 +329,11 @@ Machine-to-machine requests authenticate with `Authorization: Bearer gvs_...`; ` resolves them into `locals.apiKey` and `cancanService.canApiKey()` confines a project key to its own project. +Unauthenticated public routes for external alert recipients: `/notifications/verify` and +`/notifications/unsubscribe` accept POST requests with HMAC tokens (verifying confirmations and +one-click unsubscribes). These are allowed without a session in `hooks.server.ts` and validate +their tokens rather than checking permissions. + `locals.user.role` is a session role object, not the string `admin`. Use `isAdmin()` or the `can*` helpers. Keep authorization tests beside changes to permission behavior. diff --git a/README.md b/README.md index 0edcac19..6752db2d 100644 --- a/README.md +++ b/README.md @@ -137,7 +137,8 @@ vulnerabilities*. *greater than* `0`. 4. Recipients: the **Project Admin** role. Throttle: one email every **30** minutes at most. 5. **Test alert** shows whether an example event matches and who would get the email, without - sending anything. Then **Create alert**. + sending anything. **Send test email** also emails those recipients with an example event and a + `[Test]` subject (external addresses only once confirmed). Then **Create alert**. The same alert through the API (`gvs_` project keys only manage alerts of their own project): @@ -163,6 +164,24 @@ fields. Only recipients allowed to view the event get the email, and you can onl events you can view yourself. Some notifications are always on: users are told when their access to an organization or project changes and when a personal API key is created on their account. +#### External email recipients + +Alerts can also email people without a GitOps account (a vendor, an on-call mailbox): + +1. In the organization's **Settings → Notifications**, list the allowed domains (needs + `organization:settings:update`). `partner.com` matches only that domain; use `*.partner.com` + for its subdomains. The list is empty by default, which means no external recipients. +2. In the alert editor, add the addresses under **External emails** (needs + `organization:notifications:update` or `project:notifications:update`). The API takes them in + `recipients.externalEmails`. +3. Each new address gets a confirmation email and receives nothing until its owner confirms. Every + alert email carries a one-click unsubscribe link. + +External recipients are not checked against GitOps permissions, so their emails leave out +sensitive fields and links into the app. Removing a domain blocks its addresses without deleting +them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and +unsubscribe links can't be built and nothing is sent to external addresses. + ### Email Invitations, password resets, alerts and access notices are sent by SMTP: diff --git a/src/hooks.server.ts b/src/hooks.server.ts index b5555e6f..6315aa9e 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -6,13 +6,10 @@ import { projectService } from '#modules/projects'; import { registerAlertEngine } from '#modules/alerts'; import { isBootstrapCompleted, refreshBootstrapState } from '#lib/server/bootstrap'; import { startGitDb } from '#lib/server/gitdb'; -import { - getServerReadyState, - markServerFailed, - markServerReady, -} from '#lib/server/server-ready'; +import { getServerReadyState, markServerFailed, markServerReady } from '#lib/server/server-ready'; import { renderStartingPage } from '#lib/server/starting-page'; import { runWithActor } from '#lib/server/request-context'; +import { rememberDevOrigin } from '#lib/server/infra/notifications'; import { createLogger, createRequestLogger, logHttpRequest, logger } from '#lib/server/logger'; const startupLog = createLogger('startup'); @@ -60,6 +57,8 @@ const requestLogger: Handle = async ({ event, resolve }) => { const authGuard: Handle = async ({ event, resolve }) => { const pathname = event.url.pathname; + // dev only: email links use the port the dev server really answers on, whatever ORIGIN says + if (import.meta.env.DEV) rememberDevOrigin(event.url.origin); const isApiRequest = pathname.startsWith('/api/'); if (pathname === '/health') { @@ -115,9 +114,12 @@ const authGuard: Handle = async ({ event, resolve }) => { return new Response(null, { status: 308, headers: { location } }); } - // sign-in, sign-out, self-registration, password recovery, invitation acceptance and the Google - // SSO round trip must work without (or with a broken) session; each route re-checks what it needs + // sign-in, sign-out, self-registration, password recovery, invitation acceptance, the Google + // SSO round trip and the links emailed to external alert recipients (who have no account) must + // work without (or with a broken) session; each route re-checks what it needs (its token) if ( + pathname === '/notifications/verify' || + pathname === '/notifications/unsubscribe' || pathname === '/auth/login' || pathname === '/auth/sso/google/start' || pathname === '/auth/sso/google/callback' || diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts index c38c820c..b01822f2 100644 --- a/src/lib/alerts/summary.ts +++ b/src/lib/alerts/summary.ts @@ -63,7 +63,7 @@ export function summarizeConditions( /** "2 usuarios · Project Admin" */ export function summarizeRecipients( - recipients: { userIds: string[]; roleIds: string[] }, + recipients: { userIds: string[]; roleIds: string[]; externalEmails?: string[] }, users: AlertOption[], roles: AlertOption[], t: Translate, @@ -71,6 +71,7 @@ export function summarizeRecipients( const names = [ ...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id), ...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id), + ...(recipients.externalEmails ?? []), ]; return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients'); } diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts index c552527c..edb1243f 100644 --- a/src/lib/alerts/types.ts +++ b/src/lib/alerts/types.ts @@ -33,10 +33,22 @@ export type AlertDraft = { eventType: string; match: 'all' | 'any'; conditions: DraftCondition[]; - recipients: { userIds: string[]; roleIds: string[] }; + recipients: { userIds: string[]; roleIds: string[]; externalEmails: string[] }; throttleMinutes: number; }; +/** External email recipients as the editor needs them. */ +export type ExternalRecipientsEditorData = { + /** `:notifications:update`: needed to add addresses. */ + canManage: boolean; + /** Allowed domains of the organization; empty = external recipients are off. */ + allowedDomains: string[]; + /** Status of the alert's current addresses (`pending`, `verified`…). */ + statuses: Record; + /** Where the allowed domains are managed, when the user can open it. */ + settingsPath: string | null; +}; + type Shared = { basePath: string; scope: AlertScope; @@ -61,6 +73,7 @@ export type AlertListData = Shared & { export type AlertEditorData = Shared & { alertId: string | null; draft: AlertDraft; + external: ExternalRecipientsEditorData; canSave: boolean; canDelete: boolean; }; @@ -69,6 +82,9 @@ export type AlertTestView = { matched: boolean; recipients: Array<{ userId: string; username: string }>; deniedCount: number; + external: Array<{ email: string; status: string; delivers: boolean }>; + /** Present when a real test email was sent. */ + delivery?: { sent: number; failed: number }; event: { type: string; payload: Record; projectId: string | null }; }; diff --git a/src/lib/components/AppSidebar.svelte b/src/lib/components/AppSidebar.svelte index 6296d268..3095f1ab 100644 --- a/src/lib/components/AppSidebar.svelte +++ b/src/lib/components/AppSidebar.svelte @@ -3,6 +3,7 @@ import { Activity, BellRing, + Mail, BarChart3, Building2, ChevronDown, @@ -50,6 +51,7 @@ export let canReadOrgAudit = false; export let canReadOrgEvents = false; export let canReadOrganizationAlerts = false; + export let canReadOrgNotifications = false; export let canReadProjectInfo = false; export let canReadProjectUsers = false; export let canReadProjectRoles = false; @@ -325,6 +327,12 @@ icon: BellRing, visible: canReadOrganizationAlerts, }, + { + label: $_('sidebar.items.notifications'), + href: `/org/${organizationSlug}/settings/notifications`, + icon: Mail, + visible: canReadOrgNotifications, + }, ] .filter((item) => item.visible) .map(({ visible, ...item }) => item); @@ -401,14 +409,14 @@ ), ) as Record; - function isItemActive(href: string) { - return currentPath.startsWith(href); - } + // reactive declarations, not plain functions: the template calls them with `item` / `navModule` + // only, so a plain function would keep the active state of the first rendered page after a + // client-side navigation. Reassigning them when `currentPath` changes re-renders every call + $: isItemActive = (href: string) => currentPath.startsWith(href); - function isModuleActive(navModule: NavModule) { - if (navModule.base && currentPath.startsWith(navModule.base)) return true; - return navModule.items.some((item) => isItemActive(item.href)); - } + $: isModuleActive = (navModule: NavModule) => + (navModule.base ? currentPath.startsWith(navModule.base) : false) || + navModule.items.some((item) => isItemActive(item.href)); function toggleModule(navModule: NavModule) { openModules = { ...openModules, [navModule.name]: !moduleOpenState[navModule.name] }; diff --git a/src/lib/components/NotificationLinkPage.svelte b/src/lib/components/NotificationLinkPage.svelte new file mode 100644 index 00000000..d658f498 --- /dev/null +++ b/src/lib/components/NotificationLinkPage.svelte @@ -0,0 +1,86 @@ + + + + {$_(`${base}.title`)} - GitOps + + +
+
+ +
+ GitOps +
+ {#if kind === 'verify'} + + {:else} + + {/if} +
+

{$_(`${base}.title`)}

+ + {#if link.state === 'ready'} +

+ {$_(`${base}.question`, { + values: { email: link.email, organization: link.organization }, + })} +

+
{ + submitting = true; + return async ({ update }) => { + await update(); + submitting = false; + }; + }} + > + + +
+ {:else if link.state === 'done'} +

+ {$_(`${base}.done`, { + values: { email: link.email, organization: link.organization }, + })} +

+ {:else} + + {/if} +
+
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte index f63a2e3d..e21278a9 100644 --- a/src/lib/components/alerts/AlertEditor.svelte +++ b/src/lib/components/alerts/AlertEditor.svelte @@ -2,8 +2,18 @@ import { untrack } from 'svelte'; import { enhance } from '$app/forms'; import type { SubmitFunction } from '$app/forms'; - import { ArrowLeft, FlaskConical, Info, MailWarning, Save, Trash2 } from '@lucide/svelte'; + import { + ArrowLeft, + FlaskConical, + Info, + Send, + MailWarning, + Save, + ShieldAlert, + Trash2, + } from '@lucide/svelte'; import { _ } from '#lib/i18n'; + import { statusBadgeClass } from '#lib/notifications/status'; import type { AlertEditorData, AlertFormResult, @@ -29,7 +39,7 @@ let message = $state(initial.message); let test = $state(initial.test); let droppedConditions = $state(0); - let busy = $state<'save' | 'test' | null>(null); + let busy = $state<'save' | 'test' | 'send' | null>(null); let sampleProjectId = $state(''); let definition = $derived(data.catalog.find((entry) => entry.type === draft.eventType)); @@ -45,6 +55,26 @@ data.scope === 'organization' && definition?.scope === 'project', ); let projects = $derived(data.referenceOptions.project ?? []); + let externalText = $state(untrack(() => draft.recipients.externalEmails.join('\n'))); + let externalEnabled = $derived( + data.external.allowedDomains.length > 0 || draft.recipients.externalEmails.length > 0, + ); + let externalErrors = $derived( + Object.entries(errors) + .filter(([key]) => /^recipients\.externalEmails\.\d+$/.test(key)) + .map(([key, code]) => ({ + email: draft.recipients.externalEmails[Number(key.split('.').pop())] ?? '', + code, + })), + ); + + function updateExternal(text: string) { + externalText = text; + draft.recipients.externalEmails = text + .split(/[\n,;]+/) + .map((value) => value.trim()) + .filter(Boolean); + } function compatible(entry: CatalogEntry | undefined, condition: DraftCondition) { const field = entry?.fields.find((candidate) => candidate.key === condition.field); @@ -64,17 +94,24 @@ return errors[key] ? $_(`alerts.errors.${errors[key]}`) : ''; } - const submit: SubmitFunction = ({ action }) => { + // operation errors without field errors come as codes (`mail_not_configured`…) + const OPERATION_ERRORS = ['mail_not_configured', 'test_rate_limited']; + + const submit: SubmitFunction = ({ action, submitter }) => { + const sending = submitter?.getAttribute('name') === 'send'; const intent = action.search.includes('test') ? 'test' : 'save'; - busy = intent; + busy = sending ? 'send' : intent; message = ''; return async ({ result, update }) => { busy = null; if (result.type === 'failure') { errors = (result.data?.errors as Record) ?? {}; + const code = String(result.data?.error ?? ''); message = result.data?.errors ? $_('alerts.editor.fixErrors') - : String(result.data?.error ?? ''); + : OPERATION_ERRORS.includes(code) + ? $_(`alerts.errors.${code}`) + : code; if (intent === 'test') test = null; return; } @@ -302,6 +339,75 @@

{/if} +
+ + {#if externalEnabled} +

+ + {$_('alerts.editor.externalNotice')} +

+ +

+ {#if data.external.canManage} + {$_('alerts.editor.externalHelp', { + values: { + domains: data.external.allowedDomains.join(', ') || '—', + }, + })} + {:else} + {$_('alerts.editor.externalReadonly')} + {/if} +

+ {#if errors['recipients.externalEmails']} + + {/if} + {#if Object.keys(data.external.statuses).length > 0} +
    + {#each Object.entries(data.external.statuses) as [email, status] (email)} +
  • + {email} · {$_(`notifications.status.${status}`)} +
  • + {/each} +
+ {/if} + {:else} +

+ {$_('alerts.editor.externalDisabled')} + {#if data.external.settingsPath} + + {$_('alerts.editor.externalSettingsLink')} + + {/if} +

+ {/if} +
+
{$_('alerts.editor.channels')}