diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index bb0f61b..62def50 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -72,7 +72,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`, `code-report`, `vault`, `audit`, `alerts`, `monitoring` y `notifications`. Las rutas deben importar desde el `index.ts` publico. +`projects`, `state-iac`, `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 @@ -118,46 +118,33 @@ tambien usuarios con acceso solo a proyectos bajo la organización (ven el overv **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. Cada canal tiene un idioma -(`locale`: es | en, por defecto en), que determina el idioma de etiquetas y eventos en sus mensajes. -URLs de webhook se encriptan con `GITDB_ENCRYPTION_KEY`. Emails externos: `pending` → `verified` → `unsubscribed` -o `blocked`; template sin campos `sensitive` ni links; `List-Unsubscribe` HMAC (90 días). Canales: un mensaje -por canal en paralelo, fallo de canal nunca afecta email. **Webhook** se firma con HMAC-SHA256 -(`X-GitOps-Signature`): secreto `whsec_…` se muestra una sola vez al crear o rotar (24 h gracia, ambos secretos -validan); resuelve DNS rechazando IPs privadas/loopback; no sigue redirects; reintentos con backoff (20 fallos -= auto-deshabilita). Docs en `docs/webhooks/`. **Slack**: Incoming Webhook (solo URLs `https://hooks.slack.com/services/…`, -sin firma), formatea como Block Kit en el idioma del canal (nombre de alerta, resumen, campos, cambios de campos -con before/after, fecha en zona horaria del lector, nota de contexto y botón "Ver en GitOps" si hay link), escapa -caracteres Slack (`&<>`) en datos de usuario/evento. Un canal GitOps por webhook Slack. Los errores 4xx no se reintentan -y se muestran como último error. **Add to Slack** (`SlackConnectService`): cuando `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` están configurados, -los settings de canales muestran "Añadir a Slack"; usuario elige workspace y canal, GitOps crea el canal con webhook. -Admin abre `GitOps Settings → Slack`, crea la app Slack (manifest con scope `incoming-webhook` y redirect -`/notifications/slack/callback`, requiere https), copia credenciales al entorno y reinicia. En dev, usar -`DEV_HTTPS=true` con certificados en `.certs/` (ver `.env.example`). - -**Comando `/gitops`** (`SlackAppService`, requiere `SLACK_SIGNING_SECRET`): organización instala el app desde la -página de canales (`installSlack` action, scope `commands`), guardando el bot token en `slack_workspaces` -(GitDB, una fila por team, vinculada a organización). Los endpoints `/api/slack/commands` y -`/api/slack/interactions` verifican la firma Slack (5 min window, `verifySlackSignature`) y actúan como el -usuario Slack vinculado (`authProviders` entry `slack` = `:`) con permiso `organization:notifications:create`. -Luego en Slack: (1) `/gitops login` → link firmado a `/notifications/slack/link` para vincular usuario a su -cuenta GitOps (10 min, una vez; `hooks.server.ts` preserva la URL en `gitops_return_to`); (2) `/gitops channel` -pide nombre e idioma → link firmado a `/notifications/slack/connect` que abre selector de canales Slack, crea el -canal en GitOps con webhook y posea test → `/notifications/slack/callback` → `/notifications/slack/done`; -(3) `/gitops status` muestra organización vinculada y canales conectados. Las rutas de Slack bypass CSRF porque -Slack envía requests sin `Origin` header; solo los endpoints firmados (`CSRF_EXEMPT_PATHS`) están excluidos. - -Configuración: webhook Slack (URL: `https://hooks.slack.com/services/…`), canales tienen idioma (`locale: es|en`), -URLs de webhook encriptadas, emails externos: `pending` → `verified` o `blocked`; template sin campos `sensitive` ni -links internos; unsubscribe HMAC (90 días). **Webhook** se firma: secreto `whsec_…` (mostrado una sola vez), resuelve -DNS rechazando IPs privadas, 20 fallos consecutivos = auto-deshabilita. Variantes de desarrollo: -`NOTIFICATIONS_WEBHOOK_ALLOW_HTTP`, `NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS`. Rutas públicas -`/notifications/verify` y `/notifications/unsubscribe` aceptan POST sin sesión. Sin `ORIGIN` no se envía nada. +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` se abre un modal (`AlertSettingsPanel`) con tres tabs +(**Integraciones** / **Canales** / **Email externo**): + +- **Integraciones:** Muestra estado de Slack: `available` si está configurado (`SLACK_CLIENT_ID` / + `SLACK_CLIENT_SECRET`), `disabled` si falta alguno o `SLACK_SIGNING_SECRET`. El comando `/gitops` + se instala solo si ambos están configurados. Google Chat es `coming_soon`. +- **Canales:** Organizaciones crean canales (`NotificationChannelEntity` en GitDB) aquí; proyectos + usan los canales de su organización (#119). Webhook se firma con `whsec_…` (mostrado una sola + vez), resuelve DNS rechazando IPs privadas, 20 fallos = auto-deshabilita. Slack: Incoming Webhook, + Block Kit, URL `https://hooks.slack.com/services/…` solo. **Add to Slack** cuando credenciales + están configuradas. +- **Email externo:** Dominios permitidos y gestión de destinatarios externos (`pending` → `verified` + → `unsubscribed` o `blocked`); template sin campos `sensitive` ni links. + +**Comando `/gitops`** (requiere `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` / `SLACK_SIGNING_SECRET`): +organización instala el app, guardando bot token en `slack_workspaces` (GitDB). Endpoints +`/api/slack/commands` y `/api/slack/interactions` verifican firma (5 min window) y actúan como el +usuario Slack vinculado. Flujos: (1) `/gitops login` → link firmado para vincular cuenta; (2) +`/gitops channel` → modal nombre/idioma → selector canales Slack. Rutas de Slack usan CSRF firmado. + +Proyectos no tienen settings de notificación propios: muestran un "?" que dice dónde se gestionan, +y `/org//projects//settings/alerts/settings` redirige a la organización (404 sin acceso). + +Desarrollo con HTTPS para Slack OAuth: `DEV_HTTPS=true` con certs en `.certs/`. Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a `roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a diff --git a/CLAUDE.md b/CLAUDE.md index da1c4be..441e583 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -349,23 +349,48 @@ in `docs/adr/0001-event-bus-and-alerts.md`. (`organization:notifications:read`; resend a confirmation, or remove a `pending` address added by mistake, with `organization:notifications:update`: removing deletes the recipient, so its link stops working, and `alertService.removeEmail()` drops it from every alert of the organization). - The "Settings" button of the alert lists (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). + The "Settings" button of the organization alert list opens a modal (`AlertSettingsPanel`) with + three tabs (**Integraciones** / **Canales** / **Email externo**; without JavaScript all sections + stack vertically): (1) **Integraciones** shows Slack (status: `available` with "Add to Slack" + button if credentials set, `disabled` if only `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` or only + `SLACK_SIGNING_SECRET`, `coming_soon` for Google Chat) and an install button for the `/gitops` + command when `SLACK_SIGNING_SECRET` is set; (2) **Canales** (organization-only, `NotificationChannelEntity`), + created in a separate modal, with options to test, rotate secret and delete; (3) **Email externo** + (allowed domains and external recipient management). Forms post to `/org//settings/alerts/settings` + actions. Projects have no notification settings of their own (#119): the project alert list shows + a "?" icon (instead of a "Settings" button) whose tooltip says they are managed from the + organization, and `/org//projects//settings/alerts/settings` redirects to the + organization's page (404 for who can't open it). Alert pages get `data.external` + (`ExternalRecipientsEditorData`), `data.channels` (channel options for the location's alerts), + and `data.configPath`. - 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`) in the composition root - (`$modules/notifications/index.ts`); today `webhook` and `slack` are, and tests use - `FakeChatTransport`. Providers with incoming webhooks on a fixed host (Slack, Google Chat) only - write a formatter: `createFixedHostChatTransport({ rule, format })` - (`chat-webhook.transport.ts`) does the URL rule, guarded fetch and `postJson`; `truncateText` - (`chat-format.ts`) is shared for provider length limits. + `notification_channels`), owned by an organization only and usable by alerts of the organization + and of all its projects. **Projects have no channels of their own (#119):** `create()` refuses a + project location (`scope: 'project_channels_unsupported'`), `listChannels()` for projects returns + the usable organization channels (calling `listUsable()`), and `purgeProjectChannels()` (from + `$modules/alerts`, run in the background at startup in `hooks.server.ts`) deletes any project + rows left from before and drops them from alerts with `alertService.removeChannels()` (an alert + left without channels falls back to email). Project alert pages show a "?" hint instead of a + settings button, and `/org//projects//settings/alerts/settings` redirects to the + organization's page (404 for who can't open it). + + `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`) + in the composition root (`$modules/notifications/index.ts`); today `webhook` and `slack` are, and + tests use `FakeChatTransport`. `canCreateType` (service option) switches a built type off for new + channels: Slack needs `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` (`slackConnectService.isConfigured()`), + otherwise it is refused (`type_disabled`) and left out of the new channel type picker; existing + Slack channels keep delivering. `availableTypes()` lists types that can be created (transport + registered and type enabled, organization-only), while `registeredTypes()` lists types with a + transport. Providers with incoming webhooks on a fixed host (Slack, Google Chat) only write a + formatter: `createFixedHostChatTransport({ rule, format })` (`chat-webhook.transport.ts`) does + the URL rule, guarded fetch and `postJson`; `truncateText` (`chat-format.ts`) is shared for + provider length limits. + + UI components (`#lib/components/notifications/`): `IntegrationsSection` (integration cards with + status and install/setup links), `ChannelForm` (create/edit modal), `ChannelList` (list with + actions), and `channel-ui.ts` (helpers for integration cards and error messages). + A `ChatTransport` implements `send()` and `validateDestination()` (sync or async), the anti-SSRF check run before saving and again before every send: `validateWebhookUrl()` for providers with a fixed host (https, no credentials, no IP literal, default port, allowed host and path), @@ -405,39 +430,40 @@ in `docs/adr/0001-event-bus-and-alerts.md`. - Add to Slack (`slackConnectService` in `$modules/notifications`, `#97`): OAuth v2 install (`SlackConnectService`, `SlackOAuthClient`) with only the `incoming-webhook` scope, so Slack asks for the workspace and channel and returns its webhook URL, saved as a normal `slack` channel (same transport, - same `SLACK_WEBHOOK_RULE`). Enabled when `SLACK_CLIENT_ID` and `SLACK_CLIENT_SECRET` are both set - (`readSlackAppConfig()`; half set counts as disabled). Picking the Slack card in the create-channel - form shows an "Add to Slack" button (`formaction` to the `connectSlack` action, `channels-page.ts`; - the enhanced submit follows the redirect with `window.location`; Enter keeps creating the manual channel) - next to the manual URL fields, and GitOps admins get a link to `/gitops-settings/slack` while it is not - configured. The action needs `:notifications:create` and a session, not an API key; it sets - the `gitops_slack_flow` cookie (`signToken`, 10 min, bound to the user, location, locale and a return - path) and redirects to Slack; `/notifications/slack/callback` (fixed: it is the app's redirect URL, - needs the same session) checks the state, exchanges the code (Basic auth), creates the channel through - `createChannel()` (permission checked again) and goes back with `?slack=connected|` - (`notifications.errors.slack_*`). Self-hosted admins create the app from `/gitops-settings/slack` - (prefilled manifest link, redirect URL, status); a hosted GitOps uses the official app's credentials - the same way. Pasting a webhook URL keeps working. A central OAuth broker for self-hosted installations + same `SLACK_WEBHOOK_RULE`). The "Add to Slack" button appears in the new channel modal when + `SLACK_CLIENT_ID` and `SLACK_CLIENT_SECRET` are both set (`readSlackAppConfig()`; half set counts + as disabled); without them only the manual webhook URL fields show and the Slack type remains + available (users can paste URLs directly). The action needs `:notifications:create` and a + session, not an API key; it sets the `gitops_slack_flow` cookie (`signToken`, 10 min, bound to the + user, location, locale and a return path) and redirects to Slack; `/notifications/slack/callback` + (fixed: it is the app's redirect URL, needs the same session) checks the state, exchanges the code + (Basic auth), creates the channel through `createChannel()` (permission checked again) and goes back + with `?slack=connected|` (`notifications.errors.slack_*`). Self-hosted admins create the app + from `/gitops-settings/slack` (prefilled manifest link, redirect URL, status); a hosted GitOps uses + the official app's credentials the same way. A central OAuth broker for self-hosted installations is not implemented. -- `/gitops` (`slackAppService` in `$modules/notifications`): the same Slack app with the `commands` - scope, enabled when `SLACK_SIGNING_SECRET` is also set (`slackConnectService.commandsEnabled()`). - An organization installs it from its channels page (`installSlack` action, OAuth with only - `commands`, flow `kind: 'install'`): `slack_workspaces` (GitDB) keeps one row per Slack team, linked - to that organization (another organization gets `slack_workspace_taken`), with the bot token - encrypted (`ChannelCipher` purpose `slack-bot-token`; only used to open forms, `views.open`). - `/api/slack/commands` and `/api/slack/interactions` have no session or API key: they verify - `X-Slack-Signature` (`verifySlackSignature`, 5 min window) on the raw body and act as the GitOps - user linked to the Slack user (`authProviders` entry `slack` = `:`, `findByExternalIdentity`), - refusing disabled users and checking `organization:notifications:create` every time. - `/gitops login` answers with a signed 10-minute link to `/notifications/slack/link` (needs a session: - `hooks.server.ts` remembers it in `gitops_return_to` and the password and Google logins come back to - it, `#lib/server/return-to`; the user must see the workspace's organization). `/gitops channel` opens a - modal (name, locale); its submission answers with a signed link to `/notifications/slack/connect` - (no session), which starts Slack's channel picker (flow `kind: 'command'`, bound to the Slack team - and user: the callback refuses another one with `slack_wrong_workspace`). `/notifications/slack/callback` - then accepts requests without a session (only `command` flows can finish without one), creates the - channel through `createChannel()` as the linked user (`runWithActor`), posts a test message and ends - on `/notifications/slack/done`. Replies use the workspace's locale (picked at install). +- `/gitops` command (`slackAppService` in `$modules/notifications`): the same Slack app with the + `commands` scope, **enabled only when both `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` and + `SLACK_SIGNING_SECRET` are set.** Without `SLACK_SIGNING_SECRET`, the Slack integration card shows + as **Desactivado**: GitOps admins see a link to `/gitops-settings/slack` to configure it, others + see a note to ask an admin. An organization installs the app from its channels page (`installSlack` + action, OAuth with only `commands`, flow `kind: 'install'`): `slack_workspaces` (GitDB) keeps one + row per Slack team, linked to that organization (another organization gets `slack_workspace_taken`), + with the bot token encrypted (`ChannelCipher` purpose `slack-bot-token`; only used to open forms, + `views.open`). `/api/slack/commands` and `/api/slack/interactions` have no session or API key: they + verify `X-Slack-Signature` (`verifySlackSignature`, 5 min window) on the raw body and act as the + GitOps user linked to the Slack user (`authProviders` entry `slack` = `:`, + `findByExternalIdentity`), refusing disabled users and checking `organization:notifications:create` + every time. `/gitops login` answers with a signed 10-minute link to `/notifications/slack/link` + (needs a session: `hooks.server.ts` remembers it in `gitops_return_to` and the password and Google + logins come back to it, `#lib/server/return-to`; the user must see the workspace's organization). + `/gitops channel` opens a modal (name, locale); its submission answers with a signed link to + `/notifications/slack/connect` (no session), which starts Slack's channel picker (flow `kind: 'command'`, + bound to the Slack team and user: the callback refuses another one with `slack_wrong_workspace`). + `/notifications/slack/callback` then accepts requests without a session (only `command` flows can + finish without one), creates the channel through `createChannel()` as the linked user (`runWithActor`), + posts a test message and ends on `/notifications/slack/done`. Replies use the workspace's locale + (picked at install). - CSRF: SvelteKit's origin check is disabled in the framework (`csrf.trustedOrigins: ['*']`) and done by `csrfGuard` in `hooks.server.ts` with the same rule (`#lib/server/csrf`), because Slack posts forms without an `Origin` header. Only `CSRF_EXEMPT_PATHS` (the two signed Slack endpoints) skip it; diff --git a/README.md b/README.md index 808167b..61b3ba6 100644 --- a/README.md +++ b/README.md @@ -189,10 +189,10 @@ 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** +Alerts can also post to chat channels and webhooks. In the organization's **Settings → Alerts**, +click **Settings** to manage its integrations (the GitOps Slack app) and its channels, which every +alert of the organization and of its projects can use; projects have no channels of their own. +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. @@ -200,7 +200,9 @@ 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 and Slack are available; Google Chat is not yet. +generic webhooks and Slack are available; Google Chat is not yet. Slack channels can only be added +once the Slack app is configured (`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`); until then the Slack +integration shows as disabled and the type is not offered. A **webhook** channel posts a versioned JSON body to any public `https` URL, signed with HMAC-SHA256 in `X-GitOps-Signature`. Its signing secret is shown once when the channel is created diff --git a/e2e/global-setup.ts b/e2e/global-setup.ts index f8739a3..7951365 100644 --- a/e2e/global-setup.ts +++ b/e2e/global-setup.ts @@ -80,6 +80,11 @@ function buildEnv(): Record { MONITORING_ALLOW_PRIVATE_TARGETS: 'true', // webhook channels are created with a URL nobody resolves; no delivery is attempted NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS: 'true', + // "Add to Slack" configured (so Slack channels can be created), `/gitops` not: the Slack + // integration shows as disabled. Nothing ever reaches Slack + SLACK_CLIENT_ID: 'e2e-slack-client', + SLACK_CLIENT_SECRET: 'e2e-slack-secret', + SLACK_SIGNING_SECRET: '', // State IaC reads the fake S3 bucket with "ambient" auth: dummy static credentials AWS_ACCESS_KEY_ID: 'e2e', AWS_SECRET_ACCESS_KEY: 'e2e', diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts index dc96d09..33d67f4 100644 --- a/e2e/specs/alerts.spec.ts +++ b/e2e/specs/alerts.spec.ts @@ -114,7 +114,8 @@ test.describe('project alerts', () => { 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(); + // channels are the organization's: a project admin has no settings to open from here + await expect(card.getByRole('link', { name: 'Configurar' })).toHaveCount(0); } const targets = wizard.getByLabel('Destinatarios'); @@ -231,6 +232,8 @@ test.describe('organization alerts', () => { await expect(dialog).toBeVisible(); await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}$`)); + // the settings open on the channels tab; domains are under "Email externo" + await dialog.getByRole('tab', { name: 'Email externo' }).click(); const domains = dialog.getByLabel('Dominios (uno por línea)'); await expect(domains).toHaveValue('example.com'); await domains.fill('example.com\npartner.com'); @@ -239,28 +242,63 @@ test.describe('organization alerts', () => { await expect(domains).toHaveValue('example.com\npartner.com'); }); - test('project admins manage the project channels, not the organization domains', async ({ + test('organization admins see the integrations, Slack disabled without its configuration', async ({ page, loginAs, }) => { - await loginAs('projectAdmin'); - await page.goto(alertsUrl); + 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 dialog.getByRole('tab', { name: 'Integraciones' }).click(); + + // the e2e server has no SLACK_SIGNING_SECRET: /gitops can't work, nothing can be installed + const slack = dialog.locator('[data-testid="app-card"][data-app="slack"]'); + await expect(slack).toHaveAttribute('data-status', 'disabled'); + await expect(slack.getByTestId('app-status')).toHaveText('Desactivado'); + await expect(slack.getByTestId('app-install')).toHaveCount(0); + // not a GitOps admin: no link to the installation settings, ask one instead + await expect(slack.getByTestId('app-setup')).toHaveCount(0); + await expect(slack.getByTestId('app-disabled-hint')).toContainText( + 'Pide a un administrador de GitOps', + ); + const googleChat = dialog.locator('[data-testid="app-card"][data-app="google-chat"]'); + await expect(googleChat.getByTestId('app-status')).toHaveText('Próximamente'); + }); + + test('organization admins manage the channels every project of the organization uses', 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 dialog.getByRole('tab', { name: /Canales/ }).click(); const channels = dialog.getByTestId('notification-channels'); await expect(channels).toBeVisible(); - await expect(dialog.getByLabel('Dominios (uno por línea)')).toHaveCount(0); + + // "New channel" opens its own modal + const newChannel = async () => { + await channels.getByTestId('channel-new').click(); + const modal = page.getByRole('dialog', { name: 'Nuevo canal' }); + await expect(modal).toBeVisible(); + return modal; + }; // a webhook channel shows its signing secret once, and rotating it asks first - const types = channels.getByTestId('channel-type-cards'); + let modal = await newChannel(); + const types = modal.getByTestId('channel-type-cards'); await expect(types.getByRole('radio', { name: /Slack/ })).toBeEnabled(); await expect(types.getByRole('radio', { name: /Google Chat/ })).toBeDisabled(); await expect(types.locator('[data-channel-type="google-chat"]')).toContainText('Próximamente'); await expect(types.getByRole('radio', { name: /Webhook/ })).toBeChecked(); - await channels.getByLabel('Nombre', { exact: true }).fill('SIEM e2e'); - await channels.getByLabel('URL del webhook').fill('https://receiver.example.com/gitops'); - await channels.getByRole('button', { name: 'Añadir canal' }).click(); + await modal.getByLabel('Nombre', { exact: true }).fill('SIEM e2e'); + await modal.getByLabel('URL del webhook').fill('https://receiver.example.com/gitops'); + await modal.getByTestId('channel-create-submit').click(); + await expect(modal).toBeHidden(); const secret = page.getByRole('dialog', { name: 'Secreto de firma' }); await expect(secret.getByTestId('channel-secret')).toHaveText(/^whsec_[0-9a-f]{64}$/); @@ -280,16 +318,20 @@ test.describe('organization alerts', () => { await secret.getByTestId('channel-secret-done').click(); await expect(row).toContainText('El secreto anterior es válido hasta'); - await types.locator('[data-channel-type="slack"]').click(); - await expect(types.getByRole('radio', { name: /Slack/ })).toBeChecked(); + // Slack is offered because "Add to Slack" is configured; the webhook URL can still be pasted for (const [name, hook, locale, language] of [ ['#seguridad-e2e', 'https://hooks.slack.com/services/T000/B001/aaaa', 'es', 'Español'], ['#incidencias-e2e', 'https://hooks.slack.com/services/T000/B002/bbbb', 'en', 'Inglés'], ]) { - await channels.getByLabel('Nombre', { exact: true }).fill(name); - await channels.getByLabel('URL del webhook').fill(hook); - await channels.getByLabel('Idioma de los mensajes').selectOption(locale); - await channels.getByRole('button', { name: 'Añadir canal' }).click(); + modal = await newChannel(); + await modal.locator('[data-channel-type="slack"]').click(); + await expect(modal.getByRole('radio', { name: /Slack/ })).toBeChecked(); + await expect(modal.getByTestId('slack-connect-submit')).toBeVisible(); + await modal.getByLabel('Nombre', { exact: true }).fill(name); + await modal.getByLabel('URL del webhook').fill(hook); + await modal.getByLabel('Idioma de los mensajes').selectOption(locale); + await modal.getByTestId('channel-create-submit').click(); + await expect(modal).toBeHidden(); const slackRow = channels.locator('li[data-channel-id]').filter({ hasText: name }); await expect(slackRow).toContainText('Slack'); await expect(slackRow.getByTestId('channel-locale')).toHaveText(language); @@ -297,16 +339,40 @@ test.describe('organization alerts', () => { await expect(slackRow).not.toContainText(hook); } - await channels.getByLabel('Nombre', { exact: true }).fill('#otro'); - await channels + modal = await newChannel(); + await modal.locator('[data-channel-type="slack"]').click(); + await modal.getByLabel('Nombre', { exact: true }).fill('#otro'); + await modal .getByLabel('URL del webhook') .fill('https://hooks.slack.com.evil.example/services/x'); - await channels.getByRole('button', { name: 'Añadir canal' }).click(); + await modal.getByTestId('channel-create-submit').click(); await expect( - channels.getByText('Ese dominio no está permitido para este tipo de canal.'), + modal.getByText('Ese dominio no está permitido para este tipo de canal.'), ).toBeVisible(); }); + test('projects have no channel settings of their own', async ({ page, loginAs }) => { + await loginAs('projectAdmin'); + await page.goto(alertsUrl); + await page.waitForLoadState('networkidle'); + await expect(page.getByTestId('alert-settings')).toHaveCount(0); + // a "?" says where the settings are instead + const hint = page.getByTestId('alert-settings-hint'); + await expect(hint.getByRole('tooltip')).toBeHidden(); + await hint.hover(); + await expect(hint.getByRole('tooltip')).toHaveText( + 'La configuración de notificaciones (integraciones, canales y email externo) se realiza desde la organización.', + ); + // the old project settings page is gone for whoever can't open the organization's + const response = await page.goto(`${alertsUrl}/settings`); + expect(response?.status()).toBe(404); + + // an organization admin is sent to the organization's settings + await loginAs('orgAdmin'); + await page.goto(`${alertsUrl}/settings`); + await expect(page).toHaveURL(new RegExp(`${orgAlertsUrl}/settings$`)); + }); + test('an alert posts to the Slack channels picked in the wizard', async ({ page, loginAs }) => { await loginAs('projectAdmin'); await page.goto(alertsUrl); @@ -357,6 +423,9 @@ test.describe('without JavaScript', () => { 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/); + // every section shows, and the new channel form is inline + await expect(page.getByTestId('apps')).toBeVisible(); + await expect(page.getByTestId('channel-create-inline')).toBeVisible(); }); test('the editor still creates an alert through form actions', async ({ page, loginAs }) => { diff --git a/src/hooks.server.ts b/src/hooks.server.ts index 4836016..4564c18 100644 --- a/src/hooks.server.ts +++ b/src/hooks.server.ts @@ -3,7 +3,7 @@ import { sequence } from '@sveltejs/kit/hooks'; import { apiKeysService, authService, cancanService, ensureAuthReady } from '#modules/auth'; import { organizationService } from '#modules/organization'; import { projectService } from '#modules/projects'; -import { registerAlertEngine } from '#modules/alerts'; +import { purgeProjectChannels, registerAlertEngine } from '#modules/alerts'; import { registerStateIac } from '#modules/state-iac'; import { getMonitoringConfig, startMonitoring } from '#modules/monitoring'; import { @@ -36,6 +36,10 @@ const serverReady = (async () => { await ensureAuthReady(); // once per process (HMR-safe): system notifications and alerts on every published event registerAlertEngine(); + // channels are organization-wide (#119): leftover project channels go, in the background + purgeProjectChannels().catch((error) => + startupLog.error(error, '[startup] project channels could not be removed'), + ); // State IaC bindings follow the projects they point at registerStateIac(); await refreshBootstrapState(); diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts index acfc4fd..5b33810 100644 --- a/src/lib/alerts/types.ts +++ b/src/lib/alerts/types.ts @@ -80,6 +80,10 @@ type Shared = { export type AlertListData = Shared & { settings: NotificationSettingsPage | null; channelsSection: ChannelsSectionData | null; + /** + * The organization's notification settings page, opened in a modal; `null` for projects, which + * have none of their own (#119), and for who can't read them. + */ configPath: string | null; alerts: AlertRow[]; /** Organization alerts that also fire for this project (project pages only). */ diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte index 027ef62..b43918d 100644 --- a/src/lib/components/alerts/AlertList.svelte +++ b/src/lib/components/alerts/AlertList.svelte @@ -9,6 +9,7 @@ MessageSquare, Pencil, Plus, + CircleHelp, Settings, Trash2, Webhook, @@ -91,7 +92,26 @@

- {#if data.configPath} + {#if data.scope === 'project'} + + + + + + {:else if data.configPath} {#snippet icon()} {#snippet footer()} diff --git a/src/lib/components/alerts/AlertSettingsPanel.svelte b/src/lib/components/alerts/AlertSettingsPanel.svelte index 5639c23..b02663c 100644 --- a/src/lib/components/alerts/AlertSettingsPanel.svelte +++ b/src/lib/components/alerts/AlertSettingsPanel.svelte @@ -1,7 +1,14 @@ +
- {#if data} - {#if !data.mailConfigured || !data.originConfigured} + {#if mounted && tabs.length > 1} + + {/if} + + {#if slackOutcome} + + + {/if} -
-
- - - -
-

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

-

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

-
-
+ {#if channels} +
+ +
+
+ +
+ {/if} + + {#if data} +
+ {#if !data.mailConfigured || !data.originConfigured} +

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

+ {/if} -
-
- - -

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

- {#if domainError || formDomainError} -
+
+ + + +
+

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

+

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

- {:else if form?.saved} -

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

+
+ + +
+ + +

+ {$_('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.canEditDomains} - - {:else} -

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

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

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

-

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

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

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

+

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

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

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

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

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

- {/if} + {#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)} - - - - - - + {#if data.recipients.length === 0} +

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

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

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

- {/if} - - {#if channels} - + {/if} + + {/if} +
{/if} diff --git a/src/lib/components/notifications/ChannelForm.svelte b/src/lib/components/notifications/ChannelForm.svelte new file mode 100644 index 0000000..d7dc57a --- /dev/null +++ b/src/lib/components/notifications/ChannelForm.svelte @@ -0,0 +1,291 @@ + + + +{#snippet localeField(id: string)} +
+ + + {#if errors.locale} +

{errorText('locale')}

+ {:else} +

{$_('notifications.channels.localeHelp')}

+ {/if} +
+{/snippet} + +{#if available.length === 0} +

+ {$_('notifications.channels.noTypes')} +

+{:else} +
+ +
+ {$_('notifications.channels.type')} +
+ {#each data.channelTypes as option (option.type)} + {@const Icon = typeIcon(option.type)} + {@const enabled = option.status === 'available'} + {@const on = enabled && selectedType === option.type} + + {/each} +
+ {#if errors.type}

+ {errorText('type')} +

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

{errorText('scope')}

{/if} +
+ + + {#if slackConnectMode} + + +
+
+

+ {$_('notifications.channels.slackConnectTitle')} +

+

+ {$_('notifications.channels.slackConnectDescription')} +

+
+ {@render localeField(`${formId}-locale`)} +
+ +
+
+

+ + {$_('notifications.channels.slackManual')} + +

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

{errorText('name')}

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

{errorText('destination')}

+ {:else if selectedType === 'webhook'} +

{$_('notifications.channels.webhookHelp')}

+ {:else if selectedType === 'slack'} +

{$_('notifications.channels.slackHelp')}

+ {/if} +
+ {#if !slackConnectMode} + {@render localeField(`${formId}-locale`)} + {/if} + + {#if variant === 'inline'} + + {/if} +
+{/if} diff --git a/src/lib/components/notifications/ChannelList.svelte b/src/lib/components/notifications/ChannelList.svelte new file mode 100644 index 0000000..5c7d892 --- /dev/null +++ b/src/lib/components/notifications/ChannelList.svelte @@ -0,0 +1,453 @@ + + + +
+ {#if form?.channelTest} +

+ {form.channelTest.sent + ? $_('notifications.channels.testSent') + : $_('notifications.channels.testFailed', { + values: { reason: form.channelTest.error ?? '—' }, + })} +

+ {:else if form?.channelError && form.channelForm !== 'create' && form.channelForm !== 'slack-app' && !form.channelErrors} + + {/if} + + {#if data.channels.length === 0} +

+ {$_('notifications.channels.empty')} +

+ {:else} +
    + {#each data.channels as channel (channel.id)} + {@const Icon = typeIcon(channel.type)} +
  • + +
    +

    + {channel.name} + + {$_(`notifications.channels.types.${channel.type}`)} + + + {$_(`notifications.channels.locales.${channel.locale}`)} + + {#if !channel.enabled} + + {$_('notifications.channels.disabled')} + + {/if} + {#if channel.signed} + + {$_('notifications.channels.signed')} + + {/if} + {#if !channel.available} + + {$_('notifications.channels.unavailable')} + + {/if} +

    +

    + {channel.destinationMasked} +

    +

    + {$_('notifications.channels.lastDelivery', { + values: { date: formatDate(channel.lastDeliveryAt) }, + })} +

    + {#if channel.lastError} +

    + {$_('notifications.channels.lastError', { values: { error: channel.lastError } })} +

    + {/if} + {#if !channel.enabled && channel.disabledReason === 'failures'} +

    + {$_('notifications.channels.autoDisabled', { + values: { failures: channel.consecutiveFailures }, + })} +

    + {/if} + {#if channel.rotationEndsAt} +

    + {$_('notifications.channels.rotationEndsAt', { + values: { date: formatDate(channel.rotationEndsAt) }, + })} +

    + {/if} +
    + +
    + {#if data.canUpdate} +
    + + +
    +
    + + + +
    + {#if channel.signed && channel.available} +
    + + +
    + {/if} + + {/if} + {#if data.canDelete} +
    + + +
    + {/if} +
    +
  • + {/each} +
+ {/if} +
+ +{#if data.canUpdate} + +
+ +
+ + + {#if editErrors.name}

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

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

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

{/if} +
+
+ + {#key editTarget?.id} + + {/key} + {#if editErrors.locale}

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

{/if} +
+
+ {#snippet footer()} + + + {/snippet} +
+{/if} + +{#if data.canDelete} + + {#snippet icon()} + + {/snippet} +
+ +
+ {#snippet footer()} + + + {/snippet} +
+{/if} + +{#if data.canUpdate} + + {#snippet icon()} + + {/snippet} +
+ +
+ {#snippet footer()} + + + {/snippet} +
+{/if} diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte index 7826286..820d583 100644 --- a/src/lib/components/notifications/ChannelsSection.svelte +++ b/src/lib/components/notifications/ChannelsSection.svelte @@ -1,70 +1,35 @@ +
-
-

- - {$_('notifications.channels.title')} -

-

- {data.scope === 'project' - ? $_('notifications.channels.descriptionProject') - : $_('notifications.channels.descriptionOrganization')} -

+
+
+

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

+

+ {$_('notifications.channels.descriptionOrganization')} +

+
+ {#if data.canCreate && mounted} + + {/if}

{/if} - {#if slackOutcome} - -

- {slackOutcome === 'connected' - ? $_('notifications.channels.slackConnected') - : slackOutcome === 'installed' - ? $_('notifications.channels.slackAppInstalledToast') - : errorMessage(slackOutcome)} -

- - {/if} - - {#if data.apps} -
-
-

{$_('notifications.apps.title')}

-

{$_('notifications.apps.description')}

-
-
- {#each data.apps as app (app.provider)} - {@const Icon = typeIcons[app.provider] ?? Webhook} - {@const installed = app.installations.length > 0} - {@const installAction = APP_INSTALL_ACTIONS[app.provider]} -
- - - {$_(`notifications.channels.types.${app.provider}`)} - - - {$_(`notifications.apps.descriptions.${app.provider}`)} - - {#if app.comingSoon} - {$_('notifications.channels.comingSoon')} - {:else if installed} - {$_('notifications.apps.installed')} - {:else} - {$_('notifications.apps.notInstalled')} - {/if} - - {#if installed} - -
    - {#each app.installations as installation (installation.id)} -
  • - - - {$_('notifications.apps.connectedTo', { - values: { name: installation.name }, - })} - - {#if app.canRemove && APP_REMOVE_ACTIONS[app.provider]} - -
    - - -
    - {/if} -
  • - {/each} -
- {:else if !app.comingSoon} - {#if app.canInstall && installAction} -
- - - -
- {:else if app.setupPath} -

- {$_('notifications.apps.setupHint')} - {$_('notifications.channels.slackSetupLink')} -

- {/if} - {/if} -
- {/each} -
-
- {/if} - - {#if form?.channelTest} -

- {form.channelTest.sent - ? $_('notifications.channels.testSent') - : $_('notifications.channels.testFailed', { - values: { reason: form.channelTest.error ?? '—' }, - })} -

- {:else if form?.channelError && form.channelForm !== 'create' && !form.channelErrors} - - {/if} - - {#if data.channels.length === 0} -

- {$_('notifications.channels.empty')} -

- {:else} -
    - {#each data.channels as channel (channel.id)} - {@const Icon = typeIcons[channel.type] ?? Webhook} -
  • - -
    -

    - {channel.name} - - {$_(`notifications.channels.types.${channel.type}`)} - - - {$_(`notifications.channels.locales.${channel.locale}`)} - - {#if !channel.enabled} - - {$_('notifications.channels.disabled')} - - {/if} - {#if channel.signed} - - {$_('notifications.channels.signed')} - - {/if} - {#if !channel.available} - - {$_('notifications.channels.unavailable')} - - {/if} -

    -

    - {channel.destinationMasked} -

    -

    - {$_('notifications.channels.lastDelivery', { - values: { date: formatDate(channel.lastDeliveryAt) }, - })} -

    - {#if channel.lastError} -

    - {$_('notifications.channels.lastError', { values: { error: channel.lastError } })} -

    - {/if} - {#if !channel.enabled && channel.disabledReason === 'failures'} -

    - {$_('notifications.channels.autoDisabled', { - values: { failures: channel.consecutiveFailures }, - })} -

    - {/if} - {#if channel.rotationEndsAt} -

    - {$_('notifications.channels.rotationEndsAt', { - values: { date: formatDate(channel.rotationEndsAt) }, - })} -

    - {/if} -
    + -
    - {#if data.canUpdate} -
    - - -
    -
    - - - -
    - {#if channel.signed && channel.available} -
    - - -
    - {/if} - - {/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} -
+ {#if data.canCreate && !mounted} +

- {$_('notifications.channels.create')} + {$_('notifications.channels.new')}

- {#if data.availableTypes.length === 0} -

- {$_('notifications.channels.noTypes')} -

- {:else} - {@const errors = { ...formCreateErrors, ...createErrors }} -
- -
- {$_('notifications.channels.type')} -
- {#each CHANNEL_TYPES as type (type)} - {@const Icon = typeIcons[type] ?? Webhook} - {@const available = data.availableTypes.includes(type)} - {@const on = available && selectedType === type} - - {/each} -
- {#if errors.type}

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

{/if} -
- - {#if slackConnectMode} - - -
-
-

- {$_('notifications.channels.slackConnectTitle')} -

-

- {$_('notifications.channels.slackConnectDescription')} -

-
-
- - - {#if errors.locale} -

{errorText(errors, 'locale')}

- {:else} -

- {$_('notifications.channels.localeHelp')} -

- {/if} -
-
- -
-
-

- - {$_('notifications.channels.slackManual')} - -

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

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

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

{errorText(errors, 'destination')}

- {:else if selectedType === 'webhook'} -

{$_('notifications.channels.webhookHelp')}

- {:else if selectedType === 'slack'} -

{$_('notifications.channels.slackHelp')}

- {#if data.slackSetupPath} -

- {$_('notifications.channels.slackSetupHint')} - {$_('notifications.channels.slackSetupLink')} -

- {/if} - {/if} -
- {#if !slackConnectMode} -
- - - {#if errors.locale} -

{errorText(errors, 'locale')}

- {:else} -

- {$_('notifications.channels.localeHelp')} -

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

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

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

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

{/if} -
-
- - {#key editTarget?.id} - - {/key} - {#if editErrors.locale}

- {errorText(editErrors, 'locale')} -

{/if} -
-
- {#snippet footer()} - - - {/snippet} -
-{/if} - -{#if data.canDelete} - - {#snippet icon()} - - {/snippet} -
- -
- {#snippet footer()} - - - {/snippet} -
-{/if} - -{#if data.apps?.some((app) => app.canRemove)} +{#if data.canCreate && mounted} {#snippet icon()} - {/snippet} -
- -
- {#snippet footer()} - - - {/snippet} -
-{/if} - -{#if data.canUpdate} - - {#snippet icon()} - {/snippet} -
- -
+ {#snippet footer()} - - + {#if data.availableTypes.length > 0} + + {/if} {/snippet}
{/if} diff --git a/src/lib/components/notifications/IntegrationsSection.svelte b/src/lib/components/notifications/IntegrationsSection.svelte new file mode 100644 index 0000000..625a214 --- /dev/null +++ b/src/lib/components/notifications/IntegrationsSection.svelte @@ -0,0 +1,243 @@ + + + +
+
+

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

+

{$_('notifications.apps.description')}

+
+ +
+ {#each apps as app (app.provider)} + {@const Icon = typeIcon(app.provider)} + {@const badge = STATUS_BADGES[app.status]} + {@const installAction = APP_INSTALL_ACTIONS[app.provider]} + {@const removeFormAction = APP_REMOVE_ACTIONS[app.provider]} + {@const off = app.status === 'disabled' || app.status === 'coming_soon'} +
+
+ +
+

+ {$_(`notifications.channels.types.${app.provider}`)} +

+

+ {$_(`notifications.apps.descriptions.${app.provider}`)} +

+
+ + {#if app.status === 'disabled'}{/if} + {$_(badge.key)} + +
+ + {#if app.installations.length > 0} +
    + {#each app.installations as installation (installation.id)} +
  • + {#if app.status === 'disabled'} + + {:else} + + {/if} + + {$_( + app.status === 'disabled' + ? 'notifications.apps.connectedToInactive' + : 'notifications.apps.connectedTo', + { values: { name: installation.name } }, + )} + + {#if app.canRemove && removeFormAction} + +
    + + +
    + {/if} +
  • + {/each} +
+ {/if} + + {#if app.status === 'available' && app.canInstall && installAction} +
+ + + +
+ {:else if app.status === 'disabled'} +

+ {#if app.setupPath} + {$_('notifications.apps.setupHint')} + {$_('notifications.channels.slackSetupLink')} + {:else} + {$_('notifications.apps.askAdmin')} + {/if} +

+ {/if} +
+ {/each} +
+
+ +{#if apps.some((app) => app.canRemove)} + + {#snippet icon()} + + {/snippet} +
+ +
+ {#snippet footer()} + + + {/snippet} +
+{/if} diff --git a/src/lib/components/notifications/channel-ui.ts b/src/lib/components/notifications/channel-ui.ts new file mode 100644 index 0000000..b888e2b --- /dev/null +++ b/src/lib/components/notifications/channel-ui.ts @@ -0,0 +1,51 @@ +import { Hash, MessageSquare, Webhook } from '@lucide/svelte'; +import type { AppProvider } from '#lib/notifications/types'; + +/** Icon of each channel type and integration provider. */ +export const typeIcons: Record = { + slack: Hash, + 'google-chat': MessageSquare, + webhook: Webhook, +}; + +export function typeIcon(type: string): typeof Hash { + return typeIcons[type] ?? Webhook; +} + +/** Description of each type in the "new channel" picker (i18n keys). */ +export const typeDescriptions: Record = { + webhook: 'alerts.wizard.webhookDescription', + slack: 'alerts.wizard.slackDescription', + 'google-chat': 'alerts.wizard.googleChatDescription', +}; + +/** Form actions of each integration (`channels-page.ts`); `null` while the provider has none. */ +export const APP_INSTALL_ACTIONS: Record = { + slack: 'installSlack', + 'google-chat': null, +}; +export const APP_REMOVE_ACTIONS: Record = { + slack: 'removeSlackWorkspace', + 'google-chat': null, +}; + +/** `notifications.errors.`, or the generic failure when the code has no translation. */ +export function errorMessage(translate: (key: string) => string, code: string | undefined) { + const key = `notifications.errors.${code ?? ''}`; + const text = code ? translate(key) : key; + return text === key ? translate('alerts.wizard.failed') : text; +} + +export function formatDate(value: string | null) { + return value ? new Date(value).toLocaleString() : '—'; +} + +/** + * `?slack=` after a Slack OAuth flow (`/notifications/slack/callback`): which settings + * tab it belongs to. Installing the app is an integration; everything else creates a channel. + */ +export function slackOutcomeTab(outcome: string): 'integrations' | 'channels' { + return outcome === 'installed' || outcome === 'slack_workspace_taken' + ? 'integrations' + : 'channels'; +} diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json index c50ccc4..4b66061 100644 --- a/src/lib/i18n/locales/en.json +++ b/src/lib/i18n/locales/en.json @@ -1876,7 +1876,9 @@ "deleted": "Alert deleted", "deleteTitle": "Delete the alert?", "channelsColumn": "Destinations", - "settings": "Settings" + "settings": "Settings", + "settingsInOrganization": "Notification settings (integrations, channels and external email) are managed from the organization.", + "settingsHelp": "Notification settings" }, "editor": { "newTitle": "New alert", @@ -2212,7 +2214,7 @@ }, "settings": { "title": "Alert settings", - "description": "Allowed domains and external recipients: how the organization's alerts leave GitOps.", + "description": "Integrations, channels and external recipients: how the organization's alerts leave GitOps.", "mailNotConfigured": "SMTP is not configured: no confirmation emails or alerts will be sent.", "originNotConfigured": "ORIGIN is not set: confirmation and unsubscribe links can't be built, so external recipients will not get anything.", "domainsTitle": "Allowed domains for external emails", @@ -2239,9 +2241,11 @@ "removeDescription": "{email} hasn't confirmed yet. Its confirmation link will stop working and it will be removed from every alert of the organization.", "removed": "{email} removed", "projectDescription": "Chat channels and webhooks this project's alerts can use.", - "descriptionProject": "This project's chat channels and webhooks.", - "organizationDomains": "Allowed domains and external recipients are managed in the organization.", - "organizationDomainsLink": "Open organization settings" + "tabs": { + "integrations": "Integrations", + "channels": "Channels", + "external": "External email" + } }, "errors": { "invalid": "The value is not valid.", @@ -2273,7 +2277,9 @@ "slack_exchange_failed": "Slack did not complete the connection. Try again.", "slack_no_webhook": "Slack did not return a channel webhook: the Slack app needs the incoming-webhook scope.", "slack_wrong_workspace": "The connection was finished in another workspace or by another Slack user. Use the account that typed /gitops channel.", - "slack_workspace_taken": "This Slack workspace is already connected to another GitOps organization." + "slack_workspace_taken": "This Slack workspace is already connected to another GitOps organization.", + "type_disabled": "This channel type is disabled in this installation.", + "project_channels_unsupported": "Channels are set up in the organization; project alerts use their organization's." }, "link": { "invalid": "This link is not valid or has already been used.", @@ -2305,8 +2311,7 @@ }, "channels": { "title": "Channels", - "descriptionOrganization": "Chat channels and webhooks the alerts of the organization and its projects can post to.", - "descriptionProject": "Channels only this project's alerts can use.", + "descriptionOrganization": "Destinations the alerts of the organization and all its projects post to. Projects have no channels of their own: they use these.", "privacyNotice": "A channel is read by people who may have no GitOps account or permissions. The channel URL is stored encrypted and never shown in full again.", "empty": "No channels yet.", "types": { @@ -2329,8 +2334,6 @@ "name": "Name", "newDestination": "New URL (empty keeps the current one)", "save": "Save", - "inheritedTitle": "Organization channels", - "inheritedDescription": "This project's alerts can also use these channels. They are managed from the organization settings.", "create": "Add channel", "noTypes": "No channel type is available yet.", "type": "Type", @@ -2375,13 +2378,14 @@ "slackConnect": "Add to Slack", "slackConnected": "Slack channel added", "slackManual": "or paste an Incoming Webhook URL", - "slackSetupHint": "Add to Slack (pick the channel in Slack, no URL to copy) is not set up yet.", "slackSetupLink": "Set it up", "slackAppRemove": "Disconnect", "slackAppRemoveTitle": "Disconnect {team}?", "slackAppRemoveConfirm": "/gitops stops working in that workspace until it is installed again. Channels already connected keep posting; to revoke them, remove the app in Slack.", "slackAppInstalledToast": "Slack app installed", - "slackAppRemovedToast": "Workspace disconnected" + "slackAppRemovedToast": "Workspace disconnected", + "new": "New channel", + "newDescription": "A destination the alerts of the organization and all its projects can post to." }, "slackApp": { "notInstalled": "This Slack workspace is not connected to GitOps. An organization admin has to click *Install in Slack* in GitOps (Settings → Alerts → Settings → Channels).", @@ -2443,18 +2447,21 @@ "back": "Back to Slack" }, "apps": { - "title": "Apps", - "description": "Integrations installed in the organization. A connected app lets people manage channels from the tool itself.", + "title": "Integrations", + "description": "Connections between the organization and chat tools. A connected integration lets people manage channels from the tool itself.", "installed": "Connected", "notInstalled": "Not installed", "connectedTo": "Connected to {name}", "install": "Install", "remove": "Disconnect", - "setupHint": "The app is not set up in this installation yet.", + "setupHint": "The integration is not set up in this installation.", "descriptions": { "slack": "Connect channels from Slack with /gitops login and /gitops channel.", "google-chat": "Connect Google Chat spaces to alerts." - } + }, + "disabled": "Disabled", + "askAdmin": "It is not set up in this installation. Ask a GitOps administrator to set it up.", + "connectedToInactive": "{name} (inactive until it is set up)" } }, "stateIac": { diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json index 92c84b7..20607ae 100644 --- a/src/lib/i18n/locales/es.json +++ b/src/lib/i18n/locales/es.json @@ -1876,7 +1876,9 @@ "deleted": "Alerta eliminada", "deleteTitle": "¿Borrar la alerta?", "channelsColumn": "Destinos", - "settings": "Configuración" + "settings": "Configuración", + "settingsInOrganization": "La configuración de notificaciones (integraciones, canales y email externo) se realiza desde la organización.", + "settingsHelp": "Configuración de notificaciones" }, "editor": { "newTitle": "Nueva alerta", @@ -2212,7 +2214,7 @@ }, "settings": { "title": "Configuración de alertas", - "description": "Dominios permitidos y destinatarios externos: cómo salen las alertas de la organización fuera de GitOps.", + "description": "Integraciones, canales y destinatarios externos: cómo salen las alertas de la organización fuera de GitOps.", "mailNotConfigured": "El SMTP no está configurado: no se enviarán emails de confirmación ni alertas.", "originNotConfigured": "ORIGIN no está configurado: no se pueden generar los enlaces de confirmación y de baja, así que los destinatarios externos no recibirán nada.", "domainsTitle": "Dominios permitidos para emails externos", @@ -2239,9 +2241,11 @@ "removeDescription": "{email} todavía no ha confirmado. Se anulará su enlace de confirmación y se quitará de todas las alertas de la organización.", "removed": "{email} quitado", "projectDescription": "Canales de chat y webhooks que pueden usar las alertas de este proyecto.", - "descriptionProject": "Canales de chat y webhooks de este proyecto.", - "organizationDomains": "Los dominios permitidos y los destinatarios externos se gestionan en la organización.", - "organizationDomainsLink": "Abrir configuración de la organización" + "tabs": { + "integrations": "Integraciones", + "channels": "Canales", + "external": "Email externo" + } }, "errors": { "invalid": "El valor no es válido.", @@ -2273,7 +2277,9 @@ "slack_exchange_failed": "Slack no completó la conexión. Vuelve a intentarlo.", "slack_no_webhook": "Slack no devolvió el webhook del canal: la app de Slack necesita el scope incoming-webhook.", "slack_wrong_workspace": "La conexión se completó en otro workspace o con otro usuario de Slack. Hazlo con la cuenta que escribió /gitops channel.", - "slack_workspace_taken": "Este workspace de Slack ya está conectado a otra organización de GitOps." + "slack_workspace_taken": "Este workspace de Slack ya está conectado a otra organización de GitOps.", + "type_disabled": "Este tipo de canal está desactivado en esta instalación.", + "project_channels_unsupported": "Los canales se configuran en la organización; las alertas de los proyectos usan los de su organización." }, "link": { "invalid": "Este enlace no es válido o ya se ha usado.", @@ -2305,8 +2311,7 @@ }, "channels": { "title": "Canales", - "descriptionOrganization": "Canales de chat y webhooks donde las alertas de la organización y de sus proyectos pueden publicar.", - "descriptionProject": "Canales que solo pueden usar las alertas de este proyecto.", + "descriptionOrganization": "Destinos donde publican las alertas de la organización y de todos sus proyectos. Los proyectos no tienen canales propios: usan estos.", "privacyNotice": "Un canal lo lee gente que puede no tener cuenta ni permisos en GitOps. La URL del canal se guarda cifrada y nunca se vuelve a mostrar completa.", "empty": "Todavía no hay canales.", "types": { @@ -2329,8 +2334,6 @@ "name": "Nombre", "newDestination": "Nueva URL (vacío para mantener la actual)", "save": "Guardar", - "inheritedTitle": "Canales de la organización", - "inheritedDescription": "Las alertas de este proyecto también pueden usar estos canales. Se gestionan desde los ajustes de la organización.", "create": "Añadir canal", "noTypes": "Todavía no hay ningún tipo de canal disponible.", "type": "Tipo", @@ -2375,13 +2378,14 @@ "slackConnect": "Añadir a Slack", "slackConnected": "Canal de Slack añadido", "slackManual": "o pega una URL de Incoming Webhook", - "slackSetupHint": "Añadir a Slack (elegir el canal en Slack, sin copiar URLs) aún no está configurado.", "slackSetupLink": "Configurarlo", "slackAppRemove": "Desconectar", "slackAppRemoveTitle": "¿Desconectar {team}?", "slackAppRemoveConfirm": "/gitops dejará de funcionar en ese workspace hasta que se instale de nuevo. Los canales ya conectados siguen publicando; para revocarlos, quita la app en Slack.", "slackAppInstalledToast": "App de Slack instalada", - "slackAppRemovedToast": "Workspace desconectado" + "slackAppRemovedToast": "Workspace desconectado", + "new": "Nuevo canal", + "newDescription": "Un destino donde pueden publicar las alertas de la organización y de todos sus proyectos." }, "slackApp": { "notInstalled": "Este workspace de Slack no está conectado a GitOps. Un administrador de la organización tiene que pulsar *Instalar en Slack* en GitOps (Ajustes → Alertas → Ajustes → Canales).", @@ -2443,18 +2447,21 @@ "back": "Volver a Slack" }, "apps": { - "title": "Apps", - "description": "Integraciones instaladas en la organización. Una app conectada permite gestionar canales desde la propia herramienta.", + "title": "Integraciones", + "description": "Conexiones de la organización con herramientas de chat. Con una integración conectada se pueden gestionar canales desde la propia herramienta.", "installed": "Conectada", "notInstalled": "No instalada", "connectedTo": "Conectada a {name}", "install": "Instalar", "remove": "Desconectar", - "setupHint": "La app aún no está configurada en esta instalación.", + "setupHint": "La integración no está configurada en esta instalación.", "descriptions": { "slack": "Conecta canales desde Slack con /gitops login y /gitops channel.", "google-chat": "Conecta espacios de Google Chat a las alertas." - } + }, + "disabled": "Desactivado", + "askAdmin": "No está configurada en esta instalación. Pide a un administrador de GitOps que la configure.", + "connectedToInactive": "{name} (inactivo hasta que se configure)" } }, "stateIac": { diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts index 6490074..cdc3d15 100644 --- a/src/lib/notifications/types.ts +++ b/src/lib/notifications/types.ts @@ -42,40 +42,48 @@ export type ChannelView = { rotationEndsAt: string | null; }; +/** + * A type in the "new channel" picker: `available` can be created now, `coming_soon` is not built + * yet. Types that are built but switched off (Slack without its app configured) are left out. + */ +export type ChannelTypeOption = { type: string; status: 'available' | 'coming_soon' }; + +/** The notification settings of an organization: its integrations and its channels. */ export type ChannelsSectionData = { - scope: 'organization' | 'project'; channels: ChannelView[]; - inherited: ChannelView[]; + /** Types that can be created now. */ availableTypes: string[]; + /** What the "new channel" picker offers, in display order. */ + channelTypes: ChannelTypeOption[]; canCreate: boolean; canUpdate: boolean; canDelete: boolean; /** "Add to Slack" is available (Slack app configured and the caller can create channels). */ slackConnect: boolean; - /** Where a GitOps admin sets up "Add to Slack" while it is not configured; `null` otherwise. */ - slackSetupPath: string | null; - /** - * Apps installed in the organization (the GitOps Slack app and, later, other providers): one card - * each. `null` on project pages: apps belong to organizations. - */ - apps: AppCardData[] | null; + /** Integrations with chat providers (the GitOps Slack app and, later, others): one card each. */ + apps: AppCardData[]; }; -/** Providers with an app card; the ones without an implementation show as coming soon. */ +/** Providers with an integration card; the ones without an implementation show as coming soon. */ export const APP_PROVIDERS = ['slack', 'google-chat'] as const; export type AppProvider = (typeof APP_PROVIDERS)[number]; +/** + * - `installed`: connected to at least one workspace; + * - `available`: configured, not connected yet; + * - `disabled`: the installation lacks its configuration (`SLACK_*` variables); + * - `coming_soon`: not built yet. + */ +export type AppStatus = 'installed' | 'available' | 'disabled' | 'coming_soon'; + export type AppCardData = { provider: AppProvider; - /** Not built yet: the card only says "coming soon". */ - comingSoon: boolean; - /** The installation has the app configured (credentials set by a GitOps admin). */ - configured: boolean; + status: AppStatus; canInstall: boolean; canRemove: boolean; - /** Where it is installed (Slack workspaces); empty = not installed. */ + /** Where it is installed (Slack workspaces); still listed, and removable, while disabled. */ installations: { id: string; name: string }[]; - /** Shown to GitOps admins while the app is not configured. */ + /** Shown to GitOps admins while the integration is disabled; `null` for everyone else. */ setupPath: string | null; }; diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts index 06529f4..c2eda06 100644 --- a/src/lib/server/alerts/page.ts +++ b/src/lib/server/alerts/page.ts @@ -211,7 +211,11 @@ export async function loadAlertList( external, settings, channelsSection, - configPath: settings || channelsSection ? `${context.basePath}/settings` : null, + // projects have no notification settings of their own: they use the organization's (#119) + configPath: + location.scope === 'organization' && (settings || channelsSection) + ? `${context.basePath}/settings` + : null, canCreate: allowed.canCreate, canUpdate: allowed.canUpdate, canDelete: allowed.canDelete, diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts index 6bf8ce6..0fef9f9 100644 --- a/src/lib/server/notifications/channels-page.ts +++ b/src/lib/server/notifications/channels-page.ts @@ -4,12 +4,14 @@ import { SLACK_FLOW_COOKIE, SLACK_FLOW_COOKIE_PATH, SLACK_FLOW_TTL_MS, + notificationChannelService, slackAppService, slackConnectService, type ChannelLocation, } from '#modules/notifications'; import type { AlertLocals } from '#lib/server/alerts/access'; -import type { AppCardData, ChannelsSectionData } from '#lib/notifications/types'; +import { CHAT_CHANNEL_TYPES } from '#lib/server/infra/notifications/chat-types'; +import type { AppCardData, ChannelTypeOption, ChannelsSectionData } from '#lib/notifications/types'; import { canManageChannels, createChannel, @@ -23,11 +25,17 @@ import { updateChannel, } from './channels'; -/** The channels section of a notifications page; `null` without `:notifications:read`. */ +const SLACK_SETUP_PATH = '/gitops-settings/slack'; + +/** + * The integrations and channels of an organization's notification settings; `null` without + * `organization:notifications:read`, and for projects: channels belong to organizations (#119). + */ export async function loadChannelsSection( locals: AlertLocals, location: ChannelLocation, ): Promise { + if (location.scope !== 'organization') return null; const listed = await listChannels(locals, location); if (!listed.ok) return null; const [canCreate, canUpdate, canDelete] = await Promise.all([ @@ -35,68 +43,73 @@ export async function loadChannelsSection( canManageChannels(locals, location, 'update'), canManageChannels(locals, location, 'delete'), ]); - const slackAvailable = listed.data.availableTypes.includes('slack'); - const slackConfigured = slackConnectService.isConfigured(); + const { availableTypes } = listed.data; const isAdmin = !locals.apiKey && cancanService.canAccessAdminArea( locals.user as Parameters[0], ); - // apps belong to organizations: projects use the organization's channels - const apps: AppCardData[] | null = - location.scope === 'organization' - ? [ - await slackAppCard(locals, location.organizationId, { - canCreate, - canDelete, - isAdmin, - available: slackAvailable, - }), - { - provider: 'google-chat', - comingSoon: true, - configured: false, - canInstall: false, - canRemove: false, - installations: [], - setupPath: null, - }, - ] - : null; return { - ...listed.data, - scope: location.scope, - apps, + channels: listed.data.channels, + availableTypes, + channelTypes: channelTypeOptions(availableTypes), + apps: [ + await slackAppCard(locals, location.organizationId, { canCreate, canDelete, isAdmin }), + { + provider: 'google-chat', + status: 'coming_soon', + canInstall: false, + canRemove: false, + installations: [], + setupPath: null, + }, + ], canCreate, canUpdate, canDelete, - // "Add to Slack" only when the app is configured and Slack channels can be created - slackConnect: canCreate && slackAvailable && slackConfigured, - // without the app, GitOps admins get a link to set it up from the Slack card - slackSetupPath: - canCreate && slackAvailable && !slackConfigured && isAdmin ? '/gitops-settings/slack' : null, + // Slack channels can only be created with the Slack app configured: "Add to Slack" is there + slackConnect: canCreate && availableTypes.includes('slack'), }; } -/** The GitOps Slack app (`/gitops`): needs the app configured with its signing secret. */ +/** + * The "new channel" picker: what can be created, and what is not built yet. A type that is built + * but switched off (Slack without its app) is not offered at all. + */ +function channelTypeOptions(availableTypes: readonly string[]): ChannelTypeOption[] { + const registered = notificationChannelService.registeredTypes() as readonly string[]; + return CHAT_CHANNEL_TYPES.flatMap((type): ChannelTypeOption[] => + availableTypes.includes(type) + ? [{ type, status: 'available' }] + : registered.includes(type) + ? [] + : [{ type, status: 'coming_soon' }], + ); +} + +/** + * The GitOps Slack app (`/gitops`): disabled until `SLACK_CLIENT_ID`, `SLACK_CLIENT_SECRET` and + * `SLACK_SIGNING_SECRET` are set. Workspaces already connected stay listed and can be removed. + */ async function slackAppCard( locals: AlertLocals, organizationId: string, - input: { canCreate: boolean; canDelete: boolean; isAdmin: boolean; available: boolean }, + input: { canCreate: boolean; canDelete: boolean; isAdmin: boolean }, ): Promise { - const configured = input.available && slackConnectService.commandsEnabled(); + const enabled = + notificationChannelService.registeredTypes().includes('slack') && + slackConnectService.commandsEnabled(); const installations = (await slackAppService.workspacesOf(organizationId)).map((workspace) => ({ id: workspace.id, name: workspace.teamName, })); return { provider: 'slack', - comingSoon: false, - configured, - canInstall: configured && input.canCreate && !locals.apiKey, + status: !enabled ? 'disabled' : installations.length > 0 ? 'installed' : 'available', + canInstall: enabled && input.canCreate && !locals.apiKey && installations.length === 0, canRemove: input.canDelete, installations, - setupPath: !configured && input.isAdmin ? '/gitops-settings/slack' : null, + setupPath: !enabled && input.isAdmin ? SLACK_SETUP_PATH : null, }; } @@ -110,7 +123,7 @@ type ActionEvent = { const SLACK_AUTHORIZATION_ORIGIN = 'https://slack.com'; -/** Form actions of the channels section, shared by the organization and project pages. */ +/** Form actions of an organization's integrations and channels. */ export function channelActions(resolve: (event: ActionEvent) => Promise) { return { async createChannel(event: ActionEvent) { diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts index 19fd8f3..c693309 100644 --- a/src/lib/server/notifications/channels.ts +++ b/src/lib/server/notifications/channels.ts @@ -59,10 +59,12 @@ async function loadAuthorized(locals: AlertLocals, id: string, action: ChannelAc } export type ChannelList = { + /** + * The organization's channels. For a project, the ones its alerts can use: channels belong to + * organizations (#119), a project has none of its own. + */ 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). */ + /** Types that can be created now (transport registered and type enabled); none for projects. */ availableTypes: ChatChannelType[]; }; @@ -71,21 +73,17 @@ export async function listChannels( location: ChannelLocation, ): Promise> { if (!(await canManageChannels(locals, location, 'read'))) return forbidden; - const own = await notificationChannelService.list(location); - const inherited = + const channels = location.scope === 'project' - ? await notificationChannelService.list({ - organizationId: location.organizationId, - projectId: null, - }) - : []; + ? await notificationChannelService.listUsable(location) + : await notificationChannelService.list(location); return { ok: true, status: 200, data: { - channels: own.map((channel) => notificationChannelService.toView(channel)), - inherited: inherited.map((channel) => notificationChannelService.toView(channel)), - availableTypes: notificationChannelService.availableTypes(), + channels: channels.map((channel) => notificationChannelService.toView(channel)), + availableTypes: + location.scope === 'organization' ? notificationChannelService.availableTypes() : [], }, }; } @@ -230,6 +228,9 @@ export async function startSlackConnection( ): Promise> { const userId = locals.apiKey ? null : locals.user?.id; if (!userId || !(await canManageChannels(locals, location, 'create'))) return forbidden; + if (location.scope !== 'organization') { + return { ok: false, status: 400, error: 'project_channels_unsupported' }; + } try { return { ok: true, diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts index ce788a0..0796b0d 100644 --- a/src/modules/alerts/application/alert.channels.test.ts +++ b/src/modules/alerts/application/alert.channels.test.ts @@ -89,7 +89,9 @@ describe('alerts with notification channels', () => { let directory: FakeAlertDirectory; let service: AlertService; let orgChannel: string; + /** A second organization channel, the one the project alerts below use. */ let p1Channel: string; + /** A project channel left from before #119: nobody can use it. */ let p2Channel: string; beforeEach(async () => { @@ -113,15 +115,21 @@ describe('alerts with notification channels', () => { ) ).channel.id; p1Channel = ( - await channels.service.create(p1, { type: 'slack', name: '#p1', destination: HOOK }, 'a') + await channels.service.create( + orgLocation, + { type: 'slack', name: '#p1', destination: HOOK }, + 'a', + ) ).channel.id; p2Channel = ( await channels.service.create( - { ...p1, projectId: 'p2' }, + orgLocation, { type: 'slack', name: '#p2', destination: HOOK }, 'a', ) ).channel.id; + const legacy = channels.repository.rows.find((row) => row.id === p2Channel)!; + Object.assign(legacy, { scope: 'project', projectId: 'p2' }); repository = new InMemoryAlertRepository(); directory = new FakeAlertDirectory(); @@ -144,7 +152,7 @@ describe('alerts with notification channels', () => { }); describe('validation', () => { - it('accepts the project and organization channels a project alert may use', async () => { + it('accepts the organization channels in a project alert', async () => { const alert = await service.create( p1, input({ channelIds: [p1Channel, orgChannel, p1Channel] }), @@ -154,24 +162,47 @@ describe('alerts with notification channels', () => { expect(alert.channels).toEqual(['mail', 'slack']); }); - it('rejects channels of another project or another location', async () => { + it('rejects project channels left from before #119, in any location', async () => { expect( ( await validationErrors( - service.create(p1, input({ channelIds: [p2Channel] }), actor('admin')), + service.create( + { ...p1, projectId: 'p2' }, + 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')), + service.create(orgLocation, input({ channelIds: [p2Channel] }), actor('admin')), ) ).channelIds, ).toBe('unknown_channel'); }); + it('drops deleted channels from the alerts of the organization', async () => { + const both = await service.create( + p1, + input({ channelIds: [p1Channel, orgChannel] }), + actor('admin'), + ); + const only = await service.create( + p1, + input({ recipients: {}, channelIds: [p1Channel] }), + actor('admin'), + ); + expect(only.channels).toEqual(['slack']); + + await expect(service.removeChannels(ORG, [p1Channel])).resolves.toBe(2); + expect((await service.get(both.id)).channelIds).toEqual([orgChannel]); + // an alert left without channels falls back to email + expect(await service.get(only.id)).toMatchObject({ channelIds: [], channels: ['mail'] }); + await expect(service.removeChannels(ORG, [p1Channel])).resolves.toBe(0); + }); + 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)), @@ -259,12 +290,12 @@ describe('alerts with notification channels', () => { transports: { slack: createSlackTransport({ fetch }) }, }); const slack = await mixed.service.create( - p1, + orgLocation, { type: 'slack', name: '#seguridad', destination: SLACK_HOOK }, 'a', ); const webhook = await mixed.service.create( - p1, + orgLocation, { type: 'webhook', name: 'SIEM', destination: HOOK }, 'a', ); @@ -507,12 +538,12 @@ describe('alerts with notification channels', () => { it('builds each channel message in that channel language', async () => { const mixed = createChannelsFixture(); const es = await mixed.service.create( - p1, + orgLocation, { type: 'slack', name: '#es', destination: HOOK, locale: 'es' }, 'a', ); const en = await mixed.service.create( - p1, + orgLocation, { type: 'slack', name: '#en', destination: HOOK }, 'a', ); diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts index 9f784ec..3c08f42 100644 --- a/src/modules/alerts/application/alert.service.ts +++ b/src/modules/alerts/application/alert.service.ts @@ -291,6 +291,25 @@ export class AlertService { return affected.length; } + /** + * Drops deleted channels from every alert of the organization that points at them. An alert + * left without channels falls back to email, as a save with no channels does. + */ + async removeChannels(organizationId: string, channelIds: readonly string[]): Promise { + const gone = new Set(channelIds); + const alerts = await this.repository.listByOrganization(organizationId); + const affected = alerts.filter((alert) => alert.channelIds.some((id) => gone.has(id))); + for (const alert of affected) { + const remaining = alert.channelIds.filter((id) => !gone.has(id)); + await this.repository.update(alert.id, { + channelIds: remaining, + ...(remaining.length === 0 ? { channels: ['mail' as const] } : {}), + }); + } + if (affected.length > 0) this.onChange(); + return affected.length; + } + async delete(id: string): Promise { await this.get(id); await this.repository.delete(id); diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts index c823eaa..8a65583 100644 --- a/src/modules/alerts/index.ts +++ b/src/modules/alerts/index.ts @@ -167,6 +167,27 @@ export function registerAlertEngine(): void { } } +/** + * Deletes the project channels left from before #119 (channels are organization-wide now) and + * drops them from the alerts that used them. Runs at startup; with none left it writes nothing. + */ +export async function purgeProjectChannels(): Promise { + const deleted = await notificationChannelService.purgeProjectChannels(); + if (deleted.length === 0) return; + const byOrganization = new Map(); + for (const channel of deleted) { + byOrganization.set(channel.organizationId, [ + ...(byOrganization.get(channel.organizationId) ?? []), + channel.id, + ]); + } + let alerts = 0; + for (const [organizationId, ids] of byOrganization) { + alerts += await alertService.removeChannels(organizationId, ids); + } + log.info({ channels: deleted.length, alerts }, '[alerts] project channels removed'); +} + /** Whether emails can be sent; a broken SMTP configuration counts as not configured. */ export function isMailConfigured(): boolean { try { diff --git a/src/modules/notifications/application/notification-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts index 142a365..1a01ac0 100644 --- a/src/modules/notifications/application/notification-channel.service.test.ts +++ b/src/modules/notifications/application/notification-channel.service.test.ts @@ -154,22 +154,88 @@ describe('NotificationChannelService', () => { }); describe('scopes', () => { - it('lets a project channel serve only its project, and an organization channel all of them', async () => { + it('only creates organization channels: projects use their organization ones (#119)', async () => { + const errors = await validationErrors( + f.service.create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a'), + ); + expect(errors).toEqual({ scope: 'project_channels_unsupported' }); + expect(f.repository.rows).toHaveLength(0); + }); + + it('lets organization channels serve the organization and all its projects', async () => { const org = await create(orgLocation, { type: 'slack', name: 'org', destination: HOOK }, 'a'); - const own = await create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a'); - await create( - { ...p1, projectId: 'p2' }, - { type: 'slack', name: 'p2', destination: HOOK }, + // a project channel left from before #119 serves nobody + const legacy = await create( + orgLocation, + { type: 'slack', name: 'p1', destination: HOOK }, 'a', ); + Object.assign( + f.repository.rows.find((row) => row.id === legacy.id)!, + { + scope: 'project', + projectId: 'p1', + }, + ); - 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: 'p1' })).map((c) => c.id), + ).toEqual([org.id]); 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']); + }); + + it('purges the project channels left from before #119, once', async () => { + const org = await create(orgLocation, { type: 'slack', name: 'org', destination: HOOK }, 'a'); + const legacy = await create( + orgLocation, + { type: 'slack', name: 'p1', destination: HOOK }, + 'a', + ); + Object.assign( + f.repository.rows.find((row) => row.id === legacy.id)!, + { + scope: 'project', + projectId: 'p1', + }, + ); + + await expect(f.service.purgeProjectChannels()).resolves.toEqual([ + { id: legacy.id, organizationId: ORG }, + ]); + expect(f.repository.rows.map((row) => row.id)).toEqual([org.id]); + // nothing left: nothing written + const writes = f.repository.writes.length; + await expect(f.service.purgeProjectChannels()).resolves.toEqual([]); + expect(f.repository.writes).toHaveLength(writes); + }); + }); + + describe('types that are switched off', () => { + it('neither offers nor creates them, while existing channels keep delivering', async () => { + let slackEnabled = true; + const g = createChannelsFixture({ + types: ['slack', 'webhook'], + canCreateType: (type) => type !== 'slack' || slackEnabled, + }); + const existing = await g.service.create( + orgLocation, + { type: 'slack', name: '#old', destination: HOOK }, + 'a', + ); + slackEnabled = false; + + expect(g.service.availableTypes()).toEqual(['webhook']); + expect(g.service.registeredTypes()).toEqual(['slack', 'webhook']); + const errors = await validationErrors( + g.service.create(orgLocation, { type: 'slack', name: '#new', destination: HOOK }, 'a'), + ); + expect(errors).toEqual({ type: 'type_disabled' }); + + expect(g.service.toView(existing.channel).available).toBe(true); + await expect(g.service.deliver(existing.channel.id, message)).resolves.toBe(true); }); }); @@ -382,7 +448,7 @@ describe('NotificationChannelService: signed channels and failure streaks', () = it('disables a channel after N definitive failures in a row and announces it once', async () => { const f = webhook({ maxConsecutiveFailures: 3 }); const { channel } = await f.service.create( - p1, + orgLocation, { type: 'webhook', name: 'SIEM', destination: HOOK }, 'creator', ); @@ -412,7 +478,7 @@ describe('NotificationChannelService: signed channels and failure streaks', () = expect(announced).toHaveLength(1); expect(announced[0]).toMatchObject({ actor: { kind: 'system' }, - scope: { organizationId: ORG, projectId: 'p1' }, + scope: { organizationId: ORG, projectId: null }, payload: { channelId: channel.id, name: 'SIEM', diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts index 0de11eb..722822e 100644 --- a/src/modules/notifications/application/notification-channel.service.ts +++ b/src/modules/notifications/application/notification-channel.service.ts @@ -87,6 +87,11 @@ export type NotificationChannelServiceOptions = { rotationGraceMs?: number; /** How often a healthy channel records `lastDeliveryAt` (each record is a GitDB commit). */ deliveryStampIntervalMs?: number; + /** + * Whether channels of `type` can be created now, on top of having a transport: Slack needs its + * app configured (`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`). Existing channels keep delivering. + */ + canCreateType?: (type: ChatChannelType) => boolean; logger?: { warn: (object: object, message: string) => void; error?: (object: object, message: string) => void; @@ -131,11 +136,20 @@ export class NotificationChannelService { this.rotationGraceMs = options.rotationGraceMs ?? SECRET_ROTATION_GRACE_MS; } - /** Channel types that can be created now (a transport is registered for them). */ + /** Channel types that can be created now: a transport is registered and the type is enabled. */ availableTypes(): ChatChannelType[] { + return this.transports.available().filter((type) => this.creatable(type)); + } + + /** Types with a registered transport, enabled or not: the rest are not built yet. */ + registeredTypes(): ChatChannelType[] { return this.transports.available(); } + private creatable(type: ChatChannelType): boolean { + return this.options.canCreateType?.(type) ?? true; + } + async get(id: string): Promise { const channel = await this.repository.findById(id); if (!channel) throw new NotificationChannelNotFoundError(id); @@ -152,7 +166,7 @@ export class NotificationChannelService { ); } - /** Channels an alert of `location` may use: its project's and its organization's. */ + /** Channels an alert of `location` may use: its organization's (channels are organization-wide). */ async listUsable(location: Pick) { const channels = await this.repository.listByOrganization(location.organizationId); return channels.filter((channel) => channel.usableFrom(location)); @@ -192,6 +206,8 @@ export class NotificationChannelService { actorUserId: string, ): Promise { const errors: Record = {}; + // channels belong to organizations: project alerts use their organization's (#119) + if (location.scope !== 'organization') errors.scope = 'project_channels_unsupported'; const type = this.validateType(input.type, errors); const name = this.validateName(input.name, errors); const locale = @@ -213,8 +229,9 @@ export class NotificationChannelService { type, name, locale, - ...location, - projectId: location.scope === 'project' ? location.projectId : null, + scope: 'organization', + organizationId: location.organizationId, + projectId: null, webhookUrl: this.cipher.encrypt(id, destination), enabled: input.enabled === undefined ? true : input.enabled === true || input.enabled === 'true', @@ -296,6 +313,20 @@ export class NotificationChannelService { await this.repository.delete(id); } + /** + * Deletes every project channel (#119: channels are organization-wide now). Idempotent: with + * none left it writes nothing. Returns what it deleted so callers can drop the references. + */ + async purgeProjectChannels(): Promise> { + const channels = await this.repository.listProjectChannels(); + const deleted: Array<{ id: string; organizationId: string }> = []; + for (const channel of channels) { + await this.repository.delete(channel.id); + deleted.push({ id: channel.id, organizationId: channel.organizationId }); + } + return deleted; + } + /** * Queues `message` for the channel and resolves with whether it was delivered. Disabled, * deleted, unavailable or invalid channels resolve `false` without sending; nothing throws. @@ -493,6 +524,10 @@ export class NotificationChannelService { errors.type = 'type_unavailable'; return null; } + if (!this.creatable(value)) { + errors.type = 'type_disabled'; + return null; + } return value; } diff --git a/src/modules/notifications/application/testing.ts b/src/modules/notifications/application/testing.ts index 779698a..52c13c0 100644 --- a/src/modules/notifications/application/testing.ts +++ b/src/modules/notifications/application/testing.ts @@ -109,6 +109,7 @@ export function createChannelsFixture( transports?: Partial>; events?: EventPublisher; maxConsecutiveFailures?: number; + canCreateType?: (type: ChatChannelType) => boolean; logger?: { warn: () => void; error: () => void; debug: () => void }; } = {}, ) { @@ -159,6 +160,7 @@ export function createChannelsFixture( generateSecret: () => `whsec_test${++secret}`, events: options.events, maxConsecutiveFailures: options.maxConsecutiveFailures, + canCreateType: options.canCreateType, }, ); return { diff --git a/src/modules/notifications/domain/notification-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts index 1f72b1d..a44e4f8 100644 --- a/src/modules/notifications/domain/notification-channel.domain.ts +++ b/src/modules/notifications/domain/notification-channel.domain.ts @@ -124,12 +124,11 @@ export class NotificationChannelDomain implements NotificationChannelRow { } /** - * 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. + * Whether an alert of `location` may use it: channels belong to organizations and serve the + * organization and all its projects. Project channels (#119: no longer created) serve nobody. */ usableFrom(location: Pick): boolean { - if (location.organizationId !== this.organizationId) return false; - return this.scope === 'organization' || location.projectId === this.projectId; + return location.organizationId === this.organizationId && this.scope === 'organization'; } toJson(): NotificationChannelRow { diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts index b35cc70..2855e1b 100644 --- a/src/modules/notifications/index.ts +++ b/src/modules/notifications/index.ts @@ -116,7 +116,12 @@ export const notificationChannelService = new NotificationChannelService( createChannelCipher(() => passwordService.ensureEncryptionKey()), { get: (type) => getChatTransport(type), available: () => availableChatTypes() }, channelQueue, - { logger: log, events: eventBus }, + { + logger: log, + events: eventBus, + // new Slack channels only once the Slack app is configured; existing ones keep delivering + canCreateType: (type) => type !== 'slack' || slackConnectService.isConfigured(), + }, ); /** "Add to Slack" (#97): OAuth install that returns the webhook of the channel the user picks. */ diff --git a/src/modules/notifications/infrastructure/config/slack-app.config.ts b/src/modules/notifications/infrastructure/config/slack-app.config.ts index 21c14af..ee6f76a 100644 --- a/src/modules/notifications/infrastructure/config/slack-app.config.ts +++ b/src/modules/notifications/infrastructure/config/slack-app.config.ts @@ -23,8 +23,8 @@ function value(raw: string | undefined): string | null { /** * Read on every call so config reloads and tests see fresh values. `null` when "Add to Slack" is - * not configured (channels are then created by pasting the webhook URL); throws when only one of - * the two values is set. + * not configured (no Slack channel can be created then); throws when only one of the two values is + * set. */ export function readSlackAppConfig(): SlackAppConfig | null { const clientId = value(env.SLACK_CLIENT_ID); diff --git a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts index bb365e5..a3fec68 100644 --- a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts +++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts @@ -99,6 +99,12 @@ export class InMemoryNotificationChannelRepository implements NotificationChanne .map((row) => new NotificationChannelDomain(structuredClone(row))); } + async listProjectChannels() { + return this.rows + .filter((row) => row.scope === 'project') + .map((row) => new NotificationChannelDomain(structuredClone(row))); + } + async create(row: NotificationChannelRow) { this.rows.push(structuredClone(row)); this.writes.push({ id: row.id, changes: { ...row } }); diff --git a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts index c32aa8b..3517835 100644 --- a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts +++ b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts @@ -27,6 +27,8 @@ export interface NotificationChannelRepositoryPort { findById(id: string): Promise; /** Every channel of the organization, including those of its projects. */ listByOrganization(organizationId: string): Promise; + /** Channels owned by a project, in every organization (legacy rows: see #119). */ + listProjectChannels(): Promise; create(row: NotificationChannelRow): Promise; update(id: string, changes: NotificationChannelChanges): Promise; delete(id: string): Promise; @@ -51,6 +53,14 @@ export class NotificationChannelRepository return result.rows.map((row: any) => new NotificationChannelDomain(row)); } + async listProjectChannels() { + const result = await this.db + .select() + .from(NotificationChannelEntity) + .where({ scope: 'project' }); + return result.rows.map((row: any) => new NotificationChannelDomain(row)); + } + async create(row: NotificationChannelRow) { await this.db.insert(NotificationChannelEntity).values({ ...row }); } diff --git a/src/routes/api/alerts/server.test.ts b/src/routes/api/alerts/server.test.ts index aae44d4..574afae 100644 --- a/src/routes/api/alerts/server.test.ts +++ b/src/routes/api/alerts/server.test.ts @@ -296,7 +296,7 @@ describe('/api/alerts', () => { const fixture = (alerts as unknown as { channels: ChannelsFixture }).channels; fixture.transport.sent = []; const { channel } = await fixture.service.create( - { scope: 'project', organizationId: 'org-1', projectId: 'p1' }, + { scope: 'organization', organizationId: 'org-1', projectId: null }, { type: 'slack', name: '#ops', destination: 'https://hooks.example.com/hook/T0/B0/x' }, 'admin', ); diff --git a/src/routes/api/notification-channels/server.test.ts b/src/routes/api/notification-channels/server.test.ts index 10235e3..66b8751 100644 --- a/src/routes/api/notification-channels/server.test.ts +++ b/src/routes/api/notification-channels/server.test.ts @@ -173,13 +173,29 @@ describe('/api/notification-channels', () => { expect(notifications.fixture.transport.sent).toHaveLength(0); }); - it('keeps project admins and project keys inside their project', async () => { - const created = await call(collection.POST, { + it('creates no project channels: projects list the organization ones they can use', async () => { + const org = await createOrgChannel(); + const refused = await call(collection.POST, { locals: as('projectAdmin'), body: { projectId: 'p1', type: 'slack', name: '#p1', destination: HOOK }, }); - expect(created.status).toBe(201); + expect(refused.status).toBe(400); + await expect(refused.json()).resolves.toMatchObject({ + errors: { scope: 'project_channels_unsupported' }, + }); + const listed = await call(collection.GET, { + locals: as('projectAdmin'), + url: 'http://localhost/api/notification-channels?projectId=p1', + }); + expect(listed.status).toBe(200); + await expect(listed.json()).resolves.toMatchObject({ + channels: [{ id: org.id, scope: 'organization' }], + availableTypes: [], + }); + }); + + it('keeps project admins and project keys inside their project', async () => { // no organization channels for a project admin const orgChannel = await call(collection.POST, { locals: as('projectAdmin'), 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 index 7adbcc5..4fe76ea 100644 --- 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 @@ -1,22 +1,15 @@ -import { error } from '@sveltejs/kit'; +import { error, redirect } 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'; +/** + * Projects have no notification settings of their own: channels and integrations belong to the + * organization (#119). Old links land on the organization's page, for those who can open it. + */ 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, - }; + const { location } = await projectAlertContext(event); + if (await canOpenNotificationSettings(event.locals, location.organizationId)) { + throw redirect(303, `/org/${event.params.org}/settings/alerts/settings`); + } + throw error(404, 'Not found'); } - -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 deleted file mode 100644 index c4a1076..0000000 --- a/src/routes/org/[org]/projects/[slug]/settings/alerts/settings/+page.svelte +++ /dev/null @@ -1,39 +0,0 @@ - - - - {$_('notifications.settings.title')} - GitOps - - -
-
- - - {$_('notifications.settings.back')} - -

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

-

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

-
- - -