From b74590eead8a83beff1873c6d0d5b871012afca1 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
- {$_('notifications.settings.domainsDescription')} -
-
+
- {$_('notifications.settings.recipientsDescription')} -
-+ {$_('notifications.settings.recipientsDescription')} +
+- {$_(`notifications.errors.${form.resendError}`)} -
- {:else if form?.resent} -{$_('notifications.settings.resent')}
- {:else if form?.removeError} -- {$_(`notifications.errors.${form.removeError}`)} -
- {:else if form?.removed} -- {$_('notifications.settings.removed', { values: { email: form.removed } })} -
- {/if} + {#if form?.resendError} ++ {$_(`notifications.errors.${form.resendError}`)} +
+ {:else if form?.resent} +{$_('notifications.settings.resent')}
+ {:else if form?.removeError} ++ {$_(`notifications.errors.${form.removeError}`)} +
+ {:else if form?.removed} ++ {$_('notifications.settings.removed', { values: { email: form.removed } })} +
+ {/if} - {#if data.recipients.length === 0} -- {$_('notifications.settings.recipientsEmpty')} -
- {:else} -| - {$_('notifications.settings.email')} - | -- {$_('notifications.settings.status')} - | -- {$_('notifications.settings.verifiedAt')} - | -- {$_('notifications.settings.lastSent')} - | -- {$_('notifications.settings.actions')} - | -||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| {recipient.email} | -- - {$_(`notifications.status.${recipient.status}`)} - - | -{formatDate(recipient.verifiedAt)} | -- {formatDate(recipient.lastVerificationSentAt)} - | -
-
- {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
-
- |
+ {#if data.recipients.length === 0}
+
| + {$_('notifications.settings.email')} + | ++ {$_('notifications.settings.status')} + | ++ {$_('notifications.settings.verifiedAt')} + | ++ {$_('notifications.settings.lastSent')} + | ++ {$_('notifications.settings.actions')} + |
|---|
- {$_('notifications.settings.organizationDomains')} - {$_('notifications.settings.organizationDomainsLink')} -
- {/if} - - {#if channels} -{errorText('locale')}
+ {:else} +{$_('notifications.channels.localeHelp')}
+ {/if} ++ {$_('notifications.channels.noTypes')} +
+{:else} ++ {$_('notifications.channels.slackConnectTitle')} +
++ {$_('notifications.channels.slackConnectDescription')} +
++ + {$_('notifications.channels.slackManual')} + +
+ {/if} + +{errorText('name')}
{/if} +{errorText('destination')}
+ {:else if selectedType === 'webhook'} +{$_('notifications.channels.webhookHelp')}
+ {:else if selectedType === 'slack'} +{$_('notifications.channels.slackHelp')}
+ {/if} ++ {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} ++ {errorMessage($_, form.channelError)} +
+ {/if} + + {#if data.channels.length === 0} ++ {$_('notifications.channels.empty')} +
+ {:else} +
+ {channel.name}
+
+ {$_(`notifications.channels.types.${channel.type}`)}
+
+
+ {$_(`notifications.channels.locales.${channel.locale}`)}
+
+ {#if !channel.enabled}
+
+ {$_('notifications.channels.disabled')}
+
+ {/if}
+ {#if channel.signed}
+
+
+ {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} ++ {errorText(editErrors, 'name')} +
{/if} ++ {errorText(editErrors, 'destination')} +
{/if} ++ {errorText(editErrors, 'locale')} +
{/if} +- {data.scope === 'project' - ? $_('notifications.channels.descriptionProject') - : $_('notifications.channels.descriptionOrganization')} -
++ {$_('notifications.channels.descriptionOrganization')} +
+{/if} - {#if slackOutcome} - - - {/if} - - {#if data.apps} -
{$_('notifications.apps.description')}
-- {$_('notifications.apps.setupHint')} - {$_('notifications.channels.slackSetupLink')} -
- {/if} - {/if} -- {form.channelTest.sent - ? $_('notifications.channels.testSent') - : $_('notifications.channels.testFailed', { - values: { reason: form.channelTest.error ?? '—' }, - })} -
- {:else if form?.channelError && form.channelForm !== 'create' && !form.channelErrors} -- {errorMessage(form.channelError)} -
- {/if} - - {#if data.channels.length === 0} -- {$_('notifications.channels.empty')} -
- {:else} -
- {channel.name}
-
- {$_(`notifications.channels.types.${channel.type}`)}
-
-
- {$_(`notifications.channels.locales.${channel.locale}`)}
-
- {#if !channel.enabled}
-
- {$_('notifications.channels.disabled')}
-
- {/if}
- {#if channel.signed}
-
-
- {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} -{$_('notifications.channels.inheritedDescription')}
-- {$_('notifications.channels.noTypes')} -
- {:else} - {@const errors = { ...formCreateErrors, ...createErrors }} -- {$_('notifications.channels.slackConnectTitle')} -
-- {$_('notifications.channels.slackConnectDescription')} -
-{errorText(errors, 'locale')}
- {:else} -- {$_('notifications.channels.localeHelp')} -
- {/if} -- - {$_('notifications.channels.slackManual')} - -
- {/if} -- {errorText(errors, 'name')} -
{/if} -{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} -{errorText(errors, 'locale')}
- {:else} -- {$_('notifications.channels.localeHelp')} -
- {/if} -- {errorText(editErrors, 'name')} -
{/if} -- {errorText(editErrors, 'destination')} -
{/if} -- {errorText(editErrors, 'locale')} -
{/if} -{$_('notifications.apps.description')}
++ {$_(`notifications.channels.types.${app.provider}`)} +
++ {$_(`notifications.apps.descriptions.${app.provider}`)} +
++ {#if app.setupPath} + {$_('notifications.apps.setupHint')} + {$_('notifications.channels.slackSetupLink')} + {:else} + {$_('notifications.apps.askAdmin')} + {/if} +
+ {/if} +`, 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')}
-
-
-
-
-
From 396c2e4203b5552b5f6a607a726bb447150312b4 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Fri, 27 Nov 2026 13:38:17 +0100
Subject: [PATCH 2/2] Feat: Refactor alerts configuration
---
.github/copilot-instructions.md | 61 ++++++++++-------------
CLAUDE.md | 88 +++++++++++++++++----------------
e2e/specs/alerts.spec.ts | 2 +
3 files changed, 74 insertions(+), 77 deletions(-)
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 031e018..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
@@ -119,39 +119,32 @@ 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`
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` (modal con tabs **Integraciones** / **Canales** / **Email externo**),
-administradores configuran integraciones como Slack, dominios permitidos y canales (`NotificationChannelEntity`
-en GitDB). Alertas guardan `recipients` (usuarios, roles, emails externos) y `channelIds` (referencias a canales).
-Los canales pertenecen solo a organizaciones (#119): proyectos usan los canales de su organización, no tienen propios.
-Cada canal tiene idioma (`locale`: es | en, por defecto en). URLs de webhook encriptadas con `GITDB_ENCRYPTION_KEY`.
-Emails externos: `pending` → `verified` → `unsubscribed` o `blocked`; template sin campos `sensitive` ni links;
-`List-Unsubscribe` HMAC (90 días). **Webhook** se firma: secreto `whsec_…` una sola vez, resuelve DNS rechazando
-IPs privadas, 20 fallos consecutivos = auto-deshabilita. **Slack**: Incoming Webhook (solo `https://hooks.slack.com/services/…`),
-Block Kit en idioma del canal, escapa Slack (`&<>`) en datos de usuario/evento. Un canal GitOps por webhook.
-Errores 4xx no se reintentan. **Add to Slack** (`SlackConnectService`): cuando `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`
-están configurados, la sección de Integraciones muestra "Añadir a Slack"; usuario elige workspace y canal.
-Admin crea app Slack desde `GitOps Settings → Slack` (manifest con scope `incoming-webhook` y redirect
-`/notifications/slack/callback`, requiere https), copia credenciales. En dev: `DEV_HTTPS=true` con certs en `.certs/`.
-
-**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.
+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 ac27524..441e583 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -349,14 +349,18 @@ 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 organization alert list (no sidebar entry) opens them in a modal
- (`AlertSettingsPanel`, tabs **Integraciones** / **Canales** / **Email externo**; without JavaScript
- the three sections are stacked) whose forms post to the actions of
- `/org//settings/alerts/settings`. Projects have no notification settings of their own (#119):
- the project alert list has no "Settings" button (`data.configPath` is `null`) but a "?" 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`
+ 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
@@ -426,42 +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); without them the Slack type is not offered
- at all (see `canCreateType`). Picking the Slack card in the "New channel" modal (`ChannelForm`) 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. The integration card (`IntegrationsSection`, `AppCardData.status`:
- `installed` | `available` | `disabled` | `coming_soon`) shows Slack as **Desactivado** while `/gitops`
- is not configured (`SLACK_SIGNING_SECRET` too): GitOps admins get a link to `/gitops-settings/slack`,
- everyone else is told to ask one; workspaces already connected stay listed and can be removed. 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/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index 1582d82..33d67f4 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -232,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');