Skip to content

📈 Open source, privacy-first web analytics — a cookie-less Google Analytics alternative with built-in error tracking and performance monitoring. Self-host it or use our cloud. Get started for free!

Code review fixes & improvements

Blue Mousec7ba00f49a60
diff --git a/README.md b/README.md
index f60677a28..30d1c40b9 100644
--- a/README.md
+++ b/README.md
@@ -86,7 +86,7 @@ Cloud vs Community Edition
| **Core analytics (traffic, events, sessions, funnels, performance, errors)** | ✅ Included | ✅ Included |
| **Advanced features (Revenue, Experiments, AI)** | ✅ Included | ⚠️ Not included |
| **Teams & sharing** | ✅ Organisations to manage multiple projects and users with permissions setup; invite people to your projects directly, or share a public or password protected link with people. | ⚠️ Only direct project invites, password protected links and public projects are supported. |
-| **Alerts & notifications** | ✅ Yes (Slack/Telegram/Discord) | ⚠️ Not included |
+| **Alerts & notifications** | ✅ Yes (Email, Slack, Telegram, Discord, webhook, web push) | ⚠️ Not included |
| **Email reports** | ✅ Yes (weekly/monthly/quarterly) | ⚠️ Not included |
| **Geo analytics** | ✅ Swetrix Cloud uses premium GeoIP database to provide consistent and accurate country and city level geolocation data. | ⚠️ Less accurate, DB-IP City Lite Database; you need to pay for the full database if you want better accuracy. |
| **Release schedule** | ✅ Continuously developed with updates deployed as soon as they are ready | ℹ️ Periodic open‑source releases, latest features are not available immediately. |
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index 5a194324e..81b51d93f 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -222,7 +222,7 @@ export class AlertController {
validatedChannels.some((c) => c.type === NotificationChannelType.EMAIL) &&
!alertDTO.emailSubjectTemplate
) {
- // Use a sensible default if the user picked email but didn't supply a subject.
+ alertDTO.emailSubjectTemplate = 'Alert: {{alert.name}}'
}
try {
diff --git a/backend/apps/cloud/src/alert/dto/alert.dto.ts b/backend/apps/cloud/src/alert/dto/alert.dto.ts
index 684cd7318..ccdff5724 100644
--- a/backend/apps/cloud/src/alert/dto/alert.dto.ts
+++ b/backend/apps/cloud/src/alert/dto/alert.dto.ts
@@ -1,4 +1,5 @@
import { ApiProperty, PartialType } from '@nestjs/swagger'
+import { Transform } from 'class-transformer'
import { PID_REGEX } from '../../common/constants'
import {
IsEnum,
@@ -38,6 +39,12 @@ export enum QueryTime {
LAST_48_HOURS = 'last_48_hours',
}
+const trimBlankToNull = ({ value }: { value: unknown }) => {
+ if (typeof value !== 'string') return value
+ const trimmed = value.trim()
+ return trimmed === '' ? null : trimmed
+}
+
class AlertBaseDTO {
@ApiProperty()
@IsNotEmpty()
@@ -91,12 +98,14 @@ class AlertBaseDTO {
channelIds?: string[]
@ApiProperty({ nullable: true })
+ @Transform(trimBlankToNull)
@IsString()
@IsOptional()
@MaxLength(5000)
messageTemplate?: string | null
@ApiProperty({ nullable: true })
+ @Transform(trimBlankToNull)
@IsString()
@IsOptional()
@MaxLength(255)
diff --git a/backend/apps/cloud/src/mailer/mailer.service.ts b/backend/apps/cloud/src/mailer/mailer.service.ts
index d87f8dc99..e432bcb34 100644
--- a/backend/apps/cloud/src/mailer/mailer.service.ts
+++ b/backend/apps/cloud/src/mailer/mailer.service.ts
@@ -182,21 +182,17 @@ export class MailerService {
subject: string,
html: string,
): Promise<void> {
- try {
- const message = {
- from: `Swetrix <${process.env.FROM_EMAIL}>`,
- to: email,
- subject,
- html,
- }
+ const message = {
+ from: `Swetrix <${process.env.FROM_EMAIL}>`,
+ to: email,
+ subject,
+ html,
+ }
- if (process.env.SMTP_MOCK) {
- this.logger.log({ ...message }, 'sendRawEmail', true)
- } else {
- await this.nodeMailerService.sendMail(message)
- }
- } catch (reason) {
- this.logger.error(reason, 'sendRawEmail', true)
+ if (process.env.SMTP_MOCK) {
+ this.logger.log({ ...message }, 'sendRawEmail', true)
+ } else {
+ await this.nodeMailerService.sendMail(message)
}
}
diff --git a/backend/apps/cloud/src/main.ts b/backend/apps/cloud/src/main.ts
index 47d577cd6..af985c516 100644
--- a/backend/apps/cloud/src/main.ts
+++ b/backend/apps/cloud/src/main.ts
@@ -16,7 +16,7 @@ async function bootstrap() {
const app = await NestFactory.create(AppModule)
app.use(cookieParser())
- app.useGlobalPipes(new ValidationPipe())
+ app.useGlobalPipes(new ValidationPipe({ transform: true }))
app.enableVersioning({
type: VersioningType.URI,
diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/email-channel.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/email-channel.service.ts
index d7eafa63a..6980a9166 100644
--- a/backend/apps/cloud/src/notification-channel/dispatchers/email-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/dispatchers/email-channel.service.ts
@@ -42,16 +42,28 @@ const escapeHtml = (s: string) =>
: '&#39;',
)
+const isAllowedLinkHref = (href: string) => {
+ try {
+ const { protocol } = new URL(href)
+ return (
+ protocol === 'http:' || protocol === 'https:' || protocol === 'mailto:'
+ )
+ } catch {
+ return false
+ }
+}
+
const simpleMarkdownToHtml = (md: string) => {
// Tiny converter: bold, italics, links, code, line breaks. Anything fancier
// stays as escaped text so we never inject raw HTML from a user template.
let out = escapeHtml(md)
- out = out.replace(
- /\[([^\]]+)\]\(([^)]+)\)/g,
- '<a href="$2" style="color: #2563eb;">$1</a>',
+ out = out.replace(/\[([^\]]+)\]\(([^)]+)\)/g, (_match, text, href) =>
+ isAllowedLinkHref(href)
+ ? `<a href="${href}" style="color: #2563eb;">${text}</a>`
+ : text,
)
out = out.replace(/\*\*(.+?)\*\*/g, '<strong>$1</strong>')
- out = out.replace(/\*(.+?)\*/g, '<strong>$1</strong>')
+ out = out.replace(/\*(?!\*)(.+?)\*(?!\*)/g, '<em>$1</em>')
out = out.replace(/`([^`]+)`/g, '<code>$1</code>')
out = out.replace(/\n/g, '<br/>')
return out
@@ -68,13 +80,24 @@ export class EmailChannelService implements ChannelDispatcher {
private readonly configService: ConfigService,
) {}
+ private getUnsubscribeSecret(): string {
+ const secret =
+ this.configService.get<string>('JWT_SECRET') ||
+ this.configService.get<string>('JWT_ACCESS_TOKEN_SECRET')
+
+ if (!secret) {
+ throw new Error(
+ 'JWT_SECRET or JWT_ACCESS_TOKEN_SECRET is required for email unsubscribe tokens',
+ )
+ }
+
+ return secret
+ }
+
buildUnsubscribeToken(channelId: string) {
// Stateless one-click unsubscribe: HMAC over channel id with the JWT secret.
// Avoids storing per-channel tokens just for unsubscribe.
- const secret =
- this.configService.get<string>('JWT_SECRET') ||
- this.configService.get<string>('JWT_ACCESS_TOKEN_SECRET') ||
- 'swetrix-unsubscribe'
+ const secret = this.getUnsubscribeSecret()
const sig = createHmac('sha256', secret).update(channelId).digest('hex')
return `${channelId}.${sig}`
}
@@ -84,7 +107,10 @@ export class EmailChannelService implements ChannelDispatcher {
if (dot === -1) return null
const channelId = token.slice(0, dot)
const sig = token.slice(dot + 1)
- const expected = this.buildUnsubscribeToken(channelId).split('.')[1]
+ const secret = this.getUnsubscribeSecret()
+ const expected = createHmac('sha256', secret)
+ .update(channelId)
+ .digest('hex')
if (sig.length !== expected.length) return null
let mismatch = 0
for (let i = 0; i < sig.length; i++) {
diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
index b3414307e..cb060932b 100644
--- a/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/dispatchers/telegram-channel.service.ts
@@ -24,7 +24,6 @@ export class TelegramChannelService implements ChannelDispatcher {
if (!cfg?.chatId || !this.telegramService) return
try {
await this.telegramService.addMessage(cfg.chatId, message.body, {
- parse_mode: 'Markdown',
// @ts-expect-error untyped option
disable_web_page_preview: true,
})
diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/webhook-channel.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/webhook-channel.service.ts
index 7e6f0ec63..c7d82565d 100644
--- a/backend/apps/cloud/src/notification-channel/dispatchers/webhook-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/dispatchers/webhook-channel.service.ts
@@ -1,5 +1,9 @@
import { Injectable, Logger } from '@nestjs/common'
import { createHmac } from 'crypto'
+// using node-fetch instead of undici because the native fetch does not support
+// 'agent' option (to prevent SSRF)
+import fetch from 'node-fetch'
+import { useAgent } from 'request-filtering-agent'
import {
NotificationChannel,
NotificationChannelType,
@@ -59,16 +63,18 @@ export class WebhookChannelService implements ChannelDispatcher {
.digest('hex')
headers['X-Swetrix-Signature'] = `sha256=${sig}`
}
- const res = await fetch(cfg.url, {
+ const webhookUrl = cfg.url
+ const res = await fetch(webhookUrl, {
method: 'POST',
headers,
body: bodyStr,
+ agent: useAgent(webhookUrl),
signal: AbortSignal.timeout(10_000),
redirect: 'error',
})
if (!res.ok) {
this.logger.warn(
- `Outbound webhook ${cfg.url} responded with status ${res.status}`,
+ `Outbound webhook ${webhookUrl} responded with status ${res.status}`,
)
}
} catch (reason) {
@@ -95,6 +101,7 @@ export class WebhookChannelService implements ChannelDispatcher {
method: 'POST',
headers,
body: payload,
+ agent: useAgent(url),
signal: AbortSignal.timeout(5_000),
redirect: 'error',
})
diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/webpush-channel.service.ts b/backend/apps/cloud/src/notification-channel/dispatchers/webpush-channel.service.ts
index bf287d3a8..44467bdb3 100644
--- a/backend/apps/cloud/src/notification-channel/dispatchers/webpush-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/dispatchers/webpush-channel.service.ts
@@ -76,12 +76,15 @@ export class WebpushChannelService implements ChannelDispatcher {
try {
await webpush.sendNotification(subscription, payload)
} catch (reason: any) {
- // 404/410 mean the subscription is dead — drop it.
+ // 404/410 mean the subscription is dead; keep alert links intact.
if (reason?.statusCode === 404 || reason?.statusCode === 410) {
this.logger.warn(
- `Pruning expired webpush channel ${channel.id} (status ${reason.statusCode})`,
+ `Disabling expired webpush channel ${channel.id} (status ${reason.statusCode})`,
)
- await this.channelRepository.delete(channel.id)
+ await this.channelRepository.update(channel.id, {
+ isVerified: false,
+ disabledReason: `Expired: ${reason.statusCode} from WebPush server`,
+ })
return
}
this.logger.error(`Failed to send webpush: ${reason?.message || reason}`)
diff --git a/backend/apps/cloud/src/notification-channel/dto/notification-channel.dto.ts b/backend/apps/cloud/src/notification-channel/dto/notification-channel.dto.ts
index 8331d2ef3..8a53cd158 100644
--- a/backend/apps/cloud/src/notification-channel/dto/notification-channel.dto.ts
+++ b/backend/apps/cloud/src/notification-channel/dto/notification-channel.dto.ts
@@ -1,5 +1,6 @@
import { ApiProperty } from '@nestjs/swagger'
import {
+ IsBoolean,
IsEnum,
IsNotEmpty,
IsOptional,
@@ -8,7 +9,10 @@ import {
IsObject,
IsUUID,
Matches,
+ MaxLength,
+ ValidateNested,
} from 'class-validator'
+import { Type } from 'class-transformer'
import { PID_REGEX } from '../../common/constants'
import { NotificationChannelType } from '../entity/notification-channel.entity'
@@ -44,6 +48,7 @@ export class CreateChannelDTO {
// userId omitted: user-scoped channels are owned by the authenticated caller.
@ApiProperty({ required: false, default: false })
@IsOptional()
+ @IsBoolean()
userScoped?: boolean
}
@@ -60,19 +65,37 @@ export class UpdateChannelDTO {
config?: Record<string, unknown>
}
+class WebpushKeysDto {
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(512)
+ p256dh: string
+
+ @ApiProperty()
+ @IsString()
+ @IsNotEmpty()
+ @MaxLength(512)
+ auth: string
+}
+
export class WebpushSubscribeDTO {
@ApiProperty()
@IsString()
@IsNotEmpty()
+ @MaxLength(2048)
endpoint: string
@ApiProperty()
- @IsObject()
- keys: { p256dh: string; auth: string }
+ @IsNotEmpty()
+ @ValidateNested()
+ @Type(() => WebpushKeysDto)
+ keys: WebpushKeysDto
@ApiProperty({ required: false })
@IsOptional()
@IsString()
+ @MaxLength(512)
userAgent?: string
@ApiProperty({ required: false })
diff --git a/backend/apps/cloud/src/notification-channel/entity/notification-channel.entity.ts b/backend/apps/cloud/src/notification-channel/entity/notification-channel.entity.ts
index 7ffef2af6..2bf5c31a3 100644
--- a/backend/apps/cloud/src/notification-channel/entity/notification-channel.entity.ts
+++ b/backend/apps/cloud/src/notification-channel/entity/notification-channel.entity.ts
@@ -36,7 +36,7 @@ export type NotificationChannelConfig =
@Entity({ name: 'notification_channel' })
@Check(
- '`channel_scope_check`',
+ 'channel_scope_check',
'((`userId` IS NOT NULL) + (`organisationId` IS NOT NULL) + (`projectId` IS NOT NULL)) = 1',
)
export class NotificationChannel {
@@ -66,6 +66,9 @@ export class NotificationChannel {
@Column('varchar', { length: 64, nullable: true, default: null })
verificationToken: string | null
+ @Column('varchar', { length: 255, nullable: true, default: null })
+ disabledReason: string | null
+
@ApiProperty()
@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
created: Date
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
index df4badc19..50aad0eac 100644
--- a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
@@ -268,6 +268,7 @@ export class NotificationChannelController {
type: channel.type,
config: this.redactConfig(channel),
isVerified: channel.isVerified,
+ disabledReason: channel.disabledReason,
created: channel.created,
updated: channel.updated,
scope: channel.user
@@ -293,7 +294,10 @@ export class NotificationChannelController {
userAgent?: string | null
}
return {
- endpoint: cfg.endpoint.slice(0, 64) + '…',
+ endpoint:
+ cfg.endpoint.length > 64
+ ? cfg.endpoint.slice(0, 64) + '…'
+ : cfg.endpoint,
userAgent: cfg.userAgent,
}
}
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts b/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
index 75b1b7d19..549c8dcc2 100644
--- a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.service.ts
@@ -5,7 +5,7 @@ import {
NotFoundException,
} from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
-import { In, Repository, IsNull, Not } from 'typeorm'
+import { In, Repository } from 'typeorm'
import { randomBytes } from 'crypto'
import {
@@ -121,28 +121,14 @@ export class NotificationChannelService {
}
private async getSharedProjectChannels(userId: string) {
- // Channels owned by projects the user has admin share / org membership on.
- // We resolve through the existing projectService permission code.
- const allProjectChannels = await this.channelRepository.find({
- where: { project: Not(IsNull()) },
+ const projectIds =
+ await this.projectService.getProjectIdsViewableByUser(userId)
+ if (projectIds.length === 0) return []
+
+ return this.channelRepository.find({
+ where: { project: { id: In(projectIds) } },
relations: ['project'],
})
- if (allProjectChannels.length === 0) return []
- const accessible: NotificationChannel[] = []
- for (const channel of allProjectChannels) {
- if (!channel.project) continue
- const project = await this.projectService.getFullProject(
- channel.project.id,
- )
- if (!project) continue
- try {
- this.projectService.allowedToView(project, userId)
- accessible.push(channel)
- } catch {
- // ignore — not allowed
- }
- }
- return accessible
}
/** Channels usable on a given project (project-owned + project owner's user channels + project's organisation channels). */
@@ -154,6 +140,14 @@ export class NotificationChannelService {
if (!project) throw new NotFoundException('Project not found')
this.projectService.allowedToView(project, userId)
+ let allowedToManage = false
+ try {
+ this.projectService.allowedToManage(project, userId)
+ allowedToManage = true
+ } catch {
+ allowedToManage = false
+ }
+
const candidates: NotificationChannel[] = []
const projectChannels = await this.channelRepository.find({
@@ -161,7 +155,7 @@ export class NotificationChannelService {
})
candidates.push(...projectChannels)
- if (project.admin?.id) {
+ if (allowedToManage && project.admin?.id) {
const ownerChannels = await this.channelRepository.find({
where: { user: { id: project.admin.id } },
})
@@ -322,7 +316,8 @@ export class NotificationChannelService {
// (Slack/Discord use validated hooks; webhook still requires explicit ping).
if (
dto.type === NotificationChannelType.SLACK ||
- dto.type === NotificationChannelType.DISCORD
+ dto.type === NotificationChannelType.DISCORD ||
+ dto.type === NotificationChannelType.WEBPUSH
) {
partial.isVerified = true
}
@@ -383,7 +378,7 @@ export class NotificationChannelService {
}
case NotificationChannelType.DISCORD: {
const url = String(raw.url || '').trim()
- if (!isValidHttpsUrl(url, ['discord.com'])) {
+ if (!isValidHttpsUrl(url, ['discord.com', 'discordapp.com'])) {
throw new BadRequestException('Invalid Discord webhook URL')
}
return { url }
@@ -426,7 +421,17 @@ export class NotificationChannelService {
if (dto.name) channel.name = dto.name
if (dto.config) {
- channel.config = this.normaliseConfig(channel.type, dto.config)
+ const config =
+ channel.type === NotificationChannelType.WEBHOOK &&
+ !Object.prototype.hasOwnProperty.call(dto.config, 'secret')
+ ? {
+ ...dto.config,
+ secret:
+ (channel.config as { secret?: string | null }).secret ?? null,
+ }
+ : dto.config
+
+ channel.config = this.normaliseConfig(channel.type, config)
// Re-set isVerified based on type rules
if (
channel.type === NotificationChannelType.SLACK ||
@@ -434,12 +439,15 @@ export class NotificationChannelService {
channel.type === NotificationChannelType.WEBPUSH
) {
channel.isVerified = true
+ channel.disabledReason = null
} else if (channel.type === NotificationChannelType.EMAIL) {
channel.isVerified = false
channel.verificationToken = randomBytes(24).toString('hex')
+ channel.disabledReason = null
} else if (channel.type === NotificationChannelType.WEBHOOK) {
channel.isVerified = false
channel.verificationToken = randomBytes(24).toString('hex')
+ channel.disabledReason = null
}
}
return this.channelRepository.save(channel)
@@ -455,11 +463,14 @@ export class NotificationChannelService {
async markVerified(id: string) {
await this.channelRepository.update(id, {
isVerified: true,
+ disabledReason: null,
verificationToken: null,
})
}
async findByVerificationToken(token: string) {
+ if (!token || token.trim() === '') return null
+
return this.channelRepository.findOne({
where: { verificationToken: token },
})
@@ -498,14 +509,13 @@ export class NotificationChannelService {
}
async deleteTelegramChannelsByChatId(chatId: string) {
- const channels = await this.channelRepository.find({
- where: { type: NotificationChannelType.TELEGRAM },
- })
- const matching = channels.filter(
- (c) => (c.config as { chatId?: string })?.chatId === chatId,
- )
- if (matching.length > 0) {
- await this.channelRepository.delete(matching.map((c) => c.id))
- }
+ await this.channelRepository
+ .createQueryBuilder()
+ .delete()
+ .where('type = :type', { type: NotificationChannelType.TELEGRAM })
+ .andWhere("JSON_UNQUOTE(JSON_EXTRACT(config, '$.chatId')) = :chatId", {
+ chatId,
+ })
+ .execute()
}
}
diff --git a/backend/apps/cloud/src/project/project.service.ts b/backend/apps/cloud/src/project/project.service.ts
index b4c5cfd23..5e5c29c63 100644
--- a/backend/apps/cloud/src/project/project.service.ts
+++ b/backend/apps/cloud/src/project/project.service.ts
@@ -427,6 +427,33 @@ export class ProjectService {
return _map(projects, 'id')
}
+ async getProjectIdsViewableByUser(userId: string): Promise<string[]> {
+ const projects = await this.projectsRepository
+ .createQueryBuilder('project')
+ .select('project.id', 'id')
+ .distinct(true)
+ .leftJoin('project.admin', 'admin')
+ .leftJoin('project.share', 'share')
+ .leftJoin('share.user', 'sharedUser')
+ .leftJoin('project.organisation', 'organisation')
+ .leftJoin('organisation.members', 'organisationMembers')
+ .leftJoin('organisationMembers.user', 'organisationUser')
+ .where(
+ new Brackets((qb) => {
+ qb.where('project.public = true')
+ .orWhere('admin.id = :userId')
+ .orWhere('sharedUser.id = :userId AND share.confirmed = true')
+ .orWhere(
+ 'organisationUser.id = :userId AND organisationMembers.confirmed = true',
+ )
+ }),
+ )
+ .setParameter('userId', userId)
+ .getRawMany<{ id: string }>()
+
+ return _map(projects, 'id')
+ }
+
async create(project: DeepPartial<Project>) {
return this.projectsRepository.save(project)
}
diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.ts
index 126719385..af188f323 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -1827,11 +1827,6 @@ export class TaskManagerService {
}
}
- // @ts-expect-error
- await this.alertService.update(alert.id, {
- lastTriggered: new Date(),
- })
-
const effectiveQueryTimeString =
alert.queryMetric === QueryMetric.ERRORS
? `${CRON_INTERVAL_SECONDS / 60} minutes`
@@ -1911,6 +1906,11 @@ export class TaskManagerService {
)
const message = this.renderAlertMessage(alert, context, hasEmail)
await this.channelDispatcher.dispatch(alert.channels, message)
+
+ // @ts-expect-error TypeORM typing for partial update
+ await this.alertService.update(alert.id, {
+ lastTriggered: new Date(),
+ })
} catch (reason) {
this.logger.error(
`[CRON WORKER](checkMetricAlerts) Failed to process alert ${alert.id}: ${reason}`,
diff --git a/backend/migrations/mysql/2026_04_26_notification_channel_disabled_reason.sql b/backend/migrations/mysql/2026_04_26_notification_channel_disabled_reason.sql
new file mode 100644
index 000000000..e9dba9556
--- /dev/null
+++ b/backend/migrations/mysql/2026_04_26_notification_channel_disabled_reason.sql
@@ -0,0 +1,2 @@
+ALTER TABLE `notification_channel`
+ ADD COLUMN `disabledReason` varchar(255) DEFAULT NULL AFTER `verificationToken`;
diff --git a/backend/package-lock.json b/backend/package-lock.json
index a92b48d6e..2bb8fa42b 100644
--- a/backend/package-lock.json
+++ b/backend/package-lock.json
@@ -60,6 +60,7 @@
"mysql2": "^3.20.0",
"nestjs-i18n": "^10.6.0",
"nestjs-telegraf": "^2.9.1",
+ "node-fetch": "^2.7.0",
"nodemailer": "^8.0.5",
"otplib": "^13.4.0",
"passport": "^0.7.0",
@@ -67,6 +68,7 @@
"passport-jwt": "^4.0.1",
"php-serialize": "^5.1.3",
"reflect-metadata": "^0.2.2",
+ "request-filtering-agent": "^3.2.0",
"rimraf": "^6.1.3",
"rxjs": "^7.8.2",
"sns-payload-validator": "^2.1.0",
@@ -87,6 +89,7 @@
"@types/lodash": "^4.17.24",
"@types/multer": "^2.1.0",
"@types/node": "^25.5.2",
+ "@types/node-fetch": "^2.6.13",
"@types/nodemailer": "^8.0.0",
"@types/passport-jwt": "^4.0.1",
"knip": "^6.3.1",
@@ -4805,6 +4808,17 @@
"undici-types": "~7.18.0"
}
},
+ "node_modules/@types/node-fetch": {
+ "version": "2.6.13",
+ "resolved": "https://registry.npmjs.org/@types/node-fetch/-/node-fetch-2.6.13.tgz",
+ "integrity": "sha512-QGpRVpzSaUs30JBSGPjOg4Uveu384erbHBoT1zeONvyCfwQxIkUshLAOqN/k9EjGviPRmWTTe6aH2qySWKTVSw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/node": "*",
+ "form-data": "^4.0.4"
+ }
+ },
"node_modules/@types/nodemailer": {
"version": "8.0.0",
"resolved": "https://registry.npmjs.org/@types/nodemailer/-/nodemailer-8.0.0.tgz",
@@ -5517,6 +5531,13 @@
"license": "MIT",
"optional": true
},
+ "node_modules/asynckit": {
+ "version": "0.4.0",
+ "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz",
+ "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/available-typed-arrays": {
"version": "1.0.7",
"resolved": "https://registry.npmjs.org/available-typed-arrays/-/available-typed-arrays-1.0.7.tgz",
@@ -6339,6 +6360,19 @@
"integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==",
"license": "MIT"
},
+ "node_modules/combined-stream": {
+ "version": "1.0.8",
+ "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz",
+ "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "delayed-stream": "~1.0.0"
+ },
+ "engines": {
+ "node": ">= 0.8"
+ }
+ },
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/commander/-/commander-4.1.1.tgz",
@@ -6881,6 +6915,16 @@
"url": "https://github.com/sponsors/ljharb"
}
},
+ "node_modules/delayed-stream": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz",
+ "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">=0.4.0"
+ }
+ },
"node_modules/denque": {
"version": "2.1.0",
"resolved": "https://registry.npmjs.org/denque/-/denque-2.1.0.tgz",
@@ -7367,6 +7411,22 @@
"node": ">= 0.4"
}
},
+ "node_modules/es-set-tostringtag": {
+ "version": "2.1.0",
+ "resolved": "https://registry.npmjs.org/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
+ "integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "es-errors": "^1.3.0",
+ "get-intrinsic": "^1.2.6",
+ "has-tostringtag": "^1.0.2",
+ "hasown": "^2.0.2"
+ },
+ "engines": {
+ "node": ">= 0.4"
+ }
+ },
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://registry.npmjs.org/escalade/-/escalade-3.2.0.tgz",
@@ -7846,6 +7906,46 @@
"node": "*"
}
},
+ "node_modules/form-data": {
+ "version": "4.0.5",
+ "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.5.tgz",
+ "integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "asynckit": "^0.4.0",
+ "combined-stream": "^1.0.8",
+ "es-set-tostringtag": "^2.1.0",
+ "hasown": "^2.0.2",
+ "mime-types": "^2.1.12"
+ },
+ "engines": {
+ "node": ">= 6"
+ }
+ },
+ "node_modules/form-data/node_modules/mime-db": {
+ "version": "1.52.0",
+ "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz",
+ "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
+ "dev": true,
+ "license": "MIT",
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
+ "node_modules/form-data/node_modules/mime-types": {
+ "version": "2.1.35",
+ "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz",
+ "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "mime-db": "1.52.0"
+ },
+ "engines": {
+ "node": ">= 0.6"
+ }
+ },
"node_modules/formatly": {
"version": "0.3.0",
"resolved": "https://registry.npmjs.org/formatly/-/formatly-0.3.0.tgz",
@@ -12510,6 +12610,27 @@
"integrity": "sha512-urBwgfrvVP/eAyXx4hluJivBKzuEbSQs9rKWCrCkbSxNv8mxPcUZKeuoF3Uy4mJl3Lwprp6yy5/39VWigZ4K6Q==",
"license": "Apache-2.0"
},
+ "node_modules/request-filtering-agent": {
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/request-filtering-agent/-/request-filtering-agent-3.2.0.tgz",
+ "integrity": "sha512-tKPrKdsmTFuGG1/pBEpzTB66mDZ2lZLW8kjW4N6jj4QjnxUTKrIfv5p2zuJRfztOos86jRPD41lRaGjh+1QqDw==",
+ "license": "MIT",
+ "dependencies": {
+ "ipaddr.js": "^2.1.0"
+ },
+ "engines": {
+ "node": ">=20.0.0"
+ }
+ },
+ "node_modules/request-filtering-agent/node_modules/ipaddr.js": {
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/ipaddr.js/-/ipaddr.js-2.3.0.tgz",
+ "integrity": "sha512-Zv/pA+ciVFbCSBBjGfaKUya/CcGmUHzTydLMaTwrUUEM2DIEO3iZvueGxmacvmN50fGpGVKeTXpb2LcYQxeVdg==",
+ "license": "MIT",
+ "engines": {
+ "node": ">= 10"
+ }
+ },
"node_modules/require-directory": {
"version": "2.1.1",
"resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz",
diff --git a/backend/package.json b/backend/package.json
index 8aca40fa2..79ff1edfd 100644
--- a/backend/package.json
+++ b/backend/package.json
@@ -81,6 +81,7 @@
"mysql2": "^3.20.0",
"nestjs-i18n": "^10.6.0",
"nestjs-telegraf": "^2.9.1",
+ "node-fetch": "^2.7.0",
"nodemailer": "^8.0.5",
"otplib": "^13.4.0",
"passport": "^0.7.0",
@@ -88,6 +89,7 @@
"passport-jwt": "^4.0.1",
"php-serialize": "^5.1.3",
"reflect-metadata": "^0.2.2",
+ "request-filtering-agent": "^3.2.0",
"rimraf": "^6.1.3",
"rxjs": "^7.8.2",
"sns-payload-validator": "^2.1.0",
@@ -108,6 +110,7 @@
"@types/lodash": "^4.17.24",
"@types/multer": "^2.1.0",
"@types/node": "^25.5.2",
+ "@types/node-fetch": "^2.6.13",
"@types/nodemailer": "^8.0.0",
"@types/passport-jwt": "^4.0.1",
"knip": "^6.3.1",
diff --git a/docs/content/docs/analytics-dashboard/alerts.mdx b/docs/content/docs/analytics-dashboard/alerts.mdx
index f58f2ef0a..bbb158100 100644
--- a/docs/content/docs/analytics-dashboard/alerts.mdx
+++ b/docs/content/docs/analytics-dashboard/alerts.mdx
@@ -57,7 +57,7 @@ Decide which scope you want the channel to live at (User / Organisation / Projec
### Click "Add channel" and pick a type
-<img alt="Connect a channel" src="/docs/img/analytics-dashboard/alert-conect-a-channel.png" />
+<img alt="Connect a channel" src="/docs/img/analytics-dashboard/alert-connect-a-channel.png" />
Each type has slightly different details. Pick the tab below that matches the destination you want to wire up.
diff --git a/docs/public/img/analytics-dashboard/alert-conect-a-channel.png b/docs/public/img/analytics-dashboard/alert-connect-a-channel.png
similarity index 100%
rename from docs/public/img/analytics-dashboard/alert-conect-a-channel.png
rename to docs/public/img/analytics-dashboard/alert-connect-a-channel.png
diff --git a/web/app/components/NotificationChannels/NotificationChannels.tsx b/web/app/components/NotificationChannels/NotificationChannels.tsx
index b6469a570..2860ac744 100644
--- a/web/app/components/NotificationChannels/NotificationChannels.tsx
+++ b/web/app/components/NotificationChannels/NotificationChannels.tsx
@@ -85,7 +85,7 @@ const buildConfig = (form: ChannelFormState) => {
case 'webhook':
return {
url: form.url.trim(),
- secret: form.secret.trim() || null,
+ ...(form.secret.trim() ? { secret: form.secret.trim() } : {}),
}
default:
return {}
@@ -234,10 +234,15 @@ const NotificationChannels = ({
const onUpdate = () => {
if (!editing) return
+ const name = form.name.trim()
+ if (!name) {
+ toast.error(t('notificationChannels.nameRequired'))
+ return
+ }
const formData = new FormData()
formData.set('intent', 'update-channel')
formData.set('channelId', editing.id)
- formData.set('name', form.name.trim())
+ formData.set('name', name)
formData.set('config', JSON.stringify(buildConfig(form)))
submitMutate(formData)
}
diff --git a/web/app/lib/models/NotificationChannel.ts b/web/app/lib/models/NotificationChannel.ts
index b1a2e40a9..3eb85b2a4 100644
--- a/web/app/lib/models/NotificationChannel.ts
+++ b/web/app/lib/models/NotificationChannel.ts
@@ -14,6 +14,7 @@ export interface NotificationChannel {
type: NotificationChannelType
config: Record<string, any>
isVerified: boolean
+ disabledReason?: string | null
scope: NotificationChannelScope
userId?: string | null
organisationId?: string | null
diff --git a/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx b/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx
index f21b2e0c5..ce5791173 100644
--- a/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx
+++ b/web/app/pages/Project/Settings/Alerts/AlertTemplateEditor.tsx
@@ -1,5 +1,5 @@
import { CodeIcon, EyeIcon, PlusIcon } from '@phosphor-icons/react'
-import { marked } from 'marked'
+import { Marked } from 'marked'
import { useEffect, useMemo, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useFetcher } from 'react-router'
@@ -81,7 +81,7 @@ const interpolate = (
})
}
-marked.setOptions({ breaks: true, gfm: true })
+const markdownParser = new Marked({ breaks: true, gfm: true })
// Channels like Telegram/Slack treat single `*text*` as bold (not italic).
// Convert it to CommonMark-compatible `**text**` so the live preview matches
@@ -93,7 +93,9 @@ const normalizeChannelMarkdown = (input: string): string =>
)
const renderMarkdown = (markdown: string): string => {
- const html = marked.parse(normalizeChannelMarkdown(markdown)) as string
+ const html = markdownParser.parse(
+ normalizeChannelMarkdown(markdown),
+ ) as string
return sanitizeHtml(html, {
allowedTags: [
'a',
diff --git a/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx b/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx
index f7ac953be..221652945 100644
--- a/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx
+++ b/web/app/pages/Project/Settings/Alerts/ProjectAlertsSettings.tsx
@@ -504,6 +504,10 @@ const ProjectAlertsSettings = ({
{(form.channelIds || []).map((id) => (
<input key={id} type='hidden' name='channelIds' value={id} />
))}
+ {(form.channelIds || []).length === 0 ? (
+ <input type='hidden' name='channelIds' value='' />
+ ) : null}
+ <input type='hidden' name='channelIdsProvided' value='true' />
<input
type='hidden'
name='messageTemplate'
diff --git a/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx b/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx
index 7d65dad10..b4e426f6b 100644
--- a/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx
+++ b/web/app/pages/Project/Settings/Alerts/ProjectAlertsView.tsx
@@ -1,6 +1,5 @@
import cx from 'clsx'
import dayjs from 'dayjs'
-import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
import _reduce from 'lodash/reduce'
import _values from 'lodash/values'
@@ -98,6 +97,7 @@ interface AlertRowProps {
active: boolean
queryMetric: (typeof QUERY_METRIC)[keyof typeof QUERY_METRIC]
lastTriggered: string | null
+ channels?: Alerts['channels']
deleteAlert: (id: string) => void
openAlert: (id: string) => void
queryMetricTMapping: any
@@ -109,6 +109,7 @@ const AlertRow = ({
active,
queryMetric,
lastTriggered,
+ channels,
openAlert,
deleteAlert,
queryMetricTMapping,
@@ -122,6 +123,7 @@ const AlertRow = ({
const MetricIcon = METRIC_ICON_MAPPING[queryMetric]?.icon || FileTextIcon
const metricIconClass =
METRIC_ICON_MAPPING[queryMetric]?.className || 'text-gray-500'
+ const hasChannels = Array.isArray(channels) && channels.length > 0
const lastTriggeredText = lastTriggered
? language === 'en'
@@ -171,6 +173,12 @@ const AlertRow = ({
{t('alert.disabled')}
</span>
) : null}
+ {!hasChannels ? (
+ <span className='inline-flex items-center gap-1 rounded-md bg-amber-50 px-1.5 py-0.5 text-xs text-amber-700 ring-1 ring-amber-600/20 dark:bg-amber-500/10 dark:text-amber-300 dark:ring-amber-400/20'>
+ <WarningOctagonIcon className='size-3' />
+ {t('alert.noChannelsBadge')}
+ </span>
+ ) : null}
</div>
<div className='mt-0.5 flex items-center gap-2'>
<Badge
@@ -368,17 +376,15 @@ const ProjectAlertsInner = ({
)
}, [t])
- const isIntegrationLinked = useMemo(() => {
- if (_isEmpty(user)) {
+ const hasAnyAlertWithChannels = useMemo(() => {
+ if (!alerts) {
return false
}
- return Boolean(
- (user.telegramChatId && user.isTelegramChatIdConfirmed) ||
- user.slackWebhookUrl ||
- user.discordWebhookUrl,
+ return alerts.some(
+ (alert) => Array.isArray(alert.channels) && alert.channels.length > 0,
)
- }, [user])
+ }, [alerts])
const handleNewAlert = () => {
if (isLimitReached) {
@@ -499,7 +505,7 @@ const ProjectAlertsInner = ({
</div>
) : (
<>
- {!isIntegrationLinked ? (
+ {!hasAnyAlertWithChannels ? (
<NoNotificationChannelSet
channelsLink={`/projects/${projectId}/settings?tab=channels`}
/>
diff --git a/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx b/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx
index fee295c64..3fe494e83 100644
--- a/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx
+++ b/web/app/pages/Project/Settings/Alerts/RichTemplateInput.tsx
@@ -386,18 +386,29 @@ const RichTemplateInput = forwardRef<
}
const handleMouseMove = (e: React.MouseEvent<HTMLTextAreaElement>) => {
- if (typeof document === 'undefined') return
- // Use the underlying mirror to find the token at this point.
- // The textarea is on top with transparent text; the mirror is behind.
- const el = document.elementFromPoint(e.clientX, e.clientY)
- let target = el as HTMLElement | null
- while (target && !target.dataset?.templateToken) {
- target = target.parentElement
+ const mirror = mirrorRef.current
+ if (!mirror) return
+
+ let target: HTMLElement | null = null
+ const tokenEls = mirror.querySelectorAll<HTMLElement>(
+ '[data-template-token]',
+ )
+ for (const el of tokenEls) {
+ const rect = el.getBoundingClientRect()
+ if (
+ e.clientX >= rect.left &&
+ e.clientX <= rect.right &&
+ e.clientY >= rect.top &&
+ e.clientY <= rect.bottom
+ ) {
+ target = el
+ break
+ }
}
if (
!target ||
!target.dataset.templateToken ||
- !mirrorRef.current?.contains(target)
+ !mirror.contains(target)
) {
if (hoverDebounceRef.current !== null) {
window.clearTimeout(hoverDebounceRef.current)
diff --git a/web/app/pages/Project/Settings/SettingsSidebar.tsx b/web/app/pages/Project/Settings/SettingsSidebar.tsx
index efdb73930..7d5d4a443 100644
--- a/web/app/pages/Project/Settings/SettingsSidebar.tsx
+++ b/web/app/pages/Project/Settings/SettingsSidebar.tsx
@@ -102,9 +102,7 @@ const CollapsibleGroup = <TabId extends string>({
activeTab: TabId
onTabChange: (tabId: TabId) => void
}) => {
- const [isExpanded, setIsExpanded] = useState(() =>
- getGroupExpandedState(group.id),
- )
+ const [isExpanded, setIsExpanded] = useState(true)
const hasActiveTab = useMemo(
() => tabs.some((tab) => tab.id === activeTab),
@@ -113,6 +111,10 @@ const CollapsibleGroup = <TabId extends string>({
const prevHasActiveTab = useRef(hasActiveTab)
+ useEffect(() => {
+ setIsExpanded(getGroupExpandedState(group.id))
+ }, [group.id])
+
useEffect(() => {
if (hasActiveTab && !prevHasActiveTab.current && !isExpanded) {
setIsExpanded(true)
diff --git a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
index dcd3897af..b1cde156d 100644
--- a/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
+++ b/web/app/pages/Project/tabs/AskAI/AskAIView.tsx
@@ -38,7 +38,7 @@ import {
import _filter from 'lodash/filter'
import _isEmpty from 'lodash/isEmpty'
import _map from 'lodash/map'
-import { marked } from 'marked'
+import { Marked } from 'marked'
import React, { useState, useRef, useEffect, useCallback, useMemo } from 'react'
import { useTranslation } from 'react-i18next'
import { useSearchParams, useFetcher } from 'react-router'
@@ -124,13 +124,13 @@ interface AskAIViewProps {
projectId: string
}
-marked.setOptions({
+const markdownParser = new Marked({
breaks: true,
gfm: true,
})
const renderMarkdown = (content: string): string => {
- const html = marked.parse(content) as string
+ const html = markdownParser.parse(content) as string
return sanitizeHtml(html, {
allowedTags: sanitizeHtml.defaults.allowedTags.concat(['img']),
allowedAttributes: {
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index bcb5abcdf..7466c5b4a 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -1599,8 +1599,10 @@ const UserSettings = () => {
description={t('notificationChannels.userScopeDescription')}
isLast={!user?.isTelegramChatIdConfirmed}
>
- <div id='integrations'>
- <NotificationChannels scope='user' />
+ <div id='notification-channels'>
+ <div id='integrations'>
+ <NotificationChannels scope='user' />
+ </div>
</div>
</SettingsSection>
diff --git a/web/app/routes/notification-channel.tsx b/web/app/routes/notification-channel.tsx
index 61f6d0bbf..c7732c1dd 100644
--- a/web/app/routes/notification-channel.tsx
+++ b/web/app/routes/notification-channel.tsx
@@ -89,7 +89,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -121,7 +124,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -134,13 +140,22 @@ export async function action({ request }: ActionFunctionArgs) {
case 'update-channel': {
const channelId = formData.get('channelId')?.toString()
const name = formData.get('name')?.toString()
- const config = formData.has('config')
- ? parseConfig(formData.get('config'))
- : undefined
const body: Record<string, unknown> = {}
if (name !== undefined) body.name = name
- if (config !== undefined) body.config = config
+ if (formData.has('config')) {
+ try {
+ const rawConfig = formData.get('config')?.toString() || ''
+ const parsed = JSON.parse(rawConfig)
+ body.config =
+ typeof parsed === 'object' && parsed !== null ? parsed : {}
+ } catch {
+ return data<NotificationChannelActionData>(
+ { intent, error: 'Invalid notification channel config JSON' },
+ { status: 400 },
+ )
+ }
+ }
const result = await serverFetch<NotificationChannel>(
request,
@@ -151,7 +166,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -173,7 +191,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -195,7 +216,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -217,7 +241,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -236,7 +263,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
@@ -274,7 +304,10 @@ export async function action({ request }: ActionFunctionArgs) {
if (result.error) {
return data<NotificationChannelActionData>(
{ intent, error: result.error as string },
- { status: 400 },
+ {
+ status: 400,
+ headers: createHeadersWithCookies(result.cookies),
+ },
)
}
diff --git a/web/app/routes/projects.$id.tsx b/web/app/routes/projects.$id.tsx
index b70c3d0d9..3a062ded7 100644
--- a/web/app/routes/projects.$id.tsx
+++ b/web/app/routes/projects.$id.tsx
@@ -886,11 +886,12 @@ export async function action({ request, params }: ActionFunctionArgs) {
if (alertOnEveryCustomEvent !== undefined)
body.alertOnEveryCustomEvent = alertOnEveryCustomEvent
- if (formData.has('channelIds')) {
- body.channelIds = formData
- .getAll('channelIds')
- .map((v) => v.toString())
- .filter(Boolean)
+ const channelIds = formData
+ .getAll('channelIds')
+ .map((v) => v.toString())
+ .filter(Boolean)
+ if (formData.has('channelIdsProvided') || channelIds.length > 0) {
+ body.channelIds = channelIds
}
if (formData.has('messageTemplate')) {
const v = formData.get('messageTemplate')?.toString() || ''
diff --git a/web/public/locales/en.json b/web/public/locales/en.json
index 021d4f344..4ad3eb9af 100644
--- a/web/public/locales/en.json
+++ b/web/public/locales/en.json
@@ -1150,6 +1150,7 @@
"queryValueError": "Please fill threshold and the query value has to be a number.",
"noIntegration": "You have not configured an integration yet. Create one in your <url>account settings</url>.",
"noNotificationChannel": "You do not have a notification channel set up, please set it up to be notified when one of your alerts is triggered.",
+ "noChannelsBadge": "No channels",
"lastTriggered": "Last Triggered",
"never": "Never",
"qDelete": "Delete the alert?",
diff --git a/web/public/sw.js b/web/public/sw.js
index 967961a85..5ff0fe5dd 100644
--- a/web/public/sw.js
+++ b/web/public/sw.js
@@ -34,13 +34,23 @@ self.addEventListener('push', (event) => {
self.addEventListener('notificationclick', (event) => {
event.notification.close()
const url = (event.notification.data && event.notification.data.url) || '/'
+ let targetUrl
+ try {
+ targetUrl = new URL(url, self.location.origin)
+ } catch {
+ targetUrl = new URL('/', self.location.origin)
+ }
event.waitUntil(
- self.clients.matchAll({ type: 'window' }).then((clientList) => {
- for (const client of clientList) {
- if (client.url === url && 'focus' in client) return client.focus()
- }
- if (self.clients.openWindow) return self.clients.openWindow(url)
- return null
- }),
+ self.clients
+ .matchAll({ type: 'window', includeUncontrolled: true })
+ .then((clientList) => {
+ for (const client of clientList) {
+ if (client.url === targetUrl.href && 'focus' in client) {
+ return client.focus()
+ }
+ }
+ if (self.clients.openWindow) return self.clients.openWindow(url)
+ return null
+ }),
)
})