From d8ee041495723e8c6ab93bff0a676c45563dbe34 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Mon, 30 Nov 2026 09:39:56 +0100
Subject: [PATCH 1/2] Feat: Fix connect 2 org same workspace
---
.github/copilot-instructions.md | 11 +-
CLAUDE.md | 35 ++-
.../components/notifications/channel-ui.ts | 4 +-
src/lib/i18n/locales/en.json | 12 +-
src/lib/i18n/locales/es.json | 12 +-
.../infra/notifications/chat-notification.ts | 2 +
.../infra/notifications/slack/slack-blocks.ts | 6 +
.../slack/slack.transport.test.ts | 2 +
src/lib/server/notifications/channels.ts | 8 +-
.../alerts/application/alert.channels.test.ts | 10 +
.../infrastructure/alert-channel-message.ts | 7 +-
.../application/slack-app.service.test.ts | 187 ++++++++++--
.../application/slack-app.service.ts | 266 +++++++++++++-----
.../domain/slack-workspace.domain.ts | 5 +-
.../slack-workspace.repository.ts | 22 +-
.../notifications/slack/link/+page.server.ts | 18 +-
.../notifications/slack/link/+page.svelte | 2 +
17 files changed, 470 insertions(+), 139 deletions(-)
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 62def50..247aa31 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -136,10 +136,13 @@ En `/org//settings/alerts/settings` se abre un modal (`AlertSettingsPanel`)
→ `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.
+cada organización instala el app guardando su fila en `slack_workspaces` (GitDB): **un workspace
+puede instalarse en varias organizaciones** (una fila por workspace+organización), compartiendo bot token
+(re-encriptado en todas). 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 (usuario debe ver ≥1 org del workspace); (2) `/gitops channel` →
+modal nombre/idioma/organización (picker si hay varias permitidas); (3) `/gitops status` →
+cuenta y canales por cada org visible. 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).
diff --git a/CLAUDE.md b/CLAUDE.md
index 441e583..08ed927 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -418,8 +418,8 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- Slack (`#lib/server/infra/notifications/slack/`): Incoming Webhook, URL limited to
`https://hooks.slack.com/services/` only (`SLACK_WEBHOOK_RULE`), unsigned. `buildSlackPayload()` turns
the `ChannelMessage` into Block Kit in the channel's language only: header (alert name, `plain_text`), the
- summary only when it differs from the event label, a fields section with `location`
- (`Project`/`Organization`: name) and the date (`slackDate()`, ``, reader's time zone),
+ summary only when it differs from the event label, a fields section with the organization of a project
+ event (`organization`), `location` (`Project`/`Organization`: name) and the date (`slackDate()`, ``, reader's time zone),
a divider and a `*Changes*` title (`labels.changes`), then one section per change (`*Label*` /
`Before: …` / `New: …`, `labels.empty` for a `null` side,
only the label when both are `null`), remaining field sections of 10, "View in GitOps" button,
@@ -448,22 +448,28 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
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
+ row per (Slack team, organization): **several organizations can install the same workspace**
+ (each keeps its own row: `teamId` + `organizationId` unique pair), and each one removes only its own row.
+ The bot token is shared by every row of a team (a new install re-encrypts it in all of them),
+ 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).
+ logins come back to it, `#lib/server/return-to`; the user must belong to at least one organization
+ of the workspace). `/gitops channel` opens a modal with name, locale and an organization picker
+ (listing only the workspace's organizations where the account has `organization:notifications:create`);
+ with one, it goes in `private_metadata` and skips the picker; checked again on submit. 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`. `/gitops status` lists the linked account and, per each organization
+ of the workspace the account can see, its Slack channels (unlinked users see nothing). Replies use
+ the locale picked at the workspace's first 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;
@@ -483,7 +489,8 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
`labels` carries the translated `Date`/`Changes`/`Before`/`New`/`empty`, and `text` only adds the summary
when it differs from the event label, so nothing is said twice in two languages.
`note` is the translated side note (test send, throttled count); the raw `suppressed` count is
- still there. `occurredAt` and `location` are always present; `changes` only for update events;
+ still there. `occurredAt` and `location` are always present; `organization` is added when the location is a project
+ (shows the organization name as an extra field for context); `changes` only for update events;
`labels` only when any of `occurredAt`, `location` or `changes` is used by the transport.
- Update events carry `changes?: FieldChange[]` (`{ field, before, after }`, plain text cut to 200
chars by `fieldChange()` in `#lib/events/field-changes.ts`, `null` when empty or not shown):
diff --git a/src/lib/components/notifications/channel-ui.ts b/src/lib/components/notifications/channel-ui.ts
index b888e2b..f3d576f 100644
--- a/src/lib/components/notifications/channel-ui.ts
+++ b/src/lib/components/notifications/channel-ui.ts
@@ -45,7 +45,5 @@ export function formatDate(value: string | null) {
* 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';
+ return outcome === 'installed' ? 'integrations' : 'channels';
}
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index 4b66061..cbe5f19 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -1939,6 +1939,7 @@
"sendTestHelp": "Sends an example event to every destination of the alert: an email to the recipients that would get it (external ones only once confirmed) and a message to each selected channel.",
"channelsHelp": "The email goes to the recipients above. You can also post the alert to chat channels or webhooks: one message per channel.",
"noChannels": "There are no channels for this scope.",
+ "noOrganizations": "Your account cannot see any of the organizations connected to this workspace.",
"channelsSettingsLink": "Configure channels",
"channelFromOrganization": "(from the organization)",
"channelsNotice": "A channel is read by people who may not be allowed to see this event. The message leaves out sensitive fields.",
@@ -2277,7 +2278,6 @@
"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.",
"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."
},
@@ -2389,10 +2389,10 @@
},
"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).",
- "help": "*GitOps commands*\n• `/gitops login`: link your Slack user to your GitOps account (once).\n• `/gitops channel`: connect a Slack channel to the organization's alerts.\n• `/gitops status`: linked organization, your account and the connected channels.",
+ "help": "*GitOps commands*\n• `/gitops login`: link your Slack user to your GitOps account (once).\n• `/gitops channel`: connect a Slack channel to the alerts of an organization.\n• `/gitops status`: your account and, for each connected organization you can see, its channels.",
"notLinked": "Link your GitOps account first with `/gitops login`.",
"disabled": "Your GitOps account is disabled.",
- "forbidden": "Your GitOps account is not allowed to create channels in this organization.",
+ "forbidden": "Your GitOps account is not allowed to create channels in any organization connected to this workspace.",
"failed": "GitOps could not complete the action ({code}).",
"linkExpires": "This link is only for you and expires in 10 minutes.",
"login": {
@@ -2417,6 +2417,10 @@
"cancel": "Cancel",
"close": "Close",
"intro": "The channel is added to *{organization}*, where its alerts can use it.",
+ "introMany": "Pick the GitOps organization the channel is added to; its alerts can use it.",
+ "organization": "Organization",
+ "organizationPlaceholder": "Pick an organization",
+ "organizationRequired": "Pick one of the organizations in the list.",
"name": "Name",
"nameHint": "How the configuration shows in GitOps.",
"namePlaceholder": "DevOps ES",
@@ -2435,7 +2439,7 @@
"errors": {
"invalid": "The link is invalid or has expired. Type /gitops login in Slack again.",
"taken": "This Slack user is already linked to another GitOps account.",
- "forbidden": "Your account does not belong to the organization of this Slack workspace.",
+ "forbidden": "Your account does not belong to any organization connected to this Slack workspace.",
"not_installed": "The Slack workspace is no longer connected to GitOps."
}
},
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index 20607ae..af01ade 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -1939,6 +1939,7 @@
"sendTestHelp": "Envía un evento de ejemplo a todos los destinos de la alerta: email a los destinatarios que lo recibirían (los externos solo si están confirmados) y un mensaje a cada canal seleccionado.",
"channelsHelp": "El email llega a los destinatarios de arriba. Además, puedes publicar la alerta en canales de chat o webhooks: un mensaje por canal.",
"noChannels": "No hay canales configurados para este ámbito.",
+ "noOrganizations": "Tu cuenta no puede ver ninguna de las organizaciones conectadas a este workspace.",
"channelsSettingsLink": "Configurar canales",
"channelFromOrganization": "(de la organización)",
"channelsNotice": "Un canal lo lee gente que puede no tener permiso para ver este evento. El mensaje no incluye los campos sensibles.",
@@ -2277,7 +2278,6 @@
"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.",
"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."
},
@@ -2389,10 +2389,10 @@
},
"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).",
- "help": "*Comandos de GitOps*\n• `/gitops login`: vincula tu usuario de Slack con tu cuenta de GitOps (una vez).\n• `/gitops channel`: conecta un canal de Slack a las alertas de la organización.\n• `/gitops status`: organización vinculada, tu cuenta y los canales conectados.",
+ "help": "*Comandos de GitOps*\n• `/gitops login`: vincula tu usuario de Slack con tu cuenta de GitOps (una vez).\n• `/gitops channel`: conecta un canal de Slack a las alertas de una organización.\n• `/gitops status`: tu cuenta y, por cada organización conectada que puedes ver, sus canales.",
"notLinked": "Primero vincula tu cuenta de GitOps con `/gitops login`.",
"disabled": "Tu cuenta de GitOps está deshabilitada.",
- "forbidden": "Tu cuenta de GitOps no tiene permiso para crear canales en esta organización.",
+ "forbidden": "Tu cuenta de GitOps no tiene permiso para crear canales en ninguna organización conectada a este workspace.",
"failed": "GitOps no ha podido completar la acción ({code}).",
"linkExpires": "El enlace es solo para ti y caduca en 10 minutos.",
"login": {
@@ -2417,6 +2417,10 @@
"cancel": "Cancelar",
"close": "Cerrar",
"intro": "El canal se añadirá a *{organization}* y lo podrán usar sus alertas.",
+ "introMany": "Elige la organización de GitOps a la que se añade el canal; lo podrán usar sus alertas.",
+ "organization": "Organización",
+ "organizationPlaceholder": "Elige una organización",
+ "organizationRequired": "Elige una de las organizaciones de la lista.",
"name": "Nombre",
"nameHint": "Así se verá la configuración en GitOps.",
"namePlaceholder": "DevOps ES",
@@ -2435,7 +2439,7 @@
"errors": {
"invalid": "El enlace no es válido o ha caducado. Vuelve a escribir /gitops login en Slack.",
"taken": "Este usuario de Slack ya está vinculado a otra cuenta de GitOps.",
- "forbidden": "Tu cuenta no pertenece a la organización de este workspace de Slack.",
+ "forbidden": "Tu cuenta no pertenece a ninguna organización conectada a este workspace de Slack.",
"not_installed": "El workspace de Slack ya no está conectado a GitOps."
}
},
diff --git a/src/lib/server/infra/notifications/chat-notification.ts b/src/lib/server/infra/notifications/chat-notification.ts
index a846628..90e2882 100644
--- a/src/lib/server/infra/notifications/chat-notification.ts
+++ b/src/lib/server/infra/notifications/chat-notification.ts
@@ -30,6 +30,8 @@ export type ChannelMessage = {
fields: Array<{ label: string; value: string }>;
occurredAt?: string;
location?: { label: string; name: string };
+ /** The organization of a project `location` (an organization location needs no second line). */
+ organization?: { label: string; name: string };
labels?: { date: string; changes: string; before: string; after: string; empty: string };
changes?: Array<{ label: string; before: string | null; after: string | null }>;
/** Absolute link to the resource in GitOps (`ORIGIN`), when there is one. */
diff --git a/src/lib/server/infra/notifications/slack/slack-blocks.ts b/src/lib/server/infra/notifications/slack/slack-blocks.ts
index 5396cc2..c31f00f 100644
--- a/src/lib/server/infra/notifications/slack/slack-blocks.ts
+++ b/src/lib/server/infra/notifications/slack/slack-blocks.ts
@@ -86,6 +86,12 @@ export function buildSlackPayload(message: ChannelMessage): SlackPayload {
const date = message.occurredAt ? slackDate(message.occurredAt) : null;
const whereAndWhen = [
+ message.organization
+ ? mrkdwn(
+ `*${inline(message.organization.label)}*\n${inline(message.organization.name)}`,
+ FIELD_TEXT_MAX,
+ )
+ : null,
message.location
? mrkdwn(
`*${inline(message.location.label)}*\n${inline(message.location.name)}`,
diff --git a/src/lib/server/infra/notifications/slack/slack.transport.test.ts b/src/lib/server/infra/notifications/slack/slack.transport.test.ts
index be9c9bb..d4a1b04 100644
--- a/src/lib/server/infra/notifications/slack/slack.transport.test.ts
+++ b/src/lib/server/infra/notifications/slack/slack.transport.test.ts
@@ -106,6 +106,7 @@ describe('Slack Block Kit payload', () => {
link: null,
occurredAt: '2026-11-26T08:49:41.000Z',
location: { label: 'Proyecto', name: 'Mordor' },
+ organization: { label: 'Organización', name: 'Kettu ' },
labels: ES_LABELS,
changes: [
{ label: 'Descripción', before: null, after: 'Texto nuevo\ncon saltos' },
@@ -118,6 +119,7 @@ describe('Slack Block Kit payload', () => {
{
type: 'section',
fields: [
+ { type: 'mrkdwn', text: '*Organización*\nKettu <!here>' },
{ type: 'mrkdwn', text: '*Proyecto*\nMordor' },
{
type: 'mrkdwn',
diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts
index c693309..002a38f 100644
--- a/src/lib/server/notifications/channels.ts
+++ b/src/lib/server/notifications/channels.ts
@@ -349,12 +349,8 @@ export async function completeSlackFlow(
if (!(await canManageChannels(locals, location, 'create'))) {
return { location: withStatus(result.returnTo, 'Forbidden'), error: 'Forbidden' };
}
- const installed = await slackAppService.installWorkspace(result);
- const status = installed === 'installed' ? 'installed' : 'slack_workspace_taken';
- return {
- location: withStatus(result.returnTo, status),
- error: installed === 'installed' ? null : status,
- };
+ await slackAppService.installWorkspace(result);
+ return { location: withStatus(result.returnTo, 'installed'), error: null };
}
if (result.kind === 'channel') {
diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts
index 0796b0d..917cebc 100644
--- a/src/modules/alerts/application/alert.channels.test.ts
+++ b/src/modules/alerts/application/alert.channels.test.ts
@@ -497,6 +497,7 @@ describe('alerts with notification channels', () => {
it('says what changed instead of repeating the project, the date or the field names', () => {
const message = buildAlertChannelMessage(projectUpdated());
expect(message.location).toEqual({ label: 'Project', name: 'Mordor' });
+ expect(message.organization).toEqual({ label: 'Organization', name: 'Kettu' });
expect(message.text).toBe('[GitOps] Proyecto actualizado');
expect(message.labels).toEqual({
date: 'Date',
@@ -513,6 +514,15 @@ describe('alerts with notification channels', () => {
expect(message.fields).toEqual([]);
});
+ it('an organization event names the organization once, as its location', () => {
+ const message = buildAlertChannelMessage({
+ ...projectUpdated(),
+ where: { organization: 'Kettu', organizationSlug: 'kettu' },
+ });
+ expect(message.location).toEqual({ label: 'Organization', name: 'Kettu' });
+ expect(message).not.toHaveProperty('organization');
+ });
+
it('is written in the language it is asked for', () => {
const es = buildAlertChannelMessage(projectUpdated(), 'es');
const en = buildAlertChannelMessage(projectUpdated(), 'en');
diff --git a/src/modules/alerts/infrastructure/alert-channel-message.ts b/src/modules/alerts/infrastructure/alert-channel-message.ts
index 7e67fc5..6d325a5 100644
--- a/src/modules/alerts/infrastructure/alert-channel-message.ts
+++ b/src/modules/alerts/infrastructure/alert-channel-message.ts
@@ -41,6 +41,10 @@ export function buildAlertChannelMessage(
: where.organization
? { label: t('alerts.email.organization'), name: where.organization }
: undefined;
+ const organization =
+ where.project && where.organization
+ ? { label: t('alerts.email.organization'), name: where.organization }
+ : undefined;
const changes = describeChanges(input, t);
const fields = describeEventFields(event, definition, input.names, { omitSensitive: true })
@@ -49,7 +53,7 @@ export function buildAlertChannelMessage(
label: t(field.label),
value: fieldText(field, t),
}))
- .filter((field) => !location || field.value !== location.name);
+ .filter((field) => field.value !== location?.name && field.value !== organization?.name);
const headline =
summary !== eventLabel
@@ -64,6 +68,7 @@ export function buildAlertChannelMessage(
fields,
occurredAt: event.occurredAt,
...(location ? { location } : {}),
+ ...(organization ? { organization } : {}),
labels: {
date: t('alerts.email.occurredAt'),
changes: t('alerts.channel.changes'),
diff --git a/src/modules/notifications/application/slack-app.service.test.ts b/src/modules/notifications/application/slack-app.service.test.ts
index 7bc7c8c..2e3aa43 100644
--- a/src/modules/notifications/application/slack-app.service.test.ts
+++ b/src/modules/notifications/application/slack-app.service.test.ts
@@ -26,7 +26,18 @@ const INSTALL: SlackInstall = {
type User = { id: string; username: string; disabled: boolean };
-function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean } = {}) {
+const NAMES: Record = {
+ 'org-1': 'Acme Corp',
+ 'org-2': 'Beta Corp',
+ 'org-3': 'Gamma',
+};
+
+function setup(
+ options: {
+ config?: SlackAppConfig | null;
+ canCreate?: boolean | ((organizationId: string) => boolean);
+ } = {},
+) {
const workspaces = new InMemorySlackWorkspaceRepository();
const cipher = createChannelCipher(() => 'encryption-key');
const identities = new Map();
@@ -36,6 +47,8 @@ function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean }
};
const openView = vi.fn(async () => ({ ok: true as const }));
const members = new Set(['user-1', 'admin-1']);
+ /** Members of other organizations than org-1 (org-1 uses `members`). */
+ const orgMembers = new Map>();
const service = new SlackAppService({
readConfig: () => (options.config === undefined ? CONFIG : options.config),
workspaces,
@@ -55,15 +68,23 @@ function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean }
},
},
access: {
- canCreateChannels: async () => options.canCreate ?? true,
- canViewOrganization: async (userId) => members.has(userId),
- organizationName: async () => 'Acme Corp',
+ canCreateChannels: async (_userId, organizationId) =>
+ typeof options.canCreate === 'function'
+ ? options.canCreate(organizationId)
+ : (options.canCreate ?? true),
+ canViewOrganization: async (userId, organizationId) =>
+ (organizationId === 'org-1' ? members : orgMembers.get(organizationId))?.has(userId) ??
+ false,
+ organizationName: async (id) => NAMES[id] ?? null,
},
channels: {
- listSlack: async () => [
- { name: 'DevOps ES', enabled: true },
- { name: '', enabled: false },
- ],
+ listSlack: async (organizationId) =>
+ organizationId === 'org-1'
+ ? [
+ { name: 'DevOps ES', enabled: true },
+ { name: '', enabled: false },
+ ]
+ : [],
},
secret: () => 'token-secret',
now: () => NOW,
@@ -88,16 +109,33 @@ function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean }
result: await service.confirmLink(url.searchParams.get('token'), userId),
};
};
- const submit = (name: string, locale = 'en', ids = { team: 'T1', user: 'U1' }) =>
+ /** Submits the channel form: `organization` is the picked one, or the form's single one. */
+ const submit = (
+ name: string,
+ locale = 'en',
+ organization: { picked?: string; only?: string } = { only: 'org-1' },
+ ) =>
service.handleInteraction(
{
type: 'view_submission',
- team: { id: ids.team },
- user: { id: ids.user },
+ team: { id: 'T1' },
+ user: { id: 'U1' },
view: {
callback_id: 'gitops_channel',
+ private_metadata: organization.only ?? '',
state: {
values: {
+ ...('picked' in organization
+ ? {
+ organization: {
+ value: {
+ selected_option: organization.picked
+ ? { value: organization.picked }
+ : null,
+ },
+ },
+ }
+ : {}),
name: { value: { type: 'plain_text_input', value: name } },
locale: { value: { selected_option: { value: locale } } },
},
@@ -106,7 +144,17 @@ function setup(options: { config?: SlackAppConfig | null; canCreate?: boolean }
},
ORIGIN,
);
- return { service, workspaces, cipher, openView, command, link, submit, members };
+ return {
+ service,
+ workspaces,
+ cipher,
+ openView,
+ command,
+ link,
+ submit,
+ members,
+ orgMembers,
+ };
}
describe('SlackAppService', () => {
@@ -141,7 +189,7 @@ describe('SlackAppService', () => {
describe('workspaces', () => {
it('stores the workspace with its token encrypted and never shows it', async () => {
const { service, workspaces, cipher } = setup();
- expect(await service.installWorkspace(INSTALL)).toBe('installed');
+ await service.installWorkspace(INSTALL);
const [stored] = [...workspaces.rows.values()];
expect(stored.botToken).not.toContain('xoxb');
expect(cipher.decrypt(stored.id, stored.botToken, 'slack-bot-token')).toBe('xoxb-secret');
@@ -150,24 +198,43 @@ describe('SlackAppService', () => {
expect(view).not.toHaveProperty('botToken');
});
- it('reinstalls in place, but never moves a workspace to another organization', async () => {
+ it('reinstalls in place within the organization', async () => {
const { service, workspaces } = setup();
await service.installWorkspace(INSTALL);
- expect(await service.installWorkspace({ ...INSTALL, teamName: 'Acme Inc' })).toBe(
- 'installed',
- );
+ await service.installWorkspace({ ...INSTALL, teamName: 'Acme Inc' });
expect(workspaces.rows.size).toBe(1);
expect([...workspaces.rows.values()][0].teamName).toBe('Acme Inc');
- expect(await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' })).toBe('taken');
+ });
+
+ it('installs the same workspace in several organizations, sharing the newest bot token', async () => {
+ const { service, workspaces, cipher } = setup();
+ await service.installWorkspace(INSTALL);
+ await service.installWorkspace({
+ ...INSTALL,
+ organizationId: 'org-2',
+ userId: 'admin-2',
+ locale: 'en',
+ botToken: 'xoxb-new',
+ });
+ expect(workspaces.rows.size).toBe(2);
+ const [first] = await service.workspacesOf('org-1');
+ const [second] = await service.workspacesOf('org-2');
+ expect(first).toMatchObject({ teamId: 'T1', locale: 'es', installedByUserId: 'admin-1' });
+ expect(second).toMatchObject({ teamId: 'T1', locale: 'en', installedByUserId: 'admin-2' });
+ for (const row of workspaces.rows.values()) {
+ expect(cipher.decrypt(row.id, row.botToken, 'slack-bot-token')).toBe('xoxb-new');
+ }
});
it('removes a workspace of the organization only', async () => {
const { service } = setup();
await service.installWorkspace(INSTALL);
+ await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' });
const [view] = await service.workspacesOf('org-1');
expect(await service.removeWorkspace('org-2', view.id)).toBe(false);
expect(await service.removeWorkspace('org-1', view.id)).toBe(true);
expect(await service.workspacesOf('org-1')).toEqual([]);
+ expect(await service.workspacesOf('org-2')).toHaveLength(1);
});
});
@@ -197,7 +264,15 @@ describe('SlackAppService', () => {
slackUserId: 'U1',
slackUserName: 'ana.slack',
});
- expect(request?.workspace.teamName).toBe('Acme');
+ expect(request).toMatchObject({ teamName: 'Acme', organizationIds: ['org-1'] });
+ });
+
+ it('login: an account of any organization of the workspace can link', async () => {
+ const { service, link, orgMembers } = setup();
+ await service.installWorkspace(INSTALL);
+ await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' });
+ orgMembers.set('org-2', new Set(['user-2']));
+ expect((await link('user-2')).result).toBe('linked');
});
it('login: the link points at the link page of this origin', async () => {
@@ -244,6 +319,36 @@ describe('SlackAppService', () => {
);
});
+ it('channel: offers only the organizations where the account can create channels', async () => {
+ const { service, command, link, openView } = setup({
+ canCreate: (organizationId) => organizationId !== 'org-3',
+ });
+ for (const organizationId of ['org-1', 'org-2', 'org-3']) {
+ await service.installWorkspace({ ...INSTALL, organizationId });
+ }
+ await link();
+ expect(await command('channel')).toBeNull();
+ const view = (openView.mock.calls[0] as unknown[])[2] as any;
+ expect(view.private_metadata).toBeUndefined();
+ const picker = view.blocks.find((block: any) => block.block_id === 'organization');
+ expect(picker.element.options.map((option: any) => option.value)).toEqual(['org-1', 'org-2']);
+ expect(picker.element.options[1].text.text).toBe('Beta Corp');
+ });
+
+ it('channel: with one organization the form names it and carries it', async () => {
+ const { service, command, link, openView } = setup({
+ canCreate: (organizationId) => organizationId === 'org-2',
+ });
+ await service.installWorkspace(INSTALL);
+ await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' });
+ await link();
+ await command('channel');
+ const view = (openView.mock.calls[0] as unknown[])[2] as any;
+ expect(view.private_metadata).toBe('org-2');
+ expect(view.blocks.some((block: any) => block.block_id === 'organization')).toBe(false);
+ expect(JSON.stringify(view.blocks[0])).toContain('Beta Corp');
+ });
+
it('channel: needs notifications:create in the organization', async () => {
const { service, command, link, openView } = setup({ canCreate: false });
await service.installWorkspace(INSTALL);
@@ -252,7 +357,7 @@ describe('SlackAppService', () => {
expect(openView).not.toHaveBeenCalled();
});
- it('status: the organization, the account and the Slack channels, escaped', async () => {
+ it('status: the account and the Slack channels of its organizations, escaped', async () => {
const { service, command, link } = setup();
await service.installWorkspace(INSTALL);
await link();
@@ -263,6 +368,20 @@ describe('SlackAppService', () => {
expect(text).toContain('<!here>');
expect(text).not.toContain('');
});
+
+ it('status: never names organizations the account cannot see, nor any to unlinked users', async () => {
+ const { service, command, link } = setup();
+ await service.installWorkspace(INSTALL);
+ await service.installWorkspace({ ...INSTALL, organizationId: 'org-2' });
+ const unlinked = (await command('status')) as { text: string };
+ expect(unlinked.text).not.toContain('Acme Corp');
+ expect(unlinked.text).toContain('/gitops login');
+
+ await link();
+ const { text } = (await command('status')) as { text: string };
+ expect(text).toContain('Acme Corp');
+ expect(text).not.toContain('Beta Corp');
+ });
});
describe('channel form', () => {
@@ -285,6 +404,34 @@ describe('SlackAppService', () => {
});
});
+ it('uses the organization picked in the form, checked against the workspace', async () => {
+ const { service, link, submit } = setup({
+ canCreate: (organizationId) => organizationId !== 'org-3',
+ });
+ for (const organizationId of ['org-1', 'org-2', 'org-3']) {
+ await service.installWorkspace({ ...INSTALL, organizationId });
+ }
+ await link();
+ const reply = (await submit('Ops', 'es', { picked: 'org-2' })) as { view: any };
+ const url = new URL(reply.view.blocks[1].elements[0].url);
+ expect(service.readChannelRequest(url.searchParams.get('token'))).toMatchObject({
+ organizationId: 'org-2',
+ });
+ // nothing picked, not allowed there, or an organization of another workspace
+ expect(await submit('Ops', 'es', { picked: undefined })).toMatchObject({
+ errors: { organization: expect.any(String) },
+ });
+ expect(await submit('Ops', 'es', { picked: 'org-3' })).toMatchObject({
+ errors: { organization: expect.any(String) },
+ });
+ expect(await submit('Ops', 'es', { picked: 'org-9' })).toMatchObject({
+ errors: { organization: expect.any(String) },
+ });
+ expect(await submit('Ops', 'es', { only: 'org-9' })).toMatchObject({
+ response_action: 'errors',
+ });
+ });
+
it('reports field errors: empty or long names, unlinked users, no permission', async () => {
const { service, link, submit } = setup();
await service.installWorkspace(INSTALL);
diff --git a/src/modules/notifications/application/slack-app.service.ts b/src/modules/notifications/application/slack-app.service.ts
index 90a388d..7da6472 100644
--- a/src/modules/notifications/application/slack-app.service.ts
+++ b/src/modules/notifications/application/slack-app.service.ts
@@ -56,6 +56,12 @@ export type SlackChannelRequest = {
export type SlackLinkResult = 'linked' | 'taken' | 'invalid' | 'not_installed' | 'forbidden';
+/** A `/notifications/slack/link` request: the Slack user and the organizations of its workspace. */
+export type SlackLinkDetails = SlackLinkRequest & {
+ teamName: string;
+ organizationIds: string[];
+};
+
type Dependencies = {
readConfig: () => SlackAppConfig | null;
workspaces: SlackWorkspaceRepositoryPort;
@@ -82,8 +88,10 @@ type Dependencies = {
};
/**
- * The GitOps Slack app: workspaces installed per organization, and the `/gitops` command that
- * links Slack users to their GitOps accounts and connects channels. A channel connected from Slack
+ * The GitOps Slack app: workspaces installed per organization (one Slack workspace can be installed
+ * in several organizations), and the `/gitops` command that links Slack users to their GitOps
+ * accounts and connects channels. A Slack user acts only in the organizations of the workspace that
+ * their linked GitOps account can reach. A channel connected from Slack
* still goes through Slack's own channel picker (the only way to get its webhook): the form here
* only names it, then hands a short-lived link to `/notifications/slack/connect`.
*/
@@ -110,11 +118,19 @@ export class SlackAppService {
/**
* Saves the workspace of an install for its organization (the caller checked the permission).
- * A workspace belongs to one organization: installing it from another one is refused.
+ * Several organizations can install the same workspace; they share the app's bot token, so the
+ * new one (and the workspace name) is saved in every organization that has it.
*/
- async installWorkspace(install: SlackInstall): Promise<'installed' | 'taken'> {
- const existing = await this.deps.workspaces.findByTeamId(install.teamId);
- if (existing && existing.organizationId !== install.organizationId) return 'taken';
+ async installWorkspace(install: SlackInstall): Promise {
+ const installed = await this.deps.workspaces.listByTeamId(install.teamId);
+ for (const other of installed) {
+ if (other.organizationId === install.organizationId) continue;
+ await this.deps.workspaces.update(other.id, {
+ teamName: install.teamName,
+ botToken: this.deps.cipher.encrypt(other.id, install.botToken, BOT_TOKEN_PURPOSE),
+ });
+ }
+ const existing = installed.find((item) => item.organizationId === install.organizationId);
if (existing) {
await this.deps.workspaces.update(existing.id, {
teamName: install.teamName,
@@ -122,7 +138,7 @@ export class SlackAppService {
locale: install.locale,
installedByUserId: install.userId,
});
- return 'installed';
+ return;
}
const id = crypto.randomUUID();
const timestamp = new Date(this.now()).toISOString();
@@ -137,7 +153,6 @@ export class SlackAppService {
createdAt: timestamp,
updatedAt: timestamp,
});
- return 'installed';
}
async workspacesOf(organizationId: string): Promise {
@@ -147,8 +162,8 @@ export class SlackAppService {
}
/**
- * Forgets a workspace of the organization: `/gitops` stops working there until it is installed
- * again. Its channels keep their webhooks (remove the app in Slack to revoke them).
+ * Forgets a workspace of the organization: `/gitops` stops acting on it until it is installed
+ * again (other organizations with the same workspace keep it). Its channels keep their webhooks (remove the app in Slack to revoke them).
*/
async removeWorkspace(organizationId: string, workspaceId: string): Promise {
const workspace = (await this.deps.workspaces.listByOrganization(organizationId)).find(
@@ -167,20 +182,20 @@ export class SlackAppService {
const slackUserId = params.get('user_id') ?? '';
const [action = ''] = (params.get('text') ?? '').trim().toLowerCase().split(/\s+/);
- const workspace = teamId ? await this.deps.workspaces.findByTeamId(teamId) : null;
- const t = translator(workspace?.locale ?? DEFAULT_CHANNEL_LOCALE);
- if (!workspace) return ephemeral(t('notifications.slackApp.notInstalled'));
+ const installs = await this.installsOf(teamId);
+ const t = translator(replyLocale(installs));
+ if (!installs.length) return ephemeral(t('notifications.slackApp.notInstalled'));
switch (action) {
case 'login':
case 'link':
- return this.login(workspace, slackUserId, params.get('user_name'), origin, t);
+ return this.login(teamId, slackUserId, params.get('user_name'), origin, t);
case 'channel':
case 'canal':
- return this.openChannelForm(workspace, slackUserId, params.get('trigger_id'), t);
+ return this.openChannelForm(installs, slackUserId, params.get('trigger_id'), t);
case 'status':
case 'estado':
- return this.status(workspace, slackUserId, t);
+ return this.status(installs, slackUserId, t);
default:
return ephemeral(t('notifications.slackApp.help'));
}
@@ -192,7 +207,11 @@ export class SlackAppService {
type?: string;
team?: { id?: string };
user?: { id?: string };
- view?: { callback_id?: string; state?: { values?: Record } };
+ view?: {
+ callback_id?: string;
+ private_metadata?: string;
+ state?: { values?: Record };
+ };
};
// link buttons also report their click: nothing to do but acknowledge it
if (data?.type !== 'view_submission' || data.view?.callback_id !== CHANNEL_VIEW) return null;
@@ -200,9 +219,20 @@ export class SlackAppService {
const teamId = data.team?.id ?? '';
const slackUserId = data.user?.id ?? '';
const values = data.view.state?.values ?? {};
- const workspace = teamId ? await this.deps.workspaces.findByTeamId(teamId) : null;
- const t = translator(workspace?.locale ?? DEFAULT_CHANNEL_LOCALE);
- if (!workspace) return fieldError('name', t('notifications.slackApp.notInstalled'));
+ const installs = await this.installsOf(teamId);
+ const t = translator(replyLocale(installs));
+ if (!installs.length) return fieldError('name', t('notifications.slackApp.notInstalled'));
+
+ // the organization picked in the form, or the only one it offered
+ const organizationId = String(
+ values.organization?.value?.selected_option?.value ?? data.view.private_metadata ?? '',
+ );
+ const workspace = installs.find((item) => item.organizationId === organizationId);
+ if (!workspace) {
+ return values.organization
+ ? fieldError('organization', t('notifications.slackApp.channel.organizationRequired'))
+ : fieldError('name', t('notifications.slackApp.notInstalled'));
+ }
const name = String(values.name?.value?.value ?? '').trim();
const selected = values.locale?.value?.selected_option?.value;
@@ -216,7 +246,10 @@ export class SlackAppService {
const user = await this.linkedUser(teamId, slackUserId);
if (!user || user.disabled) return fieldError('name', t('notifications.slackApp.notLinked'));
if (!(await this.deps.access.canCreateChannels(user.id, workspace.organizationId))) {
- return fieldError('name', t('notifications.slackApp.forbidden'));
+ return fieldError(
+ values.organization ? 'organization' : 'name',
+ t('notifications.slackApp.forbidden'),
+ );
}
const token = signToken(
@@ -265,10 +298,11 @@ export class SlackAppService {
// --- linking accounts -------------------------------------------------------------------
- /** The Slack user behind a `/notifications/slack/link` token, with its workspace, or `null`. */
- async readLinkRequest(
- token: string | null,
- ): Promise<(SlackLinkRequest & { workspace: SlackWorkspaceView }) | null> {
+ /**
+ * The Slack user behind a `/notifications/slack/link` token, with the organizations its
+ * workspace is installed in, or `null`.
+ */
+ async readLinkRequest(token: string | null): Promise {
if (!token) return null;
const data = verifySignedToken(LINK_PURPOSE, token, {
secret: this.deps.secret(),
@@ -277,24 +311,26 @@ export class SlackAppService {
if (!data || typeof data.teamId !== 'string' || typeof data.slackUserId !== 'string') {
return null;
}
- const workspace = await this.deps.workspaces.findByTeamId(data.teamId);
- if (!workspace) return null;
+ const installs = await this.deps.workspaces.listByTeamId(data.teamId);
+ if (!installs.length) return null;
return {
teamId: data.teamId,
slackUserId: data.slackUserId,
slackUserName: typeof data.slackUserName === 'string' ? data.slackUserName : null,
- workspace: toSlackWorkspaceView(workspace),
+ teamName: installs[installs.length - 1].teamName,
+ organizationIds: installs.map((item) => item.organizationId),
};
}
/**
- * Links the Slack user of `token` to the signed-in `userId`. The user must belong to the
- * workspace's organization: a link never gives access to another organization.
+ * Links the Slack user of `token` to the signed-in `userId`. The user must belong to one of the
+ * organizations of the workspace. A link never gives access to anything: every command checks
+ * the account's permissions in the organization it acts on.
*/
async confirmLink(token: string | null, userId: string): Promise {
const request = await this.readLinkRequest(token);
if (!request) return 'invalid';
- if (!(await this.deps.access.canViewOrganization(userId, request.workspace.organizationId))) {
+ if (!(await this.visibleOrganizations(userId, request.organizationIds)).length) {
return 'forbidden';
}
const result = await this.deps.identities.link(
@@ -307,12 +343,33 @@ export class SlackAppService {
// --- commands ---------------------------------------------------------------------------
+ private installsOf(teamId: string): Promise {
+ return teamId ? this.deps.workspaces.listByTeamId(teamId) : Promise.resolve([]);
+ }
+
private linkedUser(teamId: string, slackUserId: string) {
return this.deps.identities.find(SLACK_IDENTITY_PROVIDER, slackIdentity(teamId, slackUserId));
}
+ /** The organizations of `organizationIds` the user can see, in the same order. */
+ private async visibleOrganizations(userId: string, organizationIds: string[]) {
+ const visible = await Promise.all(
+ organizationIds.map((id) => this.deps.access.canViewOrganization(userId, id)),
+ );
+ return organizationIds.filter((_, index) => visible[index]);
+ }
+
+ private async organizationOptions(installs: SlackWorkspace[]) {
+ return Promise.all(
+ installs.map(async (item) => ({
+ id: item.organizationId,
+ name: (await this.deps.access.organizationName(item.organizationId)) ?? item.teamName,
+ })),
+ );
+ }
+
private login(
- workspace: SlackWorkspace,
+ teamId: string,
slackUserId: string,
slackUserName: string | null,
origin: string,
@@ -320,7 +377,7 @@ export class SlackAppService {
): SlackReply {
const token = signToken(
LINK_PURPOSE,
- { teamId: workspace.teamId, slackUserId, slackUserName },
+ { teamId, slackUserId, slackUserName },
{ secret: this.deps.secret(), ttlMs: SLACK_LINK_TTL_MS, now: this.now() },
);
const url = `${origin}${SLACK_LINK_PATH}?${new URLSearchParams({ token })}`;
@@ -346,69 +403,101 @@ export class SlackAppService {
};
}
+ /**
+ * Opens the channel form with the organizations of the workspace where the linked account can
+ * create channels: a picker when there are several, none when there is one.
+ */
private async openChannelForm(
- workspace: SlackWorkspace,
+ installs: SlackWorkspace[],
slackUserId: string,
triggerId: string | null,
t: Translate,
): Promise {
- const user = await this.linkedUser(workspace.teamId, slackUserId);
+ const user = await this.linkedUser(installs[0].teamId, slackUserId);
if (!user) return ephemeral(t('notifications.slackApp.notLinked'));
if (user.disabled) return ephemeral(t('notifications.slackApp.disabled'));
- if (!(await this.deps.access.canCreateChannels(user.id, workspace.organizationId))) {
- return ephemeral(t('notifications.slackApp.forbidden'));
- }
+ const allowed = await Promise.all(
+ installs.map((item) => this.deps.access.canCreateChannels(user.id, item.organizationId)),
+ );
+ const targets = installs.filter((_, index) => allowed[index]);
+ if (!targets.length) return ephemeral(t('notifications.slackApp.forbidden'));
if (!triggerId) return ephemeral(t('notifications.slackApp.failed', { code: 'no_trigger' }));
- const organization =
- (await this.deps.access.organizationName(workspace.organizationId)) ?? workspace.teamName;
+ // every install of the workspace holds the same bot token; the newest one is the freshest
+ const newest = [...installs].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))[0];
let botToken: string;
try {
- botToken = this.deps.cipher.decrypt(workspace.id, workspace.botToken, BOT_TOKEN_PURPOSE);
+ botToken = this.deps.cipher.decrypt(newest.id, newest.botToken, BOT_TOKEN_PURPOSE);
} catch {
return ephemeral(t('notifications.slackApp.failed', { code: 'token' }));
}
const opened = await this.deps.api.openView(
botToken,
triggerId,
- channelFormView(t, organization, workspace.locale),
+ channelFormView(
+ t,
+ (await this.organizationOptions(targets)).sort((a, b) => a.name.localeCompare(b.name)),
+ replyLocale(targets),
+ ),
);
return opened.ok ? null : ephemeral(t('notifications.slackApp.failed', { code: opened.error }));
}
+ /**
+ * The account and, for each organization of the workspace it can see, its Slack channels. An
+ * unlinked Slack user learns nothing about the organizations.
+ */
private async status(
- workspace: SlackWorkspace,
+ installs: SlackWorkspace[],
slackUserId: string,
t: Translate,
): Promise {
- const [user, organization, channels] = await Promise.all([
- this.linkedUser(workspace.teamId, slackUserId),
- this.deps.access.organizationName(workspace.organizationId),
- this.deps.channels.listSlack(workspace.organizationId),
- ]);
- const lines = [
- t('notifications.slackApp.status.organization', {
- organization: escapeSlack(organization ?? workspace.organizationId),
+ const user = await this.linkedUser(installs[0].teamId, slackUserId);
+ if (!user) return ephemeral(t('notifications.slackApp.status.notLinked'));
+ const visible = new Set(
+ await this.visibleOrganizations(
+ user.id,
+ installs.map((item) => item.organizationId),
+ ),
+ );
+ const organizations = await Promise.all(
+ (
+ await this.organizationOptions(installs.filter((item) => visible.has(item.organizationId)))
+ ).map(async (organization) => {
+ const channels = await this.deps.channels.listSlack(organization.id);
+ return [
+ t('notifications.slackApp.status.organization', {
+ organization: escapeSlack(organization.name),
+ }),
+ channels.length
+ ? t('notifications.slackApp.status.channels', {
+ channels: channels
+ .map((channel) =>
+ channel.enabled
+ ? escapeSlack(channel.name)
+ : `${escapeSlack(channel.name)} (${t('notifications.slackApp.status.disabled')})`,
+ )
+ .join(', '),
+ })
+ : t('notifications.slackApp.status.noChannels'),
+ ].join('\n');
}),
- user
- ? t('notifications.slackApp.status.linked', { username: escapeSlack(user.username) })
- : t('notifications.slackApp.status.notLinked'),
- channels.length
- ? t('notifications.slackApp.status.channels', {
- channels: channels
- .map((channel) =>
- channel.enabled
- ? escapeSlack(channel.name)
- : `${escapeSlack(channel.name)} (${t('notifications.slackApp.status.disabled')})`,
- )
- .join(', '),
- })
- : t('notifications.slackApp.status.noChannels'),
+ );
+ const lines = [
+ t('notifications.slackApp.status.linked', { username: escapeSlack(user.username) }),
+ ...(organizations.length
+ ? organizations
+ : [t('notifications.slackApp.status.noOrganizations')]),
];
- return ephemeral(lines.join('\n'));
+ return ephemeral(lines.join('\n\n'));
}
}
+/** Replies before anyone is known use the language picked at the first install of the workspace. */
+function replyLocale(installs: SlackWorkspace[]): ChannelLocale {
+ return installs[0]?.locale ?? DEFAULT_CHANNEL_LOCALE;
+}
+
// --- Block Kit ------------------------------------------------------------------------------
function plain(text: string) {
@@ -441,21 +530,58 @@ function title(text: string) {
return plain(text.length > 24 ? `${text.slice(0, 23)}…` : text);
}
-function channelFormView(t: Translate, organization: string, locale: ChannelLocale) {
+/** Slack caps option texts at 75 characters. */
+function optionText(text: string) {
+ return plain(text.length > 75 ? `${text.slice(0, 74)}…` : text);
+}
+
+/**
+ * The channel form. With one organization it is named in the intro and travels in
+ * `private_metadata`; with several the user picks it (checked again on submit either way).
+ */
+function channelFormView(
+ t: Translate,
+ organizations: { id: string; name: string }[],
+ locale: ChannelLocale,
+) {
const option = (value: ChannelLocale) => ({
text: plain(t(`notifications.slackApp.locale.${value}`)),
value,
});
+ const [only] = organizations;
+ const target =
+ organizations.length === 1
+ ? [
+ section(
+ t('notifications.slackApp.channel.intro', { organization: escapeSlack(only.name) }),
+ ),
+ ]
+ : [
+ section(t('notifications.slackApp.channel.introMany')),
+ {
+ type: 'input',
+ block_id: 'organization',
+ label: plain(t('notifications.slackApp.channel.organization')),
+ element: {
+ type: 'static_select',
+ action_id: 'value',
+ placeholder: plain(t('notifications.slackApp.channel.organizationPlaceholder')),
+ options: organizations.slice(0, 100).map((organization) => ({
+ text: optionText(organization.name),
+ value: organization.id,
+ })),
+ },
+ },
+ ];
return {
type: 'modal',
callback_id: CHANNEL_VIEW,
+ ...(organizations.length === 1 ? { private_metadata: only.id } : {}),
title: title(t('notifications.slackApp.channel.title')),
submit: plain(t('notifications.slackApp.channel.next')),
close: plain(t('notifications.slackApp.channel.cancel')),
blocks: [
- section(
- t('notifications.slackApp.channel.intro', { organization: escapeSlack(organization) }),
- ),
+ ...target,
{
type: 'input',
block_id: 'name',
diff --git a/src/modules/notifications/domain/slack-workspace.domain.ts b/src/modules/notifications/domain/slack-workspace.domain.ts
index b8af341..f051309 100644
--- a/src/modules/notifications/domain/slack-workspace.domain.ts
+++ b/src/modules/notifications/domain/slack-workspace.domain.ts
@@ -1,6 +1,9 @@
import type { ChannelLocale } from '#lib/server/infra/notifications/chat-types';
-/** A Slack workspace with the GitOps app installed, linked to one organization. */
+/**
+ * A Slack workspace with the GitOps app installed in one organization. The same workspace can be
+ * installed in several organizations: one row per (workspace, organization).
+ */
export type SlackWorkspace = {
id: string;
teamId: string;
diff --git a/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts b/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts
index 0a01b5d..0237841 100644
--- a/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts
+++ b/src/modules/notifications/infrastructure/repositories/slack-workspace.repository.ts
@@ -7,7 +7,8 @@ import {
import type { SlackWorkspace } from '../../domain/slack-workspace.domain';
export interface SlackWorkspaceRepositoryPort {
- findByTeamId(teamId: string): Promise;
+ /** Every organization the Slack workspace is installed in, oldest install first. */
+ listByTeamId(teamId: string): Promise;
listByOrganization(organizationId: string): Promise;
insert(workspace: SlackWorkspace): Promise;
update(
@@ -37,10 +38,14 @@ function toWorkspace(row: Record): SlackWorkspace {
};
}
+function byCreation(rows: SlackWorkspace[]): SlackWorkspace[] {
+ return rows.sort((a, b) => a.createdAt.localeCompare(b.createdAt) || a.id.localeCompare(b.id));
+}
+
export class SlackWorkspaceRepository extends Repository implements SlackWorkspaceRepositoryPort {
- async findByTeamId(teamId: string) {
- const result = await this.db.select().from(SlackWorkspaceEntity).where({ teamId }).limit(1);
- return result.rows[0] ? toWorkspace(result.rows[0]) : null;
+ async listByTeamId(teamId: string) {
+ const result = await this.db.select().from(SlackWorkspaceEntity).where({ teamId });
+ return byCreation(result.rows.map(toWorkspace));
}
async listByOrganization(organizationId: string) {
@@ -68,9 +73,12 @@ export class SlackWorkspaceRepository extends Repository implements SlackWorkspa
export class InMemorySlackWorkspaceRepository implements SlackWorkspaceRepositoryPort {
rows = new Map();
- async findByTeamId(teamId: string) {
- const row = [...this.rows.values()].find((item) => item.teamId === teamId);
- return row ? structuredClone(row) : null;
+ async listByTeamId(teamId: string) {
+ return byCreation(
+ [...this.rows.values()]
+ .filter((item) => item.teamId === teamId)
+ .map((item) => structuredClone(item)),
+ );
}
async listByOrganization(organizationId: string) {
diff --git a/src/routes/notifications/slack/link/+page.server.ts b/src/routes/notifications/slack/link/+page.server.ts
index 71c0652..2607222 100644
--- a/src/routes/notifications/slack/link/+page.server.ts
+++ b/src/routes/notifications/slack/link/+page.server.ts
@@ -1,4 +1,5 @@
import { fail, redirect } from '@sveltejs/kit';
+import { cancanService } from '#modules/auth';
import { organizationService } from '#modules/organization';
import { slackAppService } from '#modules/notifications';
import { LINK_PAGE_HEADERS } from '#lib/server/notifications/links';
@@ -13,16 +14,23 @@ export async function load({ url, locals, setHeaders }) {
const token = url.searchParams.get('token') ?? '';
const request = await slackAppService.readLinkRequest(token);
if (!request) return { token, link: { state: 'invalid' as const } };
- const organization = await organizationService
- .getOrganization(request.workspace.organizationId)
- .catch(() => null);
+ // only the organizations of the workspace this account can see: the page never names the rest
+ const organizations = [];
+ for (const organizationId of request.organizationIds) {
+ if (!(await cancanService.canViewOrganization(locals.user, organizationId))) continue;
+ const organization = await organizationService
+ .getOrganization(organizationId)
+ .catch(() => null);
+ if (organization) organizations.push(organization.name);
+ }
+ if (!organizations.length) return { token, link: { state: 'forbidden' as const } };
return {
token,
link: {
state: 'ready' as const,
- teamName: request.workspace.teamName,
+ teamName: request.teamName,
slackUserName: request.slackUserName,
- organization: organization?.name ?? request.workspace.teamName,
+ organization: organizations.join(', '),
username: locals.user.username as string,
},
};
diff --git a/src/routes/notifications/slack/link/+page.svelte b/src/routes/notifications/slack/link/+page.svelte
index 2c6d20e..ddad77b 100644
--- a/src/routes/notifications/slack/link/+page.svelte
+++ b/src/routes/notifications/slack/link/+page.svelte
@@ -51,6 +51,8 @@
{$_('notifications.slackLink.confirm')}
+ {:else if data.link.state === 'forbidden'}
+ {$_('notifications.slackLink.errors.forbidden')}
{:else}
{$_('notifications.slackLink.errors.invalid')}
{/if}
From 77947f38b2d1d6b816b18f2fb6294dc986342b12 Mon Sep 17 00:00:00 2001
From: "Liam Verdejo (ES)"
Date: Mon, 30 Nov 2026 10:29:55 +0100
Subject: [PATCH 2/2] Feat Fix disconnect slack disabled card and alerts
---
.github/copilot-instructions.md | 54 ++++++++----
CLAUDE.md | 86 +++++++++++++------
src/lib/alerts/delivery.test.ts | 31 +++++++
src/lib/alerts/delivery.ts | 47 ++++++++++
src/lib/alerts/types.ts | 6 ++
src/lib/components/alerts/AlertEditor.svelte | 8 +-
src/lib/components/alerts/AlertList.svelte | 60 +++++++++++--
src/lib/components/alerts/AlertWizard.svelte | 60 ++++++++++---
.../notifications/ChannelList.svelte | 10 ++-
src/lib/i18n/locales/en.json | 20 +++--
src/lib/i18n/locales/es.json | 20 +++--
src/lib/notifications/channel-connection.ts | 14 +++
src/lib/notifications/types.ts | 3 +
src/lib/server/alerts/page.ts | 15 +++-
src/lib/server/notifications/channels.ts | 11 ++-
.../alerts/application/alert.channels.test.ts | 54 ++++++++++++
.../alerts/application/alert.service.ts | 23 ++++-
src/modules/alerts/application/types.ts | 3 +
src/modules/alerts/index.ts | 1 +
.../notification-channel.service.test.ts | 50 ++++++++++-
.../notification-channel.service.ts | 63 ++++++++++++--
.../domain/notification-channel.domain.ts | 17 +++-
src/modules/notifications/index.ts | 1 +
src/routes/api/alerts/server.test.ts | 1 +
24 files changed, 565 insertions(+), 93 deletions(-)
create mode 100644 src/lib/alerts/delivery.test.ts
create mode 100644 src/lib/alerts/delivery.ts
create mode 100644 src/lib/notifications/channel-connection.ts
diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 247aa31..185a6e3 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -101,6 +101,7 @@ para obtener flags de lectura de alto nivel que se filtran en AppSidebar según
Roles por defecto en `src/modules/auth/domain/role-permissions.data.ts`. Los permisos incluyen scope
como prefijo (ej: `organization:projects:read`, `project:vault:secrets:all`) y se almacenan verbatim sin
transformaciones. Recursos de módulos tienen sub-permisos granulares (ej: `project:vault:secrets:read`, `project:vault:environments:read`):
+
- **GitOps Admin** (`cluster-admin`) — vault, openreport, stateiac (todos)
- **GitOps User** (`cluster-user`) — rol base sin permisos propios para acceso a nivel sistema
- **Organization Admin** — todos los permisos de org (proyectos, usuarios, roles, configuración global, backups, server-access-keys, audit)
@@ -119,32 +120,51 @@ 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.
+canales de notificación (webhook, Slack, Google Chat), verificación y desuscripción.
+
+**Conexión de canales:** `ChannelConnection` (`#lib/notifications/channel-connection.ts`) describe si un
+canal entrega ahora o por qué no:
+- `connected`: entregable
+- `disabled`: deshabilitado manualmente
+- `failures`: auto-deshabilitado tras 20 fallos consecutivos
+- `integration_disabled`: su tipo está apagado en el entorno (Slack sin `SLACK_CLIENT_ID`/`SECRET`), o la
+ organización lo desconectó (ej: último workspace de Slack removido)
+- `unavailable`: sin transport
+
+Cuando se remueve el último workspace de Slack, `disableForIntegration()` deshabilita todos los canales Slack
+habilitados con `disabledReason: 'integration'`; al reinstalar Slack, `restoreForIntegration()` re-habilita solo
+esos (manuales o fallos quedan como estaban).
+
+**Alertas pausadas:** `alertDelivery()` (`#lib/alerts/delivery.ts`, compartido cliente/servidor) dice si una
+alerta es `live` (tiene recipients de email o ≥1 canal conectado) o `paused` (solo canales desconectados):
+muestra como pausada en lista con icono Unplug y razón (ej "Slack desconectado"), se edita pero no se activa sin
+destinos activos, resume automáticamente cuando un canal se conecta. `AlertService` rechaza añadir canal
+desconectado (`channel_disconnected`) y crear/activar alerta sin destinos activos (`no_active_destination`).
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`
+- **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`
+- **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. Los canales muestran badge de `integration_disabled` si su tipo está apagado.
+- **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`):
-cada organización instala el app guardando su fila en `slack_workspaces` (GitDB): **un workspace
-puede instalarse en varias organizaciones** (una fila por workspace+organización), compartiendo bot token
-(re-encriptado en todas). 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 (usuario debe ver ≥1 org del workspace); (2) `/gitops channel` →
-modal nombre/idioma/organización (picker si hay varias permitidas); (3) `/gitops status` →
+**Comando `/gitops`** (requiere `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET` / `SLACK_SIGNING_SECRET`):
+cada organización instala el app guardando su fila en `slack_workspaces` (GitDB): **un workspace
+puede instalarse en varias organizaciones** (una fila por workspace+organización), compartiendo bot token
+(re-encriptado en todas). 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 (usuario debe ver ≥1 org del workspace); (2) `/gitops channel` →
+modal nombre/idioma/organización (picker si hay varias permitidas); (3) `/gitops status` →
cuenta y canales por cada org visible. Rutas de Slack usan CSRF firmado.
-Proyectos no tienen settings de notificación propios: muestran un "?" que dice dónde se gestionan,
+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/`.
diff --git a/CLAUDE.md b/CLAUDE.md
index 79fe560..0402366 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -374,24 +374,25 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
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
+ otherwise it is refused (`type_disabled`) and left out of the new channel type picker, and the
+ existing Slack channels count as disconnected (`integration_disabled`) and deliver nothing until
+ the variables are back. `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.
-
+ 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),
@@ -403,7 +404,35 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(`channel-cipher.ts`, AES-GCM bound to the channel id and the value's purpose) and only ever
leaves the server masked (`https://hooks.slack.com/…/••••1a2b`); changing it means typing it
again. `enabled` flag can disable delivery without deleting the channel; `disabledReason:
- 'failures'` means the platform disabled it after 20 consecutive failures.
+'failures'` means the platform disabled it after 20 consecutive failures.
+
+- Channel connection: `notificationChannelService.connection(channel)` (`ChannelConnection` in
+ `#lib/notifications/channel-connection.ts`) says whether a channel delivers now or why not:
+ - `connected`: deliverable
+ - `disabled`: manually disabled by a person
+ - `failures`: auto-disabled by the platform after 20 consecutive delivery failures
+ - `integration_disabled`: its type is off in the environment (Slack without `SLACK_CLIENT_ID`/`SECRET`), or the
+ organization disconnected it (e.g., last Slack workspace was removed)
+ - `unavailable`: no transport registered
+
+ It is computed, never stored. When an organization removes its last Slack workspace (`removeSlackWorkspace()`),
+ `disableForIntegration()` disables all enabled Slack channels with `disabledReason: 'integration'`; when Slack
+ is installed again, `restoreForIntegration()` enables only those back (ones manually disabled or failed stay
+ as they are). `deliver()` only sends to `connected` channels, the views (`toView()`, alert channel options)
+ carry it, and the settings list badges `integration_disabled`.
+- Paused alerts and delivery status: `alertDelivery()` (`#lib/alerts/delivery.ts`, shared with the
+ client) says whether an alert is `live`: it has email recipients or at least one connected
+ channel. It computes `disconnectedTypes` (types of the alert's disconnected channels without repeats,
+ or `['unknown']` if none exist). Nothing is stored: an enabled alert that is not live shows as
+ **paused** ("Pausada") in the list with an Unplug icon and reason (e.g. "Slack desconectado"), and
+ resumes by itself when a channel is connected again or email recipients are added. `AlertService`
+ refuses to add a disconnected channel to a draft (`channel_disconnected`) and to create or switch on
+ an alert that is not live (`no_active_destination`); other edits of a paused alert (name, conditions,
+ recipients) are allowed. The alert list shows paused alerts with a warning badge, disables the toggle,
+ and shows the disconnected channel types. The wizard locks a channel type whose integration is off
+ (`disconnectedTypes` in the alert page data) or whose channels are all disconnected ("Desconectado" +
+ "Reconectar" link to settings), and both the wizard and the no-JS editor prevent a disconnected channel
+ from being ticked.
- Channel language: `NotificationChannelEntity.locale` (`es` | `en`, rows without it read as `en`,
`CHANNEL_LOCALES` in `chat-types.ts`), set in the channel forms and the API (`locale`, invalid →
`invalid_locale`). The engine passes `deliver()` a builder `(locale) => ChannelMessage`
@@ -411,11 +440,11 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
- Signed channels: webhook is a signed type. The service generates a signing secret on create
(`whsec_` + 32 random bytes, encrypted in `signingSecret`) and returns it in clear **only once**
from `createChannel()` or `POST /api/notification-channels/[id]/rotate-secret` (never readable
- again). Rotation keeps the previous secret in `previousSigningSecret` for 24 h
+ again). Rotation keeps the previous secret in `previousSigningSecret` for 24 h
(`previousSecretExpiresAt`); both are handed to `send()` in `ChatNotification.signingSecrets`
with a stable `deliveryId` per message so receivers can deduplicate retries. The signature is
`X-GitOps-Signature: t=,v1=[,v1=]` using `HMAC-SHA256(secret,
- ".")` on the JSON sent (not encoded).
+".")` on the JSON sent (not encoded).
- Slack (`#lib/server/infra/notifications/slack/`): Incoming Webhook, URL limited to
`https://hooks.slack.com/services/` only (`SLACK_WEBHOOK_RULE`), unsigned. `buildSlackPayload()` turns
the `ChannelMessage` into Block Kit in the channel's language only: header (alert name, `plain_text`), the
@@ -449,27 +478,27 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
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, organization): **several organizations can install the same workspace**
- (each keeps its own row: `teamId` + `organizationId` unique pair), and each one removes only its own row.
- The bot token is shared by every row of a team (a new install re-encrypts it in all of them),
- encrypted (`ChannelCipher` purpose `slack-bot-token`; only used to open forms, `views.open`).
+ row per (Slack team, organization): **several organizations can install the same workspace**
+ (each keeps its own row: `teamId` + `organizationId` unique pair), and each one removes only its own row.
+ The bot token is shared by every row of a team (a new install re-encrypts it in all of them),
+ 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 belong to at least one organization
- of the workspace). `/gitops channel` opens a modal with name, locale and an organization picker
- (listing only the workspace's organizations where the account has `organization:notifications:create`);
- with one, it goes in `private_metadata` and skips the picker; checked again on submit. 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`. `/gitops status` lists the linked account and, per each organization
- of the workspace the account can see, its Slack channels (unlinked users see nothing). Replies use
+ logins come back to it, `#lib/server/return-to`; the user must belong to at least one organization
+ of the workspace). `/gitops channel` opens a modal with name, locale and an organization picker
+ (listing only the workspace's organizations where the account has `organization:notifications:create`);
+ with one, it goes in `private_metadata` and skips the picker; checked again on submit. 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`. `/gitops status` lists the linked account and, per each organization
+ of the workspace the account can see, its Slack channels (unlinked users see nothing). Replies use
the locale picked at the workspace's first 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
@@ -478,19 +507,22 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
Local development of Slack OAuth flows requires HTTPS (Slack refuses `http://` redirect URLs).
Set `DEV_HTTPS=true` and create a self-signed certificate:
+
```bash
mkdir -p .certs && openssl req -x509 -newkey rsa:2048 -nodes -days 365 -subj /CN=localhost \
-addext subjectAltName=DNS:localhost -keyout .certs/localhost-key.pem -out .certs/localhost.pem
```
+
Then open `https://localhost:5173` and register `https://localhost:5173/notifications/slack/callback`
in the test Slack app. See `.env.example` for details.
+
- `ChannelMessage` (built by `buildAlertChannelMessage(input, locale)`): `fields` leave out what
the message says elsewhere: `occurredAt`, `location` (project or organization, and any field with
that name), and `changedFields` when `changes` (translated label + before/after) exists.
`labels` carries the translated `Date`/`Changes`/`Before`/`New`/`empty`, and `text` only adds the summary
when it differs from the event label, so nothing is said twice in two languages.
`note` is the translated side note (test send, throttled count); the raw `suppressed` count is
- still there. `occurredAt` and `location` are always present; `organization` is added when the location is a project
+ still there. `occurredAt` and `location` are always present; `organization` is added when the location is a project
(shows the organization name as an extra field for context); `changes` only for update events;
`labels` only when any of `occurredAt`, `location` or `changes` is used by the transport.
- Update events carry `changes?: FieldChange[]` (`{ field, before, after }`, plain text cut to 200
@@ -506,10 +538,10 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
`User-Agent: GitOps-Webhooks/1`. All webhooks are signed: `createChannel()` and `rotateChannelSecret()`
return the secret in `signingSecret` once; the service encrypts it after and never shows it again.
Receiver docs and the verification example are in `docs/webhooks/` (the example is unit-tested
- and must stay identical in the README). `NOTIFICATIONS_WEBHOOK_ALLOW_HTTP` /
+ and must stay identical in the README). `NOTIFICATIONS_WEBHOOK_ALLOW_HTTP` /
`NOTIFICATIONS_WEBHOOK_ALLOW_PRIVATE_TARGETS` relax the rules for local development and e2e only.
- Failure streaks: every definitive delivery failure of a real message (not tests, not
- `unavailable` types) increments `consecutiveFailures` (one commit each per channel); a success
+ `unavailable` types) increments `consecutiveFailures` (one commit each per channel); a success
resets it. At 20 (`MAX_CONSECUTIVE_FAILURES`) the channel disables itself (`enabled: false`,
`disabledReason: 'failures'`) and publishes `notifications.channel.disabled` (system actor,
organization alertable event with `organization:notifications:read`, payload includes channel
diff --git a/src/lib/alerts/delivery.test.ts b/src/lib/alerts/delivery.test.ts
new file mode 100644
index 0000000..5b8cbf4
--- /dev/null
+++ b/src/lib/alerts/delivery.test.ts
@@ -0,0 +1,31 @@
+import { describe, expect, it } from 'vitest';
+import { alertDelivery } from './delivery';
+
+const none = { userIds: [], roleIds: [], emails: [] };
+const slack = { id: 'c1', type: 'slack', connection: 'connected' as const };
+const off = { id: 'c2', type: 'slack', connection: 'integration_disabled' as const };
+const hook = { id: 'c3', type: 'webhook', connection: 'failures' as const };
+
+describe('alertDelivery', () => {
+ it('is live with a connected channel or someone to email', () => {
+ expect(alertDelivery({ recipients: none, channelIds: ['c1', 'c2'] }, [slack, off]).live).toBe(
+ true,
+ );
+ expect(
+ alertDelivery({ recipients: { ...none, userIds: ['u1'] }, channelIds: ['c2'] }, [off]).live,
+ ).toBe(true);
+ });
+
+ it('is not live when every destination is a disconnected (or deleted) channel', () => {
+ expect(
+ alertDelivery({ recipients: none, channelIds: ['c2', 'c3', 'gone'] }, [off, hook]),
+ ).toEqual({ live: false, disconnectedTypes: ['slack', 'webhook', 'unknown'] });
+ });
+
+ it('is not live when its only channel was deleted and nobody gets the email', () => {
+ expect(alertDelivery({ recipients: none, channelIds: [] }, [slack])).toEqual({
+ live: false,
+ disconnectedTypes: ['unknown'],
+ });
+ });
+});
diff --git a/src/lib/alerts/delivery.ts b/src/lib/alerts/delivery.ts
new file mode 100644
index 0000000..120854d
--- /dev/null
+++ b/src/lib/alerts/delivery.ts
@@ -0,0 +1,47 @@
+import type { ChannelConnection } from '#lib/notifications/channel-connection';
+
+type DeliveryAlert = {
+ recipients: { userIds: readonly string[]; roleIds: readonly string[]; emails: readonly string[] };
+ channelIds?: readonly string[];
+};
+
+type DeliveryChannel = { id: string; type: string; connection: ChannelConnection };
+
+export type AlertDelivery = {
+ /** At least one destination can deliver: email recipients, or a connected channel. */
+ live: boolean;
+ /** Types of the alert's channels that are disconnected, without repeats; `unknown` for one
+ * that no longer exists, and also for an alert left with no destination at all. */
+ disconnectedTypes: string[];
+};
+
+/**
+ * Whether an alert still has somewhere to deliver. An alert whose only destinations are
+ * disconnected channels is paused while it stays enabled, and can't be enabled until one of them
+ * is connected again. Nothing is stored: it follows the channels, so it resumes on its own.
+ */
+export function alertDelivery(
+ alert: DeliveryAlert,
+ channels: readonly DeliveryChannel[],
+): AlertDelivery {
+ const byId = new Map(channels.map((channel) => [channel.id, channel]));
+ const ids = alert.channelIds ?? [];
+ const picked = ids.map((id) => byId.get(id));
+ const disconnectedTypes = [
+ ...new Set(
+ ids.length === 0
+ ? ['unknown']
+ : picked
+ .filter((channel) => !channel || channel.connection !== 'connected')
+ .map((channel) => channel?.type ?? 'unknown'),
+ ),
+ ];
+ const hasEmail =
+ alert.recipients.userIds.length +
+ alert.recipients.roleIds.length +
+ alert.recipients.emails.length >
+ 0;
+ // an alert left with no recipients and no channels (its only channel was deleted) sends nothing
+ const live = hasEmail || picked.some((channel) => channel?.connection === 'connected');
+ return { live, disconnectedTypes };
+}
diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts
index 5b33810..e4e6a00 100644
--- a/src/lib/alerts/types.ts
+++ b/src/lib/alerts/types.ts
@@ -2,6 +2,7 @@
* Data shapes of the alert pages, shared by the loaders (`#lib/server/alerts/page`) and the
* components (`#lib/components/alerts`). Type-only: safe to import from the client.
*/
+import type { ChannelConnection } from '#lib/notifications/channel-connection';
import type { EventDefinition, Operator } from '#lib/events/catalog';
import type { ChannelsSectionData, NotificationSettingsPage } from '#lib/notifications/types';
import type {
@@ -50,6 +51,8 @@ export type AlertChannelOption = {
type: string;
scope: 'organization' | 'project';
enabled: boolean;
+ /** Whether it delivers now (`connected`) or why not. */
+ connection: ChannelConnection;
};
export type ExternalRecipientsEditorData = {
@@ -72,6 +75,9 @@ type Shared = {
recipientUsers: AlertOption[];
recipientRoles: AlertOption[];
channels: AlertChannelOption[];
+ /** Channel types whose integration is off in the environment (Slack without its app): shown
+ * as disconnected even without channels. */
+ disconnectedTypes: string[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
external: ExternalRecipientsEditorData;
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte
index 192fdb7..a21fa3d 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -447,7 +447,8 @@
name="channelIds"
value={channel.id}
checked={selected}
- disabled={!data.canSave || (!data.external.canManage && !selected)}
+ disabled={!data.canSave ||
+ (!selected && (!data.external.canManage || channel.connection !== 'connected'))}
onchange={(event) => {
draft.channelIds = event.currentTarget.checked
? [...draft.channelIds, channel.id]
@@ -463,9 +464,8 @@
>{$_('alerts.editor.channelFromOrganization')}
{/if}
- {#if !channel.enabled}
- {$_('notifications.channels.disabled')}
+ {#if channel.connection !== 'connected'}
+ {$_('alerts.wizard.disconnected')}
{/if}
{#if selected && !data.canSave}
diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte
index b43918d..cedc0a9 100644
--- a/src/lib/components/alerts/AlertList.svelte
+++ b/src/lib/components/alerts/AlertList.svelte
@@ -12,12 +12,14 @@
CircleHelp,
Settings,
Trash2,
+ Unplug,
Webhook,
} from '@lucide/svelte';
import AlertSettingsPanel from './AlertSettingsPanel.svelte';
import AlertWizard from './AlertWizard.svelte';
import { Modal, toast } from '#lib/components/ui';
import { _ } from '#lib/i18n';
+ import { alertDelivery } from '#lib/alerts/delivery';
import { channelTargets, summarizeConditions } from '#lib/alerts/summary';
import type { AlertListData, AlertRow } from '#lib/alerts/types';
@@ -59,6 +61,19 @@
webhook: Webhook,
};
+ /** "Slack desconectado": the disconnected channel types of an alert left with nothing live. */
+ function disconnectedText(types: string[]) {
+ const names = types.map((type) =>
+ type === 'unknown'
+ ? t('alerts.list.aChannel')
+ : t(`alerts.channels.${type.replace('-', '_')}`),
+ );
+ return t('alerts.list.disconnected', { values: { channel: names.join(', ') } });
+ }
+
+ // a code from the toggle action (`no_active_destination`) or a plain message
+ const errorText = $derived(/^[a-z_]+$/.test(error) ? t(`alerts.errors.${error}`) : error);
+
// el asistente: "Crear alerta" y "Editar" lo abren; sus enlaces siguen funcionando sin JS
let wizardOpen = $state(false);
let wizardAlert = $state(null);
@@ -149,7 +164,7 @@
class="rounded-xl border border-danger/30 bg-danger/8 px-4 py-3 text-sm text-red-200"
role="alert"
>
- {error}
+ {errorText}
{/if}
@@ -211,6 +226,13 @@
{#each alerts as alert (alert.id)}
+ {@const delivery = alertDelivery(alert, data.channels)}
+ {@const paused = alert.enabled && !delivery.live}
+ {@const statusText = paused
+ ? $_('alerts.list.paused')
+ : alert.enabled
+ ? $_('alerts.list.enabled')
+ : $_('alerts.list.disabled')}
|
{#if !readonly && data.canUpdate}
@@ -256,32 +278,54 @@
{:else}
-
- {alert.enabled ? $_('alerts.list.enabled') : $_('alerts.list.disabled')}
+
+ {statusText}
{/if}
+ {#if !delivery.live}
+
+ {disconnectedText(
+ delivery.disconnectedTypes,
+ )}
+
+ {/if}
|
{#if !readonly && (data.canUpdate || data.canDelete)}
diff --git a/src/lib/components/alerts/AlertWizard.svelte b/src/lib/components/alerts/AlertWizard.svelte
index 1791f4f..b8d9d25 100644
--- a/src/lib/components/alerts/AlertWizard.svelte
+++ b/src/lib/components/alerts/AlertWizard.svelte
@@ -26,6 +26,7 @@
Settings,
ShieldAlert,
User,
+ Unplug,
Users,
Webhook,
} from '@lucide/svelte';
@@ -65,6 +66,7 @@
mailConfigured: boolean;
external: ExternalRecipientsEditorData;
channels: AlertChannelOption[];
+ disconnectedTypes: string[];
configPath?: string | null;
};
@@ -200,10 +202,10 @@
if (typeOn(type)) {
draft.channelIds = draft.channelIds.filter((id) => !ids.includes(id));
} else if (data.external.canManage) {
- const enabled = channelsOf(type).filter((channel) => channel.enabled);
- const picked = (enabled.length > 0 ? enabled : channelsOf(type)).map(
- (channel) => channel.id,
- );
+ // only connected channels: a disconnected one can't be added to an alert
+ const picked = channelsOf(type)
+ .filter((channel) => channel.connection === 'connected')
+ .map((channel) => channel.id);
draft.channelIds = [...draft.channelIds, ...picked];
}
}
@@ -211,9 +213,19 @@
delete errors.recipients;
}
+ /** The type's integration is off, or it has channels and none of them is connected. */
+ function typeDisconnected(type: ChannelType) {
+ if (type === 'mail') return false;
+ const channels = channelsOf(type);
+ return (
+ data.disconnectedTypes.includes(type) ||
+ (channels.length > 0 && !channels.some((channel) => channel.connection === 'connected'))
+ );
+ }
+
function toggleChannel(channel: AlertChannelOption) {
const on = draft.channelIds.includes(channel.id);
- if (!on && !data.external.canManage) return;
+ if (!on && (!data.external.canManage || channel.connection !== 'connected')) return;
draft.channelIds = on
? draft.channelIds.filter((id) => id !== channel.id)
: [...draft.channelIds, channel.id];
@@ -564,9 +576,11 @@
{#each CHANNEL_TYPES as type (type)}
{@const on = typeOn(type)}
+ {@const disconnected = typeDisconnected(type)}
{@const configured = type === 'mail' || channelsOf(type).length > 0}
{@const locked =
- !on && (!configured || (type !== 'mail' && !data.external.canManage))}
+ !on &&
+ (!configured || disconnected || (type !== 'mail' && !data.external.canManage))}
{@const Icon = channelIcons[type]}
{typeMeta[type].label}
- {configured ? typeMeta[type].description : $_('alerts.wizard.notConfigured')}
+ {disconnected
+ ? $_('alerts.wizard.disconnectedHelp', {
+ values: { channel: typeMeta[type].label },
+ })
+ : configured
+ ? typeMeta[type].description
+ : $_('alerts.wizard.notConfigured')}
- {#if configured}
+ {#if disconnected && !on}
+ {$_('alerts.wizard.disconnected')}
+ {#if data.configPath}
+
+ {$_('alerts.wizard.reconnect')}
+
+ {/if}
+ {:else if configured}
toggleChannel(channel)}
/>
{channel.name}
@@ -720,10 +756,8 @@
>{$_('alerts.editor.channelFromOrganization')}
{/if}
- {#if !channel.enabled}
- {$_('notifications.channels.disabled')}
+ {#if channel.connection !== 'connected'}
+ {$_('alerts.wizard.disconnected')}
{/if}
{/each}
diff --git a/src/lib/components/notifications/ChannelList.svelte b/src/lib/components/notifications/ChannelList.svelte
index 5c7d892..7aa30d9 100644
--- a/src/lib/components/notifications/ChannelList.svelte
+++ b/src/lib/components/notifications/ChannelList.svelte
@@ -154,7 +154,7 @@
{$_(`notifications.channels.locales.${channel.locale}`)}
- {#if !channel.enabled}
+ {#if !channel.enabled && channel.connection !== 'integration_disabled'}
{$_('notifications.channels.signed')}
{/if}
+ {#if channel.connection === 'integration_disabled'}
+
+ {$_('notifications.channels.integrationDisabled')}
+
+ {/if}
{#if !channel.available}
{$_('notifications.channels.unavailable')}
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index 7ab5ad4..369d7bb 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -2084,7 +2084,9 @@
"mail_not_configured": "SMTP is not configured and the alert has no channels: there is nowhere to send the test.",
"test_rate_limited": "You sent too many tests. Wait a few minutes.",
"unknown_channel": "Some channel does not exist or can't be used from here.",
- "forbidden_channel": "You are not allowed to add channels to the alert."
+ "forbidden_channel": "You are not allowed to add channels to the alert.",
+ "channel_disconnected": "That channel is disconnected: reconnect it in the alert settings before adding it.",
+ "no_active_destination": "The alert has no connected destination. Reconnect the channel or add email recipients to enable it."
},
"channels": {
"mail": "Email",
@@ -2123,7 +2125,11 @@
"channelsColumn": "Destinations",
"settings": "Settings",
"settingsInOrganization": "Notification settings (integrations, channels and external email) are managed from the organization.",
- "settingsHelp": "Notification settings"
+ "settingsHelp": "Notification settings",
+ "paused": "Paused",
+ "disconnected": "{channel} disconnected",
+ "aChannel": "A channel",
+ "reconnectToEnable": "Reconnect the channel to enable the alert"
},
"editor": {
"newTitle": "New alert",
@@ -2251,7 +2257,10 @@
"saved": "Alert saved",
"failed": "Could not complete it. Try again.",
"notConfigured": "Not configured",
- "configure": "Configure"
+ "configure": "Configure",
+ "disconnected": "Disconnected",
+ "disconnectedHelp": "{channel} disconnected: reconnect it to use it in alerts.",
+ "reconnect": "Reconnect"
},
"channel": {
"before": "Before",
@@ -2626,11 +2635,12 @@
"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.",
+ "slackAppRemoveConfirm": "/gitops stops working in that workspace and, if it is the organization's last one, its Slack channels are disabled: alerts that only post to Slack are paused. They are enabled again when Slack is installed again.",
"slackAppInstalledToast": "Slack app installed",
"slackAppRemovedToast": "Workspace disconnected",
"new": "New channel",
- "newDescription": "A destination the alerts of the organization and all its projects can post to."
+ "newDescription": "A destination the alerts of the organization and all its projects can post to.",
+ "integrationDisabled": "Disconnected: integration switched off"
},
"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).",
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index e230455..b4244f2 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -2084,7 +2084,9 @@
"mail_not_configured": "El SMTP no está configurado y la alerta no tiene canales: no hay a dónde enviar la prueba.",
"test_rate_limited": "Has enviado demasiadas pruebas. Espera unos minutos.",
"unknown_channel": "Algún canal no existe o no se puede usar desde aquí.",
- "forbidden_channel": "No tienes permiso para añadir canales a la alerta."
+ "forbidden_channel": "No tienes permiso para añadir canales a la alerta.",
+ "channel_disconnected": "Ese canal está desconectado: reconéctalo en los ajustes de alertas antes de añadirlo.",
+ "no_active_destination": "La alerta no tiene ningún destino conectado. Reconecta el canal o añade destinatarios de email para activarla."
},
"channels": {
"mail": "Email",
@@ -2123,7 +2125,11 @@
"channelsColumn": "Destinos",
"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"
+ "settingsHelp": "Configuración de notificaciones",
+ "paused": "Pausada",
+ "disconnected": "{channel} desconectado",
+ "aChannel": "Un canal",
+ "reconnectToEnable": "Reconecta el canal para activar la alerta"
},
"editor": {
"newTitle": "Nueva alerta",
@@ -2251,7 +2257,10 @@
"saved": "Alerta guardada",
"failed": "No se pudo completar. Inténtalo de nuevo.",
"notConfigured": "No configurado",
- "configure": "Configurar"
+ "configure": "Configurar",
+ "disconnected": "Desconectado",
+ "disconnectedHelp": "{channel} desconectado: reconéctalo para usarlo en alertas.",
+ "reconnect": "Reconectar"
},
"channel": {
"before": "Anterior",
@@ -2626,11 +2635,12 @@
"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.",
+ "slackAppRemoveConfirm": "/gitops dejará de funcionar en ese workspace y, si es el último de la organización, sus canales de Slack se desactivarán: las alertas que solo publiquen en Slack quedarán pausadas. Al volver a instalar Slack se reactivan solos.",
"slackAppInstalledToast": "App de Slack instalada",
"slackAppRemovedToast": "Workspace desconectado",
"new": "Nuevo canal",
- "newDescription": "Un destino donde pueden publicar las alertas de la organización y de todos sus proyectos."
+ "newDescription": "Un destino donde pueden publicar las alertas de la organización y de todos sus proyectos.",
+ "integrationDisabled": "Desconectado: integración desactivada"
},
"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).",
diff --git a/src/lib/notifications/channel-connection.ts b/src/lib/notifications/channel-connection.ts
new file mode 100644
index 0000000..8096e95
--- /dev/null
+++ b/src/lib/notifications/channel-connection.ts
@@ -0,0 +1,14 @@
+/**
+ * Whether a notification channel can deliver now, and why not: disabled by a person, by the
+ * platform after repeated failures, its integration switched off in the environment (Slack without
+ * `SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`), or a type without transport. Shared by the
+ * notifications module, the alerts module and the client.
+ */
+export const CHANNEL_CONNECTIONS = [
+ 'connected',
+ 'disabled',
+ 'failures',
+ 'integration_disabled',
+ 'unavailable',
+] as const;
+export type ChannelConnection = (typeof CHANNEL_CONNECTIONS)[number];
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
index cdc3d15..89ba697 100644
--- a/src/lib/notifications/types.ts
+++ b/src/lib/notifications/types.ts
@@ -1,3 +1,4 @@
+import type { ChannelConnection } from '#lib/notifications/channel-connection';
import type { ExternalRecipientView } from '#modules/notifications/domain/external-recipient.domain';
/** Alert settings of an organization (allowed domains and external recipients), as the page and
@@ -36,6 +37,8 @@ export type ChannelView = {
consecutiveFailures: number;
/** `failures` when the platform disabled it. */
disabledReason: string | null;
+ /** Whether it delivers now (`connected`) or why not. */
+ connection: ChannelConnection;
/** Signs its deliveries (webhook): has a rotatable secret. */
signed: boolean;
/** End of a rotation's grace period, while the previous secret still signs. */
diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts
index c2eda06..f8487d9 100644
--- a/src/lib/server/alerts/page.ts
+++ b/src/lib/server/alerts/page.ts
@@ -97,9 +97,16 @@ async function channelOptions(location: AlertLocation): Promise(notificationChannelService.availableTypes());
+ return notificationChannelService.registeredTypes().filter((type) => !available.has(type));
+}
+
async function recipientOptions(location: AlertLocation) {
const [members, roles] = await Promise.all([
alertDirectory.listMembers(location).catch(() => []),
@@ -207,6 +214,7 @@ export async function loadAlertList(
recipientUsers: own.users,
recipientRoles: own.roles,
channels,
+ disconnectedTypes: disconnectedTypes(),
mailConfigured: isMailConfigured(),
external,
settings,
@@ -305,6 +313,7 @@ export async function loadAlertEditor(
recipientUsers: recipients.users,
recipientRoles: recipients.roles,
channels,
+ disconnectedTypes: disconnectedTypes(),
mailConfigured: isMailConfigured(),
external,
canSave: alert ? allowed.canUpdate : allowed.canCreate,
@@ -451,7 +460,11 @@ export function alertActions(
const result = await updateAlert(event.locals, alertId, {
enabled: form.get('enabled') === 'true',
});
- if (!result.ok) return fail(result.status, { error: result.error, alertId });
+ if (!result.ok) {
+ // switching on an alert whose channels are all disconnected: say why
+ const code = result.errors?.channelIds;
+ return fail(result.status, { error: code ?? result.error, alertId });
+ }
return { toggled: alertId };
},
diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts
index 002a38f..90defa8 100644
--- a/src/lib/server/notifications/channels.ts
+++ b/src/lib/server/notifications/channels.ts
@@ -291,9 +291,13 @@ export async function removeSlackWorkspace(
const location: ChannelLocation = { scope: 'organization', organizationId, projectId: null };
if (!(await canManageChannels(locals, location, 'delete'))) return forbidden;
const removed = await slackAppService.removeWorkspace(organizationId, workspaceId);
- return removed
- ? { ok: true, status: 200, data: { id: workspaceId } }
- : { ok: false, status: 404, error: 'Workspace not found' };
+ if (!removed) return { ok: false, status: 404, error: 'Workspace not found' };
+ // Slack disconnected from the organization: its Slack channels stop with it (alerts that only
+ // post there show as paused) and come back when Slack is installed again
+ if ((await slackAppService.workspacesOf(organizationId)).length === 0) {
+ await notificationChannelService.disableForIntegration(organizationId, 'slack');
+ }
+ return { ok: true, status: 200, data: { id: workspaceId } };
}
/** Where the callback sends the browser, and the error code to log when it failed. */
@@ -350,6 +354,7 @@ export async function completeSlackFlow(
return { location: withStatus(result.returnTo, 'Forbidden'), error: 'Forbidden' };
}
await slackAppService.installWorkspace(result);
+ await notificationChannelService.restoreForIntegration(result.organizationId, 'slack');
return { location: withStatus(result.returnTo, 'installed'), error: null };
}
diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts
index 917cebc..c658b19 100644
--- a/src/modules/alerts/application/alert.channels.test.ts
+++ b/src/modules/alerts/application/alert.channels.test.ts
@@ -104,6 +104,7 @@ describe('alerts with notification channels', () => {
type: channel.type,
scope: channel.scope,
enabled: channel.enabled,
+ connection: channels.service.connection(channel),
})),
deliver: (id, message, context) => channels.service.deliver(id, message, context),
};
@@ -183,6 +184,58 @@ describe('alerts with notification channels', () => {
).toBe('unknown_channel');
});
+ describe('disconnected channels', () => {
+ const disable = (id: string) =>
+ channels.service.update(id, { enabled: false }).then(() => undefined);
+
+ it('can not be added to an alert', async () => {
+ await disable(orgChannel);
+ expect(
+ (
+ await validationErrors(
+ service.create(p1, input({ channelIds: [orgChannel] }), actor('admin')),
+ )
+ ).channelIds,
+ ).toBe('channel_disconnected');
+ });
+
+ it('pause an alert left without live destinations, which can not be switched on', async () => {
+ const alert = await service.create(
+ p1,
+ input({ recipients: {}, channelIds: [orgChannel] }),
+ actor('admin'),
+ );
+ await disable(orgChannel);
+ // still enabled (paused): edits that keep it so are fine
+ const renamed = await service.update(alert.id, { name: 'Renamed' }, actor('admin'));
+ expect(renamed.enabled).toBe(true);
+
+ await service.update(alert.id, { enabled: false }, actor('admin'));
+ expect(
+ (await validationErrors(service.update(alert.id, { enabled: true }, actor('admin'))))
+ .channelIds,
+ ).toBe('no_active_destination');
+
+ // the channel is back: the alert can be switched on again
+ await channels.service.update(orgChannel, { enabled: true });
+ await expect(
+ service.update(alert.id, { enabled: true }, actor('admin')),
+ ).resolves.toMatchObject({ enabled: true });
+ });
+
+ it('do not block an alert that still emails someone', async () => {
+ const alert = await service.create(
+ p1,
+ input({ channelIds: [orgChannel], enabled: false }),
+ actor('admin'),
+ );
+ await disable(orgChannel);
+ await expect(
+ service.update(alert.id, { enabled: true }, actor('admin')),
+ ).resolves.toMatchObject({ enabled: true });
+ });
+ });
+
it('drops deleted channels from the alerts of the organization', async () => {
const both = await service.create(
p1,
@@ -308,6 +361,7 @@ describe('alerts with notification channels', () => {
type: channel.type,
scope: channel.scope,
enabled: channel.enabled,
+ connection: mixed.service.connection(channel),
})),
deliver: (id, message, context) => mixed.service.deliver(id, message, context),
};
diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts
index 3c08f42..a21a0cd 100644
--- a/src/modules/alerts/application/alert.service.ts
+++ b/src/modules/alerts/application/alert.service.ts
@@ -1,3 +1,4 @@
+import { alertDelivery } from '#lib/alerts/delivery';
import {
getEventDefinition,
isEventType,
@@ -130,7 +131,12 @@ export class AlertService {
location: AlertLocation,
input: AlertInput,
actor: AlertActor,
- previous: { emails?: readonly string[]; channelIds?: readonly string[] } = {},
+ previous: {
+ emails?: readonly string[];
+ channelIds?: readonly string[];
+ /** Stored state: an enabled alert left without live destinations stays (paused). */
+ enabled?: boolean;
+ } = {},
): Promise {
const errors: AlertValidationErrors = {};
const references: ReferenceCache = new Map();
@@ -177,6 +183,15 @@ export class AlertService {
const hasEmailRecipients =
recipients.userIds.length + recipients.roleIds.length + recipients.emails.length > 0;
if (errors.recipients === 'required' && channelIds.length > 0) delete errors.recipients;
+ // switching an alert on (or creating it) needs a destination that delivers now
+ if (
+ enabled &&
+ previous.enabled !== true &&
+ !Object.keys(errors).some((key) => key === 'channelIds' || key.startsWith('recipients')) &&
+ !alertDelivery({ recipients, channelIds }, selected).live
+ ) {
+ errors.channelIds = 'no_active_destination';
+ }
const channels = [
...new Set([
...(hasEmailRecipients || channelIds.length === 0 ? (['mail'] as const) : []),
@@ -252,6 +267,7 @@ export class AlertService {
const fields = await this.validate(current.location, merged, actor, {
emails: current.recipients.emails,
channelIds: current.channelIds,
+ enabled: current.enabled,
});
await this.repository.update(id, fields);
this.onChange();
@@ -598,6 +614,11 @@ export class AlertService {
return { channelIds, selected };
}
const known = new Set(previous);
+ // a disconnected channel can stay in an alert, but can't be added to one
+ if (selected.some((channel) => !known.has(channel.id) && channel.connection !== 'connected')) {
+ errors.channelIds = 'channel_disconnected';
+ return { channelIds, selected };
+ }
if (channelIds.some((id) => !known.has(id))) {
const permission = `${location.scope}:notifications:update` as const;
if (!(await actor.canRead(permission, locationContext(location)))) {
diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts
index 826f817..a0f7ace 100644
--- a/src/modules/alerts/application/types.ts
+++ b/src/modules/alerts/application/types.ts
@@ -1,4 +1,5 @@
import type { FieldReference } from '#lib/events/catalog';
+import type { ChannelConnection } from '#lib/notifications/channel-connection';
import type { PermissionGrant } from '#lib/permissions';
import type { AlertLocation } from '../domain/alert.domain';
@@ -78,6 +79,8 @@ export type UsableChannel = {
type: string;
scope: 'organization' | 'project';
enabled: boolean;
+ /** Whether it delivers now (`connected`) or why not (`ChannelConnection`). */
+ connection: ChannelConnection;
};
export interface NotificationChannelsPort {
diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts
index 8a65583..84c165a 100644
--- a/src/modules/alerts/index.ts
+++ b/src/modules/alerts/index.ts
@@ -56,6 +56,7 @@ const alertChannels: NotificationChannelsPort = {
type: channel.type,
scope: channel.scope,
enabled: channel.enabled,
+ connection: notificationChannelService.connection(channel),
}));
},
deliver: (channelId, message, context) =>
diff --git a/src/modules/notifications/application/notification-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts
index 1a01ac0..a3b90e0 100644
--- a/src/modules/notifications/application/notification-channel.service.test.ts
+++ b/src/modules/notifications/application/notification-channel.service.test.ts
@@ -213,8 +213,34 @@ describe('NotificationChannelService', () => {
});
});
+ describe('integration disconnected by the organization', () => {
+ it('disables its channels of that type and restores only those', async () => {
+ f = createChannelsFixture({ types: ['slack', 'webhook'] });
+ const slack = await create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x');
+ const off = await create(orgLocation, { type: 'slack', name: 'b', destination: HOOK }, 'x');
+ const hook = await create(
+ orgLocation,
+ { type: 'webhook', name: 'c', destination: HOOK },
+ 'x',
+ );
+ await f.service.update(off.id, { enabled: false });
+
+ await expect(f.service.disableForIntegration(ORG, 'slack')).resolves.toBe(1);
+ const disabled = await f.service.get(slack.id);
+ expect(disabled).toMatchObject({ enabled: false, disabledReason: 'integration' });
+ expect(f.service.connection(disabled)).toBe('integration_disabled');
+ await expect(f.service.deliver(slack.id, message)).resolves.toBe(false);
+ expect((await f.service.get(hook.id)).enabled).toBe(true);
+
+ await expect(f.service.restoreForIntegration(ORG, 'slack')).resolves.toBe(1);
+ expect(await f.service.get(slack.id)).toMatchObject({ enabled: true, disabledReason: null });
+ // disabled by a person: stays disabled
+ expect((await f.service.get(off.id)).enabled).toBe(false);
+ });
+ });
+
describe('types that are switched off', () => {
- it('neither offers nor creates them, while existing channels keep delivering', async () => {
+ it('neither offers nor creates them, and the existing ones stay disconnected meanwhile', async () => {
let slackEnabled = true;
const g = createChannelsFixture({
types: ['slack', 'webhook'],
@@ -235,8 +261,30 @@ describe('NotificationChannelService', () => {
expect(errors).toEqual({ type: 'type_disabled' });
expect(g.service.toView(existing.channel).available).toBe(true);
+ expect(g.service.connection(existing.channel)).toBe('integration_disabled');
+ expect(g.service.toView(existing.channel).connection).toBe('integration_disabled');
+ await expect(g.service.deliver(existing.channel.id, message)).resolves.toBe(false);
+
+ // configured again: connected and delivering, nothing to re-enable by hand
+ slackEnabled = true;
+ expect(g.service.connection(existing.channel)).toBe('connected');
await expect(g.service.deliver(existing.channel.id, message)).resolves.toBe(true);
});
+
+ it('tells why a channel is disconnected', async () => {
+ const channel = await create(
+ orgLocation,
+ { type: 'slack', name: 'ops', destination: HOOK },
+ 'a',
+ );
+ expect(f.service.connection(channel)).toBe('connected');
+ expect(f.service.connection({ ...channel, enabled: false, disabledReason: null })).toBe(
+ 'disabled',
+ );
+ expect(f.service.connection({ ...channel, enabled: false, disabledReason: 'failures' })).toBe(
+ 'failures',
+ );
+ });
});
describe('delivery', () => {
diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts
index 722822e..0f8f75d 100644
--- a/src/modules/notifications/application/notification-channel.service.ts
+++ b/src/modules/notifications/application/notification-channel.service.ts
@@ -21,6 +21,7 @@ import {
NotificationChannelNotFoundError,
NotificationChannelValidationError,
maskDestination,
+ type ChannelConnection,
type ChannelLocation,
type NotificationChannelView,
} from '../domain/notification-channel.domain';
@@ -88,8 +89,9 @@ export type NotificationChannelServiceOptions = {
/** 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.
+ * Whether the integration of `type` is on, on top of having a transport: Slack needs its app
+ * configured (`SLACK_CLIENT_ID` / `SLACK_CLIENT_SECRET`). While it is off no channel of the type
+ * can be created and the existing ones count as disconnected: they deliver nothing.
*/
canCreateType?: (type: ChatChannelType) => boolean;
logger?: {
@@ -150,6 +152,19 @@ export class NotificationChannelService {
return this.options.canCreateType?.(type) ?? true;
}
+ /** Whether the channel delivers now, or why not (see `ChannelConnection`). */
+ connection(
+ channel: Pick,
+ ): ChannelConnection {
+ if (!this.transports.get(channel.type)) return 'unavailable';
+ if (!this.creatable(channel.type)) return 'integration_disabled';
+ if (!channel.enabled) {
+ if (channel.disabledReason === 'integration') return 'integration_disabled';
+ return channel.disabledReason === 'failures' ? 'failures' : 'disabled';
+ }
+ return 'connected';
+ }
+
async get(id: string): Promise {
const channel = await this.repository.findById(id);
if (!channel) throw new NotificationChannelNotFoundError(id);
@@ -191,6 +206,7 @@ export class NotificationChannelService {
const transport = this.transports.get(channel.type);
return {
...rest,
+ connection: this.connection(channel),
destinationMasked,
available: transport !== null,
signed: transport?.signed === true || channel.signingSecret !== null,
@@ -277,6 +293,39 @@ export class NotificationChannelService {
};
}
+ /**
+ * The organization disconnected the integration of `type` (its last Slack workspace): its
+ * enabled channels of that type are disabled with reason `integration`. Returns how many.
+ */
+ async disableForIntegration(organizationId: string, type: ChatChannelType): Promise {
+ const channels = (await this.repository.listByOrganization(organizationId)).filter(
+ (channel) => channel.type === type && channel.enabled,
+ );
+ for (const channel of channels) {
+ await this.repository.update(channel.id, { enabled: false, disabledReason: 'integration' });
+ }
+ return channels.length;
+ }
+
+ /**
+ * The integration of `type` is connected again: the channels `disableForIntegration()` turned
+ * off are enabled again (those disabled by a person or by failures stay as they are).
+ */
+ async restoreForIntegration(organizationId: string, type: ChatChannelType): Promise {
+ const channels = (await this.repository.listByOrganization(organizationId)).filter(
+ (channel) =>
+ channel.type === type && !channel.enabled && channel.disabledReason === 'integration',
+ );
+ for (const channel of channels) {
+ await this.repository.update(channel.id, {
+ enabled: true,
+ disabledReason: null,
+ consecutiveFailures: 0,
+ });
+ }
+ return channels.length;
+ }
+
/** Name, enabled and destination; the type can't change. An empty destination keeps it. */
async update(id: string, input: ChannelInput): Promise {
const channel = await this.get(id);
@@ -328,8 +377,9 @@ export class NotificationChannelService {
}
/**
- * Queues `message` for the channel and resolves with whether it was delivered. Disabled,
- * deleted, unavailable or invalid channels resolve `false` without sending; nothing throws.
+ * Queues `message` for the channel and resolves with whether it was delivered. Disconnected
+ * (disabled, integration off, no transport), deleted or invalid channels resolve `false` without
+ * sending; nothing throws.
*/
async deliver(
channelId: string,
@@ -337,7 +387,10 @@ export class NotificationChannelService {
context: Record = {},
): Promise {
const channel = await this.repository.findById(channelId).catch(() => null);
- if (!channel || !channel.enabled) return false;
+ if (!channel) return false;
+ const connection = this.connection(channel);
+ // a type without transport goes on to `send()`, which records it as `unavailable`
+ if (connection !== 'connected' && connection !== 'unavailable') return false;
return this.send(channel, message, context);
}
diff --git a/src/modules/notifications/domain/notification-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts
index a44e4f8..d0d75b0 100644
--- a/src/modules/notifications/domain/notification-channel.domain.ts
+++ b/src/modules/notifications/domain/notification-channel.domain.ts
@@ -1,3 +1,4 @@
+import type { ChannelConnection } from '#lib/notifications/channel-connection';
import {
DEFAULT_CHANNEL_LOCALE,
isChannelLocale,
@@ -40,13 +41,22 @@ export type NotificationChannelRow = ChannelLocation & {
disabledReason: ChannelDisabledReason | null;
};
-export type ChannelDisabledReason = 'failures';
+/**
+ * Why the platform disabled a channel: `failures` after repeated failed deliveries, `integration`
+ * when its organization disconnected the integration (the last Slack workspace); the latter are
+ * enabled again when the integration is connected again.
+ */
+export type ChannelDisabledReason = 'failures' | 'integration';
/** Encrypted fields: none of them ever leaves the server. */
type SecretFields = 'webhookUrl' | 'signingSecret' | 'previousSigningSecret';
/** What the API and the pages may show: the destination only masked, secrets never. */
+export type { ChannelConnection } from '#lib/notifications/channel-connection';
+
export type NotificationChannelView = Omit & {
+ /** Whether it delivers now (`connected`) or why not. */
+ connection: ChannelConnection;
/** `https://hooks.slack.com/…/••••1a2b` */
destinationMasked: string;
/** Whether its type has a transport: channels of other types are kept but send nothing. */
@@ -110,7 +120,10 @@ export class NotificationChannelDomain implements NotificationChannelRow {
this.previousSecretExpiresAt = toIso(row.previousSecretExpiresAt);
const failures = Number(row.consecutiveFailures);
this.consecutiveFailures = Number.isInteger(failures) && failures > 0 ? failures : 0;
- this.disabledReason = row.disabledReason === 'failures' ? 'failures' : null;
+ this.disabledReason =
+ row.disabledReason === 'failures' || row.disabledReason === 'integration'
+ ? row.disabledReason
+ : null;
}
/** Whether the previous secret still signs at `now` (rotation grace period). */
diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts
index 2855e1b..9cd4bb6 100644
--- a/src/modules/notifications/index.ts
+++ b/src/modules/notifications/index.ts
@@ -204,6 +204,7 @@ export {
NotificationChannelNotFoundError,
NotificationChannelValidationError,
MAX_CONSECUTIVE_FAILURES,
+ type ChannelConnection,
type ChannelLocation,
type NotificationChannelView,
} from './domain/notification-channel.domain';
diff --git a/src/routes/api/alerts/server.test.ts b/src/routes/api/alerts/server.test.ts
index 574afae..4edc6c3 100644
--- a/src/routes/api/alerts/server.test.ts
+++ b/src/routes/api/alerts/server.test.ts
@@ -75,6 +75,7 @@ vi.mock('#modules/alerts', async () => {
type: channel.type,
scope: channel.scope,
enabled: channel.enabled,
+ connection: channels.service.connection(channel),
})),
deliver: (id: string, message: never, context?: Record) =>
channels.service.deliver(id, message, context),
|