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!

Minor refactor

Blue Mouse9913cdf157e2
diff --git a/backend/apps/cloud/src/alert/alert.controller.ts b/backend/apps/cloud/src/alert/alert.controller.ts
index 81b51d93f..f3864c5d7 100644
--- a/backend/apps/cloud/src/alert/alert.controller.ts
+++ b/backend/apps/cloud/src/alert/alert.controller.ts
@@ -42,7 +42,10 @@ import { AlertService } from './alert.service'
import { getIPFromHeaders } from '../common/utils'
import { trackCustom } from '../common/analytics'
import { NotificationChannelService } from '../notification-channel/notification-channel.service'
-import { TemplateRendererService } from '../notification-channel/template-renderer.service'
+import {
+ DEFAULT_EMAIL_SUBJECT_TEMPLATE,
+ TemplateRendererService,
+} from '../notification-channel/template-renderer.service'
import { NotificationChannelType } from '../notification-channel/entity/notification-channel.entity'
const ALERTS_MAXIMUM = ACCOUNT_PLANS[PlanCode.free].maxAlerts
@@ -222,7 +225,7 @@ export class AlertController {
validatedChannels.some((c) => c.type === NotificationChannelType.EMAIL) &&
!alertDTO.emailSubjectTemplate
) {
- alertDTO.emailSubjectTemplate = 'Alert: {{alert.name}}'
+ alertDTO.emailSubjectTemplate = DEFAULT_EMAIL_SUBJECT_TEMPLATE
}
try {
diff --git a/backend/apps/cloud/src/main.ts b/backend/apps/cloud/src/main.ts
index af985c516..c42ad225b 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({ transform: true }))
+ app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: 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 6980a9166..f1e3b3353 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
@@ -7,6 +7,7 @@ import {
NotificationChannelType,
} from '../entity/notification-channel.entity'
import { ChannelDispatcher, RenderedAlertMessage } from './types'
+import { buildNotificationChannelUnsubscribeUrl } from '../notification-channel.paths'
const wrapEmailHtml = (
body: string,
@@ -129,7 +130,10 @@ export class EmailChannelService implements ChannelDispatcher {
try {
const clientUrl =
this.configService.get<string>('CLIENT_URL') || 'https://swetrix.com'
- const unsubscribeUrl = `${clientUrl}/notification-channel/unsubscribe/${this.buildUnsubscribeToken(channel.id)}`
+ const unsubscribeUrl = buildNotificationChannelUnsubscribeUrl(
+ clientUrl,
+ this.buildUnsubscribeToken(channel.id),
+ )
const subject = message.subject || 'Swetrix alert'
const html = wrapEmailHtml(message.body, unsubscribeUrl, subject)
await this.mailerService.sendRawEmail(cfg.address, subject, html)
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 50aad0eac..4a0946299 100644
--- a/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.controller.ts
@@ -37,6 +37,20 @@ import { EmailChannelService } from './dispatchers/email-channel.service'
import { WebhookChannelService } from './dispatchers/webhook-channel.service'
import { WebpushChannelService } from './dispatchers/webpush-channel.service'
import { MailerService } from '../mailer/mailer.service'
+import { buildNotificationChannelVerifyUrl } from './notification-channel.paths'
+
+const escapeHtml = (value: string) =>
+ value.replace(/[&<>"']/g, (char) =>
+ char === '&'
+ ? '&amp;'
+ : char === '<'
+ ? '&lt;'
+ : char === '>'
+ ? '&gt;'
+ : char === '"'
+ ? '&quot;'
+ : '&#39;',
+ )
@ApiTags('NotificationChannel')
@Controller('notification-channel')
@@ -247,11 +261,16 @@ export class NotificationChannelController {
if (!channel.verificationToken) return
const clientUrl =
this.configService.get<string>('CLIENT_URL') || 'https://swetrix.com'
- const url = `${clientUrl}/api/notification-channel/verify/${channel.verificationToken}`
+ const url = buildNotificationChannelVerifyUrl(
+ clientUrl,
+ channel.verificationToken,
+ )
+ const safeAddress = escapeHtml(cfg.address)
+ const safeUrl = escapeHtml(url)
const html = `<!DOCTYPE html><html><body style="font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif; padding: 24px; color: #111827;">
<h2>Confirm your Swetrix notification channel</h2>
- <p>Click the button below to confirm we can send alerts to <strong>${cfg.address}</strong>.</p>
- <p><a href="${url}" style="display:inline-block; padding: 10px 18px; background: #2563eb; color: #fff; border-radius: 6px; text-decoration: none;">Confirm channel</a></p>
+ <p>Click the button below to confirm we can send alerts to <strong>${safeAddress}</strong>.</p>
+ <p><a href="${safeUrl}" style="display:inline-block; padding: 10px 18px; background: #2563eb; color: #fff; border-radius: 6px; text-decoration: none;">Confirm channel</a></p>
<p style="color: #6b7280; font-size: 12px;">If you didn't set this up, ignore this email.</p>
</body></html>`
await this.mailerService.sendRawEmail(
diff --git a/backend/apps/cloud/src/notification-channel/notification-channel.paths.ts b/backend/apps/cloud/src/notification-channel/notification-channel.paths.ts
new file mode 100644
index 000000000..904cdfad2
--- /dev/null
+++ b/backend/apps/cloud/src/notification-channel/notification-channel.paths.ts
@@ -0,0 +1,22 @@
+const NOTIFICATION_CHANNEL_API_PATH = '/api/notification-channel'
+
+const joinClientUrl = (clientUrl: string, path: string) =>
+ `${clientUrl.replace(/\/$/, '')}${path}`
+
+export const buildNotificationChannelVerifyUrl = (
+ clientUrl: string,
+ token: string,
+) =>
+ joinClientUrl(
+ clientUrl,
+ `${NOTIFICATION_CHANNEL_API_PATH}/verify/${encodeURIComponent(token)}`,
+ )
+
+export const buildNotificationChannelUnsubscribeUrl = (
+ clientUrl: string,
+ token: string,
+) =>
+ joinClientUrl(
+ clientUrl,
+ `${NOTIFICATION_CHANNEL_API_PATH}/unsubscribe/${encodeURIComponent(token)}`,
+ )
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 af188f323..0b13995f5 100644
--- a/backend/apps/cloud/src/task-manager/task-manager.service.ts
+++ b/backend/apps/cloud/src/task-manager/task-manager.service.ts
@@ -1843,13 +1843,14 @@ export class TaskManagerService {
this.logger.warn(
`[CRON WORKER](checkMetricAlerts) Error details not found for alert ${alert.id}`,
)
- return
}
let context: AlertContext
if (alert.queryMetric === QueryMetric.ERRORS) {
- const errors_url = `${dashboardUrl}?tab=errors&eid=${errorDetails!.eid}`
+ const errors_url = errorDetails?.eid
+ ? `${dashboardUrl}?tab=errors&eid=${errorDetails.eid}`
+ : `${dashboardUrl}?tab=errors`
context = {
alert_name: alert.name,
project_name: project.name,
@@ -1861,8 +1862,8 @@ export class TaskManagerService {
condition: null,
time_window: effectiveQueryTimeString,
error_count: count,
- error_message: errorDetails!.message || '',
- error_name: errorDetails!.name || '',
+ error_message: errorDetails?.message || '',
+ error_name: errorDetails?.name || '',
errors_url,
is_new_only: !!alert.alertOnNewErrorsOnly,
} as AlertContextErrors
@@ -1904,13 +1905,13 @@ export class TaskManagerService {
const hasEmail = alert.channels.some(
(c) => c.type === NotificationChannelType.EMAIL,
)
- 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(),
})
+
+ const message = this.renderAlertMessage(alert, context, hasEmail)
+ await this.channelDispatcher.dispatch(alert.channels, message)
} catch (reason) {
this.logger.error(
`[CRON WORKER](checkMetricAlerts) Failed to process alert ${alert.id}: ${reason}`,
diff --git a/web/app/components/NotificationChannels/NotificationChannels.tsx b/web/app/components/NotificationChannels/NotificationChannels.tsx
index 2860ac744..83c0c501b 100644
--- a/web/app/components/NotificationChannels/NotificationChannels.tsx
+++ b/web/app/components/NotificationChannels/NotificationChannels.tsx
@@ -243,7 +243,9 @@ const NotificationChannels = ({
formData.set('intent', 'update-channel')
formData.set('channelId', editing.id)
formData.set('name', name)
- formData.set('config', JSON.stringify(buildConfig(form)))
+ if (editing.type !== 'webpush') {
+ formData.set('config', JSON.stringify(buildConfig(form)))
+ }
submitMutate(formData)
}
@@ -299,6 +301,7 @@ const NotificationChannels = ({
const isMutating = mutateFetcher.state !== 'idle'
const isFormOpen = creating || !!editing
+ const canSubmitForm = !!editing || form.type !== 'webpush'
return (
<section>
@@ -623,13 +626,13 @@ const NotificationChannels = ({
}
closeText={t('common.cancel')}
submitText={
- form.type !== 'webpush'
+ canSubmitForm
? editing
? t('common.save')
: t('common.create')
: undefined
}
- onSubmit={editing ? onUpdate : onCreate}
+ onSubmit={canSubmitForm ? (editing ? onUpdate : onCreate) : undefined}
isLoading={isMutating}
submitDisabled={isMutating}
/>
diff --git a/web/public/sw.js b/web/public/sw.js
index 5ff0fe5dd..07b9a2198 100644
--- a/web/public/sw.js
+++ b/web/public/sw.js
@@ -49,7 +49,9 @@ self.addEventListener('notificationclick', (event) => {
return client.focus()
}
}
- if (self.clients.openWindow) return self.clients.openWindow(url)
+ if (self.clients.openWindow) {
+ return self.clients.openWindow(targetUrl.href)
+ }
return null
}),
)