diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md
index 2691982..1701f9b 100644
--- a/.github/copilot-instructions.md
+++ b/.github/copilot-instructions.md
@@ -114,22 +114,18 @@ aplican (regla most-specific-wins). Permite delegación de autoridad granular co
`canManageOrganization()` controla acceso al area `/settings`, mientras que `canViewOrganization()` incluye
tambien usuarios con acceso solo a proyectos bajo la organización (ven el overview pero no pueden acciones de org-scope).
-**Alertas y destinatarios externos:** `organization:alerts:read|update` y `project:alerts:read|update`
-gestionan alertas por eventos; `organization:notifications:read|update` y `project:notifications:update`
-gestionan destinatarios externos (personas sin cuenta GitOps: vendors, on-call mailboxes). El módulo
-`$modules/notifications` maneja dominios permitidos, verificación y desuscripción. En
-`/org//settings/alerts/settings`, los administradores listan dominios permitidos (ej: `partner.com`,
-`*.partner.com` para subdominos, normalizado a punycode); en alertas, se agregan addresses en `recipients.emails`.
-Cada dirección nueva es `pending` y genera email de confirmación (token aleatorio, hash almacenado, 7 días TTL,
-single use, rate limitado 3/h por address y 30/h por org). Solo addresses `verified` se entregan; estados:
-`pending` → `verified` → `unsubscribed`, o `blocked` si su dominio se quita de la lista permitida. Una dirección
-`pending` agregada por error puede quitarse desde Settings antes de confirmar: su enlace de confirmación se anula
-y se quita de todas las alertas de la organización (`alertService.removeEmail()`). Las rutas públicas
-`/notifications/verify` y `/notifications/unsubscribe` aceptan POST con tokens (no requieren sesión,
-no permiten GET para evitar que scanners abran URLs). Emails a externos usan template reducido (sin campos
-`sensitive`, sin links a la app) con footer de desuscripción y `List-Unsubscribe` HMAC stateless (90 días TTL).
-Sin `ORIGIN` no se envía nada. Infra: `src/lib/server/infra/tokens.ts` (HMAC con `GITDB_ENCRYPTION_KEY`) y
-`rate-limit.ts`.
+**Alertas, destinatarios externos y canales de notificación:** `organization:alerts:read|update` y
+`project:alerts:read|update` gestionan alertas por eventos; `organization:notifications:read|update`
+y `project:notifications:update` gestionan destinatarios externos y canales. El módulo
+`$modules/notifications` maneja dominios permitidos, canales de notificación (webhook, Slack, Google Chat),
+verificación y desuscripción. En `/org//settings/alerts/settings`, administradores configuran dominios
+permitidos y canales (`NotificationChannelEntity` en GitDB). Alertas guardan `recipients` (usuarios, roles,
+emails externos) y `channelIds` (referencias a canales, no destinatarios individuales). Canales de organización
+se usan en alertas de org y proyecto; canales de proyecto solo en sus alertas. URLs de webhook se encriptan
+con `GITDB_ENCRYPTION_KEY` (AES-GCM por channel id). Emails externos: `pending` → `verified` → `unsubscribed`
+o `blocked` si dominio se quita; template reducido sin campos `sensitive` ni links; `List-Unsubscribe` HMAC
+(90 días). Canales: un mensaje por canal en paralelo, fallo de canal nunca afecta email. Rutas públicas
+`/notifications/verify` y `/notifications/unsubscribe` aceptan POST (no GET). Sin `ORIGIN` no se envía nada.
Al crear una organización (vía bootstrap o `/gitops-settings`), se llama automáticamente a
`roleService.createDefaultOrganizationRoles()`. Al crear un proyecto, se llama a
diff --git a/CLAUDE.md b/CLAUDE.md
index b196040..eb807dd 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -121,10 +121,8 @@ session like any other page. Check it there before inventing a new style.
a `Modal` (`role="alertdialog"`), and deleting a top-level entity asks to type its name.
- Floating panels (`DropdownMenu`, `Select`, `TagInput` suggestions) render in `` through
`floating` in `ui/overlay.ts`, so no `overflow` (tables, modal bodies) clips them.
-- Alerts: one alert notifies several channels (`mail`, `slack`, `google_chat`, `webhook`), one
- message each; targets live in `recipients` (`userIds`/`roleIds`/`emails`, `slackChannels`,
- `googleChatSpaces`, `webhookUrls`). Only `mail` is delivered (`DELIVERED_CHANNELS`); the rest are
- stored and validated. Create/edit happens in `AlertWizard` (modal); the `/new` and `/[id]` pages
+- Alerts: email targets live in `recipients` (`userIds`/`roleIds`/`emails`) and chat or webhook
+ targets in `channelIds` (notification channels); `channels` is derived on save. Create/edit happens in `AlertWizard` (modal); the `/new` and `/[id]` pages
keep the no-JS editor (`AlertEditor`), so new alert fields must be added to both.
- `toast.*` is client-only (module state): call it from event handlers, never during SSR.
- Tokens: `bg-ink-950…500`, `brand-50…900`, text `text-fg|fg-muted|fg-subtle`, status
@@ -239,12 +237,15 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(`scope: 'organization'`, covers every project of it) or a project. `conditions`
(`{ field, operator, value }`) use the catalog fields, combined with `match: 'all' | 'any'`; an
empty list always matches. Organization alerts on project events also get a `projectId` field
- (`listAlertFields`, value taken from the event scope).
+ (`listAlertFields`, value taken from the event scope). Email recipients are in `recipients`
+ (users, roles, external emails); chat and webhook targets are in `channelIds` (references to
+ `NotificationChannelEntity`), not in recipients (a channel delivers to its configured destination,
+ not to individual recipients).
- `AlertService` validates every write against the catalog and the location and throws
`AlertValidationError` with field-level codes (`conditions.0.operator: 'invalid_operator'`):
alertable event compatible with the scope, operators of the field, typed values, references and
- recipients (users, roles) inside the location, and **anti-escalation** (the author must hold the
- event's `readPermission`).
+ recipients (users, roles, emails) inside the location, channels in the location, and
+ **anti-escalation** (the author must hold the event's `readPermission`).
- `AlertEngine` subscribes to `'*'` once per process (`registerAlertEngine()` in `hooks.server.ts`,
HMR-safe). Per event: fixed system notifications first (`system-notifications.data.ts`: access
granted/updated/revoked to the affected user, new personal API keys to their owner, never to the
@@ -272,7 +273,9 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
recipient hash, never the content or the address. `registerMailShutdown()` drains it on
`sveltekit:shutdown` (10 s). Invitations and password resets call `notify()` directly: their
tokens must not travel through the bus or the queue. Without SMTP (`isMailConfigured()`), the
- engine skips events (debug log), warns once at startup and the alert pages show a banner.
+ engine skips emails and system notifications (debug log) but still posts to channels, warns once
+ at startup and the alert pages show a banner. `MailQueue` is a `DeliveryQueue`
+ (`#lib/server/infra/notifications/delivery-queue.ts`), the generic queue channels reuse.
- HTTP: `#lib/server/alerts` (`access.ts` for permissions/location/actor, `operations.ts` shared by
the API and form actions). Routes: `GET /api/events/catalog`, `GET|POST /api/alerts`,
`GET|PATCH|DELETE /api/alerts/[id]`, `POST /api/alerts/[id]/test` and `POST /api/alerts/test`
@@ -310,11 +313,46 @@ in `docs/adr/0001-event-bus-and-alerts.md`.
(`organization:notifications:read`; resend a confirmation, or remove a `pending` address added by
mistake, with `organization:notifications:update`: removing deletes the recipient, so its link
stops working, and `alertService.removeEmail()` drops it from every alert of the organization).
- The "Settings" button of the alert lists (organization and project ones, no sidebar entry) opens
- them in a modal (`AlertSettingsPanel`, data in `AlertListData.settings`) whose forms post to the
- actions of `/org//settings/alerts/settings`, the same page browsers without JavaScript get.
- The alert pages also get `data.external` (`ExternalRecipientsEditorData`: allowed domains, whether
- the user may add addresses, statuses).
+ The "Settings" button of the alert lists (no sidebar entry) opens them in a modal
+ (`AlertSettingsPanel`) together with the location's notification channels; its forms post to the
+ actions of `/settings` (`/org//settings/alerts/settings` or
+ `/org//projects//settings/alerts/settings`), the same pages browsers without
+ JavaScript get. Project settings only hold channels (domains are the organization's). The alert
+ pages also get `data.external` (`ExternalRecipientsEditorData`), `data.channels` (channel options
+ the location's alerts may use), `data.channelsSection` and `data.configPath` (for the settings modal).
+- Notification channels (`$modules/notifications`): `NotificationChannelEntity` (GitDB
+ `notification_channels`), owned by an organization (usable by alerts of the organization and of
+ all its projects) or a project (only its alerts). `type` is `webhook`, `slack` or `google-chat`;
+ a type is available only once its transport is registered with `registerChatTransport()`
+ (`#lib/server/infra/notifications/chat-notification.ts`). This base registers none: each
+ transport (webhook, Slack, Google Chat) activates its own, and tests use `FakeChatTransport`.
+ A `ChatTransport` implements `send()` and `validateDestination()`, the anti-SSRF check
+ (`validateWebhookUrl()`: https, no credentials, no IP literal, default port, allowed host and
+ path) run before saving and again before every send. The destination (`webhookUrl`) is
+ encrypted with `GITDB_ENCRYPTION_KEY` (`channel-cipher.ts`, AES-GCM bound to the channel id)
+ and only ever leaves the server masked (`https://hooks.slack.com/…/••••1a2b`); changing it
+ means typing it again. `enabled` flag can disable delivery without deleting the channel.
+- Channel delivery: alerts store `channelIds` (references to `NotificationChannelEntity`). Adding
+ a channel needs `:notifications:update` (`forbidden_channel`), and a channel must be
+ usable from the alert's location (`unknown_channel`). The engine emails each recipient and
+ posts **one message per channel** in parallel; a failing channel never affects the emails or
+ the other channels, and system notifications never go to channels. The message is a
+ provider-neutral `ChannelMessage` (`buildAlertChannelMessage()`: default language, no
+ `sensitive` fields, "View in GitOps" link, throttled count); transports format it. Deliveries
+ go through the process-wide `channelQueue` (concurrency 3; `postJson()` from
+ `#lib/server/infra/http/webhook-request.ts` with a 5 s timeout and no redirects; `withRetry`
+ only on network errors, 429 honoring `Retry-After`, and 5xx). A permanent failure (4xx,
+ invalid or undecryptable destination, type without transport) sets `lastError`; a success
+ clears it. `lastDeliveryAt` is only refreshed hourly, since each write is a commit. Logs carry
+ the channel id and type, never the URL nor the message.
+- Channels HTTP: `#lib/server/notifications/channels.ts` (permission-first with
+ `:notifications:read|create|update|delete`; a channel the caller can't read is a 404).
+ Routes: `GET|POST /api/notification-channels` (`organizationId` or `projectId`),
+ `GET|PATCH|DELETE /api/notification-channels/[id]` and `POST /api/notification-channels/[id]/test`
+ (posts a test even to a disabled channel). Form actions for the settings pages live in
+ `#lib/server/notifications/channels-page.ts`; the UI is `ChannelsSection`
+ (`#lib/components/notifications/`), and the alert editors pick channels from `data.channels`
+ (the alert's draft has `channelIds: string[]`, not direct recipients by channel type).
- UI: `/org//settings/alerts` and `/org//projects//settings/alerts` (list, `new`,
`[id]`), thin routes over `#lib/server/alerts/page.ts` (loaders and form actions `draft`, `save`,
`test`, `toggle`, `delete`; everything works without JavaScript). Components live in
diff --git a/README.md b/README.md
index 0d4e826..a6a7f56 100644
--- a/README.md
+++ b/README.md
@@ -186,6 +186,21 @@ sensitive fields and links into the app. Removing a domain blocks its addresses
them, and allowing it again restores them. `ORIGIN` must be set: without it, confirmation and
unsubscribe links can't be built and nothing is sent to external addresses.
+#### Notification channels
+
+Alerts can also post to chat channels and webhooks. In **Settings → Alerts**, click **Settings** to
+manage the channels of the organization (usable by every alert of the organization and its
+projects) or of a project (only its alerts). Each channel has a name and the webhook URL its
+provider gives you; the URL is stored encrypted and only ever shown masked. **Send test message**
+posts an example to check it works. Then pick the channels in the alert, next to its email
+recipients: each firing sends one message per channel, and a failing channel never stops the
+emails or the other channels.
+
+Adding channels to an alert needs `organization:notifications:update` or
+`project:notifications:update`: people reading a channel may have no access to the resource.
+Messages leave out sensitive fields. Channel types become available as their transports land
+(generic webhooks, Slack and Google Chat); until then the settings say no type is available yet.
+
### Monitoring
HTTP monitors check a URL (method, headers and body of your choice) every 60 seconds by default and
diff --git a/e2e/specs/alerts.spec.ts b/e2e/specs/alerts.spec.ts
index ce12308..1976df0 100644
--- a/e2e/specs/alerts.spec.ts
+++ b/e2e/specs/alerts.spec.ts
@@ -95,7 +95,7 @@ test.describe('project alerts', () => {
await expect(row.getByRole('switch')).toHaveAttribute('aria-checked', 'true');
});
- test('only email can be enabled and the alert is edited in the same wizard', async ({
+ test('without channels only email can be picked and the alert is edited in the same wizard', async ({
page,
loginAs,
}) => {
@@ -108,12 +108,13 @@ test.describe('project alerts', () => {
await expect(wizard.getByLabel('Nombre', { exact: true })).toHaveValue(GUIDED_NAME);
await wizard.getByRole('button', { name: /Destinos/ }).click();
- // Slack, Google Chat and Webhook have no notifier yet: shown as "soon" and not selectable
- for (const channel of [/^Slack/, /^Google Chat/, /^Webhook/]) {
- const card = wizard.getByRole('checkbox', { name: channel });
- await expect(card).toBeDisabled();
- await expect(card).toContainText('Próximamente');
- await expect(card).toHaveAttribute('aria-checked', 'false');
+ const channels = wizard.getByTestId('alert-channels');
+ await expect(channels.getByRole('checkbox', { name: /^Email/ })).toBeEnabled();
+ for (const type of ['slack', 'google-chat', 'webhook']) {
+ const card = channels.locator(`[data-channel-type="${type}"]`);
+ await expect(card.getByRole('checkbox')).toBeDisabled();
+ await expect(card).toContainText('No configurado');
+ await expect(card.getByRole('link', { name: 'Configurar' })).toBeVisible();
}
const targets = wizard.getByLabel('Destinatarios');
@@ -238,12 +239,23 @@ test.describe('organization alerts', () => {
await expect(domains).toHaveValue('example.com\npartner.com');
});
- test('project admins without organization access get no settings button', async ({
+ test('project admins manage the project channels, not the organization domains', async ({
page,
loginAs,
}) => {
await loginAs('projectAdmin');
await page.goto(alertsUrl);
+ await page.waitForLoadState('networkidle');
+ await page.getByTestId('alert-settings').click();
+ const dialog = page.getByRole('dialog', { name: 'Configuración de alertas' });
+ await expect(dialog.getByTestId('notification-channels')).toBeVisible();
+ await expect(dialog.getByTestId('channel-types-unavailable')).toBeVisible();
+ await expect(dialog.getByLabel('Dominios (uno por línea)')).toHaveCount(0);
+ });
+
+ test('a project viewer gets no settings button', async ({ page, loginAs }) => {
+ await loginAs('projectViewer');
+ await page.goto(alertsUrl);
await expect(page.getByTestId('alert-settings')).toHaveCount(0);
});
});
diff --git a/src/lib/alerts/draft.ts b/src/lib/alerts/draft.ts
index 7f5eee5..a8fc7e5 100644
--- a/src/lib/alerts/draft.ts
+++ b/src/lib/alerts/draft.ts
@@ -13,8 +13,8 @@ export function emptyDraft(): AlertDraft {
eventType: '',
match: 'all',
conditions: [],
- channels: ['mail'],
recipients: emptyRecipients(),
+ channelIds: [],
throttleMinutes: 0,
};
}
@@ -36,7 +36,6 @@ export function draftFromAlert(alert: AlertRow): AlertDraft {
? [...condition.value]
: condition.value,
})),
- channels: [...alert.channels],
// copia de cada lista: `alert` puede ser un proxy reactivo (no admite structuredClone)
recipients: Object.fromEntries(
Object.entries({ ...emptyRecipients(), ...alert.recipients }).map(([key, list]) => [
@@ -44,6 +43,7 @@ export function draftFromAlert(alert: AlertRow): AlertDraft {
[...list],
]),
) as AlertDraft['recipients'],
+ channelIds: [...(alert.channelIds ?? [])],
throttleMinutes: alert.throttleMinutes,
};
}
@@ -60,14 +60,11 @@ export function draftToFormData(
form.set('eventType', draft.eventType);
form.set('match', draft.match);
form.set('throttleMinutes', String(draft.throttleMinutes));
- for (const channel of draft.channels) form.append('channels', channel);
const lists = {
userIds: draft.recipients.userIds,
roleIds: draft.recipients.roleIds,
emails: draft.recipients.emails,
- slackChannels: draft.recipients.slackChannels,
- googleChatSpaces: draft.recipients.googleChatSpaces,
- webhookUrls: draft.recipients.webhookUrls,
+ channelIds: draft.channelIds,
};
for (const [name, values] of Object.entries(lists)) {
for (const value of values) form.append(name, value);
diff --git a/src/lib/alerts/summary.ts b/src/lib/alerts/summary.ts
index b143106..75d6e05 100644
--- a/src/lib/alerts/summary.ts
+++ b/src/lib/alerts/summary.ts
@@ -67,29 +67,31 @@ export function summarizeRecipients(
users: AlertOption[],
roles: AlertOption[],
t: Translate,
+ channels: { ids: string[]; options: Array<{ id: string; name: string }> } = {
+ ids: [],
+ options: [],
+ },
): string {
const names = [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
...(recipients.emails ?? []),
+ ...channels.ids.map((id) => channels.options.find((option) => option.id === id)?.name ?? id),
];
return names.length > 0 ? names.join(', ') : t('alerts.summary.noRecipients');
}
-/** Targets of one channel, ready to print: names for mail, `#canal` for Slack, spaces, URLs. */
export function channelTargets(
channel: string,
- recipients: {
- userIds: string[];
- roleIds: string[];
- emails?: string[];
- slackChannels?: string[];
- googleChatSpaces?: string[];
- webhookUrls?: string[];
+ alert: {
+ recipients: { userIds: string[]; roleIds: string[]; emails?: string[] };
+ channelIds?: string[];
},
users: AlertOption[],
roles: AlertOption[],
+ channels: Array<{ id: string; name: string; type: string }> = [],
): string[] {
+ const { recipients } = alert;
if (channel === 'mail') {
return [
...recipients.roleIds.map((id) => roles.find((role) => role.id === id)?.label ?? id),
@@ -97,8 +99,8 @@ export function channelTargets(
...(recipients.emails ?? []),
];
}
- if (channel === 'slack') return recipients.slackChannels ?? [];
- if (channel === 'google_chat') return recipients.googleChatSpaces ?? [];
- if (channel === 'webhook') return recipients.webhookUrls ?? [];
- return [];
+ return (alert.channelIds ?? [])
+ .map((id) => channels.find((option) => option.id === id))
+ .filter((option) => option?.type === channel)
+ .map((option) => option!.name);
}
diff --git a/src/lib/alerts/types.ts b/src/lib/alerts/types.ts
index d06c065..acfc4fd 100644
--- a/src/lib/alerts/types.ts
+++ b/src/lib/alerts/types.ts
@@ -3,7 +3,7 @@
* components (`#lib/components/alerts`). Type-only: safe to import from the client.
*/
import type { EventDefinition, Operator } from '#lib/events/catalog';
-import type { NotificationSettingsPage } from '#lib/notifications/types';
+import type { ChannelsSectionData, NotificationSettingsPage } from '#lib/notifications/types';
import type {
AlertChannel,
AlertRecipients,
@@ -39,11 +39,19 @@ export type AlertDraft = {
eventType: string;
match: 'all' | 'any';
conditions: DraftCondition[];
- channels: AlertChannel[];
recipients: AlertRecipients;
+ channelIds: string[];
throttleMinutes: number;
};
+export type AlertChannelOption = {
+ id: string;
+ name: string;
+ type: string;
+ scope: 'organization' | 'project';
+ enabled: boolean;
+};
+
export type ExternalRecipientsEditorData = {
canManage: boolean;
allowedDomains: string[];
@@ -63,6 +71,7 @@ type Shared = {
* organization ones, only to name the recipients of inherited alerts). */
recipientUsers: AlertOption[];
recipientRoles: AlertOption[];
+ channels: AlertChannelOption[];
/** `false` when SMTP is not configured: alerts are saved but nothing is sent. */
mailConfigured: boolean;
external: ExternalRecipientsEditorData;
@@ -70,6 +79,8 @@ type Shared = {
export type AlertListData = Shared & {
settings: NotificationSettingsPage | null;
+ channelsSection: ChannelsSectionData | null;
+ configPath: string | null;
alerts: AlertRow[];
/** Organization alerts that also fire for this project (project pages only). */
inherited: AlertRow[];
@@ -90,6 +101,7 @@ export type AlertTestView = {
recipients: Array<{ userId: string; username: string }>;
deniedCount: number;
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
diff --git a/src/lib/components/alerts/AlertEditor.svelte b/src/lib/components/alerts/AlertEditor.svelte
index 64929ae..a196090 100644
--- a/src/lib/components/alerts/AlertEditor.svelte
+++ b/src/lib/components/alerts/AlertEditor.svelte
@@ -23,7 +23,6 @@
DraftCondition,
} from '#lib/alerts/types';
import ConditionBuilder from './ConditionBuilder.svelte';
- import { DELIVERED_CHANNELS } from '#modules/alerts/domain/alert.domain';
import OptionPicker from './OptionPicker.svelte';
type Props = { data: AlertEditorData; form: AlertFormResult };
@@ -39,8 +38,6 @@
}));
let draft = $state(initial.draft);
// canales sin envío todavía: solo se pueden mantener (o quitar) si la alerta ya los tenía
- const initialChannels: string[] = [...initial.draft.channels];
- const isSoon = (channel: string) => !(DELIVERED_CHANNELS as readonly string[]).includes(channel);
let errors = $state>(initial.errors);
let message = $state(initial.message);
let test = $state(initial.test);
@@ -428,47 +425,67 @@
{/if}
-
+
{$_('alerts.editor.channels')}
- {#each [{ key: 'mail', list: null }, { key: 'slack', list: 'slackChannels' }, { key: 'google_chat', list: 'googleChatSpaces' }, { key: 'webhook', list: 'webhookUrls' }] as const as channel (channel.key)}
-
+
{$_('alerts.editor.channelsHelp')}
+ {#if data.channels.length === 0}
+
+ {$_('alerts.editor.noChannels')}
+ {#if data.external.settingsPath}
+
+ {$_('alerts.editor.channelsSettingsLink')}
+
+ {/if}
+
+ {:else}
+ {#each data.channels as channel (channel.id)}
+ {@const selected = draft.channelIds.includes(channel.id)}
{
+ draft.channelIds = event.currentTarget.checked
+ ? [...draft.channelIds, channel.id]
+ : draft.channelIds.filter((id) => id !== channel.id);
+ }}
/>
- {$_(`alerts.channels.${channel.key}`)}
- {#if isSoon(channel.key)}
- {$_('alerts.channels.soon')}
+ {$_(`notifications.channels.types.${channel.type}`)}
+
+ {#if channel.scope === 'organization' && data.scope === 'project'}
+ {$_('alerts.editor.channelFromOrganization')}
{/if}
-
- {#if channel.list && (!isSoon(channel.key) || initialChannels.includes(channel.key))}
-
- {#if errors[`recipients.${channel.list}`]}
-
- {errorFor(`recipients.${channel.list}`)}
-
+ {#if !channel.enabled}
+
{$_('notifications.channels.disabled')}
{/if}
+
+ {#if selected && !data.canSave}
+
{/if}
-
- {/each}
- {#if errors.channels}
- {errorFor('channels')}
+ {/each}
+ {#if draft.channelIds.length > 0}
+
+
+ {$_('alerts.editor.channelsNotice')}
+
+ {/if}
+ {#if !data.external.canManage}
+ {$_('alerts.editor.channelsReadonly')}
+ {/if}
+ {/if}
+ {#if errors.channelIds}
+ {errorFor('channelIds')}
{/if}
@@ -555,6 +572,17 @@
{$_('alerts.test.denied', { values: { count: test.deniedCount } })}
{/if}
+ {#if test.channels?.length > 0}
+
+ {#each test.channels as channel (channel.id)}
+
+ {channel.name}: {channel.delivers
+ ? $_('alerts.test.channelDelivers')
+ : $_('alerts.test.channelSkipped')}
+
+ {/each}
+
+ {/if}
{#if test.external.length > 0}
{#each test.external as recipient (recipient.email)}
diff --git a/src/lib/components/alerts/AlertList.svelte b/src/lib/components/alerts/AlertList.svelte
index 350800b..027ef62 100644
--- a/src/lib/components/alerts/AlertList.svelte
+++ b/src/lib/components/alerts/AlertList.svelte
@@ -51,7 +51,12 @@
const examples = ['alerts.list.example1', 'alerts.list.example2', 'alerts.list.example3'];
- const channelIcons = { mail: Mail, slack: Hash, google_chat: MessageSquare, webhook: Webhook };
+ const channelIcons = {
+ mail: Mail,
+ slack: Hash,
+ 'google-chat': MessageSquare,
+ webhook: Webhook,
+ };
// el asistente: "Crear alerta" y "Editar" lo abren; sus enlaces siguen funcionando sin JS
let wizardOpen = $state(false);
@@ -65,7 +70,7 @@
let settingsOpen = $state(false);
function openSettings(event: MouseEvent) {
- if (!data.settings || event.metaKey || event.ctrlKey || event.shiftKey) return;
+ if (!data.configPath || event.metaKey || event.ctrlKey || event.shiftKey) return;
event.preventDefault();
settingsOpen = true;
}
@@ -86,9 +91,9 @@
- {#if data.external.settingsPath}
+ {#if data.configPath}
{channelTargets(channel, alert.recipients, data.users, data.roles).join(
+ >{channelTargets(channel, alert, data.users, data.roles, data.channels).join(
', ',
) || $_('alerts.summary.noRecipients')}
@@ -344,15 +349,22 @@
{#if data.canCreate || data.canUpdate}
-
+ (settingsOpen = true)}
+ />
{/if}
-{#if data.settings && data.external.settingsPath}
+{#if data.configPath}
{#snippet icon()}
{/snippet}
-
+
{#snippet footer()}
(settingsOpen = false)}
>{$_('common.close')} ;
- saved?: boolean;
- blocked?: number;
- restored?: number;
- resendError?: string;
- resent?: string;
- removeError?: string;
- removed?: string;
- } | null;
+ form?:
+ | ({
+ domains?: string;
+ errors?: Record;
+ saved?: boolean;
+ blocked?: number;
+ restored?: number;
+ resendError?: string;
+ resent?: string;
+ removeError?: string;
+ removed?: string;
+ } & NonNullable)
+ | null;
};
- let { data, action, form = null }: Props = $props();
+ let {
+ data,
+ channels = null,
+ organizationSettingsPath = null,
+ action,
+ form = null,
+ }: Props = $props();
let domainError = $state('');
const formDomainError = $derived(
@@ -43,7 +58,7 @@
let busy = $state<'domains' | string | null>(null);
let domainsText = $derived(
- typeof form?.domains === 'string' ? form.domains : data.allowedDomains.join('\n'),
+ typeof form?.domains === 'string' ? form.domains : (data?.allowedDomains ?? []).join('\n'),
);
function formatDate(value: string | null) {
@@ -123,199 +138,216 @@
- {#if !data.mailConfigured || !data.originConfigured}
-
-
- {!data.mailConfigured
- ? $_('notifications.settings.mailNotConfigured')
- : $_('notifications.settings.originNotConfigured')}
-
- {/if}
+ {#if data}
+ {#if !data.mailConfigured || !data.originConfigured}
+
+
+ {!data.mailConfigured
+ ? $_('notifications.settings.mailNotConfigured')
+ : $_('notifications.settings.originNotConfigured')}
+
+ {/if}
-
-
-
-
-
-
-
- {$_('notifications.settings.domainsTitle')}
-
-
- {$_('notifications.settings.domainsDescription')}
-
+
+
+
+
+
+
+
+ {$_('notifications.settings.domainsTitle')}
+
+
+ {$_('notifications.settings.domainsDescription')}
+
+
-
-
-
+
+
- {#if data.recipients}
-
-
-
-
- {$_('notifications.settings.recipientsTitle')}
-
-
- {$_('notifications.settings.recipientsDescription')}
-
-
+ {#if data.recipients}
+
+
+
+
+ {$_('notifications.settings.recipientsTitle')}
+
+
+ {$_('notifications.settings.recipientsDescription')}
+
+
- {#if form?.resendError}
-
- {$_(`notifications.errors.${form.resendError}`)}
-
- {:else if form?.resent}
- {$_('notifications.settings.resent')}
- {:else if form?.removeError}
-
- {$_(`notifications.errors.${form.removeError}`)}
-
- {:else if form?.removed}
-
- {$_('notifications.settings.removed', { values: { email: form.removed } })}
-
- {/if}
+ {#if form?.resendError}
+
+ {$_(`notifications.errors.${form.resendError}`)}
+
+ {:else if form?.resent}
+ {$_('notifications.settings.resent')}
+ {:else if form?.removeError}
+
+ {$_(`notifications.errors.${form.removeError}`)}
+
+ {:else if form?.removed}
+
+ {$_('notifications.settings.removed', { values: { email: form.removed } })}
+
+ {/if}
- {#if data.recipients.length === 0}
-
- {$_('notifications.settings.recipientsEmpty')}
-
- {:else}
-
-
-
-
-
-
- {$_('notifications.settings.email')}
-
-
- {$_('notifications.settings.status')}
-
-
- {$_('notifications.settings.verifiedAt')}
-
-
- {$_('notifications.settings.lastSent')}
-
-
- {$_('notifications.settings.actions')}
-
-
-
-
- {#each data.recipients as recipient (recipient.id)}
-
- {recipient.email}
-
-
- {$_(`notifications.status.${recipient.status}`)}
-
-
- {formatDate(recipient.verifiedAt)}
-
- {formatDate(recipient.lastVerificationSentAt)}
-
-
-
- {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
-
-
-
- {#if busy === recipient.id} {:else} {/if}
-
-
- {/if}
- {#if data.canManageRecipients && recipient.status === 'pending'}
-
-
- askRemove(event, recipient)}
- data-testid="remove-recipient"
- >
-
-
-
- {/if}
-
-
+ {#if data.recipients.length === 0}
+
+ {$_('notifications.settings.recipientsEmpty')}
+
+ {:else}
+
+
+
+
+
+
+ {$_('notifications.settings.email')}
+
+
+ {$_('notifications.settings.status')}
+
+
+ {$_('notifications.settings.verifiedAt')}
+
+
+ {$_('notifications.settings.lastSent')}
+
+
+ {$_('notifications.settings.actions')}
+
- {/each}
-
-
+
+
+ {#each data.recipients as recipient (recipient.id)}
+
+ {recipient.email}
+
+
+ {$_(`notifications.status.${recipient.status}`)}
+
+
+ {formatDate(recipient.verifiedAt)}
+
+ {formatDate(recipient.lastVerificationSentAt)}
+
+
+
+ {#if data.canManageRecipients && (recipient.status === 'pending' || recipient.status === 'unsubscribed')}
+
+
+
+ {#if busy === recipient.id} {:else} {/if}
+
+
+ {/if}
+ {#if data.canManageRecipients && recipient.status === 'pending'}
+
+
+ askRemove(event, recipient)}
+ data-testid="remove-recipient"
+ >
+
+
+
+ {/if}
+
+
+
+ {/each}
+
+
+
-
- {/if}
-
+ {/if}
+
+ {/if}
+ {:else if organizationSettingsPath}
+
+ {$_('notifications.settings.organizationDomains')}
+ {$_('notifications.settings.organizationDomainsLink')}
+
+ {/if}
+
+ {#if channels}
+
{/if}
-{#if data.canManageRecipients}
+{#if data?.canManageRecipients}
void;
+ } = $props();
const STEPS = ['event', 'conditions', 'channels', 'review'] as const;
type Step = (typeof STEPS)[number];
@@ -87,6 +95,7 @@
let eventQuery = $state('');
let sampleProjectId = $state('');
let droppedConditions = $state(0);
+ let mailOn = $state(true);
// cada apertura empieza de cero (o desde la alerta que se edita)
let wasOpen = false;
@@ -100,6 +109,12 @@
eventQuery = '';
sampleProjectId = '';
droppedConditions = 0;
+ mailOn =
+ !alert ||
+ draft.recipients.userIds.length +
+ draft.recipients.roleIds.length +
+ draft.recipients.emails.length >
+ 0;
}
wasOpen = open;
});
@@ -139,53 +154,77 @@
delete errors.eventType;
}
- // ---------- paso 3: canales ----------
- type ChannelMeta = {
- key: AlertChannel;
- icon: typeof Mail;
- label: string;
- description: string;
+ const channelIcons: Record = {
+ mail: Mail,
+ slack: Hash,
+ 'google-chat': MessageSquare,
+ webhook: Webhook,
};
- const channelMeta: ChannelMeta[] = $derived([
- {
- key: 'mail',
- icon: Mail,
- label: $_('alerts.channels.mail'),
- description: $_('alerts.wizard.mailDescription'),
- },
- {
- key: 'slack',
- icon: Hash,
+
+ const CHANNEL_TYPES = ['mail', 'slack', 'google-chat', 'webhook'] as const;
+ type ChannelType = (typeof CHANNEL_TYPES)[number];
+ const typeMeta = $derived({
+ mail: { label: $_('alerts.channels.mail'), description: $_('alerts.wizard.mailDescription') },
+ slack: {
label: $_('alerts.channels.slack'),
description: $_('alerts.wizard.slackDescription'),
},
- {
- key: 'google_chat',
- icon: MessageSquare,
+ 'google-chat': {
label: $_('alerts.channels.google_chat'),
description: $_('alerts.wizard.googleChatDescription'),
},
- {
- key: 'webhook',
- icon: Webhook,
+ webhook: {
label: $_('alerts.channels.webhook'),
description: $_('alerts.wizard.webhookDescription'),
},
- ]);
+ } satisfies Record);
+
+ const channelsOf = (type: ChannelType) =>
+ data.channels.filter((channel) => channel.type === type);
+
+ function typeOn(type: ChannelType) {
+ if (type === 'mail') return mailOn;
+ return channelsOf(type).some((channel) => draft.channelIds.includes(channel.id));
+ }
- // canales sin envío todavía: no se pueden activar (sí desactivar si una alerta ya los tenía)
- const isSoon = (channel: AlertChannel) => !DELIVERED_CHANNELS.includes(channel);
-
- function toggleChannel(channel: AlertChannel) {
- if (isSoon(channel) && !draft.channels.includes(channel)) return;
- draft.channels = draft.channels.includes(channel)
- ? draft.channels.filter((item) => item !== channel)
- : [...draft.channels, channel].sort(
- (a, b) =>
- channelMeta.findIndex((meta) => meta.key === a) -
- channelMeta.findIndex((meta) => meta.key === b),
+ function toggleType(type: ChannelType) {
+ if (type === 'mail') {
+ mailOn = !mailOn;
+ if (!mailOn) {
+ draft.recipients.userIds = [];
+ draft.recipients.roleIds = [];
+ draft.recipients.emails = [];
+ }
+ } else {
+ const ids = channelsOf(type).map((channel) => channel.id);
+ if (typeOn(type)) {
+ draft.channelIds = draft.channelIds.filter((id) => !ids.includes(id));
+ } else if (data.external.canManage) {
+ const enabled = channelsOf(type).filter((channel) => channel.enabled);
+ const picked = (enabled.length > 0 ? enabled : channelsOf(type)).map(
+ (channel) => channel.id,
);
- delete errors.channels;
+ draft.channelIds = [...draft.channelIds, ...picked];
+ }
+ }
+ delete errors.channelIds;
+ delete errors.recipients;
+ }
+
+ function toggleChannel(channel: AlertChannelOption) {
+ const on = draft.channelIds.includes(channel.id);
+ if (!on && !data.external.canManage) return;
+ draft.channelIds = on
+ ? draft.channelIds.filter((id) => id !== channel.id)
+ : [...draft.channelIds, channel.id];
+ delete errors.channelIds;
+ delete errors.recipients;
+ }
+
+ function configure(event: MouseEvent) {
+ if (!onConfigure || event.metaKey || event.ctrlKey || event.shiftKey) return;
+ event.preventDefault();
+ onConfigure();
}
// destinatarios de email como etiquetas: `role:`, `user:`, `email:`
@@ -274,38 +313,25 @@
code,
})),
);
- const parseSlack = (text: string) => {
- const name = text.trim().toLowerCase().replace(/^#/, '');
- return /^[a-z0-9][a-z0-9._-]{0,79}$/.test(name) ? `#${name}` : null;
- };
- const parseSpace = (text: string) => (text.trim() ? text.trim().slice(0, 128) : null);
- const parseUrl = (text: string) => {
- try {
- const url = new URL(text.trim());
- return url.protocol === 'https:' || url.protocol === 'http:' ? url.toString() : null;
- } catch {
- return null;
- }
- };
-
- function targetsOf(channel: AlertChannel): number {
- return channelTargets(channel, draft.recipients, data.recipientUsers, data.recipientRoles)
- .length;
- }
-
// ---------- validación por paso (lo mínimo para avanzar; el servidor valida todo) ----------
const stepReady = $derived({
event: Boolean(draft.eventType),
conditions: true,
channels:
- draft.channels.length > 0 && draft.channels.every((channel) => targetsOf(channel) > 0),
+ (mailOn
+ ? draft.recipients.userIds.length +
+ draft.recipients.roleIds.length +
+ draft.recipients.emails.length
+ : 0) +
+ draft.channelIds.length >
+ 0,
review: true,
} satisfies Record);
const stepOfError = (key: string): Step => {
if (key === 'eventType') return 'event';
if (key.startsWith('conditions') || key === 'match') return 'conditions';
- if (key.startsWith('recipients') || key === 'channels' || key === 'throttleMinutes') {
+ if (key.startsWith('recipients') || key === 'channelIds' || key === 'throttleMinutes') {
return 'channels';
}
return 'review';
@@ -532,180 +558,191 @@
{:else if step === 'channels'}
-
+
{$_('alerts.wizard.channelsTitle')}
-
{$_('alerts.wizard.channelsHelp')}
+
{$_('alerts.wizard.channelsHelp')}
- {#each channelMeta as meta (meta.key)}
- {@const on = draft.channels.includes(meta.key)}
- {@const soon = isSoon(meta.key) && !on}
-
toggleChannel(meta.key)}
+ data-channel-type={type}
>
- toggleType(type)}
>
- {meta.label}
- {meta.description}
- {#if soon}
- {$_('alerts.channels.soon')}
- {:else}
+ {typeMeta[type].label}
+
+ {configured ? typeMeta[type].description : $_('alerts.wizard.notConfigured')}
+
+
+ {#if configured}
{#if on} {/if}
+ {:else}
+
{$_('alerts.wizard.notConfigured')}
+ {#if data.configPath}
+
+ {$_('alerts.wizard.configure')}
+
+ {/if}
{/if}
-
+
{/each}
- {#if errorFor('channels')}
-
{errorFor('channels')}
+ {#if errorFor('channelIds')}
+
{errorFor('channelIds')}
{/if}
- {#each channelMeta.filter((meta) => draft.channels.includes(meta.key)) as meta (meta.key)}
+ {#if mailOn}
- {meta.label}
+ {$_('alerts.channels.mail')}
- {#if meta.key === 'mail'}
- {#if !data.mailConfigured}
-
- {$_(
- 'alerts.mailDisabled',
- )}
-
- {/if}
-
- {#snippet children(control)}
-
- {/snippet}
-
- {#if externalErrors.length > 0}
-
- {#each externalErrors as failure (failure.email + failure.code)}
- {failure.email}: {$_(`alerts.errors.${failure.code}`)}
- {/each}
-
- {/if}
- {#if draft.recipients.emails.length > 0}
-
-
- {$_('alerts.editor.externalNotice')}
-
- {:else if !data.external.allowedDomains.length && data.external.settingsPath}
-
- {$_('alerts.editor.externalDisabled')}
- {$_('alerts.editor.externalSettingsLink')}
-
- {/if}
-
- {$_('alerts.editor.recipientsNotice')}
+ {$_(
+ 'alerts.mailDisabled',
+ )}
- {:else if meta.key === 'slack'}
-
- {#snippet children(control)}
- ({ label: value, icon: Hash })}
- placeholder="#alertas"
- invalidMessage={$_('alerts.errors.invalid_slack_channel')}
- />
- {/snippet}
-
- {:else if meta.key === 'google_chat'}
-
- {#snippet children(control)}
- ({ label: value, icon: MessageSquare })}
- placeholder={$_('alerts.wizard.googleChatPlaceholder')}
- />
- {/snippet}
-
- {:else}
-
+ {#snippet children(control)}
+
+ {/snippet}
+
+ {#if externalErrors.length > 0}
+
+ {#each externalErrors as failure (failure.email + failure.code)}
+ {failure.email}: {$_(`alerts.errors.${failure.code}`)}
+ {/each}
+
+ {/if}
+ {#if draft.recipients.emails.length > 0}
+
- {#snippet children(control)}
- ({ label: value, icon: Webhook })}
- placeholder="https://hooks.example.com/gitops"
- invalidMessage={$_('alerts.errors.invalid_url')}
- />
- {/snippet}
-
+
+ {$_('alerts.editor.externalNotice')}
+
+ {:else if !data.external.allowedDomains.length && data.external.settingsPath}
+
+ {$_('alerts.editor.externalDisabled')}
+ {$_('alerts.editor.externalSettingsLink')}
+
{/if}
+
+ {$_('alerts.editor.recipientsNotice')}
+
+
+ {/if}
+
+ {#each CHANNEL_TYPES.filter((type) => type !== 'mail' && typeOn(type)) as type (type)}
+ {@const Icon = channelIcons[type]}
+
{/each}
+ {#if draft.channelIds.length > 0}
+
+
+ {$_('alerts.editor.channelsNotice')}
+
+ {/if}
+ {#if !data.external.canManage && data.channels.length > 0}
+
{$_('alerts.editor.channelsReadonly')}
+ {/if}
+
{$_('alerts.wizard.throttle')}
@@ -822,17 +859,29 @@
{$_('alerts.wizard.step.channels')}
- {#each channelMeta.filter( (meta) => draft.channels.includes(meta.key) ) as meta (meta.key)}
+ {#if channelTargets('mail', draft, data.recipientUsers, data.recipientRoles).length > 0}
-
+
- {meta.label}:
+ {$_('alerts.channels.mail')}:
{channelTargets(
- meta.key,
- draft.recipients,
+ 'mail',
+ draft,
data.recipientUsers,
data.recipientRoles,
- ).join(', ') || '—'}
+ ).join(', ')}
+
+
+ {/if}
+ {#each data.channels.filter( (channel) => draft.channelIds.includes(channel.id) ) as channel (channel.id)}
+ {@const Icon = channelIcons[channel.type] ?? Webhook}
+
+
+
+ {$_(`notifications.channels.types.${channel.type}`)}:
+ {channel.name}
{/each}
@@ -944,7 +993,7 @@
post('test', true)}
data-testid="alert-send-test"
diff --git a/src/lib/components/audit-summary.ts b/src/lib/components/audit-summary.ts
index 2960d4d..32c5b32 100644
--- a/src/lib/components/audit-summary.ts
+++ b/src/lib/components/audit-summary.ts
@@ -3,7 +3,12 @@
export type EntityRowChange =
| { type: 'added'; row: Record }
| { type: 'removed'; row: Record }
- | { type: 'modified'; before: Record; after: Record; changedFields: string[] };
+ | {
+ type: 'modified';
+ before: Record;
+ after: Record;
+ changedFields: string[];
+ };
export type FieldValue =
| { kind: 'text'; text: string }
@@ -103,7 +108,10 @@ export function classifyValue(value: unknown): FieldValue {
if (isFlagsObject(value)) {
return {
kind: 'flags',
- flags: Object.entries(value).map(([key, entry]) => ({ label: humanizeField(key), value: Boolean(entry) })),
+ flags: Object.entries(value).map(([key, entry]) => ({
+ label: humanizeField(key),
+ value: Boolean(entry),
+ })),
};
}
return { kind: 'json', json: value };
diff --git a/src/lib/components/notifications/ChannelsSection.svelte b/src/lib/components/notifications/ChannelsSection.svelte
new file mode 100644
index 0000000..cb4cb70
--- /dev/null
+++ b/src/lib/components/notifications/ChannelsSection.svelte
@@ -0,0 +1,481 @@
+
+
+
+
+
+
+ {$_('notifications.channels.title')}
+
+
+ {data.scope === 'project'
+ ? $_('notifications.channels.descriptionProject')
+ : $_('notifications.channels.descriptionOrganization')}
+
+
+
+
+
+ {$_('notifications.channels.privacyNotice')}
+
+
+ {#if form?.channelTest}
+
+ {form.channelTest.sent
+ ? $_('notifications.channels.testSent')
+ : $_('notifications.channels.testFailed', {
+ values: { reason: form.channelTest.error ?? '—' },
+ })}
+
+ {:else if form?.channelError && form.channelForm !== 'create' && !form.channelErrors}
+
+ {errorMessage(form.channelError)}
+
+ {/if}
+
+ {#if data.channels.length === 0}
+
+ {$_('notifications.channels.empty')}
+
+ {:else}
+
+ {#each data.channels as channel (channel.id)}
+ {@const Icon = typeIcons[channel.type] ?? Webhook}
+
+
+
+
+ {channel.name}
+
+ {$_(`notifications.channels.types.${channel.type}`)}
+
+ {#if !channel.enabled}
+
+ {$_('notifications.channels.disabled')}
+
+ {/if}
+ {#if !channel.available}
+
+ {$_('notifications.channels.unavailable')}
+
+ {/if}
+
+
+ {channel.destinationMasked}
+
+
+ {$_('notifications.channels.lastDelivery', {
+ values: { date: formatDate(channel.lastDeliveryAt) },
+ })}
+
+ {#if channel.lastError}
+
+ {$_('notifications.channels.lastError', { values: { error: channel.lastError } })}
+
+ {/if}
+
+
+
+ {#if data.canUpdate}
+
+
+
+ {#if busy === `test:${channel.id}`} {:else} {/if}
+
+
+
+
+
+
+
+
+
+
openEdit(event, channel)}
+ >
+
+
+ {/if}
+ {#if data.canDelete}
+
+
+ openDelete(event, channel)}
+ >
+
+
+
+ {/if}
+
+
+ {/each}
+
+ {/if}
+
+ {#if data.inherited.length > 0}
+
+
+ {$_('notifications.channels.inheritedTitle')}
+
+
{$_('notifications.channels.inheritedDescription')}
+
+ {#each data.inherited as channel (channel.id)}
+ {@const Icon = typeIcons[channel.type] ?? Webhook}
+
+ {channel.name}
+ {#if !channel.enabled}
+ · {$_('notifications.channels.disabled')}
+ {/if}
+
+ {/each}
+
+
+ {/if}
+
+ {#if data.canCreate}
+
+
+
+ {$_('notifications.channels.create')}
+
+ {#if data.availableTypes.length === 0}
+
+ {$_('notifications.channels.noTypes')}
+
+ {:else}
+ {@const errors = { ...formCreateErrors, ...createErrors }}
+
+
+
{$_('notifications.channels.type')}
+
+ {#each data.availableTypes as type (type)}
+ {$_(`notifications.channels.types.${type}`)}
+ {/each}
+
+ {#if errors.type}
+ {errorText(errors, 'type')}
+
{/if}
+
+
+
{$_('notifications.channels.name')}
+
+ {#if errors.name}
+ {errorText(errors, 'name')}
+
{/if}
+
+
+
{$_('notifications.channels.destination')}
+
+ {#if errors.destination}
+
{errorText(errors, 'destination')}
+ {/if}
+
+
+
+ {#if busy === 'create'} {:else} {/if}
+ {$_('notifications.channels.create')}
+
+
+
+ {/if}
+
+ {/if}
+
+
+{#if data.canUpdate}
+
+
+
+
+
{$_('notifications.channels.name')}
+
+ {#if editErrors.name}
+ {errorText(editErrors, 'name')}
+
{/if}
+
+
+
{$_('notifications.channels.newDestination')}
+
+ {#if editErrors.destination}
+ {errorText(editErrors, 'destination')}
+
{/if}
+
+
+ {#snippet footer()}
+ (editOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'edit'} {/if}
+ {$_('notifications.channels.save')}
+
+ {/snippet}
+
+{/if}
+
+{#if data.canDelete}
+
+ {#snippet icon()}
+
+ {/snippet}
+
+
+
+ {#snippet footer()}
+ (deleteOpen = false)}
+ >{$_('common.cancel')}
+
+ {#if busy === 'delete'} {/if}
+ {$_('notifications.channels.delete')}
+
+ {/snippet}
+
+{/if}
diff --git a/src/lib/database/schemas.ts b/src/lib/database/schemas.ts
index dda5f7d..a9e5f5a 100644
--- a/src/lib/database/schemas.ts
+++ b/src/lib/database/schemas.ts
@@ -431,6 +431,26 @@ export const ExternalRecipientEntity = entity('external_recipients', {
.$defaultFn(() => new Date().toISOString()),
});
+export const NotificationChannelEntity = entity('notification_channels', {
+ id: uuid().primaryKey(),
+ type: text().notNull(),
+ name: text().notNull(),
+ scope: text().notNull(),
+ organizationId: uuid().notNull(),
+ projectId: uuid().$defaultFn(() => null),
+ webhookUrl: text().notNull(),
+ enabled: bool().notNull().default(true),
+ createdByUserId: uuid().notNull(),
+ createdAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ updatedAt: timestamp()
+ .notNull()
+ .$defaultFn(() => new Date().toISOString()),
+ lastDeliveryAt: timestamp(),
+ lastError: text(),
+});
+
relations.for(ProjectEntity, ({ one, many }) => ({
roles: many(RoleEntity, { fields: ['id'], references: ['projectId'] }),
organization: one(OrganizationEntity, { fields: ['organizationId'], references: ['id'] }),
diff --git a/src/lib/i18n/locales/en.json b/src/lib/i18n/locales/en.json
index 538e189..fb75b7d 100644
--- a/src/lib/i18n/locales/en.json
+++ b/src/lib/i18n/locales/en.json
@@ -895,6 +895,9 @@
"filterByDate": "Filter by date",
"reportSingular": "report",
"reportPlural": "reports",
+ "pagination": "Pagination",
+ "previousPage": "Previous",
+ "nextPage": "Next",
"noReports": "No reports match the filters.",
"serviceDeleted": "Deleted service",
"serviceLabel": "Service",
@@ -1721,7 +1724,9 @@
"domain_not_allowed": "The domain is not allowed for external recipients.",
"forbidden_external": "You are not allowed to add external recipients.",
"mail_not_configured": "SMTP is not configured: the test email can't be sent.",
- "test_rate_limited": "You sent too many test emails. Wait a few minutes."
+ "test_rate_limited": "You sent too many test emails. 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."
},
"channels": {
"mail": "Email",
@@ -1816,7 +1821,13 @@
"externalStatus": "Status of the external emails",
"sendTest": "Send test email",
"sendingTest": "Sending…",
- "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed)."
+ "sendTestHelp": "Sends a real email with an example event to the alert's recipients that would get it (external ones only once confirmed).",
+ "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.",
+ "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.",
+ "channelsReadonly": "Only people who manage notifications can add channels."
},
"test": {
"matched": "The example event matches the conditions.",
@@ -1828,7 +1839,9 @@
"externalDelivers": "would get it",
"externalSkipped": "would not get it ({status})",
"delivered": "Test email sent: {sent} sent, {failed} failed.",
- "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again."
+ "externalVerificationSent": "does not get the test until it confirms: the confirmation email was sent. Once confirmed, send the test again.",
+ "channelDelivers": "would get the message",
+ "channelSkipped": "would not get it (disabled or deleted)"
},
"mailDisabled": "Email is not configured (NOTIFICATION_SMTP_*): alerts are saved but will not be sent.",
"wizard": {
@@ -1875,7 +1888,9 @@
"skipConditions": "No conditions",
"created": "Alert created",
"saved": "Alert saved",
- "failed": "Could not complete it. Try again."
+ "failed": "Could not complete it. Try again.",
+ "notConfigured": "Not configured",
+ "configure": "Configure"
}
},
"monitoring": {
@@ -2103,7 +2118,11 @@
"remove": "Remove",
"removeTitle": "Remove this recipient?",
"removeDescription": "{email} hasn't confirmed yet. Its confirmation link will stop working and it will be removed from every alert of the organization.",
- "removed": "{email} removed"
+ "removed": "{email} removed",
+ "projectDescription": "Chat channels and webhooks this project's alerts can use.",
+ "descriptionProject": "This project's chat channels and webhooks.",
+ "organizationDomains": "Allowed domains and external recipients are managed in the organization.",
+ "organizationDomainsLink": "Open organization settings"
},
"errors": {
"invalid": "The value is not valid.",
@@ -2113,7 +2132,18 @@
"invalid_status": "This recipient does not need a confirmation.",
"rate_limited": "Too many confirmation emails were sent. Try again later.",
"send_failed": "The confirmation email could not be sent.",
- "Forbidden": "You are not allowed to do this."
+ "Forbidden": "You are not allowed to do this.",
+ "required": "This field is required.",
+ "too_long": "It is too long.",
+ "invalid_type": "Invalid channel type.",
+ "type_unavailable": "This channel type is not available yet.",
+ "invalid_url": "The URL is not valid.",
+ "not_https": "The URL must use https.",
+ "credentials": "The URL can't include a user or a password.",
+ "ip_address": "The URL can't point to an IP address.",
+ "port": "The URL can't use another port.",
+ "host_not_allowed": "That domain is not allowed for this channel type.",
+ "path_not_allowed": "The URL path does not match this channel type."
},
"link": {
"invalid": "This link is not valid or has already been used.",
@@ -2142,6 +2172,52 @@
"ignore": "If you did not expect this email, ignore it: you will not get anything.",
"footer": "You receive this email because someone in a GitOps organization added your address to an alert."
}
+ },
+ "channels": {
+ "title": "Channels",
+ "descriptionOrganization": "Chat channels and webhooks the alerts of the organization and its projects can post to.",
+ "descriptionProject": "Channels only this project's alerts can use.",
+ "privacyNotice": "A channel is read by people who may have no GitOps account or permissions. The channel URL is stored encrypted and never shown in full again.",
+ "empty": "No channels yet.",
+ "types": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
+ },
+ "disabled": "Disabled",
+ "unavailable": "Type not available",
+ "lastDelivery": "Last delivery: {date}",
+ "lastError": "Last error: {error}",
+ "test": "Send test message",
+ "testSent": "Test message sent.",
+ "testFailed": "The test message could not be sent ({reason}).",
+ "enable": "Enable",
+ "disable": "Disable",
+ "delete": "Delete",
+ "confirmDelete": "Delete this channel? Alerts using it will stop posting to it.",
+ "edit": "Edit",
+ "name": "Name",
+ "newDestination": "New URL (empty keeps the current one)",
+ "save": "Save",
+ "inheritedTitle": "Organization channels",
+ "inheritedDescription": "This project's alerts can also use these channels. They are managed from the organization settings.",
+ "create": "Add channel",
+ "noTypes": "No channel type is available yet.",
+ "type": "Type",
+ "destination": "Webhook URL",
+ "testMessage": {
+ "title": "GitOps test message for {channel}",
+ "summary": "This channel will get the alerts of {where}.",
+ "event": "Test message",
+ "channel": "Channel",
+ "open": "Open in GitOps"
+ },
+ "created": "Channel added",
+ "saved": "Channel saved",
+ "deleted": "Channel deleted",
+ "disabledToast": "Channel disabled",
+ "enabledToast": "Channel enabled",
+ "deleteTitle": "Delete the channel?"
}
}
}
diff --git a/src/lib/i18n/locales/es.json b/src/lib/i18n/locales/es.json
index 00e62ce..efbca96 100644
--- a/src/lib/i18n/locales/es.json
+++ b/src/lib/i18n/locales/es.json
@@ -895,6 +895,9 @@
"filterByDate": "Filtrar por fecha",
"reportSingular": "informe",
"reportPlural": "informes",
+ "pagination": "Paginación",
+ "previousPage": "Anterior",
+ "nextPage": "Siguiente",
"noReports": "No hay informes que coincidan con los filtros.",
"serviceDeleted": "Servicio eliminado",
"serviceLabel": "Servicio",
@@ -1721,7 +1724,9 @@
"domain_not_allowed": "El dominio no está permitido para destinatarios externos.",
"forbidden_external": "No tienes permiso para añadir destinatarios externos.",
"mail_not_configured": "El SMTP no está configurado: no se puede enviar el email de prueba.",
- "test_rate_limited": "Has enviado demasiados emails de prueba. Espera unos minutos."
+ "test_rate_limited": "Has enviado demasiados emails de prueba. 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."
},
"channels": {
"mail": "Email",
@@ -1816,7 +1821,13 @@
"externalStatus": "Estado de los emails externos",
"sendTest": "Enviar email de prueba",
"sendingTest": "Enviando…",
- "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados)."
+ "sendTestHelp": "Envía un email real con un evento de ejemplo a los destinatarios de la alerta que lo recibirían (los externos solo si están confirmados).",
+ "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.",
+ "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.",
+ "channelsReadonly": "Solo quien puede gestionar las notificaciones puede añadir canales."
},
"test": {
"matched": "El evento de ejemplo cumple las condiciones.",
@@ -1828,7 +1839,9 @@
"externalDelivers": "lo recibiría",
"externalSkipped": "no lo recibiría ({status})",
"delivered": "Email de prueba enviado: {sent} enviados, {failed} fallidos.",
- "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba."
+ "externalVerificationSent": "no recibe la prueba hasta que confirme: se le ha enviado el email de confirmación. Cuando confirme, vuelve a enviar la prueba.",
+ "channelDelivers": "recibiría el mensaje",
+ "channelSkipped": "no lo recibiría (deshabilitado o eliminado)"
},
"mailDisabled": "El email no está configurado (NOTIFICATION_SMTP_*): las alertas se guardan, pero no se enviarán.",
"wizard": {
@@ -1875,7 +1888,9 @@
"skipConditions": "Sin condiciones",
"created": "Alerta creada",
"saved": "Alerta guardada",
- "failed": "No se pudo completar. Inténtalo de nuevo."
+ "failed": "No se pudo completar. Inténtalo de nuevo.",
+ "notConfigured": "No configurado",
+ "configure": "Configurar"
}
},
"monitoring": {
@@ -2103,7 +2118,11 @@
"remove": "Quitar",
"removeTitle": "¿Quitar este destinatario?",
"removeDescription": "{email} todavía no ha confirmado. Se anulará su enlace de confirmación y se quitará de todas las alertas de la organización.",
- "removed": "{email} quitado"
+ "removed": "{email} quitado",
+ "projectDescription": "Canales de chat y webhooks que pueden usar las alertas de este proyecto.",
+ "descriptionProject": "Canales de chat y webhooks de este proyecto.",
+ "organizationDomains": "Los dominios permitidos y los destinatarios externos se gestionan en la organización.",
+ "organizationDomainsLink": "Abrir configuración de la organización"
},
"errors": {
"invalid": "El valor no es válido.",
@@ -2113,7 +2132,18 @@
"invalid_status": "Este destinatario no necesita confirmación.",
"rate_limited": "Se han enviado demasiados emails de confirmación. Inténtalo más tarde.",
"send_failed": "No se ha podido enviar el email de confirmación.",
- "Forbidden": "No tienes permiso para hacer esto."
+ "Forbidden": "No tienes permiso para hacer esto.",
+ "required": "Este campo es obligatorio.",
+ "too_long": "Es demasiado largo.",
+ "invalid_type": "Tipo de canal no válido.",
+ "type_unavailable": "Este tipo de canal todavía no está disponible.",
+ "invalid_url": "La URL no es válida.",
+ "not_https": "La URL debe usar https.",
+ "credentials": "La URL no puede incluir usuario ni contraseña.",
+ "ip_address": "La URL no puede apuntar a una dirección IP.",
+ "port": "La URL no puede usar otro puerto.",
+ "host_not_allowed": "Ese dominio no está permitido para este tipo de canal.",
+ "path_not_allowed": "La ruta de la URL no corresponde a este tipo de canal."
},
"link": {
"invalid": "Este enlace no es válido o ya se ha usado.",
@@ -2142,6 +2172,52 @@
"ignore": "Si no esperabas este email, ignóralo: no recibirás nada.",
"footer": "Recibes este email porque alguien de una organización de GitOps añadió tu dirección a una alerta."
}
+ },
+ "channels": {
+ "title": "Canales",
+ "descriptionOrganization": "Canales de chat y webhooks donde las alertas de la organización y de sus proyectos pueden publicar.",
+ "descriptionProject": "Canales que solo pueden usar las alertas de este proyecto.",
+ "privacyNotice": "Un canal lo lee gente que puede no tener cuenta ni permisos en GitOps. La URL del canal se guarda cifrada y nunca se vuelve a mostrar completa.",
+ "empty": "Todavía no hay canales.",
+ "types": {
+ "webhook": "Webhook",
+ "slack": "Slack",
+ "google-chat": "Google Chat"
+ },
+ "disabled": "Deshabilitado",
+ "unavailable": "Tipo no disponible",
+ "lastDelivery": "Último envío: {date}",
+ "lastError": "Último error: {error}",
+ "test": "Enviar mensaje de prueba",
+ "testSent": "Mensaje de prueba enviado.",
+ "testFailed": "No se ha podido enviar el mensaje de prueba ({reason}).",
+ "enable": "Habilitar",
+ "disable": "Deshabilitar",
+ "delete": "Eliminar",
+ "confirmDelete": "¿Eliminar este canal? Las alertas que lo usan dejarán de publicar en él.",
+ "edit": "Editar",
+ "name": "Nombre",
+ "newDestination": "Nueva URL (vacío para mantener la actual)",
+ "save": "Guardar",
+ "inheritedTitle": "Canales de la organización",
+ "inheritedDescription": "Las alertas de este proyecto también pueden usar estos canales. Se gestionan desde los ajustes de la organización.",
+ "create": "Añadir canal",
+ "noTypes": "Todavía no hay ningún tipo de canal disponible.",
+ "type": "Tipo",
+ "destination": "URL del webhook",
+ "testMessage": {
+ "title": "Mensaje de prueba de GitOps para {channel}",
+ "summary": "Este canal recibirá las alertas de {where}.",
+ "event": "Mensaje de prueba",
+ "channel": "Canal",
+ "open": "Abrir en GitOps"
+ },
+ "created": "Canal añadido",
+ "saved": "Canal guardado",
+ "deleted": "Canal eliminado",
+ "disabledToast": "Canal deshabilitado",
+ "enabledToast": "Canal habilitado",
+ "deleteTitle": "¿Eliminar el canal?"
}
}
}
diff --git a/src/lib/notifications/types.ts b/src/lib/notifications/types.ts
index 214982c..a3f6c64 100644
--- a/src/lib/notifications/types.ts
+++ b/src/lib/notifications/types.ts
@@ -16,3 +16,40 @@ export type NotificationSettingsPage = {
export type NotificationLinkState =
| { state: 'ready' | 'done'; email: string; organization: string }
| { state: 'invalid' | 'expired' };
+
+export type ChannelView = {
+ id: string;
+ type: string;
+ name: string;
+ scope: 'organization' | 'project';
+ organizationId: string;
+ projectId: string | null;
+ enabled: boolean;
+ destinationMasked: string;
+ available: boolean;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+ lastDeliveryAt: string | null;
+ lastError: string | null;
+};
+
+export type ChannelsSectionData = {
+ scope: 'organization' | 'project';
+ channels: ChannelView[];
+ inherited: ChannelView[];
+ availableTypes: string[];
+ canCreate: boolean;
+ canUpdate: boolean;
+ canDelete: boolean;
+};
+
+export type ChannelsFormResult = {
+ channelForm?: string;
+ channelDraft?: { type: string; name: string };
+ channelError?: string;
+ channelErrors?: Record;
+ channelSaved?: string;
+ channelDeleted?: string;
+ channelTest?: { channelId: string; sent: boolean; error: string | null };
+} | null;
diff --git a/src/lib/server/alerts/operations.ts b/src/lib/server/alerts/operations.ts
index bf07843..2521869 100644
--- a/src/lib/server/alerts/operations.ts
+++ b/src/lib/server/alerts/operations.ts
@@ -191,6 +191,7 @@ export type AlertTestResult = {
/** Selected users left out because they can't read the event. */
deniedCount: number;
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
delivery?: { sent: number; failed: number };
event: { type: string; payload: Record; projectId: string | null };
};
@@ -212,6 +213,7 @@ async function dryRun(
| 'conditions'
| 'match'
| 'recipients'
+ | 'channelIds'
| 'location'
| 'appliesTo'
>,
@@ -287,6 +289,7 @@ async function dryRun(
recipients: result.recipients.map(({ userId, username }) => ({ userId, username })),
deniedCount: result.denied.length,
external: result.external,
+ channels: result.channels,
...(delivery ? { delivery } : {}),
event: { type: alert.eventType, payload: sample.payload, projectId },
},
@@ -323,9 +326,11 @@ export async function testDraftAlert(
existing &&
existing.organizationId === location.organizationId &&
existing.projectId === location.projectId;
- const previousExternal = sameLocation ? existing.recipients.emails : [];
+ const previous = sameLocation
+ ? { emails: existing.recipients.emails, channelIds: existing.channelIds }
+ : {};
try {
- const fields = await alertService.validate(location, input, actor, previousExternal);
+ const fields = await alertService.validate(location, input, actor, previous);
const draft = new AlertDomain({
id: sameLocation ? existing.id : 'draft',
...location,
diff --git a/src/lib/server/alerts/page.ts b/src/lib/server/alerts/page.ts
index 10b2f89..06529f4 100644
--- a/src/lib/server/alerts/page.ts
+++ b/src/lib/server/alerts/page.ts
@@ -6,12 +6,12 @@ import {
type AlertLocation,
type AlertRow,
} from '#modules/alerts';
+import { emptyRecipients } from '#modules/alerts/domain/alert.domain';
import {
- ALERT_CHANNELS,
- emptyRecipients,
- type AlertChannel,
-} from '#modules/alerts/domain/alert.domain';
-import { externalRecipientService, notificationSettingsService } from '#modules/notifications';
+ externalRecipientService,
+ notificationChannelService,
+ notificationSettingsService,
+} from '#modules/notifications';
import { organizationService } from '#modules/organization';
import { projectService } from '#modules/projects';
import {
@@ -24,6 +24,7 @@ import {
import type {
AlertDraft,
AlertEditorData,
+ AlertChannelOption,
AlertListData,
AlertOption,
DraftCondition,
@@ -33,6 +34,7 @@ import {
canOpenNotificationSettings,
loadNotificationSettings,
} from '#lib/server/notifications/settings';
+import { loadChannelsSection } from '#lib/server/notifications/channels-page';
import { callerCan, canManageAlerts, contextOf, type AlertLocals } from './access';
import {
createAlert,
@@ -87,6 +89,17 @@ async function referenceOptions(
);
}
+async function channelOptions(location: AlertLocation): Promise {
+ const channels = await notificationChannelService.listUsable(location).catch(() => []);
+ return channels.map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ }));
+}
+
async function recipientOptions(location: AlertLocation) {
const [members, roles] = await Promise.all([
alertDirectory.listMembers(location).catch(() => []),
@@ -150,7 +163,7 @@ export async function loadAlertList(
scope: 'organization',
projectId: null,
};
- const [references, own, organizationRecipients, external] = await Promise.all([
+ const [references, own, organizationRecipients, external, channels] = await Promise.all([
referenceOptions([...catalog, ...inheritedCatalog], organizationLocation),
recipientOptions(location),
location.scope === 'project' ? recipientOptions(organizationLocation) : null,
@@ -159,6 +172,7 @@ export async function loadAlertList(
location,
listed.data.alerts.flatMap((alert) => alert.recipients.emails ?? []),
),
+ channelOptions(location),
]);
// names for the recipients of the location's alerts and of the inherited organization ones
const merge = (a: AlertOption[], b: AlertOption[] = []) => [
@@ -169,6 +183,14 @@ export async function loadAlertList(
users: merge(own.users, organizationRecipients?.users),
roles: merge(own.roles, organizationRecipients?.roles),
};
+ const [settings, channelsSection] = await Promise.all([
+ location.scope === 'organization' && external.settingsPath
+ ? loadNotificationSettings(locals, location.organizationId).then((result) =>
+ result.ok ? result.data : null,
+ )
+ : null,
+ loadChannelsSection(locals, location).catch(() => null),
+ ]);
return {
basePath: context.basePath,
@@ -184,13 +206,12 @@ export async function loadAlertList(
roles: recipients.roles,
recipientUsers: own.users,
recipientRoles: own.roles,
+ channels,
mailConfigured: isMailConfigured(),
external,
- settings: external.settingsPath
- ? await loadNotificationSettings(locals, location.organizationId).then((result) =>
- result.ok ? result.data : null,
- )
- : null,
+ settings,
+ channelsSection,
+ configPath: settings || channelsSection ? `${context.basePath}/settings` : null,
canCreate: allowed.canCreate,
canUpdate: allowed.canUpdate,
canDelete: allowed.canDelete,
@@ -205,8 +226,8 @@ function emptyDraft(eventType: string | null): AlertDraft {
eventType: eventType ?? '',
match: 'all',
conditions: [],
- channels: ['mail'],
recipients: emptyRecipients(),
+ channelIds: [],
throttleMinutes: 0,
};
}
@@ -223,8 +244,12 @@ function toDraft(alert: AlertRow): AlertDraft {
operator: condition.operator,
value: condition.value === undefined ? '' : condition.value,
})),
- channels: [...alert.channels],
- recipients: { ...emptyRecipients(), ...alert.recipients },
+ recipients: {
+ userIds: [...alert.recipients.userIds],
+ roleIds: [...alert.recipients.roleIds],
+ emails: [...alert.recipients.emails],
+ },
+ channelIds: [...alert.channelIds],
throttleMinutes: alert.throttleMinutes,
};
}
@@ -252,10 +277,11 @@ export async function loadAlertEditor(
}
const catalog = await listCatalog(locals, location);
- const [references, recipients, external] = await Promise.all([
+ const [references, recipients, external, channels] = await Promise.all([
referenceOptions(catalog, location),
recipientOptions(location),
externalRecipientsData(locals, location, alert?.recipients.emails ?? []),
+ channelOptions(location),
]);
const draft = alert ? toDraft(alert) : emptyDraft(options.eventType ?? null);
@@ -274,6 +300,7 @@ export async function loadAlertEditor(
roles: recipients.roles,
recipientUsers: recipients.users,
recipientRoles: recipients.roles,
+ channels,
mailConfigured: isMailConfigured(),
external,
canSave: alert ? allowed.canUpdate : allowed.canCreate,
@@ -325,24 +352,12 @@ export function parseAlertForm(form: FormData): AlertDraft {
eventType: String(form.get('eventType') ?? ''),
match: form.get('match') === 'any' ? 'any' : 'all',
conditions,
- channels: (() => {
- const channels = form
- .getAll('channels')
- .map(String)
- .filter((channel): channel is AlertChannel =>
- (ALERT_CHANNELS as readonly string[]).includes(channel),
- );
- // the editor always posts at least `mail`; older clients post nothing
- return channels.length > 0 ? [...new Set(channels)] : ['mail'];
- })(),
recipients: {
userIds: form.getAll('userIds').map(String),
roleIds: form.getAll('roleIds').map(String),
emails: listField(form, 'emails'),
- slackChannels: listField(form, 'slackChannels'),
- googleChatSpaces: listField(form, 'googleChatSpaces'),
- webhookUrls: listField(form, 'webhookUrls'),
},
+ channelIds: form.getAll('channelIds').map(String).filter(Boolean),
throttleMinutes: Number(form.get('throttleMinutes') ?? 0) || 0,
};
}
diff --git a/src/lib/server/infra/http/webhook-request.test.ts b/src/lib/server/infra/http/webhook-request.test.ts
new file mode 100644
index 0000000..f268ae8
--- /dev/null
+++ b/src/lib/server/infra/http/webhook-request.test.ts
@@ -0,0 +1,125 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { withRetry } from '../notifications/retry';
+import {
+ WebhookDeliveryError,
+ isRetryableWebhookError,
+ postJson,
+ validateWebhookUrl,
+ webhookRetryAfter,
+} from './webhook-request';
+
+const rule = { hosts: ['hooks.slack.com'], pathPrefix: '/services/' };
+
+describe('validateWebhookUrl (anti-SSRF)', () => {
+ it('accepts an https URL of an allowed host and path', () => {
+ const result = validateWebhookUrl('https://hooks.slack.com/services/T0/B0/abc', rule);
+ expect(result).toMatchObject({ ok: true });
+ });
+
+ it.each([
+ ['http://hooks.slack.com/services/T0', 'not_https'],
+ ['https://user:pass@hooks.slack.com/services/T0', 'credentials'],
+ ['https://127.0.0.1/services/T0', 'ip_address'],
+ ['https://[::1]/services/T0', 'ip_address'],
+ ['https://169.254.169.254/services/T0', 'ip_address'],
+ ['https://hooks.slack.com:8443/services/T0', 'port'],
+ ['https://evil.com/services/T0', 'host_not_allowed'],
+ ['https://hooks.slack.com.evil.com/services/T0', 'host_not_allowed'],
+ ['https://hooks.slack.com/other/T0', 'path_not_allowed'],
+ ['javascript:alert(1)', 'not_https'],
+ ['not a url', 'invalid_url'],
+ ['', 'invalid_url'],
+ ])('rejects %s', (url, error) => {
+ expect(validateWebhookUrl(url, rule)).toEqual({ ok: false, error });
+ });
+});
+
+function response(status: number, headers: Record = {}) {
+ return new Response(status === 204 ? null : 'secret body', { status, headers });
+}
+
+describe('postJson', () => {
+ afterEach(() => vi.useRealTimers());
+
+ it('posts JSON without following redirects and accepts any 2xx', async () => {
+ const fetch = vi.fn(async () => response(204));
+ await postJson('https://hooks.slack.com/services/x', { text: 'hi' }, { fetch });
+ expect(fetch).toHaveBeenCalledWith(
+ 'https://hooks.slack.com/services/x',
+ expect.objectContaining({
+ method: 'POST',
+ redirect: 'manual',
+ body: '{"text":"hi"}',
+ headers: expect.objectContaining({ 'content-type': 'application/json' }),
+ }),
+ );
+ });
+
+ it('treats 429 and 5xx as retryable, honoring Retry-After', async () => {
+ const tooMany = await postJson(
+ 'https://h/x',
+ {},
+ {
+ fetch: async () => response(429, { 'retry-after': '7' }),
+ },
+ ).catch((error) => error);
+ expect(tooMany).toBeInstanceOf(WebhookDeliveryError);
+ expect(tooMany).toMatchObject({ status: 429, retryable: true, retryAfterMs: 7000 });
+
+ const down = await postJson('https://h/x', {}, { fetch: async () => response(503) }).catch(
+ (error) => error,
+ );
+ expect(down).toMatchObject({ status: 503, retryable: true });
+ });
+
+ it('treats other 4xx and redirects as permanent', async () => {
+ for (const status of [400, 403, 404, 410, 301, 302]) {
+ const error = await postJson(
+ 'https://h/x',
+ {},
+ { fetch: async () => response(status) },
+ ).catch((caught) => caught);
+ expect(error).toMatchObject({ status, retryable: false });
+ expect(error.summary).toBe(`HTTP ${status}`);
+ // the response body never ends up in the error
+ expect(String(error.message)).not.toContain('secret body');
+ }
+ });
+
+ it('times out after 5 s and calls it retryable', async () => {
+ vi.useFakeTimers();
+ const fetch = vi.fn(
+ (_url: string, init?: RequestInit) =>
+ new Promise((_resolve, reject) => {
+ init?.signal?.addEventListener('abort', () => reject(new Error('aborted')));
+ }),
+ );
+ const pending = postJson('https://h/x', {}, { fetch: fetch as never }).catch((error) => error);
+ await vi.advanceTimersByTimeAsync(5_000);
+ expect(await pending).toMatchObject({ status: null, retryable: true, reason: 'timeout' });
+ });
+
+ it('retries with withRetry only what may succeed later', async () => {
+ const sleep = vi.fn(async (_ms: number) => {});
+ const statuses = [429, 503, 200];
+ const fetch = vi.fn(async () => response(statuses.shift()!, { 'retry-after': '2' }));
+ await withRetry(() => postJson('https://h/x', {}, { fetch }), {
+ isRetryable: isRetryableWebhookError,
+ retryAfterMs: webhookRetryAfter,
+ sleep,
+ random: () => 0.5,
+ });
+ expect(fetch).toHaveBeenCalledTimes(3);
+ // 429 waits its Retry-After, 503 the regular backoff (4 s for the second retry)
+ expect(sleep.mock.calls.map(([ms]) => ms)).toEqual([2000, 4000]);
+
+ const gone = vi.fn(async () => response(404));
+ await expect(
+ withRetry(() => postJson('https://h/x', {}, { fetch: gone }), {
+ isRetryable: isRetryableWebhookError,
+ sleep,
+ }),
+ ).rejects.toMatchObject({ status: 404 });
+ expect(gone).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/lib/server/infra/http/webhook-request.ts b/src/lib/server/infra/http/webhook-request.ts
new file mode 100644
index 0000000..66292d4
--- /dev/null
+++ b/src/lib/server/infra/http/webhook-request.ts
@@ -0,0 +1,149 @@
+import { isIP } from 'node:net';
+
+/** Why a webhook URL is refused; the UI maps them to `notifications.errors.`. */
+export type WebhookUrlError =
+ | 'invalid_url'
+ | 'not_https'
+ | 'credentials'
+ | 'ip_address'
+ | 'port'
+ | 'host_not_allowed'
+ | 'path_not_allowed';
+
+export type WebhookUrlRule = {
+ /** Exact host names the URL may point at (`hooks.slack.com`). */
+ hosts: readonly string[];
+ /** Required path prefix (`/services/`). */
+ pathPrefix?: string;
+};
+
+const MAX_URL_LENGTH = 2048;
+
+/**
+ * Anti-SSRF check of a webhook URL whose provider is known: `https` only, no credentials, no IP
+ * literal, the default port, an allowed host and path. Run it before saving **and** before every
+ * send (the stored value could have been changed in GitDB by hand).
+ */
+export function validateWebhookUrl(
+ raw: unknown,
+ rule: WebhookUrlRule,
+): { ok: true; url: URL } | { ok: false; error: WebhookUrlError } {
+ if (typeof raw !== 'string' || !raw.trim() || raw.length > MAX_URL_LENGTH) {
+ return { ok: false, error: 'invalid_url' };
+ }
+ let url: URL;
+ try {
+ url = new URL(raw.trim());
+ } catch {
+ return { ok: false, error: 'invalid_url' };
+ }
+ if (url.protocol !== 'https:') return { ok: false, error: 'not_https' };
+ if (url.username || url.password) return { ok: false, error: 'credentials' };
+ const host = url.hostname.replace(/^\[|\]$/g, '').toLowerCase();
+ if (isIP(host)) return { ok: false, error: 'ip_address' };
+ if (url.port && url.port !== '443') return { ok: false, error: 'port' };
+ if (!rule.hosts.includes(host)) return { ok: false, error: 'host_not_allowed' };
+ if (rule.pathPrefix && !url.pathname.startsWith(rule.pathPrefix)) {
+ return { ok: false, error: 'path_not_allowed' };
+ }
+ return { ok: true, url };
+}
+
+/** A webhook delivery that failed; `retryable` tells whether trying again may help. */
+export class WebhookDeliveryError extends Error {
+ constructor(
+ /** HTTP status, or `null` for network errors and timeouts. */
+ readonly status: number | null,
+ readonly retryable: boolean,
+ /** `Retry-After` of a 429, in ms. */
+ readonly retryAfterMs: number | null = null,
+ readonly reason: 'timeout' | 'network' | 'redirect' | 'http' = 'http',
+ ) {
+ super(
+ status === null ? `Webhook delivery failed (${reason})` : `Webhook answered HTTP ${status}`,
+ );
+ this.name = 'WebhookDeliveryError';
+ }
+
+ /** Short description for `lastError` and the logs: never the URL nor the response body. */
+ get summary(): string {
+ if (this.status !== null) return `HTTP ${this.status}`;
+ return this.reason;
+ }
+}
+
+export const WEBHOOK_TIMEOUT_MS = 5_000;
+/** Longest `Retry-After` honored; longer waits fall back to the regular backoff. */
+const MAX_RETRY_AFTER_MS = 60_000;
+
+function parseRetryAfter(value: string | null, now: number): number | null {
+ if (!value) return null;
+ const seconds = Number(value);
+ const ms = Number.isFinite(seconds) ? seconds * 1000 : Date.parse(value) - now;
+ if (!Number.isFinite(ms) || ms < 0) return null;
+ return Math.min(ms, MAX_RETRY_AFTER_MS);
+}
+
+export type PostJsonOptions = {
+ timeoutMs?: number;
+ headers?: Record;
+ fetch?: typeof fetch;
+ now?: () => number;
+};
+
+/**
+ * POSTs `body` as JSON. Any 2xx is a success; the response body is discarded. Redirects are not
+ * followed (they would bypass the URL check). Throws `WebhookDeliveryError`: retryable for network
+ * errors, timeouts, 429 (with its `Retry-After`) and 5xx; permanent for 3xx and other 4xx.
+ */
+export async function postJson(
+ url: string,
+ body: unknown,
+ options: PostJsonOptions = {},
+): Promise {
+ const send = options.fetch ?? fetch;
+ const controller = new AbortController();
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? WEBHOOK_TIMEOUT_MS);
+ let response: Response;
+ try {
+ response = await send(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', ...options.headers },
+ body: JSON.stringify(body),
+ redirect: 'manual',
+ signal: controller.signal,
+ });
+ } catch {
+ throw new WebhookDeliveryError(
+ null,
+ true,
+ null,
+ controller.signal.aborted ? 'timeout' : 'network',
+ );
+ } finally {
+ clearTimeout(timer);
+ }
+ // nothing of the answer is kept: it is not ours to log
+ await response.body?.cancel().catch(() => {});
+
+ const { status } = response;
+ if (status >= 200 && status < 300) return;
+ if (status >= 300 && status < 400)
+ throw new WebhookDeliveryError(status, false, null, 'redirect');
+ if (status === 429) {
+ const retryAfter = parseRetryAfter(
+ response.headers.get('retry-after'),
+ (options.now ?? Date.now)(),
+ );
+ throw new WebhookDeliveryError(status, true, retryAfter);
+ }
+ throw new WebhookDeliveryError(status, status >= 500);
+}
+
+export function isRetryableWebhookError(error: unknown): boolean {
+ return error instanceof WebhookDeliveryError && error.retryable;
+}
+
+export function webhookRetryAfter(error: unknown): number | null {
+ return error instanceof WebhookDeliveryError ? error.retryAfterMs : null;
+}
diff --git a/src/lib/server/infra/notifications/chat-notification.ts b/src/lib/server/infra/notifications/chat-notification.ts
new file mode 100644
index 0000000..9a82ab7
--- /dev/null
+++ b/src/lib/server/infra/notifications/chat-notification.ts
@@ -0,0 +1,99 @@
+import { Notification } from './notification';
+import type { NotificationTransport } from './transport';
+import { registerTransport } from './notify';
+import type { WebhookUrlError } from '../http/webhook-request';
+
+import { CHAT_CHANNEL_TYPES, type ChatChannelType } from './chat-types';
+
+export { CHAT_CHANNEL_TYPES, isChatChannelType, type ChatChannelType } from './chat-types';
+
+/**
+ * Provider-neutral content of a channel message; each transport turns it into its own format
+ * (Block Kit, Cards v2, signed JSON). Texts are already translated and plain: transports escape
+ * them for their format.
+ */
+export type ChannelMessage = {
+ /** The alert's name, or the channel's for a test message. */
+ title: string;
+ /** One line: `3 critical, 5 high` or the event label. */
+ summary: string;
+ /** Translated event label (`Analysis completed`). */
+ eventLabel: string;
+ /** Catalog fields as label/value, sensitive ones left out. */
+ fields: Array<{ label: string; value: string }>;
+ /** Absolute link to the resource in GitOps (`ORIGIN`), when there is one. */
+ link: { url: string; label: string } | null;
+ /** Matching events skipped by the throttle since the previous message. */
+ suppressed: number;
+ /** Plain-text fallback (mobile notifications, clients without rich formatting). */
+ text: string;
+ /** A test from the UI, not a real event. */
+ test: boolean;
+ /** Raw event data for formats that carry it (generic webhooks); absent for test messages. */
+ event?: { id: string; type: string; occurredAt: string; scope: Record };
+ alert?: { id: string; name: string };
+};
+
+export type ChatNotificationInput = {
+ channel: ChatChannelType;
+ /** Destination URL in clear: only ever held in memory, right before sending. */
+ destination: string;
+ message: ChannelMessage;
+};
+
+export class ChatNotification extends Notification {
+ readonly channel: ChatChannelType;
+ readonly destination: string;
+ readonly message: ChannelMessage;
+
+ constructor(input: ChatNotificationInput) {
+ super();
+ this.channel = input.channel;
+ this.destination = input.destination;
+ this.message = input.message;
+ }
+
+ validate(): void {
+ if (!this.destination) throw new Error('ChatNotification requires a destination');
+ if (!this.message.title.trim()) throw new Error('ChatNotification requires a title');
+ }
+}
+
+/**
+ * Transport of one chat channel type. `validateDestination` is the anti-SSRF check of the
+ * provider's URL, run before saving a channel and again before every send.
+ */
+export interface ChatTransport extends NotificationTransport {
+ validateDestination(raw: unknown): { ok: true; url: URL } | { ok: false; error: WebhookUrlError };
+}
+
+const CHAT_TRANSPORTS_KEY = Symbol.for('gitops.notifications.chat-transports');
+type GlobalWithChatTransports = typeof globalThis & {
+ [CHAT_TRANSPORTS_KEY]?: Map;
+};
+
+function registry(): Map {
+ return ((globalThis as GlobalWithChatTransports)[CHAT_TRANSPORTS_KEY] ??= new Map());
+}
+
+/**
+ * Activates a channel type: its channels can then be created and receive messages. Each
+ * transport sub-task (#96 webhook, #97 Slack, #98 Google Chat) registers its own.
+ */
+export function registerChatTransport(type: ChatChannelType, transport: ChatTransport): void {
+ registry().set(type, transport);
+ registerTransport(type, transport as NotificationTransport);
+}
+
+export function getChatTransport(type: ChatChannelType): ChatTransport | null {
+ return registry().get(type) ?? null;
+}
+
+/** Channel types with a registered transport, in catalog order. */
+export function availableChatTypes(): ChatChannelType[] {
+ return CHAT_CHANNEL_TYPES.filter((type) => registry().has(type));
+}
+
+export function resetChatTransports(): void {
+ registry().clear();
+}
diff --git a/src/lib/server/infra/notifications/chat-types.ts b/src/lib/server/infra/notifications/chat-types.ts
new file mode 100644
index 0000000..680be4f
--- /dev/null
+++ b/src/lib/server/infra/notifications/chat-types.ts
@@ -0,0 +1,7 @@
+/** Channel types that post a message to a destination URL (`notification_channels.type`). */
+export const CHAT_CHANNEL_TYPES = ['webhook', 'slack', 'google-chat'] as const;
+export type ChatChannelType = (typeof CHAT_CHANNEL_TYPES)[number];
+
+export function isChatChannelType(value: unknown): value is ChatChannelType {
+ return (CHAT_CHANNEL_TYPES as readonly unknown[]).includes(value);
+}
diff --git a/src/lib/server/infra/notifications/delivery-queue.ts b/src/lib/server/infra/notifications/delivery-queue.ts
new file mode 100644
index 0000000..84e902e
--- /dev/null
+++ b/src/lib/server/infra/notifications/delivery-queue.ts
@@ -0,0 +1,140 @@
+import type { Logger } from 'pino';
+import { withRetry, type RetryOptions } from './retry';
+
+type Job = {
+ item: T;
+ context: Record;
+ done: (sent: boolean) => void;
+};
+
+export type DeliveryQueueOptions = {
+ /** Delivers one item; a rejection is retried when `retry.isRetryable` allows it. */
+ send: (item: T) => Promise;
+ /** Deliveries in flight at the same time; a burst waits in the queue. */
+ concurrency?: number;
+ retry?: RetryOptions;
+ logger: Pick;
+ /** Log prefix and noun: `[mail]` / `email`, `[channels]` / `message`. */
+ label: { prefix: string; noun: string; plural: string };
+ /** Extra log fields for an item; never its content nor a secret destination. */
+ describe?: (item: T) => Record;
+ /** Short code of a definitive failure for the logs (never a message: it may quote secrets). */
+ errorCode?: (error: unknown) => unknown;
+ /** Called once per item after its last attempt. */
+ onSettled?: (item: T, outcome: { sent: true } | { sent: false; error: unknown }) => void;
+};
+
+/**
+ * In-process delivery queue with limited concurrency and retries (`withRetry`). Each job is one
+ * delivery; a definitive failure is logged and dropped, never thrown at the caller. Per process:
+ * pending jobs are lost on a crash, and `drain()` flushes them on shutdown.
+ */
+export class DeliveryQueue {
+ private readonly pending: Job[] = [];
+ private active = 0;
+ private readonly idle = new Set<() => void>();
+ private readonly concurrency: number;
+
+ constructor(protected readonly options: DeliveryQueueOptions) {
+ this.concurrency = Math.max(1, options.concurrency ?? 3);
+ }
+
+ /**
+ * Queues one delivery; resolves once it succeeded (`true`) or definitively failed (`false`,
+ * already logged). It never rejects.
+ */
+ enqueue(item: T, context: Record = {}): Promise {
+ return new Promise((resolve) => {
+ this.pending.push({ item, context, done: resolve });
+ this.pump();
+ });
+ }
+
+ /** Deliveries waiting or in flight. */
+ get size(): number {
+ return this.pending.length + this.active;
+ }
+
+ /**
+ * Resolves when the queue is empty, or after `timeoutMs` with what is left (`true` when
+ * everything was delivered).
+ */
+ drain(timeoutMs = 10_000): Promise {
+ if (this.size === 0) return Promise.resolve(true);
+ return new Promise((resolve) => {
+ const onIdle = () => {
+ clearTimeout(timer);
+ resolve(true);
+ };
+ const timer = setTimeout(() => {
+ this.idle.delete(onIdle);
+ const { prefix, plural } = this.options.label;
+ this.options.logger.warn(
+ { remaining: this.size },
+ `${prefix} shutdown timeout: ${plural} left unsent`,
+ );
+ resolve(false);
+ }, timeoutMs);
+ this.idle.add(onIdle);
+ });
+ }
+
+ private pump(): void {
+ while (this.active < this.concurrency && this.pending.length > 0) {
+ const job = this.pending.shift()!;
+ this.active += 1;
+ let sent = false;
+ void this.run(job)
+ .then((result) => {
+ sent = result;
+ })
+ .finally(() => {
+ this.active -= 1;
+ job.done(sent);
+ if (this.size === 0) {
+ for (const resolve of [...this.idle]) resolve();
+ this.idle.clear();
+ } else {
+ this.pump();
+ }
+ });
+ }
+ }
+
+ private async run(job: Job): Promise {
+ const { prefix, noun } = this.options.label;
+ const fields = { ...job.context, ...this.options.describe?.(job.item) };
+ const code = this.options.errorCode ?? defaultErrorCode;
+ try {
+ await withRetry(() => this.options.send(job.item), {
+ ...this.options.retry,
+ onRetry: (error, attempt, delayMs) =>
+ this.options.logger.debug(
+ { ...fields, attempt, delayMs, code: code(error) },
+ `${prefix} retrying ${noun}`,
+ ),
+ });
+ this.options.onSettled?.(job.item, { sent: true });
+ return true;
+ } catch (error) {
+ this.options.logger.error(
+ { ...fields, code: code(error) },
+ `${prefix} ${noun} could not be sent`,
+ );
+ this.options.onSettled?.(job.item, { sent: false, error });
+ return false;
+ }
+ }
+}
+
+/** The error's code, HTTP/SMTP status or name; never its message. */
+export function defaultErrorCode(error: unknown): unknown {
+ if (!error || typeof error !== 'object') return undefined;
+ const { code, responseCode, status, name } = error as {
+ code?: unknown;
+ responseCode?: unknown;
+ status?: unknown;
+ name?: unknown;
+ };
+ return responseCode ?? status ?? code ?? name;
+}
diff --git a/src/lib/server/infra/notifications/index.ts b/src/lib/server/infra/notifications/index.ts
index 155e2aa..cbd16c7 100644
--- a/src/lib/server/infra/notifications/index.ts
+++ b/src/lib/server/infra/notifications/index.ts
@@ -24,6 +24,20 @@ export {
} from './config';
export { withRetry, isRetryableMailError, type RetryOptions } from './retry';
export { emailButton, emailNote } from './email-parts';
+export {
+ CHAT_CHANNEL_TYPES,
+ ChatNotification,
+ availableChatTypes,
+ getChatTransport,
+ isChatChannelType,
+ registerChatTransport,
+ resetChatTransports,
+ type ChannelMessage,
+ type ChatChannelType,
+ type ChatNotificationInput,
+ type ChatTransport,
+} from './chat-notification';
+export { DeliveryQueue, defaultErrorCode, type DeliveryQueueOptions } from './delivery-queue';
export { MailQueue, recipientHash, type MailContext, type MailQueueOptions } from './mail-queue';
import { createLogger } from '#lib/server/logger';
@@ -41,13 +55,17 @@ type GlobalWithQueue = typeof globalThis & {
(globalThis as GlobalWithQueue)[SEND_KEY] = send;
+export function sendWithLatestNotify(notification: Parameters[0]): Promise {
+ return ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification);
+}
+
/**
* Process-wide queue for alert and system emails (3 at a time, 4 attempts with backoff). Kept on
* `globalThis` so HMR doesn't create a second one. Invitations and password resets don't use it:
* their links carry tokens and are sent directly.
*/
export const mailQueue: Queue = ((globalThis as GlobalWithQueue)[QUEUE_KEY] ??= new Queue({
- send: (notification) => ((globalThis as GlobalWithQueue)[SEND_KEY] ?? send)(notification),
+ send: (notification) => sendWithLatestNotify(notification),
concurrency: 3,
logger: createLogger('mail'),
}));
diff --git a/src/lib/server/infra/notifications/mail-queue.ts b/src/lib/server/infra/notifications/mail-queue.ts
index 2a2f2b7..2fdc7da 100644
--- a/src/lib/server/infra/notifications/mail-queue.ts
+++ b/src/lib/server/infra/notifications/mail-queue.ts
@@ -1,17 +1,12 @@
import crypto from 'node:crypto';
import type { Logger } from 'pino';
+import { DeliveryQueue } from './delivery-queue';
import type { MailNotification } from './mail-notification';
-import { isRetryableMailError, withRetry, type RetryOptions } from './retry';
+import { isRetryableMailError, type RetryOptions } from './retry';
/** What the logs may say about an email: never its content or the address in clear. */
export type MailContext = { alertId?: string; eventId?: string; kind?: string };
-type Job = {
- notification: MailNotification;
- context: MailContext;
- done: (sent: boolean) => void;
-};
-
export type MailQueueOptions = {
send: (notification: MailNotification) => Promise;
/** Emails sent at the same time; a burst of events waits in the queue. */
@@ -34,103 +29,19 @@ export function recipientHash(address: string): string {
* is one email; a definitive failure is logged and dropped, never thrown at the caller. Per
* process: pending emails are lost on a crash, and `drain()` flushes them on shutdown.
*/
-export class MailQueue {
- private readonly pending: Job[] = [];
- private active = 0;
- private readonly idle = new Set<() => void>();
- private readonly concurrency: number;
-
- constructor(private readonly options: MailQueueOptions) {
- this.concurrency = Math.max(1, options.concurrency ?? 3);
- }
-
- enqueue(notification: MailNotification, context: MailContext = {}): Promise {
- return new Promise((resolve) => {
- this.pending.push({ notification, context, done: resolve });
- this.pump();
- });
- }
-
- /** Emails waiting or being sent. */
- get size(): number {
- return this.pending.length + this.active;
- }
-
- /**
- * Resolves when the queue is empty, or after `timeoutMs` with what is left (`true` when
- * everything was sent).
- */
- drain(timeoutMs = 10_000): Promise {
- if (this.size === 0) return Promise.resolve(true);
- return new Promise((resolve) => {
- const onIdle = () => {
- clearTimeout(timer);
- resolve(true);
- };
- const timer = setTimeout(() => {
- this.idle.delete(onIdle);
- this.options.logger.warn(
- { remaining: this.size },
- '[mail] shutdown timeout: emails left unsent',
- );
- resolve(false);
- }, timeoutMs);
- this.idle.add(onIdle);
+export class MailQueue extends DeliveryQueue {
+ constructor(options: MailQueueOptions) {
+ super({
+ send: options.send,
+ concurrency: options.concurrency,
+ retry: { isRetryable: isRetryableMailError, ...options.retry },
+ logger: options.logger,
+ label: { prefix: '[mail]', noun: 'email', plural: 'emails' },
+ describe: (notification) => ({ recipients: notification.to.map(recipientHash) }),
});
}
- private pump(): void {
- while (this.active < this.concurrency && this.pending.length > 0) {
- const job = this.pending.shift()!;
- this.active += 1;
- let sent = false;
- void this.run(job)
- .then((result) => {
- sent = result;
- })
- .finally(() => {
- this.active -= 1;
- job.done(sent);
- if (this.size === 0) {
- for (const resolve of [...this.idle]) resolve();
- this.idle.clear();
- } else {
- this.pump();
- }
- });
- }
- }
-
- private async run(job: Job): Promise {
- const recipients = job.notification.to.map(recipientHash);
- try {
- await withRetry(() => this.options.send(job.notification), {
- isRetryable: isRetryableMailError,
- ...this.options.retry,
- onRetry: (error, attempt, delayMs) =>
- this.options.logger.debug(
- { ...job.context, recipients, attempt, delayMs, code: errorCode(error) },
- '[mail] retrying email',
- ),
- });
- return true;
- } catch (error) {
- this.options.logger.error(
- // only the error code: SMTP messages may quote the recipient address
- { ...job.context, recipients, code: errorCode(error) },
- '[mail] email could not be sent',
- );
- return false;
- }
+ enqueue(notification: MailNotification, context: MailContext = {}): Promise {
+ return super.enqueue(notification, context);
}
}
-
-function errorCode(error: unknown): unknown {
- if (!error || typeof error !== 'object') return undefined;
- const { code, responseCode, name } = error as {
- code?: unknown;
- responseCode?: unknown;
- name?: unknown;
- };
- return responseCode ?? code ?? name;
-}
diff --git a/src/lib/server/infra/notifications/notification.ts b/src/lib/server/infra/notifications/notification.ts
index 1244b06..eee81ee 100644
--- a/src/lib/server/infra/notifications/notification.ts
+++ b/src/lib/server/infra/notifications/notification.ts
@@ -1,4 +1,4 @@
-export type NotificationChannel = 'mail' | 'slack';
+export type NotificationChannel = 'mail' | 'slack' | 'google-chat' | 'webhook';
export abstract class Notification {
abstract readonly channel: NotificationChannel;
diff --git a/src/lib/server/infra/notifications/retry.ts b/src/lib/server/infra/notifications/retry.ts
index 48ac060..ad36bff 100644
--- a/src/lib/server/infra/notifications/retry.ts
+++ b/src/lib/server/infra/notifications/retry.ts
@@ -7,6 +7,7 @@ export type RetryOptions = {
/** ± fraction of each delay added at random, so retries of a burst don't line up. */
jitter?: number;
isRetryable?: (error: unknown) => boolean;
+ retryAfterMs?: (error: unknown) => number | null | undefined;
sleep?: (ms: number) => Promise;
random?: () => number;
onRetry?: (error: unknown, attempt: number, delayMs: number) => void;
@@ -33,7 +34,11 @@ export async function withRetry(fn: () => Promise, options: RetryOptions =
} catch (error) {
if (attempt >= attempts || !isRetryable(error)) throw error;
const delay = baseDelayMs * factor ** (attempt - 1);
- const delayMs = Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1))));
+ const requested = options.retryAfterMs?.(error);
+ const delayMs =
+ typeof requested === 'number' && requested >= 0
+ ? Math.round(requested)
+ : Math.max(0, Math.round(delay * (1 + jitter * (random() * 2 - 1))));
options.onRetry?.(error, attempt, delayMs);
await sleep(delayMs);
}
diff --git a/src/lib/server/notifications/channels-page.ts b/src/lib/server/notifications/channels-page.ts
new file mode 100644
index 0000000..4dea086
--- /dev/null
+++ b/src/lib/server/notifications/channels-page.ts
@@ -0,0 +1,106 @@
+import { fail } from '@sveltejs/kit';
+import type { ChannelLocation } from '#modules/notifications';
+import type { AlertLocals } from '#lib/server/alerts/access';
+import type { ChannelsSectionData } from '#lib/notifications/types';
+import {
+ canManageChannels,
+ createChannel,
+ deleteChannel,
+ listChannels,
+ testChannel,
+ updateChannel,
+} from './channels';
+
+/** The channels section of a notifications page; `null` without `:notifications:read`. */
+export async function loadChannelsSection(
+ locals: AlertLocals,
+ location: ChannelLocation,
+): Promise {
+ const listed = await listChannels(locals, location);
+ if (!listed.ok) return null;
+ const [canCreate, canUpdate, canDelete] = await Promise.all([
+ canManageChannels(locals, location, 'create'),
+ canManageChannels(locals, location, 'update'),
+ canManageChannels(locals, location, 'delete'),
+ ]);
+ return { ...listed.data, scope: location.scope, canCreate, canUpdate, canDelete };
+}
+
+type ActionEvent = { request: Request; params: Record; locals: AlertLocals };
+
+/** Form actions of the channels section, shared by the organization and project pages. */
+export function channelActions(resolve: (event: ActionEvent) => Promise) {
+ return {
+ async createChannel(event: ActionEvent) {
+ const location = await resolve(event);
+ const form = await event.request.formData();
+ const input = {
+ type: String(form.get('type') ?? ''),
+ name: String(form.get('name') ?? ''),
+ destination: String(form.get('destination') ?? ''),
+ enabled: true,
+ };
+ const result = await createChannel(event.locals, location, input);
+ if (!result.ok) {
+ // the destination is never echoed back: it has to be typed again
+ return fail(result.status, {
+ channelForm: 'create',
+ channelDraft: { type: input.type, name: input.name },
+ channelError: result.error,
+ channelErrors: result.errors ?? {},
+ });
+ }
+ return { channelSaved: result.data.id };
+ },
+
+ async updateChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await updateChannel(event.locals, channelId, {
+ name: String(form.get('name') ?? ''),
+ destination: String(form.get('destination') ?? ''),
+ });
+ if (!result.ok) {
+ return fail(result.status, {
+ channelForm: channelId,
+ channelError: result.error,
+ channelErrors: result.errors ?? {},
+ });
+ }
+ return { channelSaved: channelId };
+ },
+
+ async toggleChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await updateChannel(event.locals, channelId, {
+ enabled: form.get('enabled') === 'true',
+ });
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelSaved: channelId };
+ },
+
+ async deleteChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await deleteChannel(event.locals, channelId);
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelDeleted: channelId };
+ },
+
+ async testChannel(event: ActionEvent) {
+ await resolve(event);
+ const form = await event.request.formData();
+ const channelId = String(form.get('channelId') ?? '');
+ const result = await testChannel(event.locals, channelId);
+ if (!result.ok)
+ return fail(result.status, { channelForm: channelId, channelError: result.error });
+ return { channelTest: { channelId, ...result.data } };
+ },
+ };
+}
diff --git a/src/lib/server/notifications/channels.ts b/src/lib/server/notifications/channels.ts
new file mode 100644
index 0000000..a8be8b0
--- /dev/null
+++ b/src/lib/server/notifications/channels.ts
@@ -0,0 +1,175 @@
+import {
+ NotificationChannelNotFoundError,
+ NotificationChannelValidationError,
+ buildChannelTestMessage,
+ notificationChannelService,
+ type ChannelInput,
+ type ChannelLocation,
+ type NotificationChannelView,
+} from '#modules/notifications';
+import { organizationService } from '#modules/organization';
+import { projectService } from '#modules/projects';
+import { absoluteUrl, type ChatChannelType } from '#lib/server/infra/notifications';
+import { actorFor, callerCan, contextOf, type AlertLocals } from '#lib/server/alerts/access';
+
+export type ChannelAction = 'read' | 'create' | 'update' | 'delete';
+
+/** Outcome of a channel operation, mapped to JSON by the API and to `fail()` by form actions. */
+export type ChannelResult =
+ | { ok: true; status: number; data: T }
+ | { ok: false; status: number; error: string; errors?: Record };
+
+const forbidden = { ok: false as const, status: 403, error: 'Forbidden' };
+const notFound = { ok: false as const, status: 404, error: 'Channel not found' };
+
+/** `:notifications:` in the channel's (or the page's) location. */
+export function canManageChannels(
+ locals: AlertLocals,
+ location: ChannelLocation,
+ action: ChannelAction,
+): Promise {
+ return callerCan(locals, `${location.scope}:notifications:${action}`, contextOf(location));
+}
+
+function failure(error: unknown): ChannelResult {
+ if (error instanceof NotificationChannelValidationError) {
+ return { ok: false, status: 400, error: 'Invalid channel', errors: error.errors };
+ }
+ if (error instanceof NotificationChannelNotFoundError) return notFound;
+ throw error;
+}
+
+async function loadAuthorized(locals: AlertLocals, id: string, action: ChannelAction) {
+ const channel = await notificationChannelService.get(id).catch(() => null);
+ if (!channel) return notFound;
+ // a channel the caller can't read is indistinguishable from a missing one
+ if (!(await canManageChannels(locals, channel.location, 'read'))) return notFound;
+ if (action !== 'read' && !(await canManageChannels(locals, channel.location, action))) {
+ return forbidden;
+ }
+ return { ok: true as const, status: 200, data: channel };
+}
+
+export type ChannelList = {
+ channels: NotificationChannelView[];
+ /** Organization channels a project's alerts can also use (project locations only). */
+ inherited: NotificationChannelView[];
+ /** Types that can be created now (a transport is registered for them). */
+ availableTypes: ChatChannelType[];
+};
+
+export async function listChannels(
+ locals: AlertLocals,
+ location: ChannelLocation,
+): Promise> {
+ if (!(await canManageChannels(locals, location, 'read'))) return forbidden;
+ const own = await notificationChannelService.list(location);
+ const inherited =
+ location.scope === 'project'
+ ? await notificationChannelService.list({
+ organizationId: location.organizationId,
+ projectId: null,
+ })
+ : [];
+ return {
+ ok: true,
+ status: 200,
+ data: {
+ channels: own.map((channel) => notificationChannelService.toView(channel)),
+ inherited: inherited.map((channel) => notificationChannelService.toView(channel)),
+ availableTypes: notificationChannelService.availableTypes(),
+ },
+ };
+}
+
+export async function getChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'read');
+ return loaded.ok
+ ? { ok: true, status: 200, data: notificationChannelService.toView(loaded.data) }
+ : loaded;
+}
+
+export async function createChannel(
+ locals: AlertLocals,
+ location: ChannelLocation,
+ input: ChannelInput,
+): Promise> {
+ if (!(await canManageChannels(locals, location, 'create'))) return forbidden;
+ const actor = actorFor(locals);
+ if (!actor) return forbidden;
+ try {
+ const channel = await notificationChannelService.create(location, input, actor.userId);
+ return { ok: true, status: 201, data: notificationChannelService.toView(channel) };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+export async function updateChannel(
+ locals: AlertLocals,
+ id: string,
+ input: ChannelInput,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'update');
+ if (!loaded.ok) return loaded;
+ try {
+ // the type can't change: a different provider is a different channel
+ const { type: _type, ...changes } = input;
+ void _type;
+ const channel = await notificationChannelService.update(id, changes);
+ return { ok: true, status: 200, data: notificationChannelService.toView(channel) };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+export async function deleteChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'delete');
+ if (!loaded.ok) return loaded;
+ try {
+ await notificationChannelService.delete(id);
+ return { ok: true, status: 200, data: { id } };
+ } catch (error) {
+ return failure(error);
+ }
+}
+
+/** Names and settings path of a channel's location, for the test message. */
+async function describeLocation(location: ChannelLocation) {
+ const organization = await organizationService
+ .getOrganization(location.organizationId)
+ .catch(() => null);
+ const project = location.projectId
+ ? await projectService.getProject(location.projectId).catch(() => null)
+ : null;
+ const where = project?.name ?? organization?.name ?? 'GitOps';
+ const path =
+ organization && project
+ ? `/org/${organization.slug}/projects/${project.slug}/settings/notifications`
+ : organization
+ ? `/org/${organization.slug}/settings/notifications`
+ : null;
+ return { where, link: absoluteUrl(path) };
+}
+
+/** "Send test message": posts a test to the channel, even a disabled one, and tells the result. */
+export async function testChannel(
+ locals: AlertLocals,
+ id: string,
+): Promise> {
+ const loaded = await loadAuthorized(locals, id, 'update');
+ if (!loaded.ok) return loaded;
+ const channel = loaded.data;
+ const { where, link } = await describeLocation(channel.location);
+ const result = await notificationChannelService.test(
+ id,
+ buildChannelTestMessage({ channelName: channel.name, where, link }),
+ );
+ return { ok: true, status: 200, data: result };
+}
diff --git a/src/modules/alerts/application/alert-engine.test.ts b/src/modules/alerts/application/alert-engine.test.ts
index d386194..c60eaff 100644
--- a/src/modules/alerts/application/alert-engine.test.ts
+++ b/src/modules/alerts/application/alert-engine.test.ts
@@ -112,6 +112,7 @@ function alertRow(overrides: Partial = {}): AlertRow {
conditions: [{ field: 'summary.critical', operator: 'gt', value: 0 }],
recipients: { ...emptyRecipients(), userIds: [], roleIds: ['project-reporter'] },
channels: ['mail'],
+ channelIds: [],
throttleMinutes: 0,
createdByUserId: 'author',
createdAt: TIMESTAMP,
diff --git a/src/modules/alerts/application/alert-engine.ts b/src/modules/alerts/application/alert-engine.ts
index 5fe4898..463b42d 100644
--- a/src/modules/alerts/application/alert-engine.ts
+++ b/src/modules/alerts/application/alert-engine.ts
@@ -2,7 +2,7 @@ import type { Logger } from 'pino';
import { recipientHash } from '#lib/server/infra/notifications/mail-queue';
import { getEventDefinition, isEventType, type EventDefinition } from '#lib/events/catalog';
import type { AnyDomainEvent, EventBus, Unsubscribe } from '#lib/server/events';
-import { DELIVERED_CHANNELS, type AlertDomain } from '../domain/alert.domain';
+import type { AlertDomain } from '../domain/alert.domain';
import { matches } from '../domain/condition-evaluator';
import {
getSystemNotification,
@@ -11,10 +11,12 @@ import {
import type { AlertRepositoryPort } from '../infrastructure/repositories/alert.repository';
import { AlertThrottle } from './alert-throttle';
import { RecipientResolver, type Recipient } from './recipient-resolver';
+import type { ChannelMessage } from '#lib/server/infra/notifications/chat-notification';
import {
eventContext,
type AlertDirectory,
type ExternalRecipientsPort,
+ type NotificationChannelsPort,
type ResolvedNames,
} from './types';
@@ -40,6 +42,18 @@ export type AlertTestDelivery = {
failed: number;
};
+type AlertToDeliver = Pick<
+ AlertDomain,
+ | 'id'
+ | 'name'
+ | 'description'
+ | 'scope'
+ | 'organizationId'
+ | 'location'
+ | 'recipients'
+ | 'channelIds'
+>;
+
export type SystemEmail = {
recipient: Recipient;
kind: SystemNotificationKind;
@@ -63,8 +77,9 @@ export type AlertEngineOptions = {
/** How long alerts of one event type stay cached; GitDB sync changes show up after this. */
cacheTtlMs?: number;
now?: () => number;
- /** `false` when no email can be sent (SMTP not configured): events are then ignored. */
deliveryEnabled?: () => boolean;
+ channels?: NotificationChannelsPort;
+ channelMessage?: (input: Omit) => ChannelMessage;
};
export type AlertDryRun = {
@@ -73,6 +88,7 @@ export type AlertDryRun = {
/** Selected users that would not get it because they can't read the event. */
denied: string[];
external: Array<{ email: string; status: string; delivers: boolean }>;
+ channels: Array<{ id: string; name: string; type: string; delivers: boolean }>;
};
const DEFAULT_CACHE_TTL_MS = 60_000;
@@ -105,7 +121,7 @@ export class AlertEngine {
async handle(event: AnyDomainEvent): Promise {
if (!isEventType(event.type)) return;
- if (this.options.deliveryEnabled && !this.options.deliveryEnabled()) {
+ if (!this.mailEnabled() && !this.options.channels) {
this.options.logger.debug(
{ eventType: event.type, eventId: event.id },
'[alerts] email is not configured, event skipped',
@@ -114,13 +130,18 @@ export class AlertEngine {
}
const definition = getEventDefinition(event.type) as EventDefinition;
- // system notifications first: they don't depend on anyone configuring an alert
- await this.sendSystemNotification(event).catch((error) =>
- this.options.logger.error(
- { err: error, eventType: event.type, eventId: event.id },
- '[alerts] system notification failed',
- ),
- );
+ if (!this.mailEnabled()) {
+ this.options.logger.debug(
+ { eventType: event.type, eventId: event.id },
+ '[alerts] email is not configured, emails skipped',
+ );
+ } else
+ await this.sendSystemNotification(event).catch((error) =>
+ this.options.logger.error(
+ { err: error, eventType: event.type, eventId: event.id },
+ '[alerts] system notification failed',
+ ),
+ );
if (!definition.alertable) return;
@@ -143,20 +164,49 @@ export class AlertEngine {
async dryRun(
alert: Pick & {
appliesTo: AlertDomain['appliesTo'];
+ channelIds?: string[];
},
event: Pick,
): Promise {
const definition = getEventDefinition(event.type) as EventDefinition;
const matched = alert.appliesTo(event.scope) && matches(event, alert, definition);
const context = eventContext(event.scope);
- if (!context) return { matched, recipients: [], denied: [], external: [] };
+ if (!context) return { matched, recipients: [], denied: [], external: [], channels: [] };
const resolved = await this.options.recipients.resolve(
alert.location,
alert.recipients,
definition.readPermission,
context,
);
- return { matched, ...resolved, external: await this.externalPreview(alert) };
+ return {
+ matched,
+ ...resolved,
+ external: await this.externalPreview(alert),
+ channels: await this.channelPreview(alert),
+ };
+ }
+
+ private mailEnabled(): boolean {
+ return !this.options.deliveryEnabled || this.options.deliveryEnabled();
+ }
+
+ private async channelPreview(alert: {
+ location: AlertDomain['location'];
+ channelIds?: string[];
+ }) {
+ const port = this.options.channels;
+ const ids = alert.channelIds ?? [];
+ if (!port || ids.length === 0) return [];
+ const usable = await port.listUsable(alert.location).catch(() => []);
+ return ids.map((id) => {
+ const channel = usable.find((candidate) => candidate.id === id);
+ return {
+ id,
+ name: channel?.name ?? id,
+ type: channel?.type ?? 'unknown',
+ delivers: Boolean(channel?.enabled),
+ };
+ });
}
private async externalPreview(alert: Pick) {
@@ -193,14 +243,6 @@ export class AlertEngine {
const context = eventContext(event.scope);
if (!context) return;
- const pending = alert.channels.filter((channel) => !DELIVERED_CHANNELS.includes(channel));
- if (pending.length > 0) {
- log.debug(
- { alertId: alert.id, channels: pending },
- '[alerts] channels without a notifier yet are skipped',
- );
- }
-
const decision = this.throttle.acquire(alert.id, alert.throttleMinutes);
if (!decision.send) {
log.info(
@@ -223,13 +265,7 @@ export class AlertEngine {
);
}
- async sendTest(
- alert: Pick<
- AlertDomain,
- 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
- >,
- event: AnyDomainEvent,
- ): Promise {
+ async sendTest(alert: AlertToDeliver, event: AnyDomainEvent): Promise {
const definition = getEventDefinition(event.type) as EventDefinition;
const { sent, failed } = await this.deliver(alert, event, definition, 0, true);
this.options.logger.info(
@@ -240,18 +276,24 @@ export class AlertEngine {
}
private async deliver(
- alert: Pick<
- AlertDomain,
- 'id' | 'name' | 'description' | 'scope' | 'organizationId' | 'location' | 'recipients'
- >,
+ alert: AlertToDeliver,
event: AnyDomainEvent,
definition: EventDefinition,
suppressed: number,
test: boolean,
- ): Promise<{ recipients: number; externalRecipients: number; sent: number; failed: number }> {
+ ): Promise<{
+ recipients: number;
+ externalRecipients: number;
+ channels: number;
+ sent: number;
+ failed: number;
+ }> {
const log = this.options.logger;
const context = eventContext(event.scope);
- if (!context) return { recipients: 0, externalRecipients: 0, sent: 0, failed: 0 };
+ if (!context) {
+ return { recipients: 0, externalRecipients: 0, channels: 0, sent: 0, failed: 0 };
+ }
+ const mail = this.mailEnabled();
const { recipients, denied } = await this.options.recipients.resolve(
alert.location,
@@ -277,14 +319,18 @@ export class AlertEngine {
.catch(() => ({}));
const memberEmails = new Set(recipients.map((recipient) => recipient.email.toLowerCase()));
- const external = (await this.externalRecipientsOf(alert)).filter(
- (recipient) => !memberEmails.has(recipient.email.toLowerCase()),
- );
-
- const targets: AlertEmailRecipient[] = [
- ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })),
- ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })),
- ];
+ const external = mail
+ ? (await this.externalRecipientsOf(alert)).filter(
+ (recipient) => !memberEmails.has(recipient.email.toLowerCase()),
+ )
+ : [];
+
+ const targets: AlertEmailRecipient[] = mail
+ ? [
+ ...recipients.map((recipient) => ({ kind: 'member' as const, ...recipient })),
+ ...external.map((recipient) => ({ kind: 'external' as const, ...recipient })),
+ ]
+ : [];
let sent = 0;
// one email per recipient: addresses are never shared, and a failure only affects one person
@@ -316,11 +362,44 @@ export class AlertEngine {
}
}
+ const channelIds = alert.channelIds ?? [];
+ let channelsSent = 0;
+ if (channelIds.length > 0 && this.options.channels && this.options.channelMessage) {
+ const message = this.options.channelMessage({
+ alert,
+ event,
+ definition,
+ suppressed,
+ names,
+ where,
+ ...(test ? { test: true } : {}),
+ });
+ const results = await Promise.all(
+ channelIds.map((channelId) =>
+ this.options
+ .channels!.deliver(channelId, message, {
+ alertId: alert.id,
+ eventId: event.id,
+ kind: test ? 'alert_test' : 'alert',
+ })
+ .catch((error) => {
+ log.warn(
+ { err: error, alertId: alert.id, eventId: event.id, channelId },
+ '[alerts] channel message failed',
+ );
+ return false;
+ }),
+ ),
+ );
+ channelsSent = results.filter(Boolean).length;
+ }
+
return {
recipients: recipients.length,
externalRecipients: external.length,
- sent,
- failed: targets.length - sent,
+ channels: channelIds.length,
+ sent: sent + channelsSent,
+ failed: targets.length - sent + (channelIds.length - channelsSent),
};
}
diff --git a/src/modules/alerts/application/alert.channels.test.ts b/src/modules/alerts/application/alert.channels.test.ts
new file mode 100644
index 0000000..a85d4ee
--- /dev/null
+++ b/src/modules/alerts/application/alert.channels.test.ts
@@ -0,0 +1,359 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { getEventDefinition, type EventDefinition } from '#lib/events/catalog';
+import type { AnyDomainEvent } from '#lib/server/events';
+import { createChannelsFixture } from '#modules/notifications/application/testing';
+import {
+ AlertDomain,
+ AlertValidationError,
+ type AlertInput,
+ type AlertLocation,
+} from '../domain/alert.domain';
+import { buildAlertChannelMessage } from '../infrastructure/alert-channel-message';
+import { InMemoryAlertRepository } from '../infrastructure/repositories/in-memory-alert.repository';
+import {
+ AlertEngine,
+ type AlertEmail,
+ type AlertNotifierPort,
+ type SystemEmail,
+} from './alert-engine';
+import { AlertService } from './alert.service';
+import { AlertThrottle } from './alert-throttle';
+import { RecipientResolver } from './recipient-resolver';
+import { FakeAlertDirectory, actor } from './testing';
+import type { NotificationChannelsPort } from './types';
+
+const ORG = 'org-1';
+const orgLocation: AlertLocation = { scope: 'organization', organizationId: ORG, projectId: null };
+const p1: AlertLocation = { scope: 'project', organizationId: ORG, projectId: 'p1' };
+const HOOK = 'https://hooks.example.com/hook/T0/B0/xyz';
+const WITHOUT_NOTIFICATIONS = ['project:codereport:reports:read', 'organization:projects:read'];
+
+function input(overrides: AlertInput = {}): AlertInput {
+ return {
+ name: 'Críticas',
+ eventType: 'code_report.analysis.completed',
+ recipients: { userIds: ['u1'] },
+ ...overrides,
+ };
+}
+
+function analysisEvent(): AnyDomainEvent {
+ return {
+ id: 'evt-1',
+ type: 'code_report.analysis.completed',
+ occurredAt: '2026-11-24T10:00:00.000Z',
+ actor: { kind: 'system' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: {
+ analysisId: 'a1',
+ serviceId: 'svc-1',
+ tool: 'trivy',
+ gitInfo: { repositoryUrl: null, branch: 'main', commit: 'abc', version: null },
+ summary: { critical: 1, high: 0, medium: 0, low: 0, unknown: 0, total: 1, secrets: 0 },
+ policies: {
+ status: 'compliant',
+ totalViolations: 0,
+ blockingFailures: 0,
+ failedPolicyIds: [],
+ },
+ },
+ } as unknown as AnyDomainEvent;
+}
+
+async function validationErrors(promise: Promise) {
+ const error = await promise.catch((caught) => caught);
+ expect(error).toBeInstanceOf(AlertValidationError);
+ return (error as AlertValidationError).errors;
+}
+
+class RecordingNotifier implements AlertNotifierPort {
+ alerts: AlertEmail[] = [];
+ system: SystemEmail[] = [];
+ fail = false;
+ async sendAlert(email: AlertEmail) {
+ if (this.fail) throw new Error('SMTP down');
+ this.alerts.push(email);
+ }
+ async sendSystemNotification(email: SystemEmail) {
+ this.system.push(email);
+ }
+}
+
+describe('alerts with notification channels', () => {
+ let channels: ReturnType;
+ let port: NotificationChannelsPort;
+ let repository: InMemoryAlertRepository;
+ let directory: FakeAlertDirectory;
+ let service: AlertService;
+ let orgChannel: string;
+ let p1Channel: string;
+ let p2Channel: string;
+
+ beforeEach(async () => {
+ channels = createChannelsFixture();
+ port = {
+ listUsable: async (location) =>
+ (await channels.service.listUsable(location)).map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ })),
+ deliver: (id, message, context) => channels.service.deliver(id, message, context),
+ };
+ orgChannel = (
+ await channels.service.create(
+ orgLocation,
+ { type: 'slack', name: '#org', destination: HOOK },
+ 'a',
+ )
+ ).id;
+ p1Channel = (
+ await channels.service.create(p1, { type: 'slack', name: '#p1', destination: HOOK }, 'a')
+ ).id;
+ p2Channel = (
+ await channels.service.create(
+ { ...p1, projectId: 'p2' },
+ { type: 'slack', name: '#p2', destination: HOOK },
+ 'a',
+ )
+ ).id;
+
+ repository = new InMemoryAlertRepository();
+ directory = new FakeAlertDirectory();
+ directory.members = [
+ {
+ organizationId: ORG,
+ projectId: 'p1',
+ userId: 'u1',
+ username: 'ana',
+ email: 'ana@kettu.io',
+ disabled: false,
+ roleIds: [],
+ },
+ ];
+ let id = 0;
+ service = new AlertService(repository, directory, {
+ generateId: () => `alert-${++id}`,
+ channels: port,
+ });
+ });
+
+ describe('validation', () => {
+ it('accepts the project and organization channels a project alert may use', async () => {
+ const alert = await service.create(
+ p1,
+ input({ channelIds: [p1Channel, orgChannel, p1Channel] }),
+ actor('admin'),
+ );
+ expect(alert.channelIds).toEqual([p1Channel, orgChannel]);
+ expect(alert.channels).toEqual(['mail', 'slack']);
+ });
+
+ it('rejects channels of another project or another location', async () => {
+ expect(
+ (
+ await validationErrors(
+ service.create(p1, input({ channelIds: [p2Channel] }), actor('admin')),
+ )
+ ).channelIds,
+ ).toBe('unknown_channel');
+ // an organization alert can't use a project channel either
+ expect(
+ (
+ await validationErrors(
+ service.create(orgLocation, input({ channelIds: [p1Channel] }), actor('admin')),
+ )
+ ).channelIds,
+ ).toBe('unknown_channel');
+ });
+
+ it('needs :notifications:update to add channels, not to keep them', async () => {
+ const refused = await validationErrors(
+ service.create(p1, input({ channelIds: [p1Channel] }), actor('dev', WITHOUT_NOTIFICATIONS)),
+ );
+ expect(refused.channelIds).toBe('forbidden_channel');
+
+ const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin'));
+ const editor = actor('dev', [...WITHOUT_NOTIFICATIONS, 'project:alerts:update']);
+ await expect(service.update(alert.id, { name: 'Renamed' }, editor)).resolves.toMatchObject({
+ channelIds: [p1Channel],
+ });
+ expect(
+ (
+ await validationErrors(
+ service.update(alert.id, { channelIds: [p1Channel, orgChannel] }, editor),
+ )
+ ).channelIds,
+ ).toBe('forbidden_channel');
+ });
+
+ it('accepts an alert whose only destination is a channel', async () => {
+ const alert = await service.create(
+ p1,
+ input({ recipients: {}, channelIds: [p1Channel] }),
+ actor('admin'),
+ );
+ expect(alert.channels).toEqual(['slack']);
+ });
+ });
+
+ describe('engine', () => {
+ let notifier: RecordingNotifier;
+ let mail: boolean;
+ let engine: AlertEngine;
+
+ beforeEach(() => {
+ notifier = new RecordingNotifier();
+ mail = true;
+ engine = new AlertEngine({
+ repository,
+ directory,
+ recipients: new RecipientResolver(directory, async () => true),
+ notifier,
+ channels: port,
+ channelMessage: buildAlertChannelMessage,
+ deliveryEnabled: () => mail,
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ });
+ });
+
+ it('emails the recipients and posts one message per channel', async () => {
+ await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin'));
+ await engine.handle(analysisEvent());
+
+ expect(notifier.alerts).toHaveLength(1);
+ expect(channels.transport.sent).toHaveLength(2);
+ expect(channels.transport.sent[0].message).toMatchObject({
+ title: 'Críticas',
+ summary: '1 critical, 0 high (1 in total)',
+ test: false,
+ alert: { name: 'Críticas' },
+ });
+ });
+
+ it('keeps going when a channel fails, and the other way around', async () => {
+ await service.create(p1, input({ channelIds: [p1Channel, orgChannel] }), actor('admin'));
+ channels.transport.failWith = [404];
+ notifier.fail = true;
+ await engine.handle(analysisEvent());
+
+ // the email failed, one channel answered 404: the other channel still got its message
+ expect(channels.transport.sent).toHaveLength(1);
+ expect(channels.repository.rows.find((row) => row.lastError === 'HTTP 404')).toBeDefined();
+ });
+
+ it('still posts to channels without SMTP, but sends no emails', async () => {
+ mail = false;
+ await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin'));
+ await engine.handle(analysisEvent());
+ expect(notifier.alerts).toHaveLength(0);
+ expect(channels.transport.sent).toHaveLength(1);
+ });
+
+ it('never posts system notifications to channels', async () => {
+ await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin'));
+ directory.users = [{ userId: 'u1', username: 'ana', email: 'ana@kettu.io', disabled: false }];
+ await engine.handle({
+ id: 'evt-2',
+ type: 'access.granted',
+ occurredAt: '2026-11-24T10:00:00.000Z',
+ actor: { kind: 'user', userId: 'admin' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: { accessId: 'x', userId: 'u1', roleId: 'r1', scope: 'project', status: 'active' },
+ } as unknown as AnyDomainEvent);
+ expect(notifier.system).toHaveLength(1);
+ expect(channels.transport.sent).toHaveLength(0);
+ });
+
+ it('reports throttled events in the next channel message', async () => {
+ let now = 0;
+ engine = new AlertEngine({
+ repository,
+ directory,
+ recipients: new RecipientResolver(directory, async () => true),
+ notifier,
+ channels: port,
+ channelMessage: buildAlertChannelMessage,
+ now: () => now,
+ throttle: new AlertThrottle(() => now),
+ logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() },
+ });
+ await service.create(
+ p1,
+ input({ throttleMinutes: 10, channelIds: [p1Channel] }),
+ actor('admin'),
+ );
+ await engine.handle(analysisEvent());
+ await engine.handle(analysisEvent());
+ expect(channels.transport.sent).toHaveLength(1);
+ expect(channels.transport.sent[0].message.suppressed).toBe(0);
+
+ now = 11 * 60 * 1000;
+ await engine.handle(analysisEvent());
+ expect(channels.transport.sent).toHaveLength(2);
+ expect(channels.transport.sent[1].message.suppressed).toBe(1);
+ });
+
+ it('includes the channels in test sends and dry runs', async () => {
+ const alert = await service.create(p1, input({ channelIds: [p1Channel] }), actor('admin'));
+ await channels.service.update(orgChannel, { enabled: false });
+
+ const delivery = await engine.sendTest(alert, analysisEvent());
+ expect(delivery).toEqual({ sent: 2, failed: 0 });
+ expect(channels.transport.sent[0].message.test).toBe(true);
+
+ const dry = await engine.dryRun(
+ new AlertDomain({ ...alert.toJson(), channelIds: [p1Channel, orgChannel] }),
+ analysisEvent(),
+ );
+ expect(dry.channels).toEqual([
+ { id: p1Channel, name: '#p1', type: 'slack', delivers: true },
+ { id: orgChannel, name: '#org', type: 'slack', delivers: false },
+ ]);
+ });
+ });
+
+ describe('channel message', () => {
+ it('leaves out sensitive fields and links to the resource', () => {
+ process.env.ORIGIN = 'https://gitops.example.com';
+ const definition = getEventDefinition('vault.secret.deleted') as EventDefinition;
+ const message = buildAlertChannelMessage({
+ alert: { id: 'a1', name: 'Secretos', description: null, scope: 'project' },
+ event: {
+ id: 'e1',
+ type: 'vault.secret.deleted',
+ occurredAt: '2026-11-24T10:00:00.000Z',
+ actor: { kind: 'system' },
+ scope: { organizationId: ORG, projectId: 'p1' },
+ payload: {
+ secretId: 's1',
+ key: 'DB_PASSWORD',
+ folderId: null,
+ folderPath: '/pay',
+ environmentIds: ['e'],
+ },
+ } as never,
+ definition,
+ suppressed: 3,
+ names: new Map([['e', 'Production']]),
+ where: {
+ organization: 'Kettu',
+ organizationSlug: 'kettu',
+ project: 'Web',
+ projectSlug: 'web',
+ },
+ });
+ const text = JSON.stringify(message);
+ expect(text).not.toContain('DB_PASSWORD');
+ expect(text).not.toContain('/pay');
+ expect(text).toContain('Production');
+ expect(message.suppressed).toBe(3);
+ expect(message.link).toEqual({
+ url: 'https://gitops.example.com/org/kettu/projects/web/vault',
+ label: 'View in GitOps',
+ });
+ });
+ });
+});
diff --git a/src/modules/alerts/application/alert.service.test.ts b/src/modules/alerts/application/alert.service.test.ts
index 248dbcc..d711ebb 100644
--- a/src/modules/alerts/application/alert.service.test.ts
+++ b/src/modules/alerts/application/alert.service.test.ts
@@ -109,7 +109,7 @@ describe('AlertService', () => {
const errors = await validationErrors(
service.create(
projectLocation,
- { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['sms'] },
+ { name: ' ', match: 'some', recipients: {}, throttleMinutes: -1, channels: ['pigeon'] },
actor(),
),
);
@@ -119,7 +119,6 @@ describe('AlertService', () => {
eventType: 'required',
recipients: 'required',
throttleMinutes: 'invalid',
- channels: 'invalid_channel',
});
expect(repository.rows).toHaveLength(0);
expect(onChange).not.toHaveBeenCalled();
@@ -267,64 +266,30 @@ describe('AlertService', () => {
});
describe('channels', () => {
- it('keeps the targets of every enabled channel and normalizes them', async () => {
+ it('derives the channels from the recipients and ignores what the client sends', async () => {
const alert = await service.create(
projectLocation,
guidedExample({
- channels: ['mail', 'slack', 'google_chat', 'webhook'],
- recipients: {
- roleIds: ['role-project-admin'],
- emails: [' Ops@Example.com ', 'ops@example.com'],
- slackChannels: ['Alerts', '#alerts'],
- googleChatSpaces: ['Incidencias'],
- webhookUrls: ['https://hooks.example.com/gitops'],
- },
+ channels: ['slack', 'pigeon'],
+ recipients: { emails: [' Ops@Example.com ', 'ops@example.com'] },
}),
actor(),
);
- expect(alert.channels).toEqual(['mail', 'slack', 'google_chat', 'webhook']);
- expect(alert.recipients).toMatchObject({
- emails: ['ops@example.com'],
- slackChannels: ['#alerts'],
- googleChatSpaces: ['Incidencias'],
- webhookUrls: ['https://hooks.example.com/gitops'],
- });
- });
-
- it('drops the targets of disabled channels', async () => {
- const alert = await service.create(
- projectLocation,
- guidedExample({
- channels: ['slack'],
- recipients: { roleIds: ['role-project-admin'], slackChannels: ['#alerts'] },
- }),
- actor(),
- );
- expect(alert.recipients.roleIds).toEqual([]);
- expect(alert.recipients.slackChannels).toEqual(['#alerts']);
+ expect(alert.channels).toEqual(['mail']);
+ expect(alert.recipients.emails).toEqual(['ops@example.com']);
});
- it('requires a valid target for each enabled channel', async () => {
+ it('reports an invalid external address per index', async () => {
const errors = await validationErrors(
service.create(
projectLocation,
- guidedExample({
- channels: ['mail', 'slack', 'google_chat', 'webhook'],
- recipients: {
- emails: ['not-an-email'],
- slackChannels: ['bad channel!'],
- webhookUrls: ['ftp://example.com'],
- },
- }),
+ guidedExample({ recipients: { emails: ['not-an-email'] } }),
actor(),
),
);
expect(errors).toEqual({
'recipients.emails': 'invalid_email',
'recipients.emails.0': 'invalid_email',
- 'recipients.slackChannels': 'invalid_slack_channel',
- 'recipients.googleChatSpaces': 'required',
- 'recipients.webhookUrls': 'invalid_url',
});
});
diff --git a/src/modules/alerts/application/alert.service.ts b/src/modules/alerts/application/alert.service.ts
index 5377bab..9f784ec 100644
--- a/src/modules/alerts/application/alert.service.ts
+++ b/src/modules/alerts/application/alert.service.ts
@@ -29,18 +29,19 @@ import {
type AlertActor,
type AlertDirectory,
type ExternalRecipientsPort,
+ type NotificationChannelsPort,
type ReferenceOption,
+ type UsableChannel,
} from './types';
const MAX_NAME_LENGTH = 120;
const MAX_DESCRIPTION_LENGTH = 1000;
const MAX_CONDITIONS = 20;
const MAX_LIST_VALUES = 100;
-const MAX_TARGETS = 50;
-export const MAX_EXTERNAL_EMAILS = MAX_TARGETS;
-const SLACK_CHANNEL_PATTERN = /^#[a-z0-9][a-z0-9._-]{0,79}$/;
-const MAX_SPACE_LENGTH = 128;
+export const MAX_EXTERNAL_EMAILS = 50;
+
+export const MAX_ALERT_CHANNELS = 20;
const VALUELESS_OPERATORS = new Set(['is_true', 'is_false', 'exists']);
const LIST_OPERATORS = new Set(['in', 'not_in']);
@@ -51,6 +52,7 @@ export type AlertServiceOptions = {
/** Called after every successful write, so the engine drops its cached alerts. */
onChange?: () => void;
externalRecipients?: ExternalRecipientsPort;
+ channels?: Pick;
logger?: { warn: (object: object, message: string) => void };
};
@@ -68,6 +70,7 @@ export class AlertService {
private readonly generateId: () => string;
private readonly onChange: () => void;
private readonly externalRecipients: ExternalRecipientsPort | null;
+ private readonly channelsPort: Pick | null;
private readonly logger: AlertServiceOptions['logger'];
constructor(
@@ -79,6 +82,7 @@ export class AlertService {
this.generateId = options.generateId ?? (() => crypto.randomUUID());
this.onChange = options.onChange ?? (() => {});
this.externalRecipients = options.externalRecipients ?? null;
+ this.channelsPort = options.channels ?? null;
this.logger = options.logger;
}
@@ -126,7 +130,7 @@ export class AlertService {
location: AlertLocation,
input: AlertInput,
actor: AlertActor,
- previousEmails: readonly string[] = [],
+ previous: { emails?: readonly string[]; channelIds?: readonly string[] } = {},
): Promise {
const errors: AlertValidationErrors = {};
const references: ReferenceCache = new Map();
@@ -155,16 +159,30 @@ export class AlertService {
? await this.validateConditions(location, definition, input.conditions, errors, references)
: [];
- const channels = this.validateChannels(input.channels, errors);
-
const recipients = await this.validateRecipients(
location,
input.recipients,
- channels,
actor,
- previousEmails,
+ previous.emails ?? [],
+ errors,
+ );
+
+ const { channelIds, selected } = await this.validateChannelIds(
+ location,
+ input.channelIds,
+ actor,
+ previous.channelIds ?? [],
errors,
);
+ const hasEmailRecipients =
+ recipients.userIds.length + recipients.roleIds.length + recipients.emails.length > 0;
+ if (errors.recipients === 'required' && channelIds.length > 0) delete errors.recipients;
+ const channels = [
+ ...new Set([
+ ...(hasEmailRecipients || channelIds.length === 0 ? (['mail'] as const) : []),
+ ...selected.map((channel) => channel.type as AlertChannel),
+ ]),
+ ].filter((channel) => (ALERT_CHANNELS as readonly string[]).includes(channel));
const throttleMinutes = Number(input.throttleMinutes ?? 0);
if (
@@ -188,6 +206,7 @@ export class AlertService {
conditions,
recipients,
channels,
+ channelIds,
throttleMinutes,
};
}
@@ -226,10 +245,14 @@ export class AlertService {
conditions: current.conditions,
recipients: current.recipients,
channels: current.channels,
+ channelIds: current.channelIds,
throttleMinutes: current.throttleMinutes,
...Object.fromEntries(Object.entries(input).filter(([, value]) => value !== undefined)),
};
- const fields = await this.validate(current.location, merged, actor, current.recipients.emails);
+ const fields = await this.validate(current.location, merged, actor, {
+ emails: current.recipients.emails,
+ channelIds: current.channelIds,
+ });
await this.repository.update(id, fields);
this.onChange();
await this.registerExternal(current.location, fields.recipients.emails, actor);
@@ -453,83 +476,37 @@ export class AlertService {
private async validateRecipients(
location: AlertLocation,
value: unknown,
- channels: AlertChannel[],
actor: AlertActor,
previousEmails: readonly string[],
errors: AlertValidationErrors,
): Promise {
const raw = (value ?? {}) as Record;
- const list = (key: string, normalize: (item: string) => string = (item) => item.trim()) =>
- Array.isArray(raw[key])
- ? [
- ...new Set(
- (raw[key] as unknown[])
- .filter((item): item is string => typeof item === 'string')
- .map(normalize)
- .filter(Boolean),
- ),
- ]
+ const ids = (list: unknown) =>
+ Array.isArray(list)
+ ? [...new Set(list.filter((item): item is string => typeof item === 'string' && !!item))]
: [];
const recipients = emptyRecipients();
- const tooMany = (key: string, items: string[]) => {
- if (items.length > MAX_TARGETS) errors[`recipients.${key}`] = 'too_many';
- };
-
- if (channels.includes('mail')) {
- recipients.userIds = list('userIds');
- recipients.roleIds = list('roleIds');
- recipients.emails = await this.validateEmails(
- location,
- raw.emails,
- actor,
- previousEmails,
- errors,
- );
- const { userIds, roleIds, emails } = recipients;
- if (userIds.length === 0 && roleIds.length === 0 && emails.length === 0) {
- if (!errors['recipients.emails']) errors.recipients = 'required';
- }
- if (userIds.length > 0) {
- const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId));
- if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user';
- }
- if (roleIds.length > 0) {
- const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id));
- if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role';
- }
- }
-
- if (channels.includes('slack')) {
- recipients.slackChannels = list('slackChannels', (item) => {
- const name = item.trim().toLowerCase();
- return name && !name.startsWith('#') ? `#${name}` : name;
- });
- if (recipients.slackChannels.length === 0) errors['recipients.slackChannels'] = 'required';
- else if (recipients.slackChannels.some((name) => !SLACK_CHANNEL_PATTERN.test(name))) {
- errors['recipients.slackChannels'] = 'invalid_slack_channel';
- }
- tooMany('slackChannels', recipients.slackChannels);
+ recipients.userIds = ids(raw.userIds);
+ recipients.roleIds = ids(raw.roleIds);
+ recipients.emails = await this.validateEmails(
+ location,
+ raw.emails,
+ actor,
+ previousEmails,
+ errors,
+ );
+ const { userIds, roleIds, emails } = recipients;
+ if (userIds.length === 0 && roleIds.length === 0 && emails.length === 0) {
+ if (!errors['recipients.emails']) errors.recipients = 'required';
}
-
- if (channels.includes('google_chat')) {
- recipients.googleChatSpaces = list('googleChatSpaces');
- if (recipients.googleChatSpaces.length === 0) {
- errors['recipients.googleChatSpaces'] = 'required';
- } else if (recipients.googleChatSpaces.some((space) => space.length > MAX_SPACE_LENGTH)) {
- errors['recipients.googleChatSpaces'] = 'too_long';
- }
- tooMany('googleChatSpaces', recipients.googleChatSpaces);
+ if (userIds.length > 0) {
+ const members = new Set((await this.directory.listMembers(location)).map((m) => m.userId));
+ if (userIds.some((id) => !members.has(id))) errors['recipients.userIds'] = 'unknown_user';
}
-
- if (channels.includes('webhook')) {
- recipients.webhookUrls = list('webhookUrls');
- if (recipients.webhookUrls.length === 0) errors['recipients.webhookUrls'] = 'required';
- else if (recipients.webhookUrls.some((url) => !isHttpUrl(url))) {
- errors['recipients.webhookUrls'] = 'invalid_url';
- }
- tooMany('webhookUrls', recipients.webhookUrls);
+ if (roleIds.length > 0) {
+ const roles = new Set((await this.directory.listRoles(location)).map((role) => role.id));
+ if (roleIds.some((id) => !roles.has(id))) errors['recipients.roleIds'] = 'unknown_role';
}
-
return recipients;
}
@@ -573,23 +550,41 @@ export class AlertService {
return emails;
}
- private validateChannels(value: unknown, errors: AlertValidationErrors): AlertChannel[] {
- if (value === undefined || value === null) return ['mail'];
- const list = Array.isArray(value) ? value : [value];
- const valid = list.every((channel) => (ALERT_CHANNELS as readonly unknown[]).includes(channel));
- if (!valid || list.length === 0) {
- errors.channels = 'invalid_channel';
- return ['mail'];
+ private async validateChannelIds(
+ location: AlertLocation,
+ value: unknown,
+ actor: AlertActor,
+ previous: readonly string[],
+ errors: AlertValidationErrors,
+ ): Promise<{ channelIds: string[]; selected: UsableChannel[] }> {
+ if (value === undefined || value === null) return { channelIds: [], selected: [] };
+ if (!Array.isArray(value)) {
+ errors.channelIds = 'invalid';
+ return { channelIds: [], selected: [] };
}
- return [...new Set(list as AlertChannel[])];
- }
-}
-
-function isHttpUrl(value: string): boolean {
- try {
- const url = new URL(value);
- return url.protocol === 'https:' || url.protocol === 'http:';
- } catch {
- return false;
+ const channelIds = [
+ ...new Set(value.filter((id): id is string => typeof id === 'string' && !!id)),
+ ];
+ if (channelIds.length === 0) return { channelIds, selected: [] };
+ if (channelIds.length > MAX_ALERT_CHANNELS) {
+ errors.channelIds = 'too_many';
+ return { channelIds: [], selected: [] };
+ }
+ const usable = this.channelsPort ? await this.channelsPort.listUsable(location) : [];
+ const selected = channelIds
+ .map((id) => usable.find((channel) => channel.id === id))
+ .filter((channel): channel is UsableChannel => !!channel);
+ if (selected.length !== channelIds.length) {
+ errors.channelIds = 'unknown_channel';
+ return { channelIds, selected };
+ }
+ const known = new Set(previous);
+ if (channelIds.some((id) => !known.has(id))) {
+ const permission = `${location.scope}:notifications:update` as const;
+ if (!(await actor.canRead(permission, locationContext(location)))) {
+ errors.channelIds = 'forbidden_channel';
+ }
+ }
+ return { channelIds, selected };
}
}
diff --git a/src/modules/alerts/application/types.ts b/src/modules/alerts/application/types.ts
index cb4b4bc..2c37756 100644
--- a/src/modules/alerts/application/types.ts
+++ b/src/modules/alerts/application/types.ts
@@ -72,6 +72,26 @@ export interface ExternalRecipientsPort {
statuses(organizationId: string, emails: readonly string[]): Promise>;
}
+export type UsableChannel = {
+ id: string;
+ name: string;
+ type: string;
+ scope: 'organization' | 'project';
+ enabled: boolean;
+};
+
+export interface NotificationChannelsPort {
+ listUsable(location: {
+ organizationId: string;
+ projectId: string | null;
+ }): Promise;
+ deliver(
+ channelId: string,
+ message: import('#lib/server/infra/notifications/chat-notification').ChannelMessage,
+ context?: Record,
+ ): Promise;
+}
+
export type AlertActor = {
userId: string;
canRead(permission: PermissionGrant, context: PermissionContext): Promise;
diff --git a/src/modules/alerts/domain/alert.domain.ts b/src/modules/alerts/domain/alert.domain.ts
index 06473da..8b4220c 100644
--- a/src/modules/alerts/domain/alert.domain.ts
+++ b/src/modules/alerts/domain/alert.domain.ts
@@ -4,15 +4,8 @@ import type { Operator } from '#lib/events/catalog';
export type AlertScope = 'organization' | 'project';
export type AlertMatch = 'all' | 'any';
-/**
- * Where an alert is delivered. An alert can use several channels at once and sends one message to
- * each. Only `mail` is delivered today; the others are stored and validated so the UI and the API
- * are ready when their notifiers land (#82).
- */
-export const ALERT_CHANNELS = ['mail', 'slack', 'google_chat', 'webhook'] as const;
+export const ALERT_CHANNELS = ['mail', 'webhook', 'slack', 'google-chat'] as const;
export type AlertChannel = (typeof ALERT_CHANNELS)[number];
-/** Channels with a notifier: the rest are skipped by the engine. */
-export const DELIVERED_CHANNELS: readonly AlertChannel[] = ['mail'];
export const ALERT_MATCHES = ['all', 'any'] as const;
@@ -27,30 +20,14 @@ export type AlertCondition = {
value?: string | number | string[];
};
-/** Targets per channel; only the arrays of the alert's enabled channels are kept. */
export type AlertRecipients = {
- /** mail: platform users */
userIds: string[];
- /** mail: every member holding one of these roles */
roleIds: string[];
emails: string[];
- /** slack: channel names, stored with their `#` */
- slackChannels: string[];
- /** google_chat: space names */
- googleChatSpaces: string[];
- /** webhook: http(s) URLs that receive a JSON POST */
- webhookUrls: string[];
};
export function emptyRecipients(): AlertRecipients {
- return {
- userIds: [],
- roleIds: [],
- emails: [],
- slackChannels: [],
- googleChatSpaces: [],
- webhookUrls: [],
- };
+ return { userIds: [], roleIds: [], emails: [] };
}
/** Where an alert lives: an organization alert has no project. */
@@ -70,6 +47,7 @@ export type AlertInput = {
conditions?: unknown;
recipients?: unknown;
channels?: unknown;
+ channelIds?: unknown;
throttleMinutes?: unknown;
};
@@ -83,6 +61,7 @@ export type AlertFields = {
conditions: AlertCondition[];
recipients: AlertRecipients;
channels: AlertChannel[];
+ channelIds: string[];
throttleMinutes: number;
};
@@ -118,6 +97,7 @@ export class AlertDomain implements AlertRow {
conditions: AlertCondition[];
recipients: AlertRecipients;
channels: AlertChannel[];
+ channelIds: string[];
throttleMinutes: number;
createdByUserId: string;
createdAt: string;
@@ -145,14 +125,14 @@ export class AlertDomain implements AlertRow {
),
]),
],
- slackChannels: stringArray(row.recipients?.slackChannels),
- googleChatSpaces: stringArray(row.recipients?.googleChatSpaces),
- webhookUrls: stringArray(row.recipients?.webhookUrls),
};
- const channels = stringArray(row.channels).filter((channel): channel is AlertChannel =>
- (ALERT_CHANNELS as readonly string[]).includes(channel),
- );
+ const channels = stringArray(row.channels)
+ .map((channel) => (channel === 'google_chat' ? 'google-chat' : channel))
+ .filter((channel): channel is AlertChannel =>
+ (ALERT_CHANNELS as readonly string[]).includes(channel),
+ );
this.channels = channels.length > 0 ? channels : ['mail'];
+ this.channelIds = stringArray(row.channelIds);
this.throttleMinutes = Number.isFinite(Number(row.throttleMinutes))
? Number(row.throttleMinutes)
: 0;
@@ -192,11 +172,9 @@ export class AlertDomain implements AlertRow {
userIds: [...this.recipients.userIds],
roleIds: [...this.recipients.roleIds],
emails: [...this.recipients.emails],
- slackChannels: [...this.recipients.slackChannels],
- googleChatSpaces: [...this.recipients.googleChatSpaces],
- webhookUrls: [...this.recipients.webhookUrls],
},
channels: [...this.channels],
+ channelIds: [...this.channelIds],
throttleMinutes: this.throttleMinutes,
createdByUserId: this.createdByUserId,
createdAt: this.createdAt,
diff --git a/src/modules/alerts/index.ts b/src/modules/alerts/index.ts
index c090eec..c8e7b11 100644
--- a/src/modules/alerts/index.ts
+++ b/src/modules/alerts/index.ts
@@ -8,7 +8,11 @@ import {
import { createLogger } from '#lib/server/logger';
import { cancanService, roleService, userAccessService, apiKeysService } from '../auth';
import { codeReportSecurityPolicyService, codeReportService } from '../code-report';
-import { externalRecipientService } from '../notifications';
+import {
+ externalRecipientService,
+ notificationChannelService,
+ registerChannelShutdown,
+} from '../notifications';
import { organizationService } from '../organization';
import { projectService } from '../projects';
import { vaultService } from '../vault';
@@ -18,6 +22,8 @@ import { AlertService } from './application/alert.service';
import { AlertThrottle } from './application/alert-throttle';
import { RecipientResolver } from './application/recipient-resolver';
import { AlertMailNotifier } from './infrastructure/alert-mail.notifier';
+import { buildAlertChannelMessage } from './infrastructure/alert-channel-message';
+import type { NotificationChannelsPort } from './application/types';
import { PlatformDirectory } from './infrastructure/platform-directory';
import { AlertRepository } from './infrastructure/repositories/alert.repository';
@@ -41,12 +47,33 @@ const recipientResolver = new RecipientResolver(alertDirectory, (userId, permiss
cancanService.can(userId, permission, context),
);
+const alertChannels: NotificationChannelsPort = {
+ async listUsable(location) {
+ const channels = await notificationChannelService.listUsable(location);
+ return channels.map((channel) => ({
+ id: channel.id,
+ name: channel.name,
+ type: channel.type,
+ scope: channel.scope,
+ enabled: channel.enabled,
+ }));
+ },
+ deliver: (channelId, message, context) =>
+ notificationChannelService.deliver(channelId, message, context),
+};
+
const ENGINE_KEY = Symbol.for('gitops.alerts.engine');
type EngineDependencies = Pick<
AlertEngineOptions,
- 'repository' | 'directory' | 'recipients' | 'externalRecipients' | 'notifier'
+ | 'repository'
+ | 'directory'
+ | 'recipients'
+ | 'externalRecipients'
+ | 'notifier'
+ | 'channels'
+ | 'channelMessage'
>;
-const ENGINE_WIRING = 2;
+const ENGINE_WIRING = 3;
type EngineSlot = {
engine: AlertEngine | null;
@@ -74,6 +101,8 @@ const dependencies: EngineDependencies = {
recipients: recipientResolver,
externalRecipients: externalRecipientService,
notifier: new AlertMailNotifier(mailQueue),
+ channels: alertChannels,
+ channelMessage: buildAlertChannelMessage,
};
// one engine per process: HMR re-evaluating this module must not subscribe a second one, and the
@@ -95,6 +124,8 @@ function createEngine(): AlertEngine {
recipients: latest(() => engineSlot.dependencies.recipients),
externalRecipients: latest(() => engineSlot.dependencies.externalRecipients!),
notifier: latest(() => engineSlot.dependencies.notifier),
+ channels: latest(() => engineSlot.dependencies.channels!),
+ channelMessage: (input) => engineSlot.dependencies.channelMessage!(input),
throttle: engineSlot.throttle,
logger: log,
// without SMTP there is nobody to tell: skip the work instead of logging a failure per event
@@ -114,6 +145,7 @@ export const alertEngine: AlertEngine = engineSlot.engine;
export const alertService = new AlertService(alertRepository, alertDirectory, {
onChange: () => alertEngine.invalidate(),
externalRecipients: externalRecipientService,
+ channels: alertChannels,
logger: log,
});
@@ -122,6 +154,7 @@ export function registerAlertEngine(): void {
if (engineSlot.attached) return;
engineSlot.detach = alertEngine.attach(eventBus);
registerMailShutdown();
+ registerChannelShutdown();
engineSlot.attached = true;
log.info('[alerts] engine registered');
diff --git a/src/modules/alerts/infrastructure/alert-channel-message.ts b/src/modules/alerts/infrastructure/alert-channel-message.ts
new file mode 100644
index 0000000..b8a5e80
--- /dev/null
+++ b/src/modules/alerts/infrastructure/alert-channel-message.ts
@@ -0,0 +1,52 @@
+import { absoluteUrl, type ChannelMessage } from '#lib/server/infra/notifications';
+import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n';
+import type { AlertEmail } from '../application/alert-engine';
+import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary';
+
+/** What a channel message is built from: an alert email without its recipient. */
+export type AlertMessageInput = Omit;
+
+/**
+ * Provider-neutral message of an alert for a notification channel. In the default language (a
+ * channel is shared by people with different ones) and without sensitive fields (people reading
+ * the channel may not be allowed to see the event); transports format it.
+ */
+export function buildAlertChannelMessage(input: AlertMessageInput): ChannelMessage {
+ const t = translator(DEFAULT_MAIL_LOCALE);
+ const { event, definition, where, alert } = input;
+ const eventLabel = t(definition.label);
+ const summary = eventSummaryText(event, definition, t);
+ const url = absoluteUrl(eventResourcePath(event, definition, where));
+
+ const fields = [
+ { label: t('alerts.email.occurredAt'), value: new Date(event.occurredAt).toUTCString() },
+ ...(where.project ? [{ label: t('alerts.email.project'), value: where.project }] : []),
+ ...describeEventFields(event, definition, input.names, { omitSensitive: true }).map(
+ (field) => ({
+ label: t(field.label),
+ value: field.translate ? t(field.value) : field.value,
+ }),
+ ),
+ ];
+
+ const headline = t('alerts.email.alertSubject', { alert: alert.name, summary });
+ const text = input.test ? t('alerts.email.testSubject', { subject: headline }) : headline;
+
+ return {
+ title: alert.name,
+ summary,
+ eventLabel,
+ fields,
+ link: url ? { url, label: t('alerts.email.viewInApp') } : null,
+ suppressed: input.suppressed,
+ text,
+ test: input.test === true,
+ event: {
+ id: event.id,
+ type: event.type,
+ occurredAt: event.occurredAt,
+ scope: { ...event.scope },
+ },
+ alert: { id: alert.id, name: alert.name },
+ };
+}
diff --git a/src/modules/alerts/infrastructure/alert-mail.notifier.ts b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
index 33eccac..1ad39c9 100644
--- a/src/modules/alerts/infrastructure/alert-mail.notifier.ts
+++ b/src/modules/alerts/infrastructure/alert-mail.notifier.ts
@@ -15,10 +15,10 @@ import {
type MailLocale,
type Translate,
} from '#lib/server/infra/notifications/i18n';
-import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog';
+import { getFieldValue, type EventDefinition } from '#lib/events/catalog';
import type { CodeReportAnalysisCompletedPayload } from '#lib/events/domain-events';
import type { AlertEmail, AlertNotifierPort, SystemEmail } from '../application/alert-engine';
-import { describeEventFields } from './event-summary';
+import { describeEventFields, eventResourcePath, eventSummaryText } from './event-summary';
export { DEFAULT_MAIL_LOCALE, translateKey, type MailLocale };
@@ -34,14 +34,6 @@ export class MailNotSentError extends Error {
}
}
-function safely(run: () => T): T | undefined {
- try {
- return run();
- } catch {
- return undefined;
- }
-}
-
function fieldsTable(rows: { label: string; value: string }[]): string {
if (rows.length === 0) return '';
const body = rows
@@ -76,27 +68,16 @@ export class AlertMailNotifier implements AlertNotifierPort {
const locale = external ? DEFAULT_MAIL_LOCALE : mailLocale(recipient.locale);
const t: Translate = translator(locale);
const { event, where } = email;
- const definition = email.definition as EventDefinition & {
- link?: (context: unknown) => string | null;
- mailSummary?: (payload: unknown) => EventMessage;
- };
+ const definition = email.definition as EventDefinition & { mailTemplate?: string };
const eventLabel = t(definition.label);
- const message = safely(() => definition.mailSummary?.(event.payload));
- const summary = message ? t(message.key, message.values) : eventLabel;
+ const summary = eventSummaryText(event, definition, t);
const baseSubject = t('alerts.email.alertSubject', { alert: email.alert.name, summary });
const subject = email.test
? t('alerts.email.testSubject', { subject: baseSubject })
: baseSubject;
- const resourcePath =
- safely(() =>
- definition.link?.({
- payload: event.payload,
- organizationSlug: where.organizationSlug ?? null,
- projectSlug: where.projectSlug ?? null,
- }),
- ) ?? null;
+ const resourcePath = eventResourcePath(event, definition, where);
const scopeName =
email.alert.scope === 'project' && where.project ? where.project : (where.organization ?? '');
diff --git a/src/modules/alerts/infrastructure/event-summary.ts b/src/modules/alerts/infrastructure/event-summary.ts
index 34e3b52..9de7f72 100644
--- a/src/modules/alerts/infrastructure/event-summary.ts
+++ b/src/modules/alerts/infrastructure/event-summary.ts
@@ -1,4 +1,4 @@
-import { getFieldValue, type EventDefinition } from '#lib/events/catalog';
+import { getFieldValue, type EventDefinition, type EventMessage } from '#lib/events/catalog';
import type { AnyDomainEvent } from '#lib/server/events';
export type EventFieldLine = {
@@ -63,3 +63,43 @@ export function describeEventFields(
}
return lines;
}
+
+type Translate = (key: string, values?: Record) => string;
+
+type DefinitionCallbacks = EventDefinition & {
+ link?: (context: unknown) => string | null;
+ mailSummary?: (payload: unknown) => EventMessage;
+};
+
+function safely(run: () => T): T | undefined {
+ try {
+ return run();
+ } catch {
+ return undefined;
+ }
+}
+
+export function eventSummaryText(
+ event: Pick,
+ definition: EventDefinition,
+ t: Translate,
+): string {
+ const message = safely(() => (definition as DefinitionCallbacks).mailSummary?.(event.payload));
+ return message ? t(message.key, message.values) : t(definition.label);
+}
+
+export function eventResourcePath(
+ event: Pick,
+ definition: EventDefinition,
+ where: { organizationSlug?: string; projectSlug?: string },
+): string | null {
+ return (
+ safely(() =>
+ (definition as DefinitionCallbacks).link?.({
+ payload: event.payload,
+ organizationSlug: where.organizationSlug ?? null,
+ projectSlug: where.projectSlug ?? null,
+ }),
+ ) ?? null
+ );
+}
diff --git a/src/modules/notifications/application/notification-channel.service.test.ts b/src/modules/notifications/application/notification-channel.service.test.ts
new file mode 100644
index 0000000..9350812
--- /dev/null
+++ b/src/modules/notifications/application/notification-channel.service.test.ts
@@ -0,0 +1,240 @@
+import { beforeEach, describe, expect, it } from 'vitest';
+import type { ChannelMessage } from '#lib/server/infra/notifications';
+import { NotificationChannelValidationError } from '../domain/notification-channel.domain';
+import { createChannelsFixture } from './testing';
+
+const ORG = 'org-1';
+const orgLocation = { scope: 'organization' as const, organizationId: ORG, projectId: null };
+const p1 = { scope: 'project' as const, organizationId: ORG, projectId: 'p1' };
+const HOOK = 'https://hooks.example.com/hook/T000/B000/secret1a2b';
+
+const message: ChannelMessage = {
+ title: 'Críticas',
+ summary: '1 critical',
+ eventLabel: 'Analysis completed',
+ fields: [],
+ link: null,
+ suppressed: 0,
+ text: '[GitOps] Críticas: 1 critical',
+ test: false,
+};
+
+async function validationErrors(promise: Promise) {
+ const error = await promise.catch((caught) => caught);
+ expect(error).toBeInstanceOf(NotificationChannelValidationError);
+ return (error as NotificationChannelValidationError).errors;
+}
+
+describe('NotificationChannelService', () => {
+ let f: ReturnType;
+
+ beforeEach(() => {
+ f = createChannelsFixture();
+ });
+
+ describe('create and storage', () => {
+ it('stores the destination encrypted and only ever shows it masked', async () => {
+ const channel = await f.service.create(
+ orgLocation,
+ { type: 'slack', name: ' #alertas ', destination: HOOK },
+ 'admin',
+ );
+
+ const [row] = f.repository.rows;
+ expect(row).toMatchObject({ id: 'channel-1', name: '#alertas', scope: 'organization' });
+ expect(row.webhookUrl).not.toContain('hooks.example.com');
+ expect(row.webhookUrl).not.toContain('secret');
+
+ const view = f.service.toView(channel);
+ expect(view.destinationMasked).toBe('https://hooks.example.com/…/••••1a2b');
+ expect(view).not.toHaveProperty('webhookUrl');
+ expect(JSON.stringify(view)).not.toContain('secret');
+ expect(view.available).toBe(true);
+ });
+
+ it('validates type, name and destination (anti-SSRF) before saving', async () => {
+ const errors = await validationErrors(
+ f.service.create(
+ orgLocation,
+ { type: 'slack', name: '', destination: 'http://hooks.example.com/hook/x' },
+ 'a',
+ ),
+ );
+ expect(errors).toEqual({ name: 'required', destination: 'not_https' });
+
+ for (const [destination, code] of [
+ ['https://evil.com/hook/x', 'host_not_allowed'],
+ ['https://10.0.0.1/hook/x', 'ip_address'],
+ ['https://u:p@hooks.example.com/hook/x', 'credentials'],
+ ['https://hooks.example.com/other', 'path_not_allowed'],
+ ]) {
+ expect(
+ await validationErrors(
+ f.service.create(orgLocation, { type: 'slack', name: 'x', destination }, 'a'),
+ ),
+ ).toEqual({ destination: code });
+ }
+ expect(f.repository.rows).toHaveLength(0);
+ });
+
+ it('only accepts types with a registered transport', async () => {
+ expect(
+ await validationErrors(
+ f.service.create(orgLocation, { type: 'google-chat', name: 'x', destination: HOOK }, 'a'),
+ ),
+ ).toEqual({ type: 'type_unavailable' });
+ expect(
+ await validationErrors(
+ f.service.create(orgLocation, { type: 'sms', name: 'x', destination: HOOK }, 'a'),
+ ),
+ ).toEqual({ type: 'invalid_type' });
+ expect(f.service.availableTypes()).toEqual(['slack']);
+ });
+
+ it('keeps the destination when an update leaves it empty, and re-encrypts a new one', async () => {
+ const channel = await f.service.create(
+ orgLocation,
+ { type: 'slack', name: 'a', destination: HOOK },
+ 'x',
+ );
+ const before = f.repository.rows[0].webhookUrl;
+
+ await f.service.update(channel.id, { name: 'b', destination: '' });
+ expect(f.repository.rows[0]).toMatchObject({ name: 'b', webhookUrl: before });
+
+ await f.service.update(channel.id, { destination: 'https://hooks.example.com/hook/new9z9z' });
+ expect(f.repository.rows[0].webhookUrl).not.toBe(before);
+ expect(f.service.toView(await f.service.get(channel.id)).destinationMasked).toMatch(/9z9z$/);
+ });
+ });
+
+ describe('scopes', () => {
+ it('lets a project channel serve only its project, and an organization channel all of them', async () => {
+ const org = await f.service.create(
+ orgLocation,
+ { type: 'slack', name: 'org', destination: HOOK },
+ 'a',
+ );
+ const own = await f.service.create(p1, { type: 'slack', name: 'p1', destination: HOOK }, 'a');
+ await f.service.create(
+ { ...p1, projectId: 'p2' },
+ { type: 'slack', name: 'p2', destination: HOOK },
+ 'a',
+ );
+
+ const usable = await f.service.listUsable({ organizationId: ORG, projectId: 'p1' });
+ expect(usable.map((channel) => channel.id).sort()).toEqual([org.id, own.id].sort());
+ expect(
+ (await f.service.listUsable({ organizationId: ORG, projectId: null })).map((c) => c.id),
+ ).toEqual([org.id]);
+ expect(await f.service.listUsable({ organizationId: 'other', projectId: null })).toEqual([]);
+ expect((await f.service.list(p1)).map((channel) => channel.name)).toEqual(['p1']);
+ });
+ });
+
+ describe('delivery', () => {
+ let channelId: string;
+
+ beforeEach(async () => {
+ channelId = (
+ await f.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x')
+ ).id;
+ });
+
+ it('sends to the decrypted destination', async () => {
+ expect(await f.service.deliver(channelId, message)).toBe(true);
+ expect(f.transport.sent).toHaveLength(1);
+ expect(f.transport.sent[0]).toMatchObject({ channel: 'slack', destination: HOOK, message });
+ });
+
+ it('skips disabled and deleted channels', async () => {
+ await f.service.update(channelId, { enabled: false });
+ expect(await f.service.deliver(channelId, message)).toBe(false);
+ expect(await f.service.deliver('missing', message)).toBe(false);
+ expect(f.transport.sent).toHaveLength(0);
+ });
+
+ it('records a permanent 4xx in lastError without retrying, and clears it on success', async () => {
+ f.transport.failWith = [404];
+ expect(await f.service.deliver(channelId, message)).toBe(false);
+ expect(f.repository.rows[0].lastError).toBe('HTTP 404');
+ expect(f.transport.sent).toHaveLength(0);
+ expect(f.transport.failWith).toEqual([]);
+
+ expect(await f.service.deliver(channelId, message)).toBe(true);
+ expect(f.repository.rows[0]).toMatchObject({ lastError: null });
+ expect(f.repository.rows[0].lastDeliveryAt).toBe(f.clock.now.toISOString());
+ });
+
+ it('retries 429, 5xx and network errors before giving up', async () => {
+ f.transport.failWith = [429, 503, 'network'];
+ expect(await f.service.deliver(channelId, message)).toBe(true);
+ expect(f.transport.sent).toHaveLength(1);
+
+ f.transport.failWith = [500, 500, 500, 500];
+ expect(await f.service.deliver(channelId, message)).toBe(false);
+ expect(f.repository.rows[0].lastError).toBe('HTTP 500');
+ });
+
+ it('checks the stored destination again before sending', async () => {
+ // someone edits GitDB by hand and points the channel elsewhere
+ const { createChannelCipher } = await import('../infrastructure/crypto/channel-cipher');
+ f.repository.rows[0].webhookUrl = createChannelCipher(() => 'test-encryption-key').encrypt(
+ channelId,
+ 'https://169.254.169.254/hook/latest',
+ );
+ expect(await f.service.deliver(channelId, message)).toBe(false);
+ expect(f.transport.sent).toHaveLength(0);
+ expect(f.repository.rows[0].lastError).toBe('invalid_destination');
+ });
+
+ it('does not commit a delivery stamp on every success', async () => {
+ await f.service.deliver(channelId, message);
+ const writes = () =>
+ f.repository.writes.filter((write) => typeof write.changes.lastDeliveryAt === 'string');
+ expect(writes()).toHaveLength(1);
+ await f.service.deliver(channelId, message);
+ await f.service.deliver(channelId, message);
+ expect(writes()).toHaveLength(1);
+ f.advance(60 * 60 * 1000);
+ await f.service.deliver(channelId, message);
+ expect(writes()).toHaveLength(2);
+ });
+
+ it('never logs the destination nor the message', async () => {
+ const lines: unknown[] = [];
+ const record = (...args: unknown[]) => void lines.push(args);
+ const g = createChannelsFixture({ logger: { warn: record, error: record, debug: record } });
+ const id = (
+ await g.service.create(orgLocation, { type: 'slack', name: 'a', destination: HOOK }, 'x')
+ ).id;
+ g.transport.failWith = [503, 503, 503, 503];
+ await g.service.deliver(id, message, { alertId: 'alert-1' });
+
+ expect(lines.length).toBeGreaterThan(0);
+ const logged = JSON.stringify(lines);
+ expect(logged).toContain(id);
+ expect(logged).not.toContain('hooks.example.com');
+ expect(logged).not.toContain('secret');
+ expect(logged).not.toContain('Críticas');
+ });
+
+ it('sends test messages even to a disabled channel and reports failures', async () => {
+ await f.service.update(channelId, { enabled: false });
+ expect(await f.service.test(channelId, { ...message, test: true })).toEqual({
+ sent: true,
+ error: null,
+ });
+ f.transport.failWith = [403];
+ expect(await f.service.test(channelId, message)).toEqual({ sent: false, error: 'HTTP 403' });
+ });
+
+ it('marks channels whose type lost its transport as unavailable', async () => {
+ const g = createChannelsFixture({ types: [] });
+ g.repository.rows = structuredClone(f.repository.rows);
+ expect(await g.service.deliver(channelId, message)).toBe(false);
+ expect(g.repository.rows[0].lastError).toBe('unavailable');
+ expect(g.service.toView(await g.service.get(channelId)).available).toBe(false);
+ });
+ });
+});
diff --git a/src/modules/notifications/application/notification-channel.service.ts b/src/modules/notifications/application/notification-channel.service.ts
new file mode 100644
index 0000000..ef98c6a
--- /dev/null
+++ b/src/modules/notifications/application/notification-channel.service.ts
@@ -0,0 +1,333 @@
+import {
+ CHAT_CHANNEL_TYPES,
+ isChatChannelType,
+ type ChatChannelType,
+} from '#lib/server/infra/notifications/chat-types';
+import type {
+ ChannelMessage,
+ ChatTransport,
+} from '#lib/server/infra/notifications/chat-notification';
+import { WebhookDeliveryError } from '#lib/server/infra/http/webhook-request';
+import {
+ MAX_CHANNEL_NAME_LENGTH,
+ NotificationChannelDomain,
+ NotificationChannelNotFoundError,
+ NotificationChannelValidationError,
+ maskDestination,
+ type ChannelLocation,
+ type NotificationChannelView,
+} from '../domain/notification-channel.domain';
+import type { ChannelCipher } from '../infrastructure/crypto/channel-cipher';
+import type {
+ NotificationChannelChanges,
+ NotificationChannelRepositoryPort,
+} from '../infrastructure/repositories/notification-channel.repository';
+
+/** One message on its way to one channel; the destination is only held in memory. */
+export type ChannelDelivery = {
+ channelId: string;
+ type: ChatChannelType;
+ destination: string;
+ message: ChannelMessage;
+ /** Called by the queue once the delivery succeeded or definitively failed. */
+ report: (outcome: { sent: true } | { sent: false; error: unknown }) => void;
+};
+
+/** Where deliveries go: the channel queue in production, a direct sender in tests. */
+export type ChannelSender = {
+ enqueue(delivery: ChannelDelivery, context?: Record): Promise;
+};
+
+export type ChannelTransports = {
+ get(type: ChatChannelType): ChatTransport | null;
+ available(): ChatChannelType[];
+};
+
+export type ChannelInput = {
+ type?: unknown;
+ name?: unknown;
+ /** Destination URL; on update an empty value keeps the stored one. */
+ destination?: unknown;
+ enabled?: unknown;
+};
+
+export type NotificationChannelServiceOptions = {
+ now?: () => Date;
+ generateId?: () => string;
+ /** How often a healthy channel records `lastDeliveryAt` (each record is a GitDB commit). */
+ deliveryStampIntervalMs?: number;
+ logger?: { warn: (object: object, message: string) => void };
+};
+
+const DEFAULT_STAMP_INTERVAL_MS = 60 * 60 * 1000;
+
+/**
+ * Notification channels (chat and webhook destinations) of organizations and projects. The
+ * destination is validated by its type's transport (anti-SSRF) before saving and before every
+ * send, stored encrypted and only ever shown masked. Deliveries go through a queue with retries;
+ * a permanent failure is recorded in `lastError`.
+ */
+export class NotificationChannelService {
+ private readonly now: () => Date;
+ private readonly generateId: () => string;
+ private readonly stampIntervalMs: number;
+
+ constructor(
+ private readonly repository: NotificationChannelRepositoryPort,
+ private readonly cipher: ChannelCipher,
+ private readonly transports: ChannelTransports,
+ private readonly sender: ChannelSender,
+ private readonly options: NotificationChannelServiceOptions = {},
+ ) {
+ this.now = options.now ?? (() => new Date());
+ this.generateId = options.generateId ?? (() => crypto.randomUUID());
+ this.stampIntervalMs = options.deliveryStampIntervalMs ?? DEFAULT_STAMP_INTERVAL_MS;
+ }
+
+ /** Channel types that can be created now (a transport is registered for them). */
+ availableTypes(): ChatChannelType[] {
+ return this.transports.available();
+ }
+
+ async get(id: string): Promise {
+ const channel = await this.repository.findById(id);
+ if (!channel) throw new NotificationChannelNotFoundError(id);
+ return channel;
+ }
+
+ /** The location's own channels: organization-level ones, or one project's. */
+ async list(location: Pick) {
+ const channels = await this.repository.listByOrganization(location.organizationId);
+ return channels.filter((channel) =>
+ location.projectId
+ ? channel.projectId === location.projectId
+ : channel.scope === 'organization',
+ );
+ }
+
+ /** Channels an alert of `location` may use: its project's and its organization's. */
+ async listUsable(location: Pick) {
+ const channels = await this.repository.listByOrganization(location.organizationId);
+ return channels.filter((channel) => channel.usableFrom(location));
+ }
+
+ toView(channel: NotificationChannelDomain): NotificationChannelView {
+ const { webhookUrl: _secret, ...rest } = channel.toJson();
+ void _secret;
+ let destinationMasked = '••••';
+ try {
+ destinationMasked = maskDestination(this.cipher.decrypt(channel.id, channel.webhookUrl));
+ } catch {
+ // an undecryptable destination (rotated key) shows as fully masked
+ }
+ return {
+ ...rest,
+ destinationMasked,
+ available: this.transports.get(channel.type) !== null,
+ };
+ }
+
+ async create(
+ location: ChannelLocation,
+ input: ChannelInput,
+ actorUserId: string,
+ ): Promise {
+ const errors: Record = {};
+ const type = this.validateType(input.type, errors);
+ const name = this.validateName(input.name, errors);
+ const destination = type ? this.validateDestination(type, input.destination, errors) : null;
+ if (Object.keys(errors).length > 0 || !type || !destination) {
+ throw new NotificationChannelValidationError(errors);
+ }
+
+ const id = this.generateId();
+ const timestamp = this.now().toISOString();
+ const row = new NotificationChannelDomain({
+ id,
+ type,
+ name,
+ ...location,
+ projectId: location.scope === 'project' ? location.projectId : null,
+ webhookUrl: this.cipher.encrypt(id, destination),
+ enabled:
+ input.enabled === undefined ? true : input.enabled === true || input.enabled === 'true',
+ createdByUserId: actorUserId,
+ createdAt: timestamp,
+ updatedAt: timestamp,
+ lastDeliveryAt: null,
+ lastError: null,
+ }).toJson();
+ await this.repository.create(row);
+ return new NotificationChannelDomain(row);
+ }
+
+ /** Name, enabled and destination; the type can't change. An empty destination keeps it. */
+ async update(id: string, input: ChannelInput): Promise {
+ const channel = await this.get(id);
+ const errors: Record = {};
+ const changes: NotificationChannelChanges = {};
+ if (input.name !== undefined) changes.name = this.validateName(input.name, errors);
+ if (input.enabled !== undefined) {
+ changes.enabled = input.enabled === true || input.enabled === 'true';
+ }
+ if (typeof input.destination === 'string' && input.destination.trim()) {
+ const destination = this.validateDestination(channel.type, input.destination, errors);
+ if (destination) {
+ changes.webhookUrl = this.cipher.encrypt(channel.id, destination);
+ // a new destination starts with a clean slate
+ changes.lastError = null;
+ }
+ }
+ if (Object.keys(errors).length > 0) throw new NotificationChannelValidationError(errors);
+ await this.repository.update(id, changes);
+ return new NotificationChannelDomain({ ...channel.toJson(), ...changes });
+ }
+
+ async delete(id: string): Promise {
+ await this.get(id);
+ await this.repository.delete(id);
+ }
+
+ /**
+ * Queues `message` for the channel and resolves with whether it was delivered. Disabled,
+ * deleted, unavailable or invalid channels resolve `false` without sending; nothing throws.
+ */
+ async deliver(
+ channelId: string,
+ message: ChannelMessage,
+ context: Record = {},
+ ): Promise {
+ const channel = await this.repository.findById(channelId).catch(() => null);
+ if (!channel || !channel.enabled) return false;
+ return this.send(channel, message, context);
+ }
+
+ /** "Send test message": delivers `message` even to a disabled channel, and tells the result. */
+ async test(
+ id: string,
+ message: ChannelMessage,
+ ): Promise<{ sent: boolean; error: string | null }> {
+ const channel = await this.get(id);
+ const sent = await this.send(channel, message, { kind: 'channel_test' });
+ const after = await this.repository.findById(id).catch(() => null);
+ return { sent, error: sent ? null : (after?.lastError ?? 'unavailable') };
+ }
+
+ private async send(
+ channel: NotificationChannelDomain,
+ message: ChannelMessage,
+ context: Record,
+ ): Promise {
+ const transport = this.transports.get(channel.type);
+ if (!transport) {
+ await this.recordFailure(channel, 'unavailable');
+ return false;
+ }
+ let destination: string;
+ try {
+ destination = this.cipher.decrypt(channel.id, channel.webhookUrl);
+ } catch {
+ await this.recordFailure(channel, 'undecryptable');
+ return false;
+ }
+ // the stored value is checked again: GitDB can be edited outside the app
+ if (!transport.validateDestination(destination).ok) {
+ await this.recordFailure(channel, 'invalid_destination');
+ return false;
+ }
+
+ let outcome: { sent: true } | { sent: false; error: unknown } = { sent: false, error: null };
+ const sent = await this.sender.enqueue(
+ {
+ channelId: channel.id,
+ type: channel.type,
+ destination,
+ message,
+ report: (result) => {
+ outcome = result;
+ },
+ },
+ { channelId: channel.id, type: channel.type, ...context },
+ );
+ if (sent) await this.recordSuccess(channel);
+ else {
+ const error = (outcome as { error?: unknown }).error;
+ await this.recordFailure(
+ channel,
+ error instanceof WebhookDeliveryError
+ ? error.summary
+ : error instanceof Error
+ ? error.name
+ : 'failed',
+ );
+ }
+ return sent;
+ }
+
+ private async recordSuccess(channel: NotificationChannelDomain) {
+ const last = channel.lastDeliveryAt ? Date.parse(channel.lastDeliveryAt) : 0;
+ const stale = this.now().getTime() - last >= this.stampIntervalMs;
+ // each write is a commit: only when the error clears or the stamp got old
+ if (!channel.lastError && !stale) return;
+ await this.repository
+ .update(channel.id, { lastDeliveryAt: this.now().toISOString(), lastError: null })
+ .catch((error) => this.logWriteFailure(channel, error));
+ }
+
+ private async recordFailure(channel: NotificationChannelDomain, reason: string) {
+ if (channel.lastError === reason) return;
+ await this.repository
+ .update(channel.id, { lastError: reason })
+ .catch((error) => this.logWriteFailure(channel, error));
+ }
+
+ private logWriteFailure(channel: NotificationChannelDomain, error: unknown) {
+ this.options.logger?.warn(
+ { channelId: channel.id, err: error instanceof Error ? error.name : 'unknown' },
+ '[channels] delivery outcome could not be recorded',
+ );
+ }
+
+ private validateType(value: unknown, errors: Record): ChatChannelType | null {
+ if (!isChatChannelType(value)) {
+ errors.type = typeof value === 'string' && value ? 'invalid_type' : 'required';
+ return null;
+ }
+ if (!this.transports.get(value)) {
+ errors.type = 'type_unavailable';
+ return null;
+ }
+ return value;
+ }
+
+ private validateName(value: unknown, errors: Record): string {
+ const name = typeof value === 'string' ? value.trim() : '';
+ if (!name) errors.name = 'required';
+ else if (name.length > MAX_CHANNEL_NAME_LENGTH) errors.name = 'too_long';
+ return name;
+ }
+
+ private validateDestination(
+ type: ChatChannelType,
+ value: unknown,
+ errors: Record,
+ ): string | null {
+ if (typeof value !== 'string' || !value.trim()) {
+ errors.destination = 'required';
+ return null;
+ }
+ const transport = this.transports.get(type);
+ if (!transport) {
+ errors.type = 'type_unavailable';
+ return null;
+ }
+ const checked = transport.validateDestination(value.trim());
+ if (!checked.ok) {
+ errors.destination = checked.error;
+ return null;
+ }
+ return checked.url.toString();
+ }
+}
+
+export { CHAT_CHANNEL_TYPES };
diff --git a/src/modules/notifications/application/testing.ts b/src/modules/notifications/application/testing.ts
index cc6c7fc..de32189 100644
--- a/src/modules/notifications/application/testing.ts
+++ b/src/modules/notifications/application/testing.ts
@@ -1,3 +1,18 @@
+import {
+ DeliveryQueue,
+ type ChatChannelType,
+ type ChatNotification,
+ type ChatTransport,
+} from '#lib/server/infra/notifications';
+import {
+ isRetryableWebhookError,
+ validateWebhookUrl,
+ webhookRetryAfter,
+ WebhookDeliveryError,
+} from '#lib/server/infra/http/webhook-request';
+import { InMemoryNotificationChannelRepository } from '../infrastructure/repositories/in-memory.repositories';
+import { createChannelCipher } from '../infrastructure/crypto/channel-cipher';
+import { NotificationChannelService, type ChannelDelivery } from './notification-channel.service';
import { RateLimiter } from '#lib/server/infra/rate-limit';
import {
InMemoryExternalRecipientRepository,
@@ -62,3 +77,71 @@ export function createNotificationsFixture(options: { origin?: string | null } =
},
};
}
+
+export class FakeChatTransport implements ChatTransport {
+ sent: ChatNotification[] = [];
+ failWith: Array = [];
+
+ validateDestination(raw: unknown) {
+ return validateWebhookUrl(raw, { hosts: ['hooks.example.com'], pathPrefix: '/hook/' });
+ }
+
+ async send(notification: ChatNotification) {
+ const failure = this.failWith.shift();
+ if (failure === 'network') throw new WebhookDeliveryError(null, true, null, 'network');
+ if (typeof failure === 'number') {
+ throw new WebhookDeliveryError(failure, failure === 429 || failure >= 500);
+ }
+ this.sent.push(notification);
+ }
+}
+
+export function createChannelsFixture(
+ options: {
+ types?: ChatChannelType[];
+ logger?: { warn: () => void; error: () => void; debug: () => void };
+ } = {},
+) {
+ const clock = { now: new Date('2026-11-24T10:00:00.000Z') };
+ const repository = new InMemoryNotificationChannelRepository();
+ const transport = new FakeChatTransport();
+ const types = options.types ?? ['slack'];
+ const logger = options.logger ?? { warn: () => {}, error: () => {}, debug: () => {} };
+ const queue = new DeliveryQueue({
+ send: (delivery) =>
+ transport.send({
+ channel: delivery.type,
+ destination: delivery.destination,
+ message: delivery.message,
+ } as ChatNotification),
+ retry: {
+ isRetryable: isRetryableWebhookError,
+ retryAfterMs: webhookRetryAfter,
+ sleep: async () => {},
+ },
+ logger,
+ label: { prefix: '[channels]', noun: 'message', plural: 'messages' },
+ describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }),
+ onSettled: (delivery, outcome) => delivery.report(outcome),
+ });
+ let id = 0;
+ const service = new NotificationChannelService(
+ repository,
+ createChannelCipher(() => 'test-encryption-key'),
+ {
+ get: (type) => (types.includes(type) ? transport : null),
+ available: () => [...types],
+ },
+ queue,
+ { now: () => clock.now, generateId: () => `channel-${++id}` },
+ );
+ return {
+ clock,
+ repository,
+ transport,
+ service,
+ advance(ms: number) {
+ clock.now = new Date(clock.now.getTime() + ms);
+ },
+ };
+}
diff --git a/src/modules/notifications/domain/notification-channel.domain.ts b/src/modules/notifications/domain/notification-channel.domain.ts
new file mode 100644
index 0000000..b55f107
--- /dev/null
+++ b/src/modules/notifications/domain/notification-channel.domain.ts
@@ -0,0 +1,131 @@
+import {
+ isChatChannelType,
+ type ChatChannelType,
+} from '#lib/server/infra/notifications/chat-types';
+
+export type ChannelScope = 'organization' | 'project';
+
+/** Where a channel lives: an organization channel has no project. */
+export type ChannelLocation = {
+ scope: ChannelScope;
+ organizationId: string;
+ projectId: string | null;
+};
+
+export type NotificationChannelRow = ChannelLocation & {
+ id: string;
+ type: ChatChannelType;
+ name: string;
+ /** Destination URL, encrypted (`channel-cipher.ts`): never returned nor logged. */
+ webhookUrl: string;
+ enabled: boolean;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+ lastDeliveryAt: string | null;
+ /** Short reason of the last failed delivery (`HTTP 404`, `timeout`), cleared on success. */
+ lastError: string | null;
+};
+
+/** What the API and the pages may show: the destination only masked. */
+export type NotificationChannelView = Omit & {
+ /** `https://hooks.slack.com/…/••••1a2b` */
+ destinationMasked: string;
+ /** Whether its type has a transport: channels of other types are kept but send nothing. */
+ available: boolean;
+};
+
+export const MAX_CHANNEL_NAME_LENGTH = 80;
+
+function toIso(value: unknown): string | null {
+ if (value instanceof Date) return value.toISOString();
+ return typeof value === 'string' && value ? value : null;
+}
+
+export class NotificationChannelDomain implements NotificationChannelRow {
+ id: string;
+ type: ChatChannelType;
+ name: string;
+ scope: ChannelScope;
+ organizationId: string;
+ projectId: string | null;
+ webhookUrl: string;
+ enabled: boolean;
+ createdByUserId: string;
+ createdAt: string;
+ updatedAt: string;
+ lastDeliveryAt: string | null;
+ lastError: string | null;
+
+ constructor(row: Record) {
+ this.id = row.id;
+ this.type = isChatChannelType(row.type) ? row.type : 'webhook';
+ this.name = row.name ?? '';
+ this.scope = row.scope === 'project' ? 'project' : 'organization';
+ this.organizationId = row.organizationId;
+ this.projectId = this.scope === 'project' ? (row.projectId ?? null) : null;
+ this.webhookUrl = row.webhookUrl ?? '';
+ this.enabled = row.enabled !== false;
+ this.createdByUserId = row.createdByUserId;
+ this.createdAt = toIso(row.createdAt) ?? new Date(0).toISOString();
+ this.updatedAt = toIso(row.updatedAt) ?? this.createdAt;
+ this.lastDeliveryAt = toIso(row.lastDeliveryAt);
+ this.lastError = row.lastError ?? null;
+ }
+
+ get location(): ChannelLocation {
+ return { scope: this.scope, organizationId: this.organizationId, projectId: this.projectId };
+ }
+
+ /**
+ * Whether an alert of `location` may use it: an organization channel serves the organization
+ * and all its projects, a project channel only alerts of its project.
+ */
+ usableFrom(location: Pick): boolean {
+ if (location.organizationId !== this.organizationId) return false;
+ return this.scope === 'organization' || location.projectId === this.projectId;
+ }
+
+ toJson(): NotificationChannelRow {
+ return {
+ id: this.id,
+ type: this.type,
+ name: this.name,
+ scope: this.scope,
+ organizationId: this.organizationId,
+ projectId: this.projectId,
+ webhookUrl: this.webhookUrl,
+ enabled: this.enabled,
+ createdByUserId: this.createdByUserId,
+ createdAt: this.createdAt,
+ updatedAt: this.updatedAt,
+ lastDeliveryAt: this.lastDeliveryAt,
+ lastError: this.lastError,
+ };
+ }
+}
+
+/** `https://hooks.slack.com/services/T0/B0/xyz1a2b` → `https://hooks.slack.com/…/••••1a2b`. */
+export function maskDestination(url: string): string {
+ try {
+ const parsed = new URL(url);
+ const tail = url.replace(/[?#].*$/, '').slice(-4);
+ return `${parsed.protocol}//${parsed.host}/…/••••${tail}`;
+ } catch {
+ return '••••';
+ }
+}
+
+export class NotificationChannelValidationError extends Error {
+ constructor(readonly errors: Record) {
+ super(`Invalid notification channel: ${Object.keys(errors).join(', ')}`);
+ this.name = 'NotificationChannelValidationError';
+ }
+}
+
+export class NotificationChannelNotFoundError extends Error {
+ constructor(id: string) {
+ super(`Notification channel not found: ${id}`);
+ this.name = 'NotificationChannelNotFoundError';
+ }
+}
diff --git a/src/modules/notifications/index.ts b/src/modules/notifications/index.ts
index 3586811..912319c 100644
--- a/src/modules/notifications/index.ts
+++ b/src/modules/notifications/index.ts
@@ -1,10 +1,25 @@
-import { absoluteUrl, notify } from '#lib/server/infra/notifications';
+import {
+ ChatNotification,
+ DeliveryQueue,
+ absoluteUrl,
+ availableChatTypes,
+ getChatTransport,
+ notify,
+ sendWithLatestNotify,
+} from '#lib/server/infra/notifications';
+import { isRetryableWebhookError, webhookRetryAfter } from '#lib/server/infra/http/webhook-request';
import { RateLimiter } from '#lib/server/infra/rate-limit';
import { createLogger } from '#lib/server/logger';
import { passwordService } from '../auth';
import { organizationService } from '../organization';
import { ExternalRecipientService } from './application/external-recipient.service';
import { NotificationSettingsService } from './application/notification-settings.service';
+import {
+ NotificationChannelService,
+ type ChannelDelivery,
+} from './application/notification-channel.service';
+import { createChannelCipher } from './infrastructure/crypto/channel-cipher';
+import { NotificationChannelRepository } from './infrastructure/repositories/notification-channel.repository';
import { ExternalRecipientMailNotifier } from './infrastructure/external-recipient-mail.notifier';
import { ExternalRecipientRepository } from './infrastructure/repositories/external-recipient.repository';
import { NotificationSettingsRepository } from './infrastructure/repositories/notification-settings.repository';
@@ -46,6 +61,49 @@ export const notificationSettingsService = new NotificationSettingsService(
externalRecipientService,
);
+const CHANNEL_QUEUE_KEY = Symbol.for('gitops.notifications.channel-queue');
+const CHANNEL_SHUTDOWN_KEY = Symbol.for('gitops.notifications.channel-shutdown');
+type GlobalWithChannelQueue = typeof globalThis & {
+ [CHANNEL_QUEUE_KEY]?: DeliveryQueue;
+ [CHANNEL_SHUTDOWN_KEY]?: boolean;
+};
+
+export const channelQueue: DeliveryQueue = ((globalThis as GlobalWithChannelQueue)[
+ CHANNEL_QUEUE_KEY
+] ??= new DeliveryQueue({
+ send: (delivery) =>
+ sendWithLatestNotify(
+ new ChatNotification({
+ channel: delivery.type,
+ destination: delivery.destination,
+ message: delivery.message,
+ }),
+ ),
+ concurrency: 3,
+ retry: { isRetryable: isRetryableWebhookError, retryAfterMs: webhookRetryAfter },
+ logger: createLogger('channels'),
+ label: { prefix: '[channels]', noun: 'message', plural: 'messages' },
+ describe: (delivery) => ({ channelId: delivery.channelId, type: delivery.type }),
+ onSettled: (delivery, outcome) => delivery.report(outcome),
+}));
+
+export const notificationChannelService = new NotificationChannelService(
+ new NotificationChannelRepository(),
+ createChannelCipher(() => passwordService.ensureEncryptionKey()),
+ { get: (type) => getChatTransport(type), available: () => availableChatTypes() },
+ channelQueue,
+ { logger: log },
+);
+
+export function registerChannelShutdown(): void {
+ const scope = globalThis as GlobalWithChannelQueue;
+ if (scope[CHANNEL_SHUTDOWN_KEY]) return;
+ scope[CHANNEL_SHUTDOWN_KEY] = true;
+ process.once('sveltekit:shutdown' as never, () => {
+ void channelQueue.drain(10_000);
+ });
+}
+
export {
ExternalRecipientService,
MAX_EXTERNAL_EMAILS,
@@ -66,4 +124,12 @@ export {
type ExternalRecipientView,
} from './domain/external-recipient.domain';
export type { NotificationSettings } from './domain/notification-settings.domain';
+export {
+ NotificationChannelNotFoundError,
+ NotificationChannelValidationError,
+ type ChannelLocation,
+ type NotificationChannelView,
+} from './domain/notification-channel.domain';
+export type { ChannelInput } from './application/notification-channel.service';
+export { buildChannelTestMessage } from './infrastructure/channel-test-message';
export { normalizeEmail } from './domain/email-address';
diff --git a/src/modules/notifications/infrastructure/channel-test-message.ts b/src/modules/notifications/infrastructure/channel-test-message.ts
new file mode 100644
index 0000000..21fe6b1
--- /dev/null
+++ b/src/modules/notifications/infrastructure/channel-test-message.ts
@@ -0,0 +1,28 @@
+import type { ChannelMessage } from '#lib/server/infra/notifications';
+import { DEFAULT_MAIL_LOCALE, translator } from '#lib/server/infra/notifications/i18n';
+
+/**
+ * The message of "Send test message": says it is a test and where it was sent from, nothing about
+ * any real event. In the default language: a channel is shared by people with different ones.
+ */
+export function buildChannelTestMessage(input: {
+ channelName: string;
+ where: string;
+ /** Absolute link to the channel settings, when `ORIGIN` is known. */
+ link: string | null;
+}): ChannelMessage {
+ const t = translator(DEFAULT_MAIL_LOCALE);
+ const summary = t('notifications.channels.testMessage.summary', { where: input.where });
+ return {
+ title: t('notifications.channels.testMessage.title', { channel: input.channelName }),
+ summary,
+ eventLabel: t('notifications.channels.testMessage.event'),
+ fields: [{ label: t('notifications.channels.testMessage.channel'), value: input.channelName }],
+ link: input.link
+ ? { url: input.link, label: t('notifications.channels.testMessage.open') }
+ : null,
+ suppressed: 0,
+ text: `${t('notifications.channels.testMessage.title', { channel: input.channelName })}: ${summary}`,
+ test: true,
+ };
+}
diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts
new file mode 100644
index 0000000..270bdf6
--- /dev/null
+++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+import { createChannelCipher } from './channel-cipher';
+
+const url = 'https://hooks.slack.com/services/T000/B000/abcdef1a2b';
+
+describe('channel cipher', () => {
+ it('round-trips a destination without keeping it readable', () => {
+ const cipher = createChannelCipher(() => 'key-1');
+ const stored = cipher.encrypt('channel-1', url);
+ expect(stored).toMatch(/^v1:/);
+ expect(stored).not.toContain('hooks.slack.com');
+ expect(cipher.decrypt('channel-1', stored)).toBe(url);
+ // a fresh IV each time
+ expect(cipher.encrypt('channel-1', url)).not.toBe(stored);
+ });
+
+ it('does not decrypt on another channel nor with another key', () => {
+ const stored = createChannelCipher(() => 'key-1').encrypt('channel-1', url);
+ expect(() => createChannelCipher(() => 'key-1').decrypt('channel-2', stored)).toThrow(
+ /could not be decrypted/,
+ );
+ expect(() => createChannelCipher(() => 'key-2').decrypt('channel-1', stored)).toThrow(
+ /could not be decrypted/,
+ );
+ expect(() => createChannelCipher(() => 'key-1').decrypt('channel-1', url)).toThrow(
+ /no encrypted destination/,
+ );
+ });
+
+ it('refuses to work without a key', () => {
+ expect(() => createChannelCipher(() => ' ').encrypt('channel-1', url)).toThrow(
+ /GITDB_ENCRYPTION_KEY/,
+ );
+ });
+});
diff --git a/src/modules/notifications/infrastructure/crypto/channel-cipher.ts b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts
new file mode 100644
index 0000000..5ab63ec
--- /dev/null
+++ b/src/modules/notifications/infrastructure/crypto/channel-cipher.ts
@@ -0,0 +1,66 @@
+import crypto from 'node:crypto';
+
+const ALGORITHM = 'aes-256-gcm';
+const VERSION = 'v1';
+const KEY_SALT = 'gitops:notifications:channel-destination:v1';
+const IV_BYTES = 12;
+const AUTH_TAG_BYTES = 16;
+
+export interface ChannelCipher {
+ encrypt(channelId: string, value: string): string;
+ decrypt(channelId: string, stored: string): string;
+}
+
+/**
+ * AES-256-GCM for channel destinations (same scheme as the vault secrets), keyed from
+ * `GITDB_ENCRYPTION_KEY`. The channel id is authenticated data: a value copied onto another
+ * channel does not decrypt.
+ */
+export function createChannelCipher(secret: () => string): ChannelCipher {
+ let cached: { material: string; key: Buffer } | null = null;
+ const key = () => {
+ const material = secret().trim();
+ if (!material) throw new Error('Missing GITDB_ENCRYPTION_KEY environment variable');
+ if (cached?.material !== material) {
+ cached = { material, key: crypto.scryptSync(material, KEY_SALT, 32) };
+ }
+ return cached.key;
+ };
+ const aad = (channelId: string) => Buffer.from(`${VERSION}:channel:${channelId}`, 'utf8');
+
+ return {
+ encrypt(channelId, value) {
+ const iv = crypto.randomBytes(IV_BYTES);
+ const cipher = crypto.createCipheriv(ALGORITHM, key(), iv, {
+ authTagLength: AUTH_TAG_BYTES,
+ });
+ cipher.setAAD(aad(channelId));
+ const ciphertext = Buffer.concat([cipher.update(value, 'utf8'), cipher.final()]);
+ return [
+ VERSION,
+ iv.toString('base64'),
+ cipher.getAuthTag().toString('base64'),
+ ciphertext.toString('base64'),
+ ].join(':');
+ },
+ decrypt(channelId, stored) {
+ const [version, iv, authTag, ciphertext, ...rest] = stored.split(':');
+ if (version !== VERSION || !iv || !authTag || !ciphertext || rest.length > 0) {
+ throw new Error(`Channel ${channelId} has no encrypted destination`);
+ }
+ try {
+ const decipher = crypto.createDecipheriv(ALGORITHM, key(), Buffer.from(iv, 'base64'), {
+ authTagLength: AUTH_TAG_BYTES,
+ });
+ decipher.setAAD(aad(channelId));
+ decipher.setAuthTag(Buffer.from(authTag, 'base64'));
+ return Buffer.concat([
+ decipher.update(Buffer.from(ciphertext, 'base64')),
+ decipher.final(),
+ ]).toString('utf8');
+ } catch {
+ throw new Error(`Channel ${channelId} destination could not be decrypted`);
+ }
+ },
+ };
+}
diff --git a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
index 7531ab8..bb365e5 100644
--- a/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
+++ b/src/modules/notifications/infrastructure/repositories/in-memory.repositories.ts
@@ -11,6 +11,14 @@ import type {
ExternalRecipientRepositoryPort,
} from './external-recipient.repository';
import type { NotificationSettingsRepositoryPort } from './notification-settings.repository';
+import {
+ NotificationChannelDomain,
+ type NotificationChannelRow,
+} from '../../domain/notification-channel.domain';
+import type {
+ NotificationChannelChanges,
+ NotificationChannelRepositoryPort,
+} from './notification-channel.repository';
/** In-memory fakes for unit tests; they store copies so callers can't mutate the stored rows. */
export class InMemoryNotificationSettingsRepository implements NotificationSettingsRepositoryPort {
@@ -75,3 +83,37 @@ export class InMemoryExternalRecipientRepository implements ExternalRecipientRep
this.rows = this.rows.filter((row) => row.id !== id);
}
}
+
+export class InMemoryNotificationChannelRepository implements NotificationChannelRepositoryPort {
+ rows: NotificationChannelRow[] = [];
+ writes: Array<{ id: string; changes: Record }> = [];
+
+ async findById(id: string) {
+ const row = this.rows.find((candidate) => candidate.id === id);
+ return row ? new NotificationChannelDomain(structuredClone(row)) : null;
+ }
+
+ async listByOrganization(organizationId: string) {
+ return this.rows
+ .filter((row) => row.organizationId === organizationId)
+ .map((row) => new NotificationChannelDomain(structuredClone(row)));
+ }
+
+ async create(row: NotificationChannelRow) {
+ this.rows.push(structuredClone(row));
+ this.writes.push({ id: row.id, changes: { ...row } });
+ }
+
+ async update(id: string, changes: NotificationChannelChanges) {
+ this.writes.push({ id, changes: { ...changes } });
+ this.rows = this.rows.map((row) =>
+ row.id === id
+ ? { ...row, ...structuredClone(changes), updatedAt: new Date().toISOString() }
+ : row,
+ );
+ }
+
+ async delete(id: string) {
+ this.rows = this.rows.filter((row) => row.id !== id);
+ }
+}
diff --git a/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
new file mode 100644
index 0000000..8f11637
--- /dev/null
+++ b/src/modules/notifications/infrastructure/repositories/notification-channel.repository.ts
@@ -0,0 +1,55 @@
+import { NotificationChannelEntity } from '#lib/database/schemas';
+import { Repository } from '#lib/server/infra/repository';
+import {
+ NotificationChannelDomain,
+ type NotificationChannelRow,
+} from '../../domain/notification-channel.domain';
+
+export type NotificationChannelChanges = Partial<
+ Pick
+>;
+
+/** Persistence port; `InMemoryNotificationChannelRepository` implements it in tests. */
+export interface NotificationChannelRepositoryPort {
+ findById(id: string): Promise;
+ /** Every channel of the organization, including those of its projects. */
+ listByOrganization(organizationId: string): Promise;
+ create(row: NotificationChannelRow): Promise;
+ update(id: string, changes: NotificationChannelChanges): Promise;
+ delete(id: string): Promise;
+}
+
+export class NotificationChannelRepository
+ extends Repository
+ implements NotificationChannelRepositoryPort
+{
+ async findById(id: string) {
+ const result = await this.db.select().from(NotificationChannelEntity).where({ id }).limit(1);
+ const row = result.rows[0];
+ return row ? new NotificationChannelDomain(row) : null;
+ }
+
+ async listByOrganization(organizationId: string) {
+ const result = await this.db
+ .select()
+ .from(NotificationChannelEntity)
+ .where({ organizationId })
+ .orderBy('createdAt', 'asc');
+ return result.rows.map((row: any) => new NotificationChannelDomain(row));
+ }
+
+ async create(row: NotificationChannelRow) {
+ await this.db.insert(NotificationChannelEntity).values({ ...row });
+ }
+
+ async update(id: string, changes: NotificationChannelChanges) {
+ await this.db
+ .update(NotificationChannelEntity)
+ .set({ ...changes, updatedAt: new Date().toISOString() })
+ .where({ id });
+ }
+
+ async delete(id: string) {
+ await this.db.delete(NotificationChannelEntity).where({ id });
+ }
+}
diff --git a/src/routes/api/notification-channels/+server.ts b/src/routes/api/notification-channels/+server.ts
new file mode 100644
index 0000000..3303cfe
--- /dev/null
+++ b/src/routes/api/notification-channels/+server.ts
@@ -0,0 +1,33 @@
+import { json } from '@sveltejs/kit';
+import { resolveLocation } from '#lib/server/alerts/access';
+import { readJson, toResponse } from '#lib/server/alerts/http';
+import { createChannel, listChannels } from '#lib/server/notifications/channels';
+
+// GET /api/notification-channels?organizationId=…|projectId=…: the location's channels (and, for a
+// project, the organization ones it inherits). The destination is only ever returned masked
+export async function GET({ url, locals }) {
+ const lookup = await resolveLocation({
+ organizationId: url.searchParams.get('organizationId'),
+ projectId: url.searchParams.get('projectId'),
+ });
+ if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status });
+ return toResponse(await listChannels(locals, lookup.location));
+}
+
+// POST /api/notification-channels { organizationId | projectId, type, name, destination, enabled? }
+export async function POST({ request, locals }) {
+ const body = await readJson(request);
+ const lookup = await resolveLocation({
+ organizationId: typeof body.organizationId === 'string' ? body.organizationId : null,
+ projectId: typeof body.projectId === 'string' ? body.projectId : null,
+ });
+ if (!lookup.ok) return json({ error: lookup.error }, { status: lookup.status });
+ return toResponse(
+ await createChannel(locals, lookup.location, {
+ type: body.type,
+ name: body.name,
+ destination: body.destination,
+ enabled: body.enabled,
+ }),
+ );
+}
diff --git a/src/routes/api/notification-channels/[id]/+server.ts b/src/routes/api/notification-channels/[id]/+server.ts
new file mode 100644
index 0000000..6a1a3e6
--- /dev/null
+++ b/src/routes/api/notification-channels/[id]/+server.ts
@@ -0,0 +1,23 @@
+import { readJson, toResponse } from '#lib/server/alerts/http';
+import { deleteChannel, getChannel, updateChannel } from '#lib/server/notifications/channels';
+
+export async function GET({ params, locals }) {
+ return toResponse(await getChannel(locals, params.id));
+}
+
+// PATCH /api/notification-channels/ { name?, destination?, enabled? }: the type can't change and
+// an omitted destination keeps the stored one
+export async function PATCH({ params, request, locals }) {
+ const body = await readJson(request);
+ return toResponse(
+ await updateChannel(locals, params.id, {
+ name: body.name,
+ destination: body.destination,
+ enabled: body.enabled,
+ }),
+ );
+}
+
+export async function DELETE({ params, locals }) {
+ return toResponse(await deleteChannel(locals, params.id));
+}
diff --git a/src/routes/api/notification-channels/[id]/test/+server.ts b/src/routes/api/notification-channels/[id]/test/+server.ts
new file mode 100644
index 0000000..6097f64
--- /dev/null
+++ b/src/routes/api/notification-channels/[id]/test/+server.ts
@@ -0,0 +1,7 @@
+import { toResponse } from '#lib/server/alerts/http';
+import { testChannel } from '#lib/server/notifications/channels';
+
+// POST /api/notification-channels//test: posts a test message, even to a disabled channel
+export async function POST({ params, locals }) {
+ return toResponse(await testChannel(locals, params.id));
+}
diff --git a/src/routes/api/notification-channels/server.test.ts b/src/routes/api/notification-channels/server.test.ts
new file mode 100644
index 0000000..a355990
--- /dev/null
+++ b/src/routes/api/notification-channels/server.test.ts
@@ -0,0 +1,260 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// grants per caller and context key (`org:` / `project:`)
+const grants: {
+ users: Record>;
+ apiKeys: Record;
+} = { users: {}, apiKeys: {} };
+
+function contextKey(context: { scope: string; organizationId?: string; projectId?: string }) {
+ return context.scope === 'project'
+ ? `project:${context.projectId}`
+ : `org:${context.organizationId}`;
+}
+
+vi.mock('#modules/auth', () => ({
+ cancanService: {
+ canSessionUser: async (user: { id?: string } | null, permission: string, context: never) =>
+ !!user?.id && (grants.users[user.id]?.[contextKey(context)] ?? []).includes(permission),
+ canApiKey: (
+ apiKey: { id: string; projectId: string | null },
+ permission: string,
+ context: { scope: string; projectId?: string },
+ ) => {
+ if (
+ apiKey.projectId &&
+ (context.scope !== 'project' || context.projectId !== apiKey.projectId)
+ ) {
+ return false;
+ }
+ return (grants.apiKeys[apiKey.id] ?? []).includes(permission);
+ },
+ },
+}));
+
+vi.mock('#modules/projects', () => ({
+ projectService: {
+ getProject: async (id: string) =>
+ ['p1', 'p2'].includes(id)
+ ? { id, name: `Project ${id}`, slug: id, organization: { id: 'org-1', slug: 'kettu' } }
+ : null,
+ },
+}));
+
+vi.mock('#modules/organization', () => ({
+ organizationService: {
+ getOrganization: async (id: string) =>
+ id === 'org-1' ? { id, name: 'Kettu', slug: 'kettu' } : null,
+ },
+}));
+
+vi.mock('#modules/notifications', async () => {
+ const { createChannelsFixture } = await import('#modules/notifications/application/testing');
+ const domain = await import('#modules/notifications/domain/notification-channel.domain');
+ const { buildChannelTestMessage } =
+ await import('#modules/notifications/infrastructure/channel-test-message');
+ const fixture = createChannelsFixture();
+ return {
+ ...domain,
+ buildChannelTestMessage,
+ notificationChannelService: fixture.service,
+ fixture,
+ };
+});
+
+const notifications = (await import('#modules/notifications')) as unknown as {
+ fixture: ReturnType<
+ typeof import('#modules/notifications/application/testing').createChannelsFixture
+ >;
+};
+const collection = await import('./+server');
+const item = await import('./[id]/+server');
+const test = await import('./[id]/test/+server');
+
+const HOOK = 'https://hooks.example.com/hook/T0/B0/topsecret1a2b';
+const ORG_ADMIN = ['read', 'create', 'update', 'delete'].map(
+ (a) => `organization:notifications:${a}`,
+);
+const PROJECT_ADMIN = ['read', 'create', 'update', 'delete'].map(
+ (a) => `project:notifications:${a}`,
+);
+
+function call(
+ handler: (event: never) => Promise,
+ input: {
+ locals?: Record;
+ body?: unknown;
+ url?: string;
+ params?: Record;
+ },
+) {
+ return handler({
+ locals: input.locals ?? {},
+ params: input.params ?? {},
+ url: new URL(input.url ?? 'http://localhost/api/notification-channels'),
+ request: { json: async () => input.body ?? {} },
+ } as never);
+}
+
+const as = (id: string) => ({ user: { id } });
+
+async function createOrgChannel() {
+ const response = await call(collection.POST, {
+ locals: as('orgAdmin'),
+ body: { organizationId: 'org-1', type: 'slack', name: '#alerts', destination: HOOK },
+ });
+ expect(response.status).toBe(201);
+ return (await response.json()) as { id: string };
+}
+
+describe('/api/notification-channels', () => {
+ beforeEach(() => {
+ notifications.fixture.repository.rows = [];
+ notifications.fixture.transport.sent = [];
+ grants.users = {
+ orgAdmin: { 'org:org-1': ORG_ADMIN },
+ orgReader: { 'org:org-1': ['organization:notifications:read'] },
+ alertsOnly: { 'org:org-1': ['organization:alerts:all', 'organization:alerts:read'] },
+ projectAdmin: { 'project:p1': PROJECT_ADMIN },
+ };
+ grants.apiKeys = { 'key-p1': PROJECT_ADMIN };
+ });
+
+ it('never returns the destination in clear', async () => {
+ const created = await createOrgChannel();
+ const listed = await call(collection.GET, {
+ locals: as('orgReader'),
+ url: 'http://localhost/api/notification-channels?organizationId=org-1',
+ });
+ const fetched = await call(item.GET, { locals: as('orgReader'), params: { id: created.id } });
+ for (const response of [listed, fetched]) {
+ expect(response.status).toBe(200);
+ const text = await response.text();
+ expect(text).not.toContain('topsecret');
+ expect(text).not.toContain('webhookUrl');
+ expect(text).toContain('••••1a2b');
+ }
+ });
+
+ it('needs *:notifications:* to see or manage channels', async () => {
+ const created = await createOrgChannel();
+
+ for (const locals of [{}, as('alertsOnly')]) {
+ const listed = await call(collection.GET, {
+ locals,
+ url: 'http://localhost/api/notification-channels?organizationId=org-1',
+ });
+ expect(listed.status).toBe(403);
+ // a channel the caller can't read looks missing
+ expect((await call(item.GET, { locals, params: { id: created.id } })).status).toBe(404);
+ }
+
+ const reader = as('orgReader');
+ expect(
+ (
+ await call(collection.POST, {
+ locals: reader,
+ body: { organizationId: 'org-1', type: 'slack', name: 'x', destination: HOOK },
+ })
+ ).status,
+ ).toBe(403);
+ expect(
+ (await call(item.PATCH, { locals: reader, params: { id: created.id }, body: { name: 'y' } }))
+ .status,
+ ).toBe(403);
+ expect((await call(item.DELETE, { locals: reader, params: { id: created.id } })).status).toBe(
+ 403,
+ );
+ expect((await call(test.POST, { locals: reader, params: { id: created.id } })).status).toBe(
+ 403,
+ );
+ expect(notifications.fixture.transport.sent).toHaveLength(0);
+ });
+
+ it('keeps project admins and project keys inside their project', async () => {
+ const created = await call(collection.POST, {
+ locals: as('projectAdmin'),
+ body: { projectId: 'p1', type: 'slack', name: '#p1', destination: HOOK },
+ });
+ expect(created.status).toBe(201);
+
+ // no organization channels for a project admin
+ const orgChannel = await call(collection.POST, {
+ locals: as('projectAdmin'),
+ body: { organizationId: 'org-1', type: 'slack', name: '#org', destination: HOOK },
+ });
+ expect(orgChannel.status).toBe(403);
+
+ const key = { apiKey: { id: 'key-p1', projectId: 'p1', userId: null, role: null } };
+ expect(
+ (
+ await call(collection.GET, {
+ locals: key,
+ url: 'http://localhost/api/notification-channels?projectId=p1',
+ })
+ ).status,
+ ).toBe(200);
+ expect(
+ (
+ await call(collection.GET, {
+ locals: key,
+ url: 'http://localhost/api/notification-channels?projectId=p2',
+ })
+ ).status,
+ ).toBe(403);
+ expect(
+ (
+ await call(collection.GET, {
+ locals: key,
+ url: 'http://localhost/api/notification-channels?organizationId=org-1',
+ })
+ ).status,
+ ).toBe(403);
+ });
+
+ it('validates the destination on the server', async () => {
+ const response = await call(collection.POST, {
+ locals: as('orgAdmin'),
+ body: {
+ organizationId: 'org-1',
+ type: 'slack',
+ name: 'x',
+ destination: 'https://127.0.0.1/hook/x',
+ },
+ });
+ expect(response.status).toBe(400);
+ await expect(response.json()).resolves.toEqual({
+ error: 'Invalid channel',
+ errors: { destination: 'ip_address' },
+ });
+ });
+
+ it('sends a test message with the fake transport', async () => {
+ const created = await createOrgChannel();
+ const response = await call(test.POST, { locals: as('orgAdmin'), params: { id: created.id } });
+ expect(response.status).toBe(200);
+ await expect(response.json()).resolves.toEqual({ sent: true, error: null });
+ expect(notifications.fixture.transport.sent[0].message).toMatchObject({
+ title: 'GitOps test message for #alerts',
+ test: true,
+ });
+ });
+
+ it('updates and deletes with the right permissions', async () => {
+ const created = await createOrgChannel();
+ const updated = await call(item.PATCH, {
+ locals: as('orgAdmin'),
+ params: { id: created.id },
+ body: { name: '#renamed', enabled: false, type: 'google-chat' },
+ });
+ await expect(updated.json()).resolves.toMatchObject({
+ name: '#renamed',
+ enabled: false,
+ type: 'slack',
+ });
+ expect(
+ (await call(item.DELETE, { locals: as('orgAdmin'), params: { id: created.id } })).status,
+ ).toBe(200);
+ expect(notifications.fixture.repository.rows).toHaveLength(0);
+ });
+});
diff --git a/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte b/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte
index 12bae55..d1aef5c 100644
--- a/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte
+++ b/src/routes/org/[org]/projects/[slug]/code-report/history/+page.svelte
@@ -1,7 +1,7 @@
+
+
+ {$_('notifications.settings.title')} - GitOps
+
+
+
diff --git a/src/routes/org/[org]/settings/alerts/settings/+page.server.ts b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
index 221be30..6a789c8 100644
--- a/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
+++ b/src/routes/org/[org]/settings/alerts/settings/+page.server.ts
@@ -6,15 +6,28 @@ import {
resendVerification,
saveAllowedDomains,
} from '#lib/server/notifications/settings';
+import { channelActions, loadChannelsSection } from '#lib/server/notifications/channels-page';
export async function load({ parent, locals }) {
const { organization } = await parent();
- const result = await loadNotificationSettings(locals, organization.id);
- if (!result.ok) throw error(result.status, result.error);
- return result.data;
+ const location = {
+ scope: 'organization' as const,
+ organizationId: organization.id,
+ projectId: null,
+ };
+ const [result, channels] = await Promise.all([
+ loadNotificationSettings(locals, organization.id),
+ loadChannelsSection(locals, location).catch(() => null),
+ ]);
+ if (!result.ok && !channels) throw error(result.status, result.error);
+ return { settings: result.ok ? result.data : null, channels };
}
export const actions = {
+ ...channelActions(async ({ params }) => {
+ const organization = await organizationOf(params.org);
+ return { scope: 'organization', organizationId: organization.id, projectId: null };
+ }),
async domains({ request, locals, params }) {
const organization = await organizationOf(params.org);
const form = await request.formData();
diff --git a/src/routes/org/[org]/settings/alerts/settings/+page.svelte b/src/routes/org/[org]/settings/alerts/settings/+page.svelte
index fa350f8..1165bef 100644
--- a/src/routes/org/[org]/settings/alerts/settings/+page.svelte
+++ b/src/routes/org/[org]/settings/alerts/settings/+page.svelte
@@ -29,5 +29,10 @@
-
+