📈 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!
TypeScript chartsclickhousedockergdprgoogle-analyticsmetricsmonitoringmysqlnestjsprivacyredisself-hostedselfhostedstatisticstailwindcssweb-analyticswebanalyticswebsite
Code refactor
Blue Mouse22ef6b2f8754
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts b/backend/apps/cloud/src/integrations/telegram/telegram.module.tsindex dd355389f..c2116a3af 100644--- a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts+++ b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts@@ -1,4 +1,10 @@-import { Module, OnModuleInit, Logger, Optional } from '@nestjs/common'+import {+ forwardRef,+ Module,+ OnModuleInit,+ Logger,+ Optional,+} from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { TelegrafModule, InjectBot } from 'nestjs-telegraf'import { session, Telegraf } from 'telegraf'@@ -15,7 +21,7 @@ import { ProjectModule } from '../../project/project.module'import { AnalyticsModule } from '../../analytics/analytics.module'import { isPrimaryNode, isPrimaryClusterNode } from '../../common/utils'import { Context } from './interface/context.interface'-import { NotificationChannel } from '../../notification-channel/entity/notification-channel.entity'+import { NotificationChannelModule } from '../../notification-channel/notification-channel.module'const shouldBotBeLaunched = isPrimaryNode() && isPrimaryClusterNode()const hasTelegramToken = !!process.env.TELEGRAM_BOT_TOKEN@@ -32,10 +38,11 @@ const hasTelegramToken = !!process.env.TELEGRAM_BOT_TOKENmiddlewares: [session()],}),}),- TypeOrmModule.forFeature([Message, NotificationChannel]),+ TypeOrmModule.forFeature([Message]),UserModule,ProjectModule,AnalyticsModule,+ forwardRef(() => NotificationChannelModule),].filter((m) => !!m),providers: [...(shouldBotBeLaunched && hasTelegramTokendiff --git a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts b/backend/apps/cloud/src/integrations/telegram/telegram.service.tsindex a0695b0e0..ab39f2468 100644--- a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts+++ b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts@@ -1,4 +1,4 @@-import { Injectable, Optional } from '@nestjs/common'+import { forwardRef, Inject, Injectable, Optional } from '@nestjs/common'import { ConfigService } from '@nestjs/config'import { InjectBot } from 'nestjs-telegraf'import { Markup, Telegraf } from 'telegraf'@@ -8,10 +8,7 @@ import { Context } from './interface/context.interface'import { Message } from './entities/message.entity'import { UserService } from '../../user/user.service'import { ExtraReplyMessage } from 'telegraf/typings/telegram-types'-import {- NotificationChannel,- NotificationChannelType,-} from '../../notification-channel/entity/notification-channel.entity'+import { NotificationChannelService } from '../../notification-channel/notification-channel.service'@Injectable()export class TelegramService {@@ -21,8 +18,9 @@ export class TelegramService {private readonly configService: ConfigService,@InjectRepository(Message)private readonly messageRepository: Repository<Message>,- @InjectRepository(NotificationChannel)- private readonly channelRepository: Repository<NotificationChannel>,+ @Optional()+ @Inject(forwardRef(() => NotificationChannelService))+ private readonly notificationChannelService?: NotificationChannelService,) {}async getStartMessage(telegramId: number) {@@ -84,7 +82,10 @@ export class TelegramService {}await this.userService.updateUserTelegramId(userId, chatId, true)- await this.upsertTelegramChannel(userId, String(chatId))+ await this.getNotificationChannelService().upsertTelegramChannel(+ userId,+ String(chatId),+ )}async cancelLinkAccount(userId: string, chatId: number) {@@ -120,45 +121,18 @@ export class TelegramService {if (!user) {return}- await this.deleteTelegramChannelsByChatId(chatId.toString())+ await this.getNotificationChannelService().deleteTelegramChannelsByChatId(+ chatId.toString(),+ user.id,+ )await this.userService.updateUserTelegramId(user.id, null)}- private async upsertTelegramChannel(userId: string, chatId: string) {- const existing = await this.channelRepository.findOne({- where: {- type: NotificationChannelType.TELEGRAM,- user: { id: userId },- },- })-- if (existing) {- existing.config = { chatId }- existing.isVerified = true- existing.disabledReason = null- return this.channelRepository.save(existing)+ private getNotificationChannelService() {+ if (!this.notificationChannelService) {+ throw new Error('NotificationChannelService is not available')}-- return this.channelRepository.save(- this.channelRepository.create({- name: 'Telegram',- type: NotificationChannelType.TELEGRAM,- config: { chatId },- isVerified: true,- user: { id: userId } as any,- }),- )- }-- private async deleteTelegramChannelsByChatId(chatId: string) {- await this.channelRepository- .createQueryBuilder()- .delete()- .where('type = :type', { type: NotificationChannelType.TELEGRAM })- .andWhere("JSON_UNQUOTE(JSON_EXTRACT(config, '$.chatId')) = :chatId", {- chatId,- })- .execute()+ return this.notificationChannelService}async addMessage(chatId: string, text: string, extra?: ExtraReplyMessage) {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.tsindex f1e3b3353..532369f8f 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@@ -1,6 +1,6 @@import { Injectable, Logger } from '@nestjs/common'import { ConfigService } from '@nestjs/config'-import { createHmac } from 'crypto'+import { createHmac, timingSafeEqual } from 'crypto'import { MailerService } from '../../mailer/mailer.service'import {NotificationChannel,@@ -113,11 +113,9 @@ export class EmailChannelService implements ChannelDispatcher {.update(channelId).digest('hex')if (sig.length !== expected.length) return null- let mismatch = 0- for (let i = 0; i < sig.length; i++) {- mismatch |= sig.charCodeAt(i) ^ expected.charCodeAt(i)- }- return mismatch === 0 ? channelId : null+ const sigBuffer = Buffer.from(sig, 'utf8')+ const expectedBuffer = Buffer.from(expected, 'utf8')+ return timingSafeEqual(sigBuffer, expectedBuffer) ? channelId : null}async send(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.tsindex 44467bdb3..916f5256b 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@@ -67,10 +67,17 @@ export class WebpushChannelService implements ChannelDispatcher {keys: cfg.keys,}+ const context = message.context as {+ dashboard_url?: string+ errors_url?: string+ }+ const url = context?.errors_url || context?.dashboard_url+const payload = JSON.stringify({title: message.subject || channel.name || 'Swetrix alert',body: message.body.replace(/[*_`]/g, '').slice(0, 240),- url: (message.context as { dashboard_url?: string })?.dashboard_url,+ url,+ tag: `${channel.id}:${url || message.subject || 'alert'}`,})try {diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.module.ts b/backend/apps/cloud/src/notification-channel/notification-channel.module.tsindex 0ee7c7eef..835442256 100644--- a/backend/apps/cloud/src/notification-channel/notification-channel.module.ts+++ b/backend/apps/cloud/src/notification-channel/notification-channel.module.ts@@ -23,7 +23,9 @@ import { DiscordModule } from '../integrations/discord/discord.module'import { SlackModule } from '../integrations/slack/slack.module'const telegramImports =- process.env.ENABLE_TELEGRAM_INTEGRATION === 'true' ? [TelegramModule] : []+ process.env.ENABLE_TELEGRAM_INTEGRATION === 'true'+ ? [forwardRef(() => TelegramModule)]+ : []@Module({imports: [diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts b/backend/apps/cloud/src/notification-channel/notification-channel.service.tsindex ec4051a82..8509480fe 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 } from 'typeorm'+import { EntityManager, In, Repository } from 'typeorm'import { randomBytes } from 'crypto'import {@@ -16,6 +16,9 @@ import {import { ProjectService } from '../project/project.service'import { OrganisationService } from '../organisation/organisation.service'import { OrganisationRole } from '../organisation/entity/organisation-member.entity'+import { Organisation } from '../organisation/entity/organisation.entity'+import { Project } from '../project/entity/project.entity'+import { User } from '../user/entities/user.entity'import {CreateChannelDTO,UpdateChannelDTO,@@ -25,6 +28,12 @@ import { WebhookChannelService } from './dispatchers/webhook-channel.service'const MAX_CHANNELS_PER_SCOPE = 50const MAX_EMAIL_LENGTH = 254const MAX_EMAIL_LOCAL_PART_LENGTH = 64+const WEB_PUSH_ALLOWED_EXACT_HOSTS = new Set([+ 'fcm.googleapis.com',+ 'updates.push.services.mozilla.com',+ 'web.push.apple.com',+])+const WEB_PUSH_ALLOWED_SUFFIX_HOSTS = ['notify.windows.com']const hasWhitespace = (value: string) => {for (const char of value) {@@ -61,6 +70,16 @@ const isValidHttpsUrl = (url: string, allowedHostSuffix: string[] = []) => {}}+const isAllowedWebPushEndpoint = (endpoint: string) => {+ if (!isValidHttpsUrl(endpoint)) return false++ const host = new URL(endpoint).hostname.toLowerCase()+ return (+ WEB_PUSH_ALLOWED_EXACT_HOSTS.has(host) ||+ WEB_PUSH_ALLOWED_SUFFIX_HOSTS.some((suffix) => host.endsWith(`.${suffix}`))+ )+}+@Injectable()export class NotificationChannelService {constructor(@@ -88,7 +107,7 @@ export class NotificationChannelService {}private async getProjectChannelsForUserOwnedProjects(userId: string) {- const pids = await this.projectService.getProjectIdsByAdminId(userId)+ const pids = await this.projectService.getProjectIdsViewableByUser(userId)if (pids.length === 0) return []return this.channelRepository.find({where: { project: { id: In(pids) } },@@ -283,12 +302,6 @@ export class NotificationChannelService {partial.project = { id: dto.projectId! } as any}- await this.enforceScopeLimit(scope, {- userId: scope === 'user' ? userId : undefined,- organisationId: scope === 'organisation' ? dto.organisationId : undefined,- projectId: scope === 'project' ? dto.projectId : undefined,- })-// Default verification for channel types where the address itself is the proof// (Slack/Discord use validated hooks; webhook still requires explicit ping).if (@@ -307,25 +320,74 @@ export class NotificationChannelService {partial.verificationToken = randomBytes(24).toString('hex')}- return this.channelRepository.save(this.channelRepository.create(partial))+ return this.saveWithinScopeLimit(+ scope,+ {+ userId: scope === 'user' ? userId : undefined,+ organisationId:+ scope === 'organisation' ? dto.organisationId : undefined,+ projectId: scope === 'project' ? dto.projectId : undefined,+ },+ partial,+ )+ }++ private getScopeWhere(+ scope: 'user' | 'organisation' | 'project',+ ids: { userId?: string; organisationId?: string; projectId?: string },+ ) {+ return scope === 'user'+ ? { user: { id: ids.userId! } }+ : scope === 'organisation'+ ? { organisation: { id: ids.organisationId! } }+ : { project: { id: ids.projectId! } }}- private async enforceScopeLimit(+ private async saveWithinScopeLimit(scope: 'user' | 'organisation' | 'project',ids: { userId?: string; organisationId?: string; projectId?: string },+ partial: Partial<NotificationChannel>,) {- const where =+ return this.channelRepository.manager.transaction(async (manager) => {+ await this.lockScopeParent(manager, scope, ids)++ const channelRepository = manager.getRepository(NotificationChannel)+ const count = await channelRepository.count({+ where: this.getScopeWhere(scope, ids),+ })+ if (count >= MAX_CHANNELS_PER_SCOPE) {+ throw new ForbiddenException(+ `Maximum number of notification channels (${MAX_CHANNELS_PER_SCOPE}) reached for this scope.`,+ )+ }++ return channelRepository.save(channelRepository.create(partial))+ })+ }++ private async lockScopeParent(+ manager: EntityManager,+ scope: 'user' | 'organisation' | 'project',+ ids: { userId?: string; organisationId?: string; projectId?: string },+ ) {+ const lock = { mode: 'pessimistic_write' as const }+ const parent =scope === 'user'- ? { user: { id: ids.userId! } }+ ? await manager.findOne(User, {+ where: { id: ids.userId! },+ lock,+ }): scope === 'organisation'- ? { organisation: { id: ids.organisationId! } }- : { project: { id: ids.projectId! } }- const count = await this.channelRepository.count({ where })- if (count >= MAX_CHANNELS_PER_SCOPE) {- throw new ForbiddenException(- `Maximum number of notification channels (${MAX_CHANNELS_PER_SCOPE}) reached for this scope.`,- )- }+ ? await manager.findOne(Organisation, {+ where: { id: ids.organisationId! },+ lock,+ })+ : await manager.findOne(Project, {+ where: { id: ids.projectId! },+ lock,+ })++ if (!parent) throw new NotFoundException('Scope not found')}normaliseConfig(@@ -374,7 +436,12 @@ export class NotificationChannelService {case NotificationChannelType.WEBPUSH: {const endpoint = String(raw.endpoint || '').trim()const keys = raw.keys as { p256dh?: string; auth?: string }- if (!endpoint || !keys?.p256dh || !keys?.auth) {+ if (+ !endpoint ||+ !isAllowedWebPushEndpoint(endpoint) ||+ !keys?.p256dh ||+ !keys?.auth+ ) {throw new BadRequestException('Invalid web push subscription')}return {@@ -474,6 +541,7 @@ export class NotificationChannelService {if (existing) {existing.config = { chatId }existing.isVerified = true+ existing.disabledReason = nullreturn this.channelRepository.save(existing)}return this.channelRepository.save(@@ -487,7 +555,7 @@ export class NotificationChannelService {)}- async deleteTelegramChannelsByChatId(chatId: string) {+ async deleteTelegramChannelsByChatId(chatId: string, userId: string) {await this.channelRepository.createQueryBuilder().delete()@@ -495,6 +563,7 @@ export class NotificationChannelService {.andWhere("JSON_UNQUOTE(JSON_EXTRACT(config, '$.chatId')) = :chatId", {chatId,})+ .andWhere('userId = :userId', { userId }).execute()}}diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex cce8d1976..83b53f2e3 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -1606,7 +1606,8 @@ export class TaskManagerService {// @ts-expect-error TypeORM typing for partial updateawait this.alertService.update(alert.id, { lastTriggered: new Date() })- const clientUrl = this.configService.get('CLIENT_URL')+ const clientUrl =+ this.configService.get<string>('CLIENT_URL') || 'https://swetrix.com'const context: AlertContext = {alert_name: alert.name,project_name: project.name,@@ -1846,7 +1847,8 @@ export class TaskManagerService {: QUERY_TIME_LABEL[alert.queryTime as QueryTime] ||getQueryTimeString(alert.queryTime as QueryTime)- const clientUrl = this.configService.get('CLIENT_URL')+ const clientUrl =+ this.configService.get<string>('CLIENT_URL') || 'https://swetrix.com'const dashboardUrl = `${clientUrl}/projects/${project.id}`if (alert.queryMetric === QueryMetric.ERRORS && !errorDetails) {diff --git a/web/app/components/NotificationChannels/NotificationChannels.tsx b/web/app/components/NotificationChannels/NotificationChannels.tsxindex 83c0c501b..56c46afcc 100644--- a/web/app/components/NotificationChannels/NotificationChannels.tsx+++ b/web/app/components/NotificationChannels/NotificationChannels.tsx@@ -73,6 +73,8 @@ const blankForm = (secret: '',})+const isRedactedUrl = (url: string) => url.includes('…') || url.includes('...')+const buildConfig = (form: ChannelFormState) => {switch (form.type) {case 'email':@@ -81,7 +83,9 @@ const buildConfig = (form: ChannelFormState) => {return { chatId: form.chatId.trim() }case 'slack':case 'discord':- return { url: form.url.trim() }+ return form.url.trim() && !isRedactedUrl(form.url.trim())+ ? { url: form.url.trim() }+ : {}case 'webhook':return {url: form.url.trim(),@@ -244,7 +248,13 @@ const NotificationChannels = ({formData.set('channelId', editing.id)formData.set('name', name)if (editing.type !== 'webpush') {- formData.set('config', JSON.stringify(buildConfig(form)))+ const config = buildConfig(form)+ if (+ (editing.type !== 'slack' && editing.type !== 'discord') ||+ Object.prototype.hasOwnProperty.call(config, 'url')+ ) {+ formData.set('config', JSON.stringify(config))+ }}submitMutate(formData)}diff --git a/web/public/sw.js b/web/public/sw.jsindex 07b9a2198..679afe1a3 100644--- a/web/public/sw.js+++ b/web/public/sw.js@@ -8,6 +8,35 @@ self.addEventListener('activate', (event) => {event.waitUntil(self.clients.claim())})+const arrayBufferToBase64 = (buffer) => {+ if (!buffer) return ''+ const bytes = new Uint8Array(buffer)+ let binary = ''+ for (let i = 0; i < bytes.byteLength; i++) {+ binary += String.fromCharCode(bytes[i])+ }+ return btoa(binary)+}++const buildSubscriptionFormData = (subscription) => {+ const sub = subscription.toJSON()+ const endpoint = sub.endpoint || subscription.endpoint+ const p256dh = sub.keys?.p256dh || arrayBufferToBase64(subscription.getKey?.('p256dh'))+ const auth = sub.keys?.auth || arrayBufferToBase64(subscription.getKey?.('auth'))++ if (!endpoint || !p256dh || !auth) {+ throw new Error('Incomplete web push subscription')+ }++ const formData = new FormData()+ formData.set('intent', 'webpush-subscribe')+ formData.set('name', 'Browser')+ formData.set('endpoint', endpoint)+ formData.set('keys', JSON.stringify({ p256dh, auth }))+ formData.set('userAgent', self.navigator?.userAgent || '')+ return formData+}+self.addEventListener('push', (event) => {let data = {}try {@@ -19,18 +48,44 @@ self.addEventListener('push', (event) => {const title = data.title || data.subject || 'Swetrix'const body = data.body || data.message || ''const url = data.url || data.dashboard_url || '/'+ const tag = data.tag || data.alert_id || data.id || urlconst options = {body,icon: '/favicon.ico',badge: '/favicon.ico',data: { url },+ tag,+ renotify: true,timestamp: Date.now(),}event.waitUntil(self.registration.showNotification(title, options))})+self.addEventListener('pushsubscriptionchange', (event) => {+ event.waitUntil(+ self.registration.pushManager+ .subscribe(event.oldSubscription?.options ?? { userVisibleOnly: true })+ .then((subscription) =>+ fetch('/notification-channel', {+ method: 'POST',+ body: buildSubscriptionFormData(subscription),+ credentials: 'same-origin',+ }),+ )+ .then((response) => {+ if (!response.ok) {+ throw new Error(`Failed to update web push subscription: ${response.status}`)+ }+ })+ .catch((error) => {+ console.error(error)+ throw error+ }),+ )+})+self.addEventListener('notificationclick', (event) => {event.notification.close()const url = (event.notification.data && event.notification.data.url) || '/'