📈 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
Access control fixes
Blue Moused40fcecb3d4c
diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts b/backend/apps/cloud/src/integrations/telegram/telegram.module.tsindex 5d0566e65..dd355389f 100644--- a/backend/apps/cloud/src/integrations/telegram/telegram.module.ts+++ b/backend/apps/cloud/src/integrations/telegram/telegram.module.ts@@ -15,6 +15,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'const shouldBotBeLaunched = isPrimaryNode() && isPrimaryClusterNode()const hasTelegramToken = !!process.env.TELEGRAM_BOT_TOKEN@@ -31,7 +32,7 @@ const hasTelegramToken = !!process.env.TELEGRAM_BOT_TOKENmiddlewares: [session()],}),}),- TypeOrmModule.forFeature([Message]),+ TypeOrmModule.forFeature([Message, NotificationChannel]),UserModule,ProjectModule,AnalyticsModule,diff --git a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts b/backend/apps/cloud/src/integrations/telegram/telegram.service.tsindex c30e0f41e..a0695b0e0 100644--- a/backend/apps/cloud/src/integrations/telegram/telegram.service.ts+++ b/backend/apps/cloud/src/integrations/telegram/telegram.service.ts@@ -8,6 +8,10 @@ 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'@Injectable()export class TelegramService {@@ -17,6 +21,8 @@ export class TelegramService {private readonly configService: ConfigService,@InjectRepository(Message)private readonly messageRepository: Repository<Message>,+ @InjectRepository(NotificationChannel)+ private readonly channelRepository: Repository<NotificationChannel>,) {}async getStartMessage(telegramId: number) {@@ -78,6 +84,7 @@ export class TelegramService {}await this.userService.updateUserTelegramId(userId, chatId, true)+ await this.upsertTelegramChannel(userId, String(chatId))}async cancelLinkAccount(userId: string, chatId: number) {@@ -113,9 +120,47 @@ export class TelegramService {if (!user) {return}+ await this.deleteTelegramChannelsByChatId(chatId.toString())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)+ }++ 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()+ }+async addMessage(chatId: string, text: string, extra?: ExtraReplyMessage) {await this.messageRepository.save({ chatId, text, extra })}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.tsindex cb060932b..b37ae2c1e 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@@ -23,10 +23,15 @@ export class TelegramChannelService implements ChannelDispatcher {const cfg = channel.config as { chatId?: string }if (!cfg?.chatId || !this.telegramService) returntry {- await this.telegramService.addMessage(cfg.chatId, message.body, {- // @ts-expect-error untyped option- disable_web_page_preview: true,- })+ await this.telegramService.addMessage(+ cfg.chatId,+ message.telegramBody || message.body,+ {+ parse_mode: 'Markdown',+ // @ts-expect-error untyped option+ disable_web_page_preview: true,+ },+ )} catch (reason) {this.logger.error(`Failed to queue Telegram alert: ${reason}`)}diff --git a/backend/apps/cloud/src/notification-channel/dispatchers/types.ts b/backend/apps/cloud/src/notification-channel/dispatchers/types.tsindex 6f0cbc6bf..035c00212 100644--- a/backend/apps/cloud/src/notification-channel/dispatchers/types.ts+++ b/backend/apps/cloud/src/notification-channel/dispatchers/types.ts@@ -6,6 +6,8 @@ import {export interface RenderedAlertMessage {/** Plain/markdown body, rendered from the alert's messageTemplate. */body: string+ /** Telegram Markdown body with interpolated values escaped for Telegram. */+ telegramBody?: string/** Optional subject (used by email). Defaults to the alert name. */subject?: string/** The raw alert context, in case a dispatcher wants extra metadata. */diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts b/backend/apps/cloud/src/notification-channel/notification-channel.service.tsindex 549c8dcc2..ec4051a82 100644--- a/backend/apps/cloud/src/notification-channel/notification-channel.service.ts+++ b/backend/apps/cloud/src/notification-channel/notification-channel.service.ts@@ -72,27 +72,16 @@ export class NotificationChannelService {// --- Scope helpers --------------------------------------------------------- /** All channel ids visible to the caller across user/orgs/projects. */+ /** All channel ids manageable by the caller across user/orgs/projects. */async getVisibleChannels(userId: string): Promise<NotificationChannel[]> {- const [- userOwned,- ownedProjectChannels,- orgChannels,- sharedProjectChannels,- ] = await Promise.all([+ const [userOwned, ownedProjectChannels, orgChannels] = await Promise.all([this.channelRepository.find({ where: { user: { id: userId } } }),this.getProjectChannelsForUserOwnedProjects(userId),- this.getOrgChannelsForUserMemberships(userId),- this.getSharedProjectChannels(userId),+ this.getOrgChannelsForManagedOrganisations(userId),])const map = new Map<string, NotificationChannel>()- for (const c of [- ...userOwned,- ...ownedProjectChannels,- ...orgChannels,- ...sharedProjectChannels,- ]) {+ for (const c of [...userOwned, ...ownedProjectChannels, ...orgChannels]) {map.set(c.id, c)}return Array.from(map.values())@@ -106,9 +95,13 @@ export class NotificationChannelService {})}- private async getOrgChannelsForUserMemberships(userId: string) {+ private async getOrgChannelsForManagedOrganisations(userId: string) {const memberships = await this.organisationService.findMemberships({- where: { user: { id: userId }, confirmed: true },+ where: {+ user: { id: userId },+ confirmed: true,+ role: In([OrganisationRole.owner, OrganisationRole.admin]),+ },relations: ['organisation'],})const orgIds = memberships@@ -120,33 +113,14 @@ export class NotificationChannelService {})}- private async getSharedProjectChannels(userId: string) {- const projectIds =- await this.projectService.getProjectIdsViewableByUser(userId)- if (projectIds.length === 0) return []-- return this.channelRepository.find({- where: { project: { id: In(projectIds) } },- relations: ['project'],- })- }-- /** Channels usable on a given project (project-owned + project owner's user channels + project's organisation channels). */+ /** Channels manageable and usable on a given project. */async getChannelsForProject(projectId: string,userId: string,): Promise<NotificationChannel[]> {const project = await this.projectService.getFullProject(projectId)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- }+ this.projectService.allowedToManage(project, userId)const candidates: NotificationChannel[] = []@@ -155,7 +129,7 @@ export class NotificationChannelService {})candidates.push(...projectChannels)- if (allowedToManage && project.admin?.id) {+ if (project.admin?.id) {const ownerChannels = await this.channelRepository.find({where: { user: { id: project.admin.id } },})@@ -174,7 +148,7 @@ export class NotificationChannelService {return Array.from(map.values())}- /** Channels owned by an organisation, accessible by a user that is a confirmed member. */+ /** Channels owned by an organisation, accessible by organisation managers. */async getChannelsForOrganisation(organisationId: string,userId: string,@@ -184,10 +158,13 @@ export class NotificationChannelService {user: { id: userId },organisation: { id: organisationId },confirmed: true,+ role: In([OrganisationRole.owner, OrganisationRole.admin]),},})if (memberships.length === 0) {- throw new ForbiddenException('You are not a member of this organisation')+ throw new ForbiddenException(+ 'You are not allowed to manage this organisation',+ )}return this.channelRepository.find({where: { organisation: { id: organisationId } },@@ -317,6 +294,7 @@ export class NotificationChannelService {if (dto.type === NotificationChannelType.SLACK ||dto.type === NotificationChannelType.DISCORD ||+ dto.type === NotificationChannelType.TELEGRAM ||dto.type === NotificationChannelType.WEBPUSH) {partial.isVerified = true@@ -436,6 +414,7 @@ export class NotificationChannelService {if (channel.type === NotificationChannelType.SLACK ||channel.type === NotificationChannelType.DISCORD ||+ channel.type === NotificationChannelType.TELEGRAM ||channel.type === NotificationChannelType.WEBPUSH) {channel.isVerified = truediff --git a/backend/apps/cloud/src/task-manager/task-manager.module.ts b/backend/apps/cloud/src/task-manager/task-manager.module.tsindex 589074d34..6296d5dba 100644--- a/backend/apps/cloud/src/task-manager/task-manager.module.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.module.ts@@ -15,6 +15,7 @@ import { SlackModule } from '../integrations/slack/slack.module'import { GoalModule } from '../goal/goal.module'import { RevenueModule } from '../revenue/revenue.module'import { NotificationChannelModule } from '../notification-channel/notification-channel.module'+import { NotificationChannel } from '../notification-channel/entity/notification-channel.entity'@Module({imports: [@@ -25,7 +26,7 @@ import { NotificationChannelModule } from '../notification-channel/notification-AlertModule,forwardRef(() => AnalyticsModule),AppLoggerModule,- TypeOrmModule.forFeature([Message]),+ TypeOrmModule.forFeature([Message, NotificationChannel]),DiscordModule,SlackModule,GoalModule,diff --git a/backend/apps/cloud/src/task-manager/task-manager.service.ts b/backend/apps/cloud/src/task-manager/task-manager.service.tsindex 0b13995f5..cce8d1976 100644--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts@@ -118,6 +118,7 @@ const CHUNK_SIZE = 5000const REPORTS_USERS_CONCURRENCY = 3const REPORTS_PROJECTS_CONCURRENCY = 5const NO_EVENTS_REMINDER_DELAY_DAYS = 2+const TELEGRAM_MARKDOWN_URL_KEYS = new Set(['dashboard_url', 'errors_url'])const mapLimit = async <T, R>(items: T[],@@ -357,13 +358,22 @@ export class TaskManagerService {this.templateRenderer.getDefaultTemplate(context.metric)const ctxRecord = context as unknown as Record<string, unknown>const body = this.templateRenderer.render(template, ctxRecord)+ const telegramContext = Object.fromEntries(+ Object.entries(ctxRecord).map(([key, value]) => {+ if (typeof value !== 'string' || TELEGRAM_MARKDOWN_URL_KEYS.has(key)) {+ return [key, value]+ }+ return [key, this.telegramService.escapeTelegramMarkdown(value)]+ }),+ )+ const telegramBody = this.templateRenderer.render(template, telegramContext)const subject = hasEmailChannel? this.templateRenderer.render(alert.emailSubjectTemplate?.trim() || DEFAULT_EMAIL_SUBJECT_TEMPLATE,ctxRecord,): alert.name- return { body, subject, context: ctxRecord }+ return { body, telegramBody, subject, context: ctxRecord }}/**