diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index 1d15a26..1701f9b 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,19 @@ 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, 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 `roleService.createDefaultProjectRoles()`. Ambas operaciones inicializan sus roles por defecto. @@ -133,6 +146,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 555c7f2..eb807dd 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 @@ -170,7 +168,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 +189,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 @@ -234,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 @@ -267,12 +273,86 @@ 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` - (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 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 (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 @@ -372,8 +452,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 +462,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 +487,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 +520,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 ab72d5c..a6a7f56 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,41 @@ 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. 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 +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/fixtures/seed.ts b/e2e/fixtures/seed.ts index 3a1e065..ef57e64 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 e1ed06e..1976df0 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(); @@ -93,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, }) => { @@ -106,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'); @@ -215,11 +218,60 @@ 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 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); + }); }); 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 39cc275..668d069 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/draft.ts b/src/lib/alerts/draft.ts index 7f5eee5..a8fc7e5 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 b143106..75d6e05 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 8080327..acfc4fd 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 { ChannelsSectionData, NotificationSettingsPage } from '#lib/notifications/types'; import type { AlertChannel, AlertRecipients, @@ -38,11 +39,26 @@ 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[]; + statuses: Record; + settingsPath: string | null; +}; + type Shared = { basePath: string; scope: AlertScope; @@ -55,11 +71,16 @@ 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; }; 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[]; @@ -79,6 +100,9 @@ export type AlertTestView = { matched: boolean; 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/NotificationLinkPage.svelte b/src/lib/components/NotificationLinkPage.svelte new file mode 100644 index 0000000..27b6bc2 --- /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 }, + })} +

+
{ + submitting = true; + return async ({ update }) => { + await update(); + submitting = false; + }; + }} + > + + +
+ {: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 a19fc52..a196090 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, @@ -20,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 }; @@ -36,13 +38,11 @@ })); 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); 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 +74,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,64 +360,132 @@

{/if} - -
+
- - {#if errors['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} + {#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')} - {#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)} - {#if channel.list && (!isSoon(channel.key) || initialChannels.includes(channel.key))} - - {#if errors[`recipients.${channel.list}`]} - + {#if !channel.enabled} + {$_('notifications.channels.disabled')} {/if} + + {#if selected && !data.canSave} + {/if} -
- {/each} - {#if errors.channels} - + {/each} + {#if draft.channelIds.length > 0} +

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

+ {/if} + {#if !data.external.canManage} +

{$_('alerts.editor.channelsReadonly')}

+ {/if} + {/if} + {#if errors.channelIds} + {/if}
@@ -481,7 +572,41 @@ {$_('alerts.test.denied', { values: { count: test.deniedCount } })}

{/if} -

{$_('alerts.test.nothingSent')}

+ {#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)} +
  • + {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 +623,21 @@ />{/if} {$_('alerts.editor.test')} + + {/snippet} + {/if} diff --git a/src/lib/components/alerts/AlertSettingsPanel.svelte b/src/lib/components/alerts/AlertSettingsPanel.svelte new file mode 100644 index 0000000..5639c23 --- /dev/null +++ b/src/lib/components/alerts/AlertSettingsPanel.svelte @@ -0,0 +1,385 @@ + + +
+ {#if data} + {#if !data.mailConfigured || !data.originConfigured} +

+ + {!data.mailConfigured + ? $_('notifications.settings.mailNotConfigured') + : $_('notifications.settings.originNotConfigured')} +

+ {/if} + +
+
+ + + +
+

+ {$_('notifications.settings.domainsTitle')} +

+

+ {$_('notifications.settings.domainsDescription')} +

+
+
+ +
+
+ + +

+ {$_('notifications.settings.domainsHelp')} +

+ {#if domainError || formDomainError} + + {:else if form?.saved} +

+ {$_('notifications.settings.domainsSaved', { + values: { blocked: form.blocked ?? 0, restored: form.restored ?? 0 }, + })} +

+ {/if} +
+ {#if data.canEditDomains} + + {:else} +

{$_('notifications.settings.domainsReadonly')}

+ {/if} +
+
+ + {#if data.recipients} +
+
+

+ + {$_('notifications.settings.recipientsTitle')} +

+

+ {$_('notifications.settings.recipientsDescription')} +

+
+ + {#if form?.resendError} + + {:else if form?.resent} +

{$_('notifications.settings.resent')}

+ {:else if form?.removeError} + + {:else if form?.removed} +

+ {$_('notifications.settings.removed', { values: { email: form.removed } })} +

+ {/if} + + {#if data.recipients.length === 0} +

+ {$_('notifications.settings.recipientsEmpty')} +

+ {:else} +
+
+ + + + + + + + + + + + {#each data.recipients as recipient (recipient.id)} + + + + + + + + {/each} + +
+ {$_('notifications.settings.email')} + + {$_('notifications.settings.status')} + + {$_('notifications.settings.verifiedAt')} + + {$_('notifications.settings.lastSent')} + + {$_('notifications.settings.actions')} +
{recipient.email} + + {$_(`notifications.status.${recipient.status}`)} + + {formatDate(recipient.verifiedAt)} + {formatDate(recipient.lastVerificationSentAt)} + +
+ {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')} +
+ + +
+ {/if} + {#if data.canManageRecipients && recipient.status === 'pending'} +
+ + +
+ {/if} +
+
+
+
+ {/if} +
+ {/if} + {:else if organizationSettingsPath} +

+ {$_('notifications.settings.organizationDomains')} + {$_('notifications.settings.organizationDomainsLink')} +

+ {/if} + + {#if channels} + + {/if} +
+ +{#if data?.canManageRecipients} + + {#snippet icon()} + + {/snippet} +
+ +
+ {#snippet footer()} + + + {/snippet} +
+{/if} diff --git a/src/lib/components/alerts/AlertWizard.svelte b/src/lib/components/alerts/AlertWizard.svelte index c4adf6b..1791f4f 100644 --- a/src/lib/components/alerts/AlertWizard.svelte +++ b/src/lib/components/alerts/AlertWizard.svelte @@ -22,6 +22,9 @@ MessageSquare, Save, Search, + Send, + Settings, + ShieldAlert, User, Users, Webhook, @@ -39,7 +42,7 @@ import { channelTargets, summarizeConditions } from '#lib/alerts/summary'; import { draftFromAlert, draftToFormData, emptyDraft } from '#lib/alerts/draft'; import type { - AlertChannel, + AlertChannelOption, AlertDraft, AlertOption, AlertRow, @@ -47,9 +50,10 @@ 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'; type WizardData = { basePath: string; @@ -59,13 +63,22 @@ recipientUsers: AlertOption[]; recipientRoles: AlertOption[]; mailConfigured: boolean; + external: ExternalRecipientsEditorData; + channels: AlertChannelOption[]; + configPath?: string | null; }; let { open = $bindable(false), data, alert = null, - }: { open?: boolean; data: WizardData; alert?: AlertRow | null } = $props(); + onConfigure, + }: { + open?: boolean; + data: WizardData; + alert?: AlertRow | null; + onConfigure?: () => void; + } = $props(); const STEPS = ['event', 'conditions', 'channels', 'review'] as const; type Step = (typeof STEPS)[number]; @@ -77,11 +90,12 @@ 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(''); let droppedConditions = $state(0); + let mailOn = $state(true); // cada apertura empieza de cero (o desde la alerta que se edita) let wasOpen = false; @@ -95,6 +109,12 @@ eventQuery = ''; sampleProjectId = ''; droppedConditions = 0; + mailOn = + !alert || + draft.recipients.userIds.length + + draft.recipients.roleIds.length + + draft.recipients.emails.length > + 0; } wasOpen = open; }); @@ -134,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:` @@ -231,45 +275,63 @@ 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; - }; - const parseSlack = (text: string) => { - const name = text.trim().toLowerCase().replace(/^#/, ''); - return /^[a-z0-9][a-z0-9._-]{0,79}$/.test(name) ? `#${name}` : null; + if (!canAddExternal || !EMAIL_PATTERN.test(email) || !domainAllowed(email)) return null; + return `email:${email}`; }; - 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; - } - + 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, + })), + ); // ---------- 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'; @@ -292,9 +354,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 +367,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; @@ -490,158 +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} - + {#if configured} {#if on}{/if} + {:else} + {$_('alerts.wizard.notConfigured')} + {#if data.configPath} + + {$_('alerts.wizard.configure')} + + {/if} {/if} - +
{/each}
- {#if errorFor('channels')} - + {#if 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} - -

- {$_('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} + + {/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]} +
+

+ {typeMeta[type].label} +

+
+ {#each channelsOf(type) as channel (channel.id)} + {@const selected = draft.channelIds.includes(channel.id)} + + {/each} +
{/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')}
@@ -758,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} @@ -807,7 +920,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 +990,19 @@ />{/if} {$_('alerts.editor.test')} + + +
+ + + +
+ + {/if} + {#if data.canDelete} +
+ + +
+ {/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 }} +
+
+ + + {#if errors.type}

+ {errorText(errors, 'type')} +

{/if} +
+
+ + + {#if errors.name}

+ {errorText(errors, 'name')} +

{/if} +
+
+ + + {#if errors.destination} +

{errorText(errors, 'destination')}

+ {/if} +
+
+ +
+
+ {/if} +
+ {/if} + + +{#if data.canUpdate} + +
+ +
+ + + {#if editErrors.name}

+ {errorText(editErrors, 'name')} +

{/if} +
+
+ + + {#if editErrors.destination}

+ {errorText(editErrors, 'destination')} +

{/if} +
+
+ {#snippet footer()} + + + {/snippet} +
+{/if} + +{#if data.canDelete} + + {#snippet icon()} + + {/snippet} +
+ +
+ {#snippet footer()} + + + {/snippet} +
+{/if} diff --git a/src/lib/config/permissions.ts b/src/lib/config/permissions.ts index 1dbdbfc..3230d08 100644 --- a/src/lib/config/permissions.ts +++ b/src/lib/config/permissions.ts @@ -69,6 +69,10 @@ const permissions = { resource: 'alerts', permissions: grantsFor('organization', 'alerts'), }, + notifications: { + resource: 'notifications', + permissions: grantsFor('organization', 'notifications'), + }, }, }, project: { @@ -96,6 +100,10 @@ const permissions = { resource: 'alerts', permissions: grantsFor('project', 'alerts'), }, + notifications: { + resource: 'notifications', + permissions: grantsFor('project', 'notifications'), + }, modules: { resource: 'modules', sections: { diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts index 23f8326..a9e5f5a 100644 --- a/src/lib/database/schemas.ts +++ b/src/lib/database/schemas.ts @@ -396,6 +396,61 @@ export const AlertEntity = entity('alerts', { .$defaultFn(() => 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()), +}); + +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/events/catalog/code-report.events.ts b/src/lib/events/catalog/code-report.events.ts index be3cb18..422f6d2 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 8adbb8b..6ba4b9f 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 79bbf06..7b95fe8 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 0000000..a3f6c64 --- /dev/null +++ b/src/lib/notifications/types.ts @@ -0,0 +1,55 @@ +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' }; + +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 128bc4b..2521869 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,64 @@ 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 }>; + channels: Array<{ id: string; name: string; type: 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' + | 'channelIds' + | '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 +240,7 @@ async function dryRun( ? (input.payload as Record) : undefined; const sample = buildSampleEvent(definition, alert, { + complete: send, payload: payloadOverride, projectId: requestedProjectId, }); @@ -220,12 +260,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 +288,9 @@ async function dryRun( matched: result.matched, 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 }, }, }; @@ -245,7 +303,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 +318,25 @@ 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 previous = sameLocation + ? { emails: existing.recipients.emails, channelIds: existing.channelIds } + : {}; 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, previous); + 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 830fbce..06529f4 100644 --- a/src/lib/server/alerts/page.ts +++ b/src/lib/server/alerts/page.ts @@ -6,11 +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'; + externalRecipientService, + notificationChannelService, + notificationSettingsService, +} from '#modules/notifications'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; import { @@ -23,11 +24,18 @@ import { import type { AlertDraft, AlertEditorData, + AlertChannelOption, AlertListData, AlertOption, DraftCondition, + ExternalRecipientsEditorData, } from '#lib/alerts/types'; -import { canManageAlerts, type AlertLocals } from './access'; +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, deleteAlert, @@ -81,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(() => []), @@ -99,6 +118,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 +163,16 @@ export async function loadAlertList( scope: 'organization', projectId: null, }; - const [references, own, organizationRecipients] = await Promise.all([ + const [references, own, organizationRecipients, external, channels] = 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 ?? []), + ), + channelOptions(location), ]); // names for the recipients of the location's alerts and of the inherited organization ones const merge = (a: AlertOption[], b: AlertOption[] = []) => [ @@ -135,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, @@ -150,7 +206,12 @@ export async function loadAlertList( roles: recipients.roles, recipientUsers: own.users, recipientRoles: own.roles, + channels, mailConfigured: isMailConfigured(), + external, + settings, + channelsSection, + configPath: settings || channelsSection ? `${context.basePath}/settings` : null, canCreate: allowed.canCreate, canUpdate: allowed.canUpdate, canDelete: allowed.canDelete, @@ -165,8 +226,8 @@ function emptyDraft(eventType: string | null): AlertDraft { eventType: eventType ?? '', match: 'all', conditions: [], - channels: ['mail'], recipients: emptyRecipients(), + channelIds: [], throttleMinutes: 0, }; } @@ -183,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, }; } @@ -212,9 +277,11 @@ export async function loadAlertEditor( } const catalog = await listCatalog(locals, location); - const [references, recipients] = 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); @@ -233,7 +300,9 @@ export async function loadAlertEditor( roles: recipients.roles, recipientUsers: recipients.users, recipientRoles: recipients.roles, + channels, mailConfigured: isMailConfigured(), + external, canSave: alert ? allowed.canUpdate : allowed.canCreate, canDelete: Boolean(alert) && allowed.canDelete, }; @@ -283,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, }; } @@ -374,6 +431,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/http/webhook-request.test.ts b/src/lib/server/infra/http/webhook-request.test.ts new file mode 100644 index 0000000..f268ae8 --- /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 0000000..66292d4 --- /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 0000000..9a82ab7 --- /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 0000000..680be4f --- /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/config.test.ts b/src/lib/server/infra/notifications/config.test.ts index 0ac5e01..9005a69 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 4fabfa6..3342fe5 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/delivery-queue.ts b/src/lib/server/infra/notifications/delivery-queue.ts new file mode 100644 index 0000000..84e902e --- /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/email-parts.ts b/src/lib/server/infra/notifications/email-parts.ts new file mode 100644 index 0000000..8963b70 --- /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 0000000..9704c06 --- /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 c703a27..cbd16c7 100644 --- a/src/lib/server/infra/notifications/index.ts +++ b/src/lib/server/infra/notifications/index.ts @@ -16,11 +16,28 @@ 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 { + 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'; @@ -29,7 +46,18 @@ 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; + +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 @@ -37,7 +65,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) => sendWithLatestNotify(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 d5632a0..0ff1a5f 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 4180296..8525125 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 7b23743..d1c6d84 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 690d0a8..2fdc7da 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: () => void; -}; - export type MailQueueOptions = { send: (notification: MailNotification) => Promise; /** Emails sent at the same time; a burst of events waits in the queue. */ @@ -34,93 +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); - } - - /** Queues one email; resolves once it was sent or definitively failed. */ - 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; - 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(); - } - }); - } + enqueue(notification: MailNotification, context: MailContext = {}): Promise { + return super.enqueue(notification, context); } - - 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', - ), - }); - } 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', - ); - } - } -} - -function errorCode(error: unknown): unknown { - if (!error || typeof error !== 'object') return undefined; - const { code, responseCode } = error as { code?: unknown; responseCode?: unknown }; - return responseCode ?? code; } diff --git a/src/lib/server/infra/notifications/mail.transport.ts b/src/lib/server/infra/notifications/mail.transport.ts index dc933e0..39c635c 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/notifications/notification.ts b/src/lib/server/infra/notifications/notification.ts index 1244b06..eee81ee 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 48ac060..ad36bff 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/infra/rate-limit.test.ts b/src/lib/server/infra/rate-limit.test.ts new file mode 100644 index 0000000..77ec434 --- /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 0000000..36eccce --- /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 0000000..e3ac317 --- /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 0000000..5d040d5 --- /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/channels-page.ts b/src/lib/server/notifications/channels-page.ts new file mode 100644 index 0000000..4dea086 --- /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 0000000..a8be8b0 --- /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/lib/server/notifications/links.ts b/src/lib/server/notifications/links.ts new file mode 100644 index 0000000..7d1b3de --- /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 0000000..91b2dda --- /dev/null +++ b/src/lib/server/notifications/settings.test.ts @@ -0,0 +1,168 @@ +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: {} })); +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'); + 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, + removeExternalRecipient, + 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, + }); + }); + + 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 new file mode 100644 index 0000000..ec85beb --- /dev/null +++ b/src/lib/server/notifications/settings.ts @@ -0,0 +1,145 @@ +import { + ExternalRecipientNotFoundError, + ExternalRecipientStateError, + NotificationSettingsValidationError, + VerificationRateLimitedError, + externalRecipientService, + notificationSettingsService, + type ExternalRecipientView, +} from '#modules/notifications'; +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'; + +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 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, + 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 52c09f9..c60eaff 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, @@ -126,7 +127,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 +150,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 +247,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 +266,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 +289,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 +325,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 2abd25d..463b42d 100644 --- a/src/modules/alerts/application/alert-engine.ts +++ b/src/modules/alerts/application/alert-engine.ts @@ -1,7 +1,8 @@ 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, @@ -10,10 +11,20 @@ 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 type { ChannelMessage } from '#lib/server/infra/notifications/chat-notification'; +import { + eventContext, + type AlertDirectory, + type ExternalRecipientsPort, + type NotificationChannelsPort, + 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,8 +34,26 @@ 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; }; +type AlertToDeliver = Pick< + AlertDomain, + | 'id' + | 'name' + | 'description' + | 'scope' + | 'organizationId' + | 'location' + | 'recipients' + | 'channelIds' +>; + export type SystemEmail = { recipient: Recipient; kind: SystemNotificationKind; @@ -40,15 +69,17 @@ export interface AlertNotifierPort { export type AlertEngineOptions = { repository: Pick; directory: AlertDirectory; - recipients: RecipientResolver; + recipients: Pick; + externalRecipients?: Pick; notifier: AlertNotifierPort; throttle?: AlertThrottle; logger: Pick; /** 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 = { @@ -56,6 +87,8 @@ 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 }>; + channels: Array<{ id: string; name: string; type: string; delivers: boolean }>; }; const DEFAULT_CACHE_TTL_MS = 60_000; @@ -88,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', @@ -97,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; @@ -126,20 +164,66 @@ 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: [] }; + 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 }; + 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) { + 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 { @@ -159,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( @@ -176,6 +252,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: 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( + { alertId: alert.id, eventType: event.type, sent, failed, test: true }, + '[alerts] test email sent', + ); + return { sent, failed }; + } + + private async deliver( + alert: AlertToDeliver, + event: AnyDomainEvent, + definition: EventDefinition, + suppressed: number, + test: boolean, + ): 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, channels: 0, sent: 0, failed: 0 }; + } + const mail = this.mailEnabled(); + const { recipients, denied } = await this.options.recipients.resolve( alert.location, alert.recipients, @@ -199,43 +318,110 @@ export class AlertEngine { }) .catch(() => ({})); + const memberEmails = new Set(recipients.map((recipient) => recipient.email.toLowerCase())); + 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 - 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', - ); + 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, + channels: channelIds.length, + sent: sent + channelsSent, + failed: targets.length - sent + (channelIds.length - channelsSent), + }; + } + + 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.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts new file mode 100644 index 0000000..a85d4ee --- /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 :notifications:update to add channels, not to keep them', async () => { + const refused = await validationErrors( + service.create(p1, input({ channelIds: [p1Channel] }), actor('dev', WITHOUT_NOTIFICATIONS)), + ); + expect(refused.channelIds).toBe('forbidden_channel'); + + const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + const editor = actor('dev', [...WITHOUT_NOTIFICATIONS, 'project:alerts:update']); + await expect(service.update(alert.id, { name: 'Renamed' }, editor)).resolves.toMatchObject({ + channelIds: [p1Channel], + }); + expect( + ( + await validationErrors( + service.update(alert.id, { channelIds: [p1Channel, orgChannel] }, editor), + ) + ).channelIds, + ).toBe('forbidden_channel'); + }); + + it('accepts an alert whose only destination is a channel', async () => { + const alert = await service.create( + p1, + input({ recipients: {}, channelIds: [p1Channel] }), + actor('admin'), + ); + expect(alert.channels).toEqual(['slack']); + }); + }); + + describe('engine', () => { + let notifier: RecordingNotifier; + let mail: boolean; + let engine: AlertEngine; + + beforeEach(() => { + notifier = new RecordingNotifier(); + mail = true; + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier, + channels: port, + channelMessage: buildAlertChannelMessage, + deliveryEnabled: () => mail, + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + }); + + it('emails the recipients and posts one message per channel', async () => { + await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin')); + await engine.handle(analysisEvent()); + + expect(notifier.alerts).toHaveLength(1); + expect(channels.transport.sent).toHaveLength(2); + expect(channels.transport.sent[0].message).toMatchObject({ + title: 'Críticas', + summary: '1 critical, 0 high (1 in total)', + test: false, + alert: { name: 'Críticas' }, + }); + }); + + it('keeps going when a channel fails, and the other way around', async () => { + await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin')); + channels.transport.failWith = [404]; + notifier.fail = true; + await engine.handle(analysisEvent()); + + // the email failed, one channel answered 404: the other channel still got its message + expect(channels.transport.sent).toHaveLength(1); + expect(channels.repository.rows.find((row) => row.lastError === 'HTTP 404')).toBeDefined(); + }); + + it('still posts to channels without SMTP, but sends no emails', async () => { + mail = false; + await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + await engine.handle(analysisEvent()); + expect(notifier.alerts).toHaveLength(0); + expect(channels.transport.sent).toHaveLength(1); + }); + + it('never posts system notifications to channels', async () => { + await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + 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: 'x', userId: 'u1', roleId: 'r1', scope: 'project', status: 'active' }, + } as unknown as AnyDomainEvent); + expect(notifier.system).toHaveLength(1); + expect(channels.transport.sent).toHaveLength(0); + }); + + it('reports throttled events in the next channel message', async () => { + let now = 0; + engine = new AlertEngine({ + repository, + directory, + recipients: new RecipientResolver(directory, async () => true), + notifier, + channels: port, + channelMessage: buildAlertChannelMessage, + now: () => now, + throttle: new AlertThrottle(() => now), + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + }); + await service.create( + p1, + input({ throttleMinutes: 10, channelIds: [p1Channel] }), + actor('admin'), + ); + await engine.handle(analysisEvent()); + await engine.handle(analysisEvent()); + expect(channels.transport.sent).toHaveLength(1); + expect(channels.transport.sent[0].message.suppressed).toBe(0); + + now = 11 * 60 * 1000; + await engine.handle(analysisEvent()); + expect(channels.transport.sent).toHaveLength(2); + expect(channels.transport.sent[1].message.suppressed).toBe(1); + }); + + it('includes the channels in test sends and dry runs', async () => { + const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin')); + await channels.service.update(orgChannel, { enabled: false }); + + const delivery = await engine.sendTest(alert, analysisEvent()); + expect(delivery).toEqual({ sent: 2, failed: 0 }); + expect(channels.transport.sent[0].message.test).toBe(true); + + const dry = await engine.dryRun( + new AlertDomain({ ...alert.toJson(), channelIds: [p1Channel, orgChannel] }), + analysisEvent(), + ); + expect(dry.channels).toEqual([ + { id: p1Channel, name: '#p1', type: 'slack', delivers: true }, + { id: orgChannel, name: '#org', type: 'slack', delivers: false }, + ]); + }); + }); + + describe('channel message', () => { + it('leaves out sensitive fields and links to the resource', () => { + process.env.ORIGIN = 'https://gitops.example.com'; + const definition = getEventDefinition('vault.secret.deleted') as EventDefinition; + const message = buildAlertChannelMessage({ + alert: { id: 'a1', name: 'Secretos', description: null, scope: 'project' }, + event: { + id: 'e1', + type: 'vault.secret.deleted', + occurredAt: '2026-11-24T10:00:00.000Z', + actor: { kind: 'system' }, + scope: { organizationId: ORG, projectId: 'p1' }, + payload: { + secretId: 's1', + key: 'DB_PASSWORD', + folderId: null, + folderPath: '/pay', + environmentIds: ['e'], + }, + } as never, + definition, + suppressed: 3, + names: new Map([['e', 'Production']]), + where: { + organization: 'Kettu', + organizationSlug: 'kettu', + project: 'Web', + projectSlug: 'web', + }, + }); + const text = JSON.stringify(message); + expect(text).not.toContain('DB_PASSWORD'); + expect(text).not.toContain('/pay'); + expect(text).toContain('Production'); + expect(message.suppressed).toBe(3); + expect(message.link).toEqual({ + url: 'https://gitops.example.com/org/kettu/projects/web/vault', + label: 'View in GitOps', + }); + }); + }); +}); 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 0000000..4fa69fb --- /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 c52b921..d711ebb 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, }); }); @@ -105,7 +109,7 @@ describe('AlertService', () => { const errors = await validationErrors( service.create( projectLocation, - { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['sms'] }, + { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['pigeon'] }, actor(), ), ); @@ -115,7 +119,6 @@ describe('AlertService', () => { eventType: 'required', recipients: 'required', throttleMinutes: 'invalid', - channels: 'invalid_channel', }); expect(repository.rows).toHaveLength(0); expect(onChange).not.toHaveBeenCalled(); @@ -263,63 +266,30 @@ describe('AlertService', () => { }); describe('channels', () => { - it('keeps the targets of every enabled channel and normalizes them', async () => { + it('derives the channels from the recipients and ignores what the client sends', async () => { const alert = await service.create( projectLocation, guidedExample({ - channels: ['mail', 'slack', 'google_chat', 'webhook'], - recipients: { - roleIds: ['role-project-admin'], - emails: [' Ops@Example.com ', 'ops@example.com'], - slackChannels: ['Alerts', '#alerts'], - googleChatSpaces: ['Incidencias'], - webhookUrls: ['https://hooks.example.com/gitops'], - }, + channels: ['slack', 'pigeon'], + recipients: { emails: [' Ops@Example.com ', 'ops@example.com'] }, }), actor(), ); - expect(alert.channels).toEqual(['mail', 'slack', 'google_chat', 'webhook']); - expect(alert.recipients).toMatchObject({ - emails: ['ops@example.com'], - slackChannels: ['#alerts'], - googleChatSpaces: ['Incidencias'], - webhookUrls: ['https://hooks.example.com/gitops'], - }); - }); - - it('drops the targets of disabled channels', async () => { - const alert = await service.create( - projectLocation, - guidedExample({ - channels: ['slack'], - recipients: { roleIds: ['role-project-admin'], slackChannels: ['#alerts'] }, - }), - actor(), - ); - expect(alert.recipients.roleIds).toEqual([]); - expect(alert.recipients.slackChannels).toEqual(['#alerts']); + expect(alert.channels).toEqual(['mail']); + expect(alert.recipients.emails).toEqual(['ops@example.com']); }); - it('requires a valid target for each enabled channel', async () => { + it('reports an invalid external address per index', async () => { const errors = await validationErrors( service.create( projectLocation, - guidedExample({ - channels: ['mail', 'slack', 'google_chat', 'webhook'], - recipients: { - emails: ['not-an-email'], - slackChannels: ['bad channel!'], - webhookUrls: ['ftp://example.com'], - }, - }), + guidedExample({ recipients: { emails: ['not-an-email'] } }), actor(), ), ); expect(errors).toEqual({ 'recipients.emails': 'invalid_email', - 'recipients.slackChannels': 'invalid_slack_channel', - 'recipients.googleChatSpaces': 'required', - 'recipients.webhookUrls': 'invalid_url', + 'recipients.emails.0': 'invalid_email', }); }); @@ -334,6 +304,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 3fbb51a..9f784ec 100644 --- a/src/modules/alerts/application/alert.service.ts +++ b/src/modules/alerts/application/alert.service.ts @@ -28,18 +28,20 @@ import { locationContext, type AlertActor, type AlertDirectory, + type ExternalRecipientsPort, + type NotificationChannelsPort, type ReferenceOption, + type UsableChannel, } from './types'; const MAX_NAME_LENGTH = 120; const MAX_DESCRIPTION_LENGTH = 1000; const MAX_CONDITIONS = 20; const MAX_LIST_VALUES = 100; -const MAX_TARGETS = 50; -const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; -const SLACK_CHANNEL_PATTERN = /^#[a-z0-9][a-z0-9._-]{0,79}$/; -const MAX_SPACE_LENGTH = 128; +export const MAX_EXTERNAL_EMAILS = 50; + +export const MAX_ALERT_CHANNELS = 20; const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']); const LIST_OPERATORS = new Set(['in', 'not_in']); @@ -49,6 +51,9 @@ export type AlertServiceOptions = { generateId?: () => string; /** Called after every successful write, so the engine drops its cached alerts. */ onChange?: () => void; + externalRecipients?: ExternalRecipientsPort; + channels?: Pick; + logger?: { warn: (object: object, message: string) => void }; }; /** Ids the location's reference lists contain, loaded once per validation. */ @@ -64,6 +69,9 @@ export class AlertService { private readonly now: () => Date; private readonly generateId: () => string; private readonly onChange: () => void; + private readonly externalRecipients: ExternalRecipientsPort | null; + private readonly channelsPort: Pick | null; + private readonly logger: AlertServiceOptions['logger']; constructor( private readonly repository: AlertRepositoryPort, @@ -73,6 +81,9 @@ 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.channelsPort = options.channels ?? null; + this.logger = options.logger; } async get(id: string): Promise { @@ -115,11 +126,11 @@ export class AlertService { }); } - /** Validates `input` for `location` and returns the normalized fields, without saving. */ async validate( location: AlertLocation, input: AlertInput, actor: AlertActor, + previous: { emails?: readonly string[]; channelIds?: readonly string[] } = {}, ): Promise { const errors: AlertValidationErrors = {}; const references: ReferenceCache = new Map(); @@ -148,9 +159,30 @@ export class AlertService { ? await this.validateConditions(location, definition, input.conditions, errors, references) : []; - const channels = this.validateChannels(input.channels, errors); + const recipients = await this.validateRecipients( + location, + input.recipients, + actor, + previous.emails ?? [], + errors, + ); - const recipients = await this.validateRecipients(location, input.recipients, channels, errors); + const { channelIds, selected } = await this.validateChannelIds( + location, + input.channelIds, + actor, + previous.channelIds ?? [], + errors, + ); + const hasEmailRecipients = + recipients.userIds.length + recipients.roleIds.length + recipients.emails.length > 0; + if (errors.recipients === 'required' && channelIds.length > 0) delete errors.recipients; + const channels = [ + ...new Set([ + ...(hasEmailRecipients || channelIds.length === 0 ? (['mail'] as const) : []), + ...selected.map((channel) => channel.type as AlertChannel), + ]), + ].filter((channel) => (ALERT_CHANNELS as readonly string[]).includes(channel)); const throttleMinutes = Number(input.throttleMinutes ?? 0); if ( @@ -174,6 +206,7 @@ export class AlertService { conditions, recipients, channels, + channelIds, throttleMinutes, }; } @@ -196,6 +229,7 @@ export class AlertService { }; await this.repository.create(row); this.onChange(); + await this.registerExternal(location, fields.recipients.emails, actor); return new AlertDomain(row); } @@ -211,15 +245,52 @@ export class AlertService { conditions: current.conditions, recipients: current.recipients, channels: current.channels, + channelIds: current.channelIds, 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, { + emails: current.recipients.emails, + channelIds: current.channelIds, + }); 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', + ); + } + } + + /** 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); @@ -405,99 +476,115 @@ export class AlertService { private async validateRecipients( location: AlertLocation, value: unknown, - channels: AlertChannel[], + actor: AlertActor, + previousEmails: readonly string[], errors: AlertValidationErrors, ): Promise { const raw = (value ?? {}) as Record; - const list = (key: string, normalize: (item: string) => string = (item) => item.trim()) => - Array.isArray(raw[key]) - ? [ - ...new Set( - (raw[key] as unknown[]) - .filter((item): item is string => typeof item === 'string') - .map(normalize) - .filter(Boolean), - ), - ] + const ids = (list: unknown) => + Array.isArray(list) + ? [...new Set(list.filter((item): item is string => typeof item === 'string' && !!item))] : []; const recipients = emptyRecipients(); - const tooMany = (key: string, items: string[]) => { - if (items.length > MAX_TARGETS) errors[`recipients.${key}`] = 'too_many'; - }; - - if (channels.includes('mail')) { - recipients.userIds = list('userIds'); - recipients.roleIds = list('roleIds'); - recipients.emails = list('emails', (item) => item.trim().toLowerCase()); - const { userIds, roleIds, emails } = recipients; - if (userIds.length === 0 && roleIds.length === 0 && emails.length === 0) { - errors.recipients = 'required'; - } - if (userIds.length > 0) { - const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId)); - if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user'; - } - if (roleIds.length > 0) { - 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); + recipients.userIds = ids(raw.userIds); + recipients.roleIds = ids(raw.roleIds); + 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) { + if (!errors['recipients.emails']) errors.recipients = 'required'; + } + if (userIds.length > 0) { + const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId)); + if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user'; } + if (roleIds.length > 0) { + 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'; + } + return recipients; + } - if (channels.includes('slack')) { - recipients.slackChannels = list('slackChannels', (item) => { - const name = item.trim().toLowerCase(); - return name && !name.startsWith('#') ? `#${name}` : name; - }); - if (recipients.slackChannels.length === 0) errors['recipients.slackChannels'] = 'required'; - else if (recipients.slackChannels.some((name) => !SLACK_CHANNEL_PATTERN.test(name))) { - errors['recipients.slackChannels'] = 'invalid_slack_channel'; - } - tooMany('slackChannels', recipients.slackChannels); + 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 []; } - if (channels.includes('google_chat')) { - recipients.googleChatSpaces = list('googleChatSpaces'); - if (recipients.googleChatSpaces.length === 0) { - errors['recipients.googleChatSpaces'] = 'required'; - } else if (recipients.googleChatSpaces.some((space) => space.length > MAX_SPACE_LENGTH)) { - errors['recipients.googleChatSpaces'] = 'too_long'; - } - tooMany('googleChatSpaces', recipients.googleChatSpaces); + 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]; } - if (channels.includes('webhook')) { - recipients.webhookUrls = list('webhookUrls'); - if (recipients.webhookUrls.length === 0) errors['recipients.webhookUrls'] = 'required'; - else if (recipients.webhookUrls.some((url) => !isHttpUrl(url))) { - errors['recipients.webhookUrls'] = 'invalid_url'; + 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'; } - tooMany('webhookUrls', recipients.webhookUrls); } - - return recipients; + return emails; } - private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] { - if (value === undefined || value === null) return ['mail']; - const list = Array.isArray(value) ? value : [value]; - const valid = list.every((channel) => (ALERT_CHANNELS as readonly unknown[]).includes(channel)); - if (!valid || list.length === 0) { - errors.channels = 'invalid_channel'; - return ['mail']; + private async validateChannelIds( + location: AlertLocation, + value: unknown, + actor: AlertActor, + previous: readonly string[], + errors: AlertValidationErrors, + ): Promise<{ channelIds: string[]; selected: UsableChannel[] }> { + if (value === undefined || value === null) return { channelIds: [], selected: [] }; + if (!Array.isArray(value)) { + errors.channelIds = 'invalid'; + return { channelIds: [], selected: [] }; } - return [...new Set(list as AlertChannel[])]; - } -} - -function isHttpUrl(value: string): boolean { - try { - const url = new URL(value); - return url.protocol === 'https:' || url.protocol === 'http:'; - } catch { - return false; + const channelIds = [ + ...new Set(value.filter((id): id is string => typeof id === 'string' && !!id)), + ]; + if (channelIds.length === 0) return { channelIds, selected: [] }; + if (channelIds.length > MAX_ALERT_CHANNELS) { + errors.channelIds = 'too_many'; + return { channelIds: [], selected: [] }; + } + const usable = this.channelsPort ? await this.channelsPort.listUsable(location) : []; + const selected = channelIds + .map((id) => usable.find((channel) => channel.id === id)) + .filter((channel): channel is UsableChannel => !!channel); + if (selected.length !== channelIds.length) { + errors.channelIds = 'unknown_channel'; + return { channelIds, selected }; + } + const known = new Set(previous); + if (channelIds.some((id) => !known.has(id))) { + const permission = `${location.scope}:notifications:update` as const; + if (!(await actor.canRead(permission, locationContext(location)))) { + errors.channelIds = 'forbidden_channel'; + } + } + return { channelIds, selected }; } } diff --git a/src/modules/alerts/application/recipient-resolver.ts b/src/modules/alerts/application/recipient-resolver.ts index 85c0038..f14db3d 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 96d6d5f..2c37756 100644 --- a/src/modules/alerts/application/types.ts +++ b/src/modules/alerts/application/types.ts @@ -59,7 +59,39 @@ 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 UsableChannel = { + id: string; + name: string; + type: string; + scope: 'organization' | 'project'; + enabled: boolean; +}; + +export interface NotificationChannelsPort { + listUsable(location: { + organizationId: string; + projectId: string | null; + }): Promise; + deliver( + channelId: string, + message: import('#lib/server/infra/notifications/chat-notification').ChannelMessage, + context?: Record, + ): 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 0000000..c30aab0 --- /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 c78c06a..8b4220c 100644 --- a/src/modules/alerts/domain/alert.domain.ts +++ b/src/modules/alerts/domain/alert.domain.ts @@ -4,15 +4,8 @@ import type { Operator } from '#lib/events/catalog'; export type AlertScope = 'organization' | 'project'; export type AlertMatch = 'all' | 'any'; -/** - * Where an alert is delivered. An alert can use several channels at once and sends one message to - * each. Only `mail` is delivered today; the others are stored and validated so the UI and the API - * are ready when their notifiers land (#82). - */ -export const ALERT_CHANNELS = ['mail', 'slack', 'google_chat', 'webhook'] as const; +export const ALERT_CHANNELS = ['mail', 'webhook', 'slack', 'google-chat'] as const; export type AlertChannel = (typeof ALERT_CHANNELS)[number]; -/** Channels with a notifier: the rest are skipped by the engine. */ -export const DELIVERED_CHANNELS: readonly AlertChannel[] = ['mail']; export const ALERT_MATCHES = ['all', 'any'] as const; @@ -27,31 +20,14 @@ export type AlertCondition = { value?: string | number | string[]; }; -/** Targets per channel; only the arrays of the alert's enabled channels are kept. */ export type AlertRecipients = { - /** mail: platform users */ 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[]; - /** google_chat: space names */ - googleChatSpaces: string[]; - /** webhook: http(s) URLs that receive a JSON POST */ - webhookUrls: string[]; }; export function emptyRecipients(): AlertRecipients { - return { - userIds: [], - roleIds: [], - emails: [], - slackChannels: [], - googleChatSpaces: [], - webhookUrls: [], - }; + return { userIds: [], roleIds: [], emails: [] }; } /** Where an alert lives: an organization alert has no project. */ @@ -71,6 +47,7 @@ export type AlertInput = { conditions?: unknown; recipients?: unknown; channels?: unknown; + channelIds?: unknown; throttleMinutes?: unknown; }; @@ -84,6 +61,7 @@ export type AlertFields = { conditions: AlertCondition[]; recipients: AlertRecipients; channels: AlertChannel[]; + channelIds: string[]; throttleMinutes: number; }; @@ -119,6 +97,7 @@ export class AlertDomain implements AlertRow { conditions: AlertCondition[]; recipients: AlertRecipients; channels: AlertChannel[]; + channelIds: string[]; throttleMinutes: number; createdByUserId: string; createdAt: string; @@ -138,15 +117,22 @@ export class AlertDomain implements AlertRow { this.recipients = { userIds: stringArray(row.recipients?.userIds), roleIds: stringArray(row.recipients?.roleIds), - emails: stringArray(row.recipients?.emails), - slackChannels: stringArray(row.recipients?.slackChannels), - googleChatSpaces: stringArray(row.recipients?.googleChatSpaces), - webhookUrls: stringArray(row.recipients?.webhookUrls), + emails: [ + ...new Set([ + ...stringArray(row.recipients?.emails), + ...stringArray( + (row.recipients as { externalEmails?: unknown } | undefined)?.externalEmails, + ), + ]), + ], }; - const channels = stringArray(row.channels).filter((channel): channel is AlertChannel => - (ALERT_CHANNELS as readonly string[]).includes(channel), - ); + const channels = stringArray(row.channels) + .map((channel) => (channel === 'google_chat' ? 'google-chat' : channel)) + .filter((channel): channel is AlertChannel => + (ALERT_CHANNELS as readonly string[]).includes(channel), + ); this.channels = channels.length > 0 ? channels : ['mail']; + this.channelIds = stringArray(row.channelIds); this.throttleMinutes = Number.isFinite(Number(row.throttleMinutes)) ? Number(row.throttleMinutes) : 0; @@ -186,11 +172,9 @@ export class AlertDomain implements AlertRow { userIds: [...this.recipients.userIds], roleIds: [...this.recipients.roleIds], emails: [...this.recipients.emails], - slackChannels: [...this.recipients.slackChannels], - googleChatSpaces: [...this.recipients.googleChatSpaces], - webhookUrls: [...this.recipients.webhookUrls], }, channels: [...this.channels], + channelIds: [...this.channelIds], throttleMinutes: this.throttleMinutes, createdByUserId: this.createdByUserId, createdAt: this.createdAt, 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 0000000..ab78f4c --- /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 a942d54..2938d52 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 17e71a7..c8e7b11 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,15 +8,22 @@ import { import { createLogger } from '#lib/server/logger'; import { cancanService, roleService, userAccessService, apiKeysService } from '../auth'; import { codeReportSecurityPolicyService, codeReportService } from '../code-report'; +import { + externalRecipientService, + notificationChannelService, + registerChannelShutdown, +} 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'; import { AlertMailNotifier } from './infrastructure/alert-mail.notifier'; +import { buildAlertChannelMessage } from './infrastructure/alert-channel-message'; +import type { NotificationChannelsPort } from './application/types'; import { PlatformDirectory } from './infrastructure/platform-directory'; import { AlertRepository } from './infrastructure/repositories/alert.repository'; @@ -40,38 +47,114 @@ const recipientResolver = new RecipientResolver(alertDirectory, (userId, permiss cancanService.can(userId, permission, context), ); +const alertChannels: NotificationChannelsPort = { + async listUsable(location) { + const channels = await notificationChannelService.listUsable(location); + return channels.map((channel) => ({ + id: channel.id, + name: channel.name, + type: channel.type, + scope: channel.scope, + enabled: channel.enabled, + })); + }, + deliver: (channelId, message, context) => + notificationChannelService.deliver(channelId, message, context), +}; + 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' + | 'channels' + | 'channelMessage' +>; +const ENGINE_WIRING = 3; + +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), + channels: alertChannels, + channelMessage: buildAlertChannelMessage, }; // 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), + channels: latest(() => engineSlot.dependencies.channels!), + channelMessage: (input) => engineSlot.dependencies.channelMessage!(input), + 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, + channels: alertChannels, + 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(); + registerChannelShutdown(); engineSlot.attached = true; log.info('[alerts] engine registered'); diff --git a/src/modules/alerts/infrastructure/alert-channel-message.ts b/src/modules/alerts/infrastructure/alert-channel-message.ts new file mode 100644 index 0000000..b8a5e80 --- /dev/null +++ b/src/modules/alerts/infrastructure/alert-channel-message.ts @@ -0,0 +1,52 @@ +import { absoluteUrl, type ChannelMessage } from '#lib/server/infra/notifications'; +import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n'; +import type { AlertEmail } from '../application/alert-engine'; +import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary'; + +/** What a channel message is built from: an alert email without its recipient. */ +export type AlertMessageInput = Omit; + +/** + * Provider-neutral message of an alert for a notification channel. In the default language (a + * channel is shared by people with different ones) and without sensitive fields (people reading + * the channel may not be allowed to see the event); transports format it. + */ +export function buildAlertChannelMessage(input: AlertMessageInput): ChannelMessage { + const t = translator(DEFAULT_MAIL_LOCALE); + const { event, definition, where, alert } = input; + const eventLabel = t(definition.label); + const summary = eventSummaryText(event, definition, t); + const url = absoluteUrl(eventResourcePath(event, definition, where)); + + const fields = [ + { label: t('alerts.email.occurredAt'), value: new Date(event.occurredAt).toUTCString() }, + ...(where.project ? [{ label: t('alerts.email.project'), value: where.project }] : []), + ...describeEventFields(event, definition, input.names, { omitSensitive: true }).map( + (field) => ({ + label: t(field.label), + value: field.translate ? t(field.value) : field.value, + }), + ), + ]; + + const headline = t('alerts.email.alertSubject', { alert: alert.name, summary }); + const text = input.test ? t('alerts.email.testSubject', { subject: headline }) : headline; + + return { + title: alert.name, + summary, + eventLabel, + fields, + link: url ? { url, label: t('alerts.email.viewInApp') } : null, + suppressed: input.suppressed, + text, + test: input.test === true, + event: { + id: event.id, + type: event.type, + occurredAt: event.occurredAt, + scope: { ...event.scope }, + }, + alert: { id: alert.id, name: alert.name }, + }; +} diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.test.ts index 4c7bda8..921c2a7 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 8f7d115..1ad39c9 100644 --- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts +++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts @@ -1,56 +1,37 @@ 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 { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog'; +import { + DEFAULT_MAIL_LOCALE, + mailLocale, + translateKey, + translator, + type MailLocale, + type Translate, +} from '#lib/server/infra/notifications/i18n'; +import { getFieldValue, type EventDefinition } 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; +import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary'; -/** 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 fieldsTable(rows: { label: string; value: string }[]): string { @@ -66,14 +47,6 @@ function fieldsTable(rows: { label: string; value: string }[]): string { return `${body}
`; } -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,25 +63,21 @@ 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; - mailSummary?: (payload: unknown) => EventMessage; - }; + const definition = email.definition as EventDefinition & { mailTemplate?: string }; const eventLabel = t(definition.label); - const message = 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 summary = eventSummaryText(event, definition, t); + 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; + const resourcePath = eventResourcePath(event, definition, where); const scopeName = email.alert.scope === 'project' && where.project ? where.project : (where.organization ?? ''); @@ -118,12 +87,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 +109,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 +121,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 697e37b..9de7f72 100644 --- a/src/modules/alerts/infrastructure/event-summary.ts +++ b/src/modules/alerts/infrastructure/event-summary.ts @@ -1,4 +1,4 @@ -import { getFieldValue, type EventDefinition } from '#lib/events/catalog'; +import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog'; import type { AnyDomainEvent } from '#lib/server/events'; export type EventFieldLine = { @@ -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; @@ -61,3 +63,43 @@ export function describeEventFields( } return lines; } + +type Translate = (key: string, values?: Record) => string; + +type DefinitionCallbacks = EventDefinition & { + link?: (context: unknown) => string | null; + mailSummary?: (payload: unknown) => EventMessage; +}; + +function safely(run: () => T): T | undefined { + try { + return run(); + } catch { + return undefined; + } +} + +export function eventSummaryText( + event: Pick, + definition: EventDefinition, + t: Translate, +): string { + const message = safely(() => (definition as DefinitionCallbacks).mailSummary?.(event.payload)); + return message ? t(message.key, message.values) : t(definition.label); +} + +export function eventResourcePath( + event: Pick, + definition: EventDefinition, + where: { organizationSlug?: string; projectSlug?: string }, +): string | null { + return ( + safely(() => + (definition as DefinitionCallbacks).link?.({ + payload: event.payload, + organizationSlug: where.organizationSlug ?? null, + projectSlug: where.projectSlug ?? null, + }), + ) ?? null + ); +} diff --git a/src/modules/auth/domain/role-permissions.data.ts b/src/modules/auth/domain/role-permissions.data.ts index 1eed368..40a25a7 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 0000000..5c75e0c --- /dev/null +++ b/src/modules/notifications/application/external-recipient.service.test.ts @@ -0,0 +1,346 @@ +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('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']); + 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 0000000..295b55a --- /dev/null +++ b/src/modules/notifications/application/external-recipient.service.ts @@ -0,0 +1,364 @@ +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(); + } + + /** 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(); + 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-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts new file mode 100644 index 0000000..9350812 --- /dev/null +++ b/src/modules/notifications/application/notification-channel.service.test.ts @@ -0,0 +1,240 @@ +import { beforeEach, describe, expect, it } from 'vitest'; +import type { ChannelMessage } from '#lib/server/infra/notifications'; +import { NotificationChannelValidationError } from '../domain/notification-channel.domain'; +import { createChannelsFixture } from './testing'; + +const ORG = 'org-1'; +const orgLocation = { scope: 'organization' as const, organizationId: ORG, projectId: null }; +const p1 = { scope: 'project' as const, organizationId: ORG, projectId: 'p1' }; +const HOOK = 'https://hooks.example.com/hook/T000/B000/secret1a2b'; + +const message: ChannelMessage = { + title: 'Críticas', + summary: '1 critical', + eventLabel: 'Analysis completed', + fields: [], + link: null, + suppressed: 0, + text: '[GitOps] Críticas: 1 critical', + test: false, +}; + +async function validationErrors(promise: Promise) { + const error = await promise.catch((caught) => caught); + expect(error).toBeInstanceOf(NotificationChannelValidationError); + return (error as NotificationChannelValidationError).errors; +} + +describe('NotificationChannelService', () => { + let f: ReturnType; + + beforeEach(() => { + f = createChannelsFixture(); + }); + + describe('create and storage', () => { + it('stores the destination encrypted and only ever shows it masked', async () => { + const channel = await f.service.create( + orgLocation, + { type: 'slack', name: ' #alertas ', destination: HOOK }, + 'admin', + ); + + const [row] = f.repository.rows; + expect(row).toMatchObject({ id: 'channel-1', name: '#alertas', scope: 'organization' }); + expect(row.webhookUrl).not.toContain('hooks.example.com'); + expect(row.webhookUrl).not.toContain('secret'); + + const view = f.service.toView(channel); + expect(view.destinationMasked).toBe('https://hooks.example.com/…/••••1a2b'); + expect(view).not.toHaveProperty('webhookUrl'); + expect(JSON.stringify(view)).not.toContain('secret'); + expect(view.available).toBe(true); + }); + + it('validates type, name and destination (anti-SSRF) before saving', async () => { + const errors = await validationErrors( + f.service.create( + orgLocation, + { type: 'slack', name: '', destination: 'http://hooks.example.com/hook/x' }, + 'a', + ), + ); + expect(errors).toEqual({ name: 'required', destination: 'not_https' }); + + for (const [destination, code] of [ + ['https://evil.com/hook/x', 'host_not_allowed'], + ['https://10.0.0.1/hook/x', 'ip_address'], + ['https://u:p@hooks.example.com/hook/x', 'credentials'], + ['https://hooks.example.com/other', 'path_not_allowed'], + ]) { + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'slack', name: 'x', destination }, 'a'), + ), + ).toEqual({ destination: code }); + } + expect(f.repository.rows).toHaveLength(0); + }); + + it('only accepts types with a registered transport', async () => { + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'google-chat', name: 'x', destination: HOOK }, 'a'), + ), + ).toEqual({ type: 'type_unavailable' }); + expect( + await validationErrors( + f.service.create(orgLocation, { type: 'sms', name: 'x', destination: HOOK }, 'a'), + ), + ).toEqual({ type: 'invalid_type' }); + expect(f.service.availableTypes()).toEqual(['slack']); + }); + + it('keeps the destination when an update leaves it empty, and re-encrypts a new one', async () => { + const channel = await f.service.create( + orgLocation, + { type: 'slack', name: 'a', destination: HOOK }, + 'x', + ); + const before = f.repository.rows[0].webhookUrl; + + await f.service.update(channel.id, { name: 'b', destination: '' }); + expect(f.repository.rows[0]).toMatchObject({ name: 'b', webhookUrl: before }); + + await f.service.update(channel.id, { destination: 'https://hooks.example.com/hook/new9z9z' }); + expect(f.repository.rows[0].webhookUrl).not.toBe(before); + expect(f.service.toView(await f.service.get(channel.id)).destinationMasked).toMatch(/9z9z$/); + }); + }); + + describe('scopes', () => { + it('lets a project channel serve only its project, and an organization channel all of them', async () => { + const org = await f.service.create( + orgLocation, + { type: 'slack', name: 'org', destination: HOOK }, + 'a', + ); + const own = await f.service.create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a'); + await f.service.create( + { ...p1, projectId: 'p2' }, + { type: 'slack', name: 'p2', destination: HOOK }, + 'a', + ); + + const usable = await f.service.listUsable({ organizationId: ORG, projectId: 'p1' }); + expect(usable.map((channel) => channel.id).sort()).toEqual([org.id, own.id].sort()); + expect( + (await f.service.listUsable({ organizationId: ORG, projectId: null })).map((c) => c.id), + ).toEqual([org.id]); + expect(await f.service.listUsable({ organizationId: 'other', projectId: null })).toEqual([]); + expect((await f.service.list(p1)).map((channel) => channel.name)).toEqual(['p1']); + }); + }); + + describe('delivery', () => { + let channelId: string; + + beforeEach(async () => { + channelId = ( + await f.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x') + ).id; + }); + + it('sends to the decrypted destination', async () => { + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.transport.sent).toHaveLength(1); + expect(f.transport.sent[0]).toMatchObject({ channel: 'slack', destination: HOOK, message }); + }); + + it('skips disabled and deleted channels', async () => { + await f.service.update(channelId, { enabled: false }); + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(await f.service.deliver('missing', message)).toBe(false); + expect(f.transport.sent).toHaveLength(0); + }); + + it('records a permanent 4xx in lastError without retrying, and clears it on success', async () => { + f.transport.failWith = [404]; + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.repository.rows[0].lastError).toBe('HTTP 404'); + expect(f.transport.sent).toHaveLength(0); + expect(f.transport.failWith).toEqual([]); + + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.repository.rows[0]).toMatchObject({ lastError: null }); + expect(f.repository.rows[0].lastDeliveryAt).toBe(f.clock.now.toISOString()); + }); + + it('retries 429, 5xx and network errors before giving up', async () => { + f.transport.failWith = [429, 503, 'network']; + expect(await f.service.deliver(channelId, message)).toBe(true); + expect(f.transport.sent).toHaveLength(1); + + f.transport.failWith = [500, 500, 500, 500]; + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.repository.rows[0].lastError).toBe('HTTP 500'); + }); + + it('checks the stored destination again before sending', async () => { + // someone edits GitDB by hand and points the channel elsewhere + const { createChannelCipher } = await import('../infrastructure/crypto/channel-cipher'); + f.repository.rows[0].webhookUrl = createChannelCipher(() => 'test-encryption-key').encrypt( + channelId, + 'https://169.254.169.254/hook/latest', + ); + expect(await f.service.deliver(channelId, message)).toBe(false); + expect(f.transport.sent).toHaveLength(0); + expect(f.repository.rows[0].lastError).toBe('invalid_destination'); + }); + + it('does not commit a delivery stamp on every success', async () => { + await f.service.deliver(channelId, message); + const writes = () => + f.repository.writes.filter((write) => typeof write.changes.lastDeliveryAt === 'string'); + expect(writes()).toHaveLength(1); + await f.service.deliver(channelId, message); + await f.service.deliver(channelId, message); + expect(writes()).toHaveLength(1); + f.advance(60 * 60 * 1000); + await f.service.deliver(channelId, message); + expect(writes()).toHaveLength(2); + }); + + it('never logs the destination nor the message', async () => { + const lines: unknown[] = []; + const record = (...args: unknown[]) => void lines.push(args); + const g = createChannelsFixture({ logger: { warn: record, error: record, debug: record } }); + const id = ( + await g.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x') + ).id; + g.transport.failWith = [503, 503, 503, 503]; + await g.service.deliver(id, message, { alertId: 'alert-1' }); + + expect(lines.length).toBeGreaterThan(0); + const logged = JSON.stringify(lines); + expect(logged).toContain(id); + expect(logged).not.toContain('hooks.example.com'); + expect(logged).not.toContain('secret'); + expect(logged).not.toContain('Críticas'); + }); + + it('sends test messages even to a disabled channel and reports failures', async () => { + await f.service.update(channelId, { enabled: false }); + expect(await f.service.test(channelId, { ...message, test: true })).toEqual({ + sent: true, + error: null, + }); + f.transport.failWith = [403]; + expect(await f.service.test(channelId, message)).toEqual({ sent: false, error: 'HTTP 403' }); + }); + + it('marks channels whose type lost its transport as unavailable', async () => { + const g = createChannelsFixture({ types: [] }); + g.repository.rows = structuredClone(f.repository.rows); + expect(await g.service.deliver(channelId, message)).toBe(false); + expect(g.repository.rows[0].lastError).toBe('unavailable'); + expect(g.service.toView(await g.service.get(channelId)).available).toBe(false); + }); + }); +}); diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts new file mode 100644 index 0000000..ef98c6a --- /dev/null +++ b/src/modules/notifications/application/notification-channel.service.ts @@ -0,0 +1,333 @@ +import { + CHAT_CHANNEL_TYPES, + isChatChannelType, + type ChatChannelType, +} from '#lib/server/infra/notifications/chat-types'; +import type { + ChannelMessage, + ChatTransport, +} from '#lib/server/infra/notifications/chat-notification'; +import { WebhookDeliveryError } from '#lib/server/infra/http/webhook-request'; +import { + MAX_CHANNEL_NAME_LENGTH, + NotificationChannelDomain, + NotificationChannelNotFoundError, + NotificationChannelValidationError, + maskDestination, + type ChannelLocation, + type NotificationChannelView, +} from '../domain/notification-channel.domain'; +import type { ChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import type { + NotificationChannelChanges, + NotificationChannelRepositoryPort, +} from '../infrastructure/repositories/notification-channel.repository'; + +/** One message on its way to one channel; the destination is only held in memory. */ +export type ChannelDelivery = { + channelId: string; + type: ChatChannelType; + destination: string; + message: ChannelMessage; + /** Called by the queue once the delivery succeeded or definitively failed. */ + report: (outcome: { sent: true } | { sent: false; error: unknown }) => void; +}; + +/** Where deliveries go: the channel queue in production, a direct sender in tests. */ +export type ChannelSender = { + enqueue(delivery: ChannelDelivery, context?: Record): Promise; +}; + +export type ChannelTransports = { + get(type: ChatChannelType): ChatTransport | null; + available(): ChatChannelType[]; +}; + +export type ChannelInput = { + type?: unknown; + name?: unknown; + /** Destination URL; on update an empty value keeps the stored one. */ + destination?: unknown; + enabled?: unknown; +}; + +export type NotificationChannelServiceOptions = { + now?: () => Date; + generateId?: () => string; + /** How often a healthy channel records `lastDeliveryAt` (each record is a GitDB commit). */ + deliveryStampIntervalMs?: number; + logger?: { warn: (object: object, message: string) => void }; +}; + +const DEFAULT_STAMP_INTERVAL_MS = 60 * 60 * 1000; + +/** + * Notification channels (chat and webhook destinations) of organizations and projects. The + * destination is validated by its type's transport (anti-SSRF) before saving and before every + * send, stored encrypted and only ever shown masked. Deliveries go through a queue with retries; + * a permanent failure is recorded in `lastError`. + */ +export class NotificationChannelService { + private readonly now: () => Date; + private readonly generateId: () => string; + private readonly stampIntervalMs: number; + + constructor( + private readonly repository: NotificationChannelRepositoryPort, + private readonly cipher: ChannelCipher, + private readonly transports: ChannelTransports, + private readonly sender: ChannelSender, + private readonly options: NotificationChannelServiceOptions = {}, + ) { + this.now = options.now ?? (() => new Date()); + this.generateId = options.generateId ?? (() => crypto.randomUUID()); + this.stampIntervalMs = options.deliveryStampIntervalMs ?? DEFAULT_STAMP_INTERVAL_MS; + } + + /** Channel types that can be created now (a transport is registered for them). */ + availableTypes(): ChatChannelType[] { + return this.transports.available(); + } + + async get(id: string): Promise { + const channel = await this.repository.findById(id); + if (!channel) throw new NotificationChannelNotFoundError(id); + return channel; + } + + /** The location's own channels: organization-level ones, or one project's. */ + async list(location: Pick) { + const channels = await this.repository.listByOrganization(location.organizationId); + return channels.filter((channel) => + location.projectId + ? channel.projectId === location.projectId + : channel.scope === 'organization', + ); + } + + /** Channels an alert of `location` may use: its project's and its organization's. */ + async listUsable(location: Pick) { + const channels = await this.repository.listByOrganization(location.organizationId); + return channels.filter((channel) => channel.usableFrom(location)); + } + + toView(channel: NotificationChannelDomain): NotificationChannelView { + const { webhookUrl: _secret, ...rest } = channel.toJson(); + void _secret; + let destinationMasked = '••••'; + try { + destinationMasked = maskDestination(this.cipher.decrypt(channel.id, channel.webhookUrl)); + } catch { + // an undecryptable destination (rotated key) shows as fully masked + } + return { + ...rest, + destinationMasked, + available: this.transports.get(channel.type) !== null, + }; + } + + async create( + location: ChannelLocation, + input: ChannelInput, + actorUserId: string, + ): Promise { + const errors: Record = {}; + const type = this.validateType(input.type, errors); + const name = this.validateName(input.name, errors); + const destination = type ? this.validateDestination(type, input.destination, errors) : null; + if (Object.keys(errors).length > 0 || !type || !destination) { + throw new NotificationChannelValidationError(errors); + } + + const id = this.generateId(); + const timestamp = this.now().toISOString(); + const row = new NotificationChannelDomain({ + id, + type, + name, + ...location, + projectId: location.scope === 'project' ? location.projectId : null, + webhookUrl: this.cipher.encrypt(id, destination), + enabled: + input.enabled === undefined ? true : input.enabled === true || input.enabled === 'true', + createdByUserId: actorUserId, + createdAt: timestamp, + updatedAt: timestamp, + lastDeliveryAt: null, + lastError: null, + }).toJson(); + await this.repository.create(row); + return new NotificationChannelDomain(row); + } + + /** Name, enabled and destination; the type can't change. An empty destination keeps it. */ + async update(id: string, input: ChannelInput): Promise { + const channel = await this.get(id); + const errors: Record = {}; + const changes: NotificationChannelChanges = {}; + if (input.name !== undefined) changes.name = this.validateName(input.name, errors); + if (input.enabled !== undefined) { + changes.enabled = input.enabled === true || input.enabled === 'true'; + } + if (typeof input.destination === 'string' && input.destination.trim()) { + const destination = this.validateDestination(channel.type, input.destination, errors); + if (destination) { + changes.webhookUrl = this.cipher.encrypt(channel.id, destination); + // a new destination starts with a clean slate + changes.lastError = null; + } + } + if (Object.keys(errors).length > 0) throw new NotificationChannelValidationError(errors); + await this.repository.update(id, changes); + return new NotificationChannelDomain({ ...channel.toJson(), ...changes }); + } + + async delete(id: string): Promise { + await this.get(id); + await this.repository.delete(id); + } + + /** + * Queues `message` for the channel and resolves with whether it was delivered. Disabled, + * deleted, unavailable or invalid channels resolve `false` without sending; nothing throws. + */ + async deliver( + channelId: string, + message: ChannelMessage, + context: Record = {}, + ): Promise { + const channel = await this.repository.findById(channelId).catch(() => null); + if (!channel || !channel.enabled) return false; + return this.send(channel, message, context); + } + + /** "Send test message": delivers `message` even to a disabled channel, and tells the result. */ + async test( + id: string, + message: ChannelMessage, + ): Promise<{ sent: boolean; error: string | null }> { + const channel = await this.get(id); + const sent = await this.send(channel, message, { kind: 'channel_test' }); + const after = await this.repository.findById(id).catch(() => null); + return { sent, error: sent ? null : (after?.lastError ?? 'unavailable') }; + } + + private async send( + channel: NotificationChannelDomain, + message: ChannelMessage, + context: Record, + ): Promise { + const transport = this.transports.get(channel.type); + if (!transport) { + await this.recordFailure(channel, 'unavailable'); + return false; + } + let destination: string; + try { + destination = this.cipher.decrypt(channel.id, channel.webhookUrl); + } catch { + await this.recordFailure(channel, 'undecryptable'); + return false; + } + // the stored value is checked again: GitDB can be edited outside the app + if (!transport.validateDestination(destination).ok) { + await this.recordFailure(channel, 'invalid_destination'); + return false; + } + + let outcome: { sent: true } | { sent: false; error: unknown } = { sent: false, error: null }; + const sent = await this.sender.enqueue( + { + channelId: channel.id, + type: channel.type, + destination, + message, + report: (result) => { + outcome = result; + }, + }, + { channelId: channel.id, type: channel.type, ...context }, + ); + if (sent) await this.recordSuccess(channel); + else { + const error = (outcome as { error?: unknown }).error; + await this.recordFailure( + channel, + error instanceof WebhookDeliveryError + ? error.summary + : error instanceof Error + ? error.name + : 'failed', + ); + } + return sent; + } + + private async recordSuccess(channel: NotificationChannelDomain) { + const last = channel.lastDeliveryAt ? Date.parse(channel.lastDeliveryAt) : 0; + const stale = this.now().getTime() - last >= this.stampIntervalMs; + // each write is a commit: only when the error clears or the stamp got old + if (!channel.lastError && !stale) return; + await this.repository + .update(channel.id, { lastDeliveryAt: this.now().toISOString(), lastError: null }) + .catch((error) => this.logWriteFailure(channel, error)); + } + + private async recordFailure(channel: NotificationChannelDomain, reason: string) { + if (channel.lastError === reason) return; + await this.repository + .update(channel.id, { lastError: reason }) + .catch((error) => this.logWriteFailure(channel, error)); + } + + private logWriteFailure(channel: NotificationChannelDomain, error: unknown) { + this.options.logger?.warn( + { channelId: channel.id, err: error instanceof Error ? error.name : 'unknown' }, + '[channels] delivery outcome could not be recorded', + ); + } + + private validateType(value: unknown, errors: Record): ChatChannelType | null { + if (!isChatChannelType(value)) { + errors.type = typeof value === 'string' && value ? 'invalid_type' : 'required'; + return null; + } + if (!this.transports.get(value)) { + errors.type = 'type_unavailable'; + return null; + } + return value; + } + + private validateName(value: unknown, errors: Record): string { + const name = typeof value === 'string' ? value.trim() : ''; + if (!name) errors.name = 'required'; + else if (name.length > MAX_CHANNEL_NAME_LENGTH) errors.name = 'too_long'; + return name; + } + + private validateDestination( + type: ChatChannelType, + value: unknown, + errors: Record, + ): string | null { + if (typeof value !== 'string' || !value.trim()) { + errors.destination = 'required'; + return null; + } + const transport = this.transports.get(type); + if (!transport) { + errors.type = 'type_unavailable'; + return null; + } + const checked = transport.validateDestination(value.trim()); + if (!checked.ok) { + errors.destination = checked.error; + return null; + } + return checked.url.toString(); + } +} + +export { CHAT_CHANNEL_TYPES }; 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 0000000..78473a9 --- /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 0000000..de32189 --- /dev/null +++ b/src/modules/notifications/application/testing.ts @@ -0,0 +1,147 @@ +import { + DeliveryQueue, + type ChatChannelType, + type ChatNotification, + type ChatTransport, +} from '#lib/server/infra/notifications'; +import { + isRetryableWebhookError, + validateWebhookUrl, + webhookRetryAfter, + WebhookDeliveryError, +} from '#lib/server/infra/http/webhook-request'; +import { InMemoryNotificationChannelRepository } from '../infrastructure/repositories/in-memory.repositories'; +import { createChannelCipher } from '../infrastructure/crypto/channel-cipher'; +import { NotificationChannelService, type ChannelDelivery } from './notification-channel.service'; +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); + }, + }; +} + +export class FakeChatTransport implements ChatTransport { + sent: ChatNotification[] = []; + failWith: Array = []; + + validateDestination(raw: unknown) { + return validateWebhookUrl(raw, { hosts: ['hooks.example.com'], pathPrefix: '/hook/' }); + } + + async send(notification: ChatNotification) { + const failure = this.failWith.shift(); + if (failure === 'network') throw new WebhookDeliveryError(null, true, null, 'network'); + if (typeof failure === 'number') { + throw new WebhookDeliveryError(failure, failure === 429 || failure >= 500); + } + this.sent.push(notification); + } +} + +export function createChannelsFixture( + options: { + types?: ChatChannelType[]; + logger?: { warn: () => void; error: () => void; debug: () => void }; + } = {}, +) { + const clock = { now: new Date('2026-11-24T10:00:00.000Z') }; + const repository = new InMemoryNotificationChannelRepository(); + const transport = new FakeChatTransport(); + const types = options.types ?? ['slack']; + const logger = options.logger ?? { warn: () => {}, error: () => {}, debug: () => {} }; + const queue = new DeliveryQueue({ + send: (delivery) => + transport.send({ + channel: delivery.type, + destination: delivery.destination, + message: delivery.message, + } as ChatNotification), + retry: { + isRetryable: isRetryableWebhookError, + retryAfterMs: webhookRetryAfter, + sleep: async () => {}, + }, + logger, + label: { prefix: '[channels]', noun: 'message', plural: 'messages' }, + describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }), + onSettled: (delivery, outcome) => delivery.report(outcome), + }); + let id = 0; + const service = new NotificationChannelService( + repository, + createChannelCipher(() => 'test-encryption-key'), + { + get: (type) => (types.includes(type) ? transport : null), + available: () => [...types], + }, + queue, + { now: () => clock.now, generateId: () => `channel-${++id}` }, + ); + return { + clock, + repository, + transport, + service, + 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 0000000..893b9e7 --- /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 0000000..cb24ed4 --- /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 0000000..c13fb5a --- /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-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts new file mode 100644 index 0000000..b55f107 --- /dev/null +++ b/src/modules/notifications/domain/notification-channel.domain.ts @@ -0,0 +1,131 @@ +import { + isChatChannelType, + type ChatChannelType, +} from '#lib/server/infra/notifications/chat-types'; + +export type ChannelScope = 'organization' | 'project'; + +/** Where a channel lives: an organization channel has no project. */ +export type ChannelLocation = { + scope: ChannelScope; + organizationId: string; + projectId: string | null; +}; + +export type NotificationChannelRow = ChannelLocation & { + id: string; + type: ChatChannelType; + name: string; + /** Destination URL, encrypted (`channel-cipher.ts`): never returned nor logged. */ + webhookUrl: string; + enabled: boolean; + createdByUserId: string; + createdAt: string; + updatedAt: string; + lastDeliveryAt: string | null; + /** Short reason of the last failed delivery (`HTTP 404`, `timeout`), cleared on success. */ + lastError: string | null; +}; + +/** What the API and the pages may show: the destination only masked. */ +export type NotificationChannelView = Omit & { + /** `https://hooks.slack.com/…/••••1a2b` */ + destinationMasked: string; + /** Whether its type has a transport: channels of other types are kept but send nothing. */ + available: boolean; +}; + +export const MAX_CHANNEL_NAME_LENGTH = 80; + +function toIso(value: unknown): string | null { + if (value instanceof Date) return value.toISOString(); + return typeof value === 'string' && value ? value : null; +} + +export class NotificationChannelDomain implements NotificationChannelRow { + id: string; + type: ChatChannelType; + name: string; + scope: ChannelScope; + organizationId: string; + projectId: string | null; + webhookUrl: string; + enabled: boolean; + createdByUserId: string; + createdAt: string; + updatedAt: string; + lastDeliveryAt: string | null; + lastError: string | null; + + constructor(row: Record) { + this.id = row.id; + this.type = isChatChannelType(row.type) ? row.type : 'webhook'; + this.name = row.name ?? ''; + this.scope = row.scope === 'project' ? 'project' : 'organization'; + this.organizationId = row.organizationId; + this.projectId = this.scope === 'project' ? (row.projectId ?? null) : null; + this.webhookUrl = row.webhookUrl ?? ''; + this.enabled = row.enabled !== false; + this.createdByUserId = row.createdByUserId; + this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString(); + this.updatedAt = toIso(row.updatedAt) ?? this.createdAt; + this.lastDeliveryAt = toIso(row.lastDeliveryAt); + this.lastError = row.lastError ?? null; + } + + get location(): ChannelLocation { + return { scope: this.scope, organizationId: this.organizationId, projectId: this.projectId }; + } + + /** + * Whether an alert of `location` may use it: an organization channel serves the organization + * and all its projects, a project channel only alerts of its project. + */ + usableFrom(location: Pick): boolean { + if (location.organizationId !== this.organizationId) return false; + return this.scope === 'organization' || location.projectId === this.projectId; + } + + toJson(): NotificationChannelRow { + return { + id: this.id, + type: this.type, + name: this.name, + scope: this.scope, + organizationId: this.organizationId, + projectId: this.projectId, + webhookUrl: this.webhookUrl, + enabled: this.enabled, + createdByUserId: this.createdByUserId, + createdAt: this.createdAt, + updatedAt: this.updatedAt, + lastDeliveryAt: this.lastDeliveryAt, + lastError: this.lastError, + }; + } +} + +/** `https://hooks.slack.com/services/T0/B0/xyz1a2b` → `https://hooks.slack.com/…/••••1a2b`. */ +export function maskDestination(url: string): string { + try { + const parsed = new URL(url); + const tail = url.replace(/[?#].*$/, '').slice(-4); + return `${parsed.protocol}//${parsed.host}/…/••••${tail}`; + } catch { + return '••••'; + } +} + +export class NotificationChannelValidationError extends Error { + constructor(readonly errors: Record) { + super(`Invalid notification channel: ${Object.keys(errors).join(', ')}`); + this.name = 'NotificationChannelValidationError'; + } +} + +export class NotificationChannelNotFoundError extends Error { + constructor(id: string) { + super(`Notification channel not found: ${id}`); + this.name = 'NotificationChannelNotFoundError'; + } +} 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 0000000..d73ba75 --- /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 0000000..912319c --- /dev/null +++ b/src/modules/notifications/index.ts @@ -0,0 +1,135 @@ +import { + ChatNotification, + DeliveryQueue, + absoluteUrl, + availableChatTypes, + getChatTransport, + notify, + sendWithLatestNotify, +} from '#lib/server/infra/notifications'; +import { isRetryableWebhookError, webhookRetryAfter } from '#lib/server/infra/http/webhook-request'; +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 { + NotificationChannelService, + type ChannelDelivery, +} from './application/notification-channel.service'; +import { createChannelCipher } from './infrastructure/crypto/channel-cipher'; +import { NotificationChannelRepository } from './infrastructure/repositories/notification-channel.repository'; +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, +); + +const CHANNEL_QUEUE_KEY = Symbol.for('gitops.notifications.channel-queue'); +const CHANNEL_SHUTDOWN_KEY = Symbol.for('gitops.notifications.channel-shutdown'); +type GlobalWithChannelQueue = typeof globalThis & { + [CHANNEL_QUEUE_KEY]?: DeliveryQueue; + [CHANNEL_SHUTDOWN_KEY]?: boolean; +}; + +export const channelQueue: DeliveryQueue = ((globalThis as GlobalWithChannelQueue)[ + CHANNEL_QUEUE_KEY +] ??= new DeliveryQueue({ + send: (delivery) => + sendWithLatestNotify( + new ChatNotification({ + channel: delivery.type, + destination: delivery.destination, + message: delivery.message, + }), + ), + concurrency: 3, + retry: { isRetryable: isRetryableWebhookError, retryAfterMs: webhookRetryAfter }, + logger: createLogger('channels'), + label: { prefix: '[channels]', noun: 'message', plural: 'messages' }, + describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }), + onSettled: (delivery, outcome) => delivery.report(outcome), +})); + +export const notificationChannelService = new NotificationChannelService( + new NotificationChannelRepository(), + createChannelCipher(() => passwordService.ensureEncryptionKey()), + { get: (type) => getChatTransport(type), available: () => availableChatTypes() }, + channelQueue, + { logger: log }, +); + +export function registerChannelShutdown(): void { + const scope = globalThis as GlobalWithChannelQueue; + if (scope[CHANNEL_SHUTDOWN_KEY]) return; + scope[CHANNEL_SHUTDOWN_KEY] = true; + process.once('sveltekit:shutdown' as never, () => { + void channelQueue.drain(10_000); + }); +} + +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 { + NotificationChannelNotFoundError, + NotificationChannelValidationError, + type ChannelLocation, + type NotificationChannelView, +} from './domain/notification-channel.domain'; +export type { ChannelInput } from './application/notification-channel.service'; +export { buildChannelTestMessage } from './infrastructure/channel-test-message'; +export { normalizeEmail } from './domain/email-address'; diff --git a/src/modules/notifications/infrastructure/channel-test-message.ts b/src/modules/notifications/infrastructure/channel-test-message.ts new file mode 100644 index 0000000..21fe6b1 --- /dev/null +++ b/src/modules/notifications/infrastructure/channel-test-message.ts @@ -0,0 +1,28 @@ +import type { ChannelMessage } from '#lib/server/infra/notifications'; +import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n'; + +/** + * The message of "Send test message": says it is a test and where it was sent from, nothing about + * any real event. In the default language: a channel is shared by people with different ones. + */ +export function buildChannelTestMessage(input: { + channelName: string; + where: string; + /** Absolute link to the channel settings, when `ORIGIN` is known. */ + link: string | null; +}): ChannelMessage { + const t = translator(DEFAULT_MAIL_LOCALE); + const summary = t('notifications.channels.testMessage.summary', { where: input.where }); + return { + title: t('notifications.channels.testMessage.title', { channel: input.channelName }), + summary, + eventLabel: t('notifications.channels.testMessage.event'), + fields: [{ label: t('notifications.channels.testMessage.channel'), value: input.channelName }], + link: input.link + ? { url: input.link, label: t('notifications.channels.testMessage.open') } + : null, + suppressed: 0, + text: `${t('notifications.channels.testMessage.title', { channel: input.channelName })}: ${summary}`, + test: true, + }; +} diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts new file mode 100644 index 0000000..270bdf6 --- /dev/null +++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, it } from 'vitest'; +import { createChannelCipher } from './channel-cipher'; + +const url = 'https://hooks.slack.com/services/T000/B000/abcdef1a2b'; + +describe('channel cipher', () => { + it('round-trips a destination without keeping it readable', () => { + const cipher = createChannelCipher(() => 'key-1'); + const stored = cipher.encrypt('channel-1', url); + expect(stored).toMatch(/^v1:/); + expect(stored).not.toContain('hooks.slack.com'); + expect(cipher.decrypt('channel-1', stored)).toBe(url); + // a fresh IV each time + expect(cipher.encrypt('channel-1', url)).not.toBe(stored); + }); + + it('does not decrypt on another channel nor with another key', () => { + const stored = createChannelCipher(() => 'key-1').encrypt('channel-1', url); + expect(() => createChannelCipher(() => 'key-1').decrypt('channel-2', stored)).toThrow( + /could not be decrypted/, + ); + expect(() => createChannelCipher(() => 'key-2').decrypt('channel-1', stored)).toThrow( + /could not be decrypted/, + ); + expect(() => createChannelCipher(() => 'key-1').decrypt('channel-1', url)).toThrow( + /no encrypted destination/, + ); + }); + + it('refuses to work without a key', () => { + expect(() => createChannelCipher(() => ' ').encrypt('channel-1', url)).toThrow( + /GITDB_ENCRYPTION_KEY/, + ); + }); +}); diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts new file mode 100644 index 0000000..5ab63ec --- /dev/null +++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts @@ -0,0 +1,66 @@ +import crypto from 'node:crypto'; + +const ALGORITHM = 'aes-256-gcm'; +const VERSION = 'v1'; +const KEY_SALT = 'gitops:notifications:channel-destination:v1'; +const IV_BYTES = 12; +const AUTH_TAG_BYTES = 16; + +export interface ChannelCipher { + encrypt(channelId: string, value: string): string; + decrypt(channelId: string, stored: string): string; +} + +/** + * AES-256-GCM for channel destinations (same scheme as the vault secrets), keyed from + * `GITDB_ENCRYPTION_KEY`. The channel id is authenticated data: a value copied onto another + * channel does not decrypt. + */ +export function createChannelCipher(secret: () => string): ChannelCipher { + let cached: { material: string; key: Buffer } | null = null; + const key = () => { + const material = secret().trim(); + if (!material) throw new Error('Missing GITDB_ENCRYPTION_KEY environment variable'); + if (cached?.material !== material) { + cached = { material, key: crypto.scryptSync(material, KEY_SALT, 32) }; + } + return cached.key; + }; + const aad = (channelId: string) => Buffer.from(`${VERSION}:channel:${channelId}`, 'utf8'); + + return { + encrypt(channelId, value) { + const iv = crypto.randomBytes(IV_BYTES); + const cipher = crypto.createCipheriv(ALGORITHM, key(), iv, { + authTagLength: AUTH_TAG_BYTES, + }); + cipher.setAAD(aad(channelId)); + const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]); + return [ + VERSION, + iv.toString('base64'), + cipher.getAuthTag().toString('base64'), + ciphertext.toString('base64'), + ].join(':'); + }, + decrypt(channelId, stored) { + const [version, iv, authTag, ciphertext, ...rest] = stored.split(':'); + if (version !== VERSION || !iv || !authTag || !ciphertext || rest.length > 0) { + throw new Error(`Channel ${channelId} has no encrypted destination`); + } + try { + const decipher = crypto.createDecipheriv(ALGORITHM, key(), Buffer.from(iv, 'base64'), { + authTagLength: AUTH_TAG_BYTES, + }); + decipher.setAAD(aad(channelId)); + decipher.setAuthTag(Buffer.from(authTag, 'base64')); + return Buffer.concat([ + decipher.update(Buffer.from(ciphertext, 'base64')), + decipher.final(), + ]).toString('utf8'); + } catch { + throw new Error(`Channel ${channelId} destination could not be decrypted`); + } + }, + }; +} 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 0000000..80521c2 --- /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 0000000..acdf2e0 --- /dev/null +++ b/src/modules/notifications/infrastructure/repositories/external-recipient.repository.ts @@ -0,0 +1,76 @@ +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; + delete(id: string): 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 }); + } + + 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 new file mode 100644 index 0000000..bb365e5 --- /dev/null +++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts @@ -0,0 +1,119 @@ +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'; +import { + NotificationChannelDomain, + type NotificationChannelRow, +} from '../../domain/notification-channel.domain'; +import type { + NotificationChannelChanges, + NotificationChannelRepositoryPort, +} from './notification-channel.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, + ); + } + + async delete(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} + +export class InMemoryNotificationChannelRepository implements NotificationChannelRepositoryPort { + rows: NotificationChannelRow[] = []; + writes: Array<{ id: string; changes: Record }> = []; + + async findById(id: string) { + const row = this.rows.find((candidate) => candidate.id === id); + return row ? new NotificationChannelDomain(structuredClone(row)) : null; + } + + async listByOrganization(organizationId: string) { + return this.rows + .filter((row) => row.organizationId === organizationId) + .map((row) => new NotificationChannelDomain(structuredClone(row))); + } + + async create(row: NotificationChannelRow) { + this.rows.push(structuredClone(row)); + this.writes.push({ id: row.id, changes: { ...row } }); + } + + async update(id: string, changes: NotificationChannelChanges) { + this.writes.push({ id, changes: { ...changes } }); + this.rows = this.rows.map((row) => + row.id === id + ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() } + : row, + ); + } + + async delete(id: string) { + this.rows = this.rows.filter((row) => row.id !== id); + } +} diff --git a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts new file mode 100644 index 0000000..8f11637 --- /dev/null +++ b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts @@ -0,0 +1,55 @@ +import { NotificationChannelEntity } from '#lib/database/schemas'; +import { Repository } from '#lib/server/infra/repository'; +import { + NotificationChannelDomain, + type NotificationChannelRow, +} from '../../domain/notification-channel.domain'; + +export type NotificationChannelChanges = Partial< + Pick +>; + +/** Persistence port; `InMemoryNotificationChannelRepository` implements it in tests. */ +export interface NotificationChannelRepositoryPort { + findById(id: string): Promise; + /** Every channel of the organization, including those of its projects. */ + listByOrganization(organizationId: string): Promise; + create(row: NotificationChannelRow): Promise; + update(id: string, changes: NotificationChannelChanges): Promise; + delete(id: string): Promise; +} + +export class NotificationChannelRepository + extends Repository + implements NotificationChannelRepositoryPort +{ + async findById(id: string) { + const result = await this.db.select().from(NotificationChannelEntity).where({ id }).limit(1); + const row = result.rows[0]; + return row ? new NotificationChannelDomain(row) : null; + } + + async listByOrganization(organizationId: string) { + const result = await this.db + .select() + .from(NotificationChannelEntity) + .where({ organizationId }) + .orderBy('createdAt', 'asc'); + return result.rows.map((row: any) => new NotificationChannelDomain(row)); + } + + async create(row: NotificationChannelRow) { + await this.db.insert(NotificationChannelEntity).values({ ...row }); + } + + async update(id: string, changes: NotificationChannelChanges) { + await this.db + .update(NotificationChannelEntity) + .set({ ...changes, updatedAt: new Date().toISOString() }) + .where({ id }); + } + + async delete(id: string) { + await this.db.delete(NotificationChannelEntity).where({ id }); + } +} 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 0000000..b7137fd --- /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 0000000..071c567 --- /dev/null +++ b/src/notifications/email/external-recipient-verify.html @@ -0,0 +1,13 @@ +

{{ title }}

+
+

{{ intro }}

+

{{ explanation }}

+
+{{{ actionButton }}} +
+

{{ expiry }}

+

{{ ignore }}

+

+ {{ verifyUrl }} +

+
diff --git a/src/routes/+layout.svelte b/src/routes/+layout.svelte index ed527f9..ec021b2 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 e817390..df6f2ae 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 ed47518..0620fe2 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 b7184e0..af3be75 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/api/notification-channels/+server.ts b/src/routes/api/notification-channels/+server.ts new file mode 100644 index 0000000..3303cfe --- /dev/null +++ b/src/routes/api/notification-channels/+server.ts @@ -0,0 +1,33 @@ +import { json } from '@sveltejs/kit'; +import { resolveLocation } from '#lib/server/alerts/access'; +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { createChannel, listChannels } from '#lib/server/notifications/channels'; + +// GET /api/notification-channels?organizationId=…|projectId=…: the location's channels (and, for a +// project, the organization ones it inherits). The destination is only ever returned masked +export async function GET({ url, locals }) { + const lookup = await resolveLocation({ + organizationId: url.searchParams.get('organizationId'), + projectId: url.searchParams.get('projectId'), + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse(await listChannels(locals, lookup.location)); +} + +// POST /api/notification-channels { organizationId | projectId, type, name, destination, enabled? } +export async function POST({ request, locals }) { + const body = await readJson(request); + const lookup = await resolveLocation({ + organizationId: typeof body.organizationId === 'string' ? body.organizationId : null, + projectId: typeof body.projectId === 'string' ? body.projectId : null, + }); + if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status }); + return toResponse( + await createChannel(locals, lookup.location, { + type: body.type, + name: body.name, + destination: body.destination, + enabled: body.enabled, + }), + ); +} diff --git a/src/routes/api/notification-channels/[id]/+server.ts b/src/routes/api/notification-channels/[id]/+server.ts new file mode 100644 index 0000000..6a1a3e6 --- /dev/null +++ b/src/routes/api/notification-channels/[id]/+server.ts @@ -0,0 +1,23 @@ +import { readJson, toResponse } from '#lib/server/alerts/http'; +import { deleteChannel, getChannel, updateChannel } from '#lib/server/notifications/channels'; + +export async function GET({ params, locals }) { + return toResponse(await getChannel(locals, params.id)); +} + +// PATCH /api/notification-channels/ { name?, destination?, enabled? }: the type can't change and +// an omitted destination keeps the stored one +export async function PATCH({ params, request, locals }) { + const body = await readJson(request); + return toResponse( + await updateChannel(locals, params.id, { + name: body.name, + destination: body.destination, + enabled: body.enabled, + }), + ); +} + +export async function DELETE({ params, locals }) { + return toResponse(await deleteChannel(locals, params.id)); +} diff --git a/src/routes/api/notification-channels/[id]/test/+server.ts b/src/routes/api/notification-channels/[id]/test/+server.ts new file mode 100644 index 0000000..6097f64 --- /dev/null +++ b/src/routes/api/notification-channels/[id]/test/+server.ts @@ -0,0 +1,7 @@ +import { toResponse } from '#lib/server/alerts/http'; +import { testChannel } from '#lib/server/notifications/channels'; + +// POST /api/notification-channels//test: posts a test message, even to a disabled channel +export async function POST({ params, locals }) { + return toResponse(await testChannel(locals, params.id)); +} diff --git a/src/routes/api/notification-channels/server.test.ts b/src/routes/api/notification-channels/server.test.ts new file mode 100644 index 0000000..a355990 --- /dev/null +++ b/src/routes/api/notification-channels/server.test.ts @@ -0,0 +1,260 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +// grants per caller and context key (`org:` / `project:`) +const grants: { + users: Record>; + apiKeys: Record; +} = { users: {}, apiKeys: {} }; + +function contextKey(context: { scope: string; organizationId?: string; projectId?: string }) { + return context.scope === 'project' + ? `project:${context.projectId}` + : `org:${context.organizationId}`; +} + +vi.mock('#modules/auth', () => ({ + cancanService: { + canSessionUser: async (user: { id?: string } | null, permission: string, context: never) => + !!user?.id && (grants.users[user.id]?.[contextKey(context)] ?? []).includes(permission), + canApiKey: ( + apiKey: { id: string; projectId: string | null }, + permission: string, + context: { scope: string; projectId?: string }, + ) => { + if ( + apiKey.projectId && + (context.scope !== 'project' || context.projectId !== apiKey.projectId) + ) { + return false; + } + return (grants.apiKeys[apiKey.id] ?? []).includes(permission); + }, + }, +})); + +vi.mock('#modules/projects', () => ({ + projectService: { + getProject: async (id: string) => + ['p1', 'p2'].includes(id) + ? { id, name: `Project ${id}`, slug: id, organization: { id: 'org-1', slug: 'kettu' } } + : null, + }, +})); + +vi.mock('#modules/organization', () => ({ + organizationService: { + getOrganization: async (id: string) => + id === 'org-1' ? { id, name: 'Kettu', slug: 'kettu' } : null, + }, +})); + +vi.mock('#modules/notifications', async () => { + const { createChannelsFixture } = await import('#modules/notifications/application/testing'); + const domain = await import('#modules/notifications/domain/notification-channel.domain'); + const { buildChannelTestMessage } = + await import('#modules/notifications/infrastructure/channel-test-message'); + const fixture = createChannelsFixture(); + return { + ...domain, + buildChannelTestMessage, + notificationChannelService: fixture.service, + fixture, + }; +}); + +const notifications = (await import('#modules/notifications')) as unknown as { + fixture: ReturnType< + typeof import('#modules/notifications/application/testing').createChannelsFixture + >; +}; +const collection = await import('./+server'); +const item = await import('./[id]/+server'); +const test = await import('./[id]/test/+server'); + +const HOOK = 'https://hooks.example.com/hook/T0/B0/topsecret1a2b'; +const ORG_ADMIN = ['read', 'create', 'update', 'delete'].map( + (a) => `organization:notifications:${a}`, +); +const PROJECT_ADMIN = ['read', 'create', 'update', 'delete'].map( + (a) => `project:notifications:${a}`, +); + +function call( + handler: (event: never) => Promise, + input: { + locals?: Record; + body?: unknown; + url?: string; + params?: Record; + }, +) { + return handler({ + locals: input.locals ?? {}, + params: input.params ?? {}, + url: new URL(input.url ?? 'http://localhost/api/notification-channels'), + request: { json: async () => input.body ?? {} }, + } as never); +} + +const as = (id: string) => ({ user: { id } }); + +async function createOrgChannel() { + const response = await call(collection.POST, { + locals: as('orgAdmin'), + body: { organizationId: 'org-1', type: 'slack', name: '#alerts', destination: HOOK }, + }); + expect(response.status).toBe(201); + return (await response.json()) as { id: string }; +} + +describe('/api/notification-channels', () => { + beforeEach(() => { + notifications.fixture.repository.rows = []; + notifications.fixture.transport.sent = []; + grants.users = { + orgAdmin: { 'org:org-1': ORG_ADMIN }, + orgReader: { 'org:org-1': ['organization:notifications:read'] }, + alertsOnly: { 'org:org-1': ['organization:alerts:all', 'organization:alerts:read'] }, + projectAdmin: { 'project:p1': PROJECT_ADMIN }, + }; + grants.apiKeys = { 'key-p1': PROJECT_ADMIN }; + }); + + it('never returns the destination in clear', async () => { + const created = await createOrgChannel(); + const listed = await call(collection.GET, { + locals: as('orgReader'), + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }); + const fetched = await call(item.GET, { locals: as('orgReader'), params: { id: created.id } }); + for (const response of [listed, fetched]) { + expect(response.status).toBe(200); + const text = await response.text(); + expect(text).not.toContain('topsecret'); + expect(text).not.toContain('webhookUrl'); + expect(text).toContain('••••1a2b'); + } + }); + + it('needs *:notifications:* to see or manage channels', async () => { + const created = await createOrgChannel(); + + for (const locals of [{}, as('alertsOnly')]) { + const listed = await call(collection.GET, { + locals, + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }); + expect(listed.status).toBe(403); + // a channel the caller can't read looks missing + expect((await call(item.GET, { locals, params: { id: created.id } })).status).toBe(404); + } + + const reader = as('orgReader'); + expect( + ( + await call(collection.POST, { + locals: reader, + body: { organizationId: 'org-1', type: 'slack', name: 'x', destination: HOOK }, + }) + ).status, + ).toBe(403); + expect( + (await call(item.PATCH, { locals: reader, params: { id: created.id }, body: { name: 'y' } })) + .status, + ).toBe(403); + expect((await call(item.DELETE, { locals: reader, params: { id: created.id } })).status).toBe( + 403, + ); + expect((await call(test.POST, { locals: reader, params: { id: created.id } })).status).toBe( + 403, + ); + expect(notifications.fixture.transport.sent).toHaveLength(0); + }); + + it('keeps project admins and project keys inside their project', async () => { + const created = await call(collection.POST, { + locals: as('projectAdmin'), + body: { projectId: 'p1', type: 'slack', name: '#p1', destination: HOOK }, + }); + expect(created.status).toBe(201); + + // no organization channels for a project admin + const orgChannel = await call(collection.POST, { + locals: as('projectAdmin'), + body: { organizationId: 'org-1', type: 'slack', name: '#org', destination: HOOK }, + }); + expect(orgChannel.status).toBe(403); + + const key = { apiKey: { id: 'key-p1', projectId: 'p1', userId: null, role: null } }; + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?projectId=p1', + }) + ).status, + ).toBe(200); + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?projectId=p2', + }) + ).status, + ).toBe(403); + expect( + ( + await call(collection.GET, { + locals: key, + url: 'http://localhost/api/notification-channels?organizationId=org-1', + }) + ).status, + ).toBe(403); + }); + + it('validates the destination on the server', async () => { + const response = await call(collection.POST, { + locals: as('orgAdmin'), + body: { + organizationId: 'org-1', + type: 'slack', + name: 'x', + destination: 'https://127.0.0.1/hook/x', + }, + }); + expect(response.status).toBe(400); + await expect(response.json()).resolves.toEqual({ + error: 'Invalid channel', + errors: { destination: 'ip_address' }, + }); + }); + + it('sends a test message with the fake transport', async () => { + const created = await createOrgChannel(); + const response = await call(test.POST, { locals: as('orgAdmin'), params: { id: created.id } }); + expect(response.status).toBe(200); + await expect(response.json()).resolves.toEqual({ sent: true, error: null }); + expect(notifications.fixture.transport.sent[0].message).toMatchObject({ + title: 'GitOps test message for #alerts', + test: true, + }); + }); + + it('updates and deletes with the right permissions', async () => { + const created = await createOrgChannel(); + const updated = await call(item.PATCH, { + locals: as('orgAdmin'), + params: { id: created.id }, + body: { name: '#renamed', enabled: false, type: 'google-chat' }, + }); + await expect(updated.json()).resolves.toMatchObject({ + name: '#renamed', + enabled: false, + type: 'slack', + }); + expect( + (await call(item.DELETE, { locals: as('orgAdmin'), params: { id: created.id } })).status, + ).toBe(200); + expect(notifications.fixture.repository.rows).toHaveLength(0); + }); +}); diff --git a/src/routes/notifications/unsubscribe/+page.server.ts b/src/routes/notifications/unsubscribe/+page.server.ts new file mode 100644 index 0000000..df184ae --- /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 0000000..be12863 --- /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 0000000..3c25c79 --- /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 0000000..a9d9be1 --- /dev/null +++ b/src/routes/notifications/verify/+page.svelte @@ -0,0 +1,8 @@ + + + diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.server.ts b/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.server.ts new file mode 100644 index 0000000..7adbcc5 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.server.ts @@ -0,0 +1,22 @@ +import { error } from '@sveltejs/kit'; +import { projectAlertContext } from '#lib/server/alerts/page'; +import { channelActions, loadChannelsSection } from '#lib/server/notifications/channels-page'; +import { canOpenNotificationSettings } from '#lib/server/notifications/settings'; + +export async function load(event) { + const { location, basePath } = await projectAlertContext(event); + const [channels, canOpenOrganization] = await Promise.all([ + loadChannelsSection(event.locals, location), + canOpenNotificationSettings(event.locals, location.organizationId), + ]); + if (!channels) throw error(403, 'Forbidden'); + return { + channels, + alertsPath: basePath, + organizationSettingsPath: canOpenOrganization + ? `/org/${event.params.org}/settings/alerts/settings` + : null, + }; +} + +export const actions = channelActions(async (event) => (await projectAlertContext(event)).location); diff --git a/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.svelte b/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.svelte new file mode 100644 index 0000000..c4a1076 --- /dev/null +++ b/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.svelte @@ -0,0 +1,39 @@ + + + + {$_('notifications.settings.title')} - GitOps + + +
+
+ + + {$_('notifications.settings.back')} + +

+ {$_('notifications.settings.title')} +

+

+ {$_('notifications.settings.descriptionProject')} +

+
+ + +
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 0000000..6a789c8 --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts @@ -0,0 +1,65 @@ +import { error, fail } from '@sveltejs/kit'; +import { organizationService } from '#modules/organization'; +import { + loadNotificationSettings, + removeExternalRecipient, + resendVerification, + saveAllowedDomains, +} from '#lib/server/notifications/settings'; +import { channelActions, loadChannelsSection } from '#lib/server/notifications/channels-page'; + +export async function load({ parent, locals }) { + const { organization } = await parent(); + const location = { + scope: 'organization' as const, + organizationId: organization.id, + projectId: null, + }; + const [result, channels] = await Promise.all([ + loadNotificationSettings(locals, organization.id), + loadChannelsSection(locals, location).catch(() => null), + ]); + if (!result.ok && !channels) throw error(result.status, result.error); + return { settings: result.ok ? result.data : null, channels }; +} + +export const actions = { + ...channelActions(async ({ params }) => { + const organization = await organizationOf(params.org); + return { scope: 'organization', organizationId: organization.id, projectId: null }; + }), + 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 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) { + 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 0000000..1165bef --- /dev/null +++ b/src/routes/org/[org]/settings/alerts/settings/+page.svelte @@ -0,0 +1,38 @@ + + + + {$_('notifications.settings.title')} - {$_('orgSettings.title')} + + +
+
+ + + {$_('notifications.settings.back')} + +

+ {$_('notifications.settings.title')} +

+

+ {$_('notifications.settings.description')} +

+
+ + +