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 hardening

Blue Mouse32aff4016aa5
diff --git a/backend/apps/cloud/src/analytics/analytics.controller.ts b/backend/apps/cloud/src/analytics/analytics.controller.ts
index d755f6e5f..8fa6767c0 100644
--- a/backend/apps/cloud/src/analytics/analytics.controller.ts
+++ b/backend/apps/cloud/src/analytics/analytics.controller.ts
@@ -112,6 +112,9 @@ const BOT_RESPONSE = { message: 'Bot traffic detected, request is ignored' }
const ONLINE_VISITORS_WINDOW_MINUTES = 5 // minutes
+// Maximum range for "all time" GSC queries (~16 months, GSC's data retention)
+const GSC_ALL_TIME_DAYS = 480
+
// Performance object validator: none of the values cannot be bigger than 1000 * 60 * 5 (5 minutes) and are >= 0
const MAX_PERFORMANCE_VALUE = 1000 * 60 * 5
const isPerformanceValid = (perf: any) => {
@@ -963,16 +966,7 @@ export class AnalyticsController {
this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/keywords')
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
@@ -1022,16 +1016,7 @@ export class AnalyticsController {
'GET /analytics/gsc-dashboard',
)
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
@@ -1082,16 +1067,7 @@ export class AnalyticsController {
await this.analyticsService.checkBillingAccess(pid)
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
diff --git a/backend/apps/cloud/src/project/gsc.service.ts b/backend/apps/cloud/src/project/gsc.service.ts
index 192412842..6b48313eb 100644
--- a/backend/apps/cloud/src/project/gsc.service.ts
+++ b/backend/apps/cloud/src/project/gsc.service.ts
@@ -1,3 +1,4 @@
+import { randomBytes } from 'crypto'
import { parse as parseDomain } from 'tldts'
import countries from 'i18n-iso-countries'
import _isEmpty from 'lodash/isEmpty'
@@ -108,7 +109,7 @@ export class GSCService {
const oauth2Client = this.getOAuthClient()
- const state = `${pid}:${uid}:${Date.now()}`
+ const state = randomBytes(32).toString('hex')
await redis.set(
REDIS_STATE_PREFIX + state,
JSON.stringify({ uid, pid }),
@@ -130,12 +131,27 @@ export class GSCService {
}
async handleOAuthCallback(uid: string, code: string, state: string) {
+ if (!state) {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
const cached = await redis.get(REDIS_STATE_PREFIX + state)
if (!cached) {
throw new BadRequestException('Invalid or expired OAuth state')
}
- const { pid } = JSON.parse(cached)
+ let payload: { uid?: string; pid?: string }
+ try {
+ payload = JSON.parse(cached)
+ } catch {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
+ if (!payload?.pid || !payload?.uid || payload.uid !== uid) {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
+ const { pid } = payload
const project = await this.projectService.getRedisProject(pid)
@@ -337,14 +353,28 @@ export class GSCService {
}
async setProperty(pid: string, propertyUri: string) {
+ if (typeof propertyUri !== 'string' || propertyUri.trim().length === 0) {
+ throw new BadRequestException('propertyUri is required')
+ }
+
const tokens = await this.getStoredTokens(pid)
if (_isEmpty(tokens)) {
throw new BadRequestException(
'Search Console is not connected for this project',
)
}
+
+ const sites = await this.listSites(pid)
+ const isOwned = sites.some((site) => site.siteUrl === propertyUri)
+
+ if (!isOwned) {
+ throw new BadRequestException(
+ 'The provided propertyUri is not available for the connected account',
+ )
+ }
+
await this.projectService.update({ id: pid }, {
- gscPropertyUri: propertyUri ?? null,
+ gscPropertyUri: propertyUri,
} as any)
}
@@ -881,10 +911,12 @@ export class GSCService {
const fromDate = dayjs(from)
const toDate = dayjs(to)
- const days = toDate.diff(fromDate, 'day') + 1
- const prevTo = fromDate.subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
+ const durationMs = toDate.diff(fromDate)
+ const prevTo = fromDate
+ .subtract(1, 'millisecond')
+ .format('YYYY-MM-DD HH:mm:ss')
const prevFrom = fromDate
- .subtract(days, 'day')
+ .subtract(durationMs, 'millisecond')
.format('YYYY-MM-DD HH:mm:ss')
const [
diff --git a/backend/apps/community/src/analytics/analytics.controller.ts b/backend/apps/community/src/analytics/analytics.controller.ts
index b2e7689ce..c6313fad7 100644
--- a/backend/apps/community/src/analytics/analytics.controller.ts
+++ b/backend/apps/community/src/analytics/analytics.controller.ts
@@ -99,6 +99,9 @@ const BOT_RESPONSE = { message: 'Bot traffic detected, request is ignored' }
const ONLINE_VISITORS_WINDOW_MINUTES = 5 // minutes
+// Maximum range for "all time" GSC queries (~16 months, GSC's data retention)
+const GSC_ALL_TIME_DAYS = 480
+
// Performance object validator: none of the values cannot be bigger than 1000 * 60 * 5 (5 minutes) and are >= 0
const MAX_PERFORMANCE_VALUE = 1000 * 60 * 5
const isPerformanceValid = (perf: any) => {
@@ -2572,16 +2575,7 @@ export class AnalyticsController {
this.logger.log(`pid: ${pid}, period: ${period}`, 'GET /analytics/keywords')
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
@@ -2629,16 +2623,7 @@ export class AnalyticsController {
'GET /analytics/gsc-dashboard',
)
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
@@ -2687,16 +2672,7 @@ export class AnalyticsController {
headers['x-password'],
)
- let diff
-
- if (period === 'all') {
- const res = await this.analyticsService.calculateTimeBucketForAllTime(
- pid,
- 'analytics',
- )
-
- diff = res.diff
- }
+ const diff = period === 'all' ? GSC_ALL_TIME_DAYS : undefined
const safeTimezone = this.analyticsService.getSafeTimezone(timezone)
const { groupFrom, groupTo } = this.analyticsService.getGroupFromTo(
diff --git a/backend/apps/community/src/project/gsc.service.ts b/backend/apps/community/src/project/gsc.service.ts
index 58ed9a76d..06768b58b 100644
--- a/backend/apps/community/src/project/gsc.service.ts
+++ b/backend/apps/community/src/project/gsc.service.ts
@@ -1,3 +1,4 @@
+import { randomBytes } from 'crypto'
import { parse as parseDomain } from 'tldts'
import countries from 'i18n-iso-countries'
import _isEmpty from 'lodash/isEmpty'
@@ -135,7 +136,7 @@ export class GSCService {
const oauth2Client = this.getOAuthClient()
- const state = `${pid}:${uid}:${Date.now()}`
+ const state = randomBytes(32).toString('hex')
await redis.set(
REDIS_STATE_PREFIX + state,
JSON.stringify({ uid, pid }),
@@ -157,12 +158,27 @@ export class GSCService {
}
async handleOAuthCallback(uid: string, code: string, state: string) {
+ if (!state) {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
const cached = await redis.get(REDIS_STATE_PREFIX + state)
if (!cached) {
throw new BadRequestException('Invalid or expired OAuth state')
}
- const { pid } = JSON.parse(cached)
+ let payload: { uid?: string; pid?: string }
+ try {
+ payload = JSON.parse(cached)
+ } catch {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
+ if (!payload?.pid || !payload?.uid || payload.uid !== uid) {
+ throw new BadRequestException('Invalid or expired OAuth state')
+ }
+
+ const { pid } = payload
const project = await this.projectService.getRedisProject(pid)
@@ -394,14 +410,28 @@ export class GSCService {
}
async setProperty(pid: string, propertyUri: string) {
+ if (typeof propertyUri !== 'string' || propertyUri.trim().length === 0) {
+ throw new BadRequestException('propertyUri is required')
+ }
+
const tokens = await this.getStoredTokens(pid)
if (_isEmpty(tokens)) {
throw new BadRequestException(
'Search Console is not connected for this project',
)
}
+
+ const sites = await this.listSites(pid)
+ const isOwned = sites.some((site) => site.siteUrl === propertyUri)
+
+ if (!isOwned) {
+ throw new BadRequestException(
+ 'The provided propertyUri is not available for the connected account',
+ )
+ }
+
await updateProjectClickhouse(
- { id: pid, gscPropertyUri: propertyUri ?? null },
+ { id: pid, gscPropertyUri: propertyUri },
{ ignoreAllowedKeys: true },
)
await deleteProjectRedis(pid)
@@ -946,10 +976,12 @@ export class GSCService {
const fromDate = dayjs(from)
const toDate = dayjs(to)
- const days = toDate.diff(fromDate, 'day') + 1
- const prevTo = fromDate.subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
+ const durationMs = toDate.diff(fromDate)
+ const prevTo = fromDate
+ .subtract(1, 'millisecond')
+ .format('YYYY-MM-DD HH:mm:ss')
const prevFrom = fromDate
- .subtract(days, 'day')
+ .subtract(durationMs, 'millisecond')
.format('YYYY-MM-DD HH:mm:ss')
const [
diff --git a/backend/apps/community/src/project/project.service.ts b/backend/apps/community/src/project/project.service.ts
index 637b025d6..0d6147406 100644
--- a/backend/apps/community/src/project/project.service.ts
+++ b/backend/apps/community/src/project/project.service.ts
@@ -479,14 +479,21 @@ export class ProjectService {
? []
: _split(updProject.countryBlacklist, ',')
- if (updProject.brandKeywords && _isString(updProject.brandKeywords)) {
- try {
- const parsed = JSON.parse(updProject.brandKeywords)
- updProject.brandKeywords = Array.isArray(parsed) ? parsed : null
- } catch {
+ if (_isString(updProject.brandKeywords)) {
+ const trimmed = updProject.brandKeywords.trim()
+
+ if (trimmed.length === 0) {
updProject.brandKeywords = null
+ } else {
+ try {
+ const parsed = JSON.parse(trimmed)
+ updProject.brandKeywords =
+ Array.isArray(parsed) && parsed.length > 0 ? parsed : null
+ } catch {
+ updProject.brandKeywords = null
+ }
}
- } else if (updProject.brandKeywords === undefined) {
+ } else if (!Array.isArray(updProject.brandKeywords)) {
updProject.brandKeywords = null
}
diff --git a/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx b/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx
index 8207ed49b..e860991ea 100644
--- a/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx
+++ b/docs/content/docs/sitesettings/embed-your-analytics-dashboard-into-your-website.mdx
@@ -42,7 +42,7 @@ Here is a list of all available options:
- `theme`: `light` or `dark` - the theme of the dashboard.
- `lng`: language to display the dashboard in. Supported languages: `en`, `uk`, `pl`, `de`, `fr`. Defaults to user's browser language.
-- `tab`: `traffic`, `performance`, `profiles`, `funnels`, `sessions`, `errors`, `goals`, `experiments`, `featureFlags`, `captcha`, `ai` - the default tab to show. By default, the traffic tab is shown.
-- `tabs`: `traffic`, `performance`, `profiles`, `funnels`, `sessions`, `errors`, `goals`, `experiments`, `featureFlags`, `captcha`, `ai` - a comma-separated list of tabs that should be accessible in dashboard. Example: `tabs=traffic,performance,sessions` will only show the traffic, performance and sessions tabs. By default, all tabs are shown.
+- `tab`: `traffic`, `seo`, `performance`, `profiles`, `funnels`, `sessions`, `errors`, `goals`, `experiments`, `featureFlags`, `captcha`, `ai` - the default tab to show. By default, the traffic tab is shown.
+- `tabs`: `traffic`, `seo`, `performance`, `profiles`, `funnels`, `sessions`, `errors`, `goals`, `experiments`, `featureFlags`, `captcha`, `ai` - a comma-separated list of tabs that should be accessible in dashboard. Example: `tabs=traffic,performance,sessions` will only show the traffic, performance and sessions tabs. By default, all tabs are shown.
- `embedded` - if set to `true`, header, footer and any marketing CTAs will be hidden.
- `password` - if your dashboard is password-protected, you can pass the password as a query parameter. Example: `password=yourpassword`, this way the dashboard will be unlocked without the need to enter the password.
diff --git a/web/app/pages/Project/Settings/ProjectSettings.tsx b/web/app/pages/Project/Settings/ProjectSettings.tsx
index 8be33a485..32198df0c 100644
--- a/web/app/pages/Project/Settings/ProjectSettings.tsx
+++ b/web/app/pages/Project/Settings/ProjectSettings.tsx
@@ -658,6 +658,12 @@ const ProjectSettings = () => {
: t('apiNotifications.somethingWentWrong'),
)
setGscPropertiesPending(false)
+
+ if (intent === 'gsc-status') {
+ setGscConnected(false)
+ setGscEmail(null)
+ setGscProperties([])
+ }
}
}, [gscFetcher.state, gscFetcher.data, t])