Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 12 additions & 16 deletions .github/copilot-instructions.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/<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/<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
Expand Down
64 changes: 51 additions & 13 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 `<body>` 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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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`
Expand Down Expand Up @@ -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/<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 `<alerts path>/settings` (`/org/<org>/settings/alerts/settings` or
`/org/<org>/projects/<slug>/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 `<scope>: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
`<scope>: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/<org>/settings/alerts` and `/org/<org>/projects/<slug>/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
Expand Down
15 changes: 15 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
28 changes: 20 additions & 8 deletions e2e/specs/alerts.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
}) => {
Expand All @@ -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');
Expand Down Expand Up @@ -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);
});
});
Expand Down
9 changes: 3 additions & 6 deletions src/lib/alerts/draft.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ export function emptyDraft(): AlertDraft {
eventType: '',
match: 'all',
conditions: [],
channels: ['mail'],
recipients: emptyRecipients(),
channelIds: [],
throttleMinutes: 0,
};
}
Expand All @@ -36,14 +36,14 @@ 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]) => [
key,
[...list],
]),
) as AlertDraft['recipients'],
channelIds: [...(alert.channelIds ?? [])],
throttleMinutes: alert.throttleMinutes,
};
}
Expand All @@ -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);
Expand Down
26 changes: 14 additions & 12 deletions src/lib/alerts/summary.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,38 +67,40 @@ 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),
...recipients.userIds.map((id) => users.find((user) => user.id === id)?.label ?? id),
...(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);
}
Loading
Loading