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!

more optimisations and improvements

Blue Mouse87769ec61b18
diff --git a/package.json b/package.json
index 3891d529e..06a6202cb 100644
--- a/package.json
+++ b/package.json
@@ -58,7 +58,8 @@
"rxjs": "^7.5.2",
"typeorm": "^0.2.41",
"ua-parser-js": "^1.0.2",
- "uuid": "^8.3.2"
+ "uuid": "^8.3.2",
+ "validator": "^13.7.0"
},
"devDependencies": {
"@nestjs/cli": "^8.2.0",
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.ts
index 5e8e58ecb..ac4d3645d 100644
--- a/src/analytics/analytics.controller.ts
+++ b/src/analytics/analytics.controller.ts
@@ -84,11 +84,11 @@ export class AnalyticsController {
async getData(@Query() data: AnalyticsGET_DTO, @CurrentUserId() uid: string): Promise<any> {
const { pid, period, timeBucket, from, to } = data
this.analyticsService.validatePID(pid)
+ this.analyticsService.validatePeriod(period)
+ this.analyticsService.validateTimebucket(timeBucket)
await this.analyticsService.checkProjectAccess(pid, uid)
let groupFrom = from, groupTo = to
- // TODO: data validation
- // TODO: automatic timeBucket detection based on period provided
let queryCustoms = `SELECT ev, count() FROM customEV WHERE pid='${pid}'`
let subQuery = `FROM analytics WHERE pid='${pid}'`
@@ -205,7 +205,6 @@ export class AnalyticsController {
const dto = customLogDTO(eventsDTO.pid, eventsDTO.ev)
- // todo: fix: may be vulnerable to sql injection attack
const values = `(${dto.map(getElValue).join(',')})`
try {
await redis.rpush(REDIS_LOG_CUSTOM_CACHE_KEY, values)
@@ -253,7 +252,7 @@ export class AnalyticsController {
const os = ua.os.name
// trying to get country from timezome, otherwise using CloudFlare's IP based country code as a fallback
const cc = ct.getCountryForTimezone(logDTO.tz)?.id || (headers['cf-ipcountry'] === 'XX' ? 'NULL' : headers['cf-ipcountry'])
- dto = analyticsDTO(logDTO.pid, logDTO.pg, dv, br, os, logDTO.lc, logDTO.ref, logDTO.so, logDTO.me, logDTO.ca, logDTO.lt, cc, 1)
+ dto = analyticsDTO(logDTO.pid, logDTO.pg, dv, br, os, logDTO.lc, logDTO.ref, logDTO.so, logDTO.me, logDTO.ca, 'NULL' /* logDTO.lt */, cc, 1)
} else if (!logDTO.unique) {
dto = analyticsDTO(logDTO.pid, logDTO.pg, 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 'NULL', 0)
} else {
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index d5f05659b..32c92006e 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -6,6 +6,7 @@ import * as _size from 'lodash/size'
import * as _isNull from 'lodash/isNull'
import * as _includes from 'lodash/includes'
import * as _map from 'lodash/map'
+import * as _toUpper from 'lodash/toUpper'
import * as _join from 'lodash/join'
import * as _some from 'lodash/some'
import * as _keys from 'lodash/keys'
@@ -13,9 +14,10 @@ import * as _find from 'lodash/find'
import * as _values from 'lodash/values'
import * as dayjs from 'dayjs'
import * as utc from 'dayjs/plugin/utc'
+import { isLocale } from 'validator'
import { hash } from 'blake3'
import {
- Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,
+ Injectable, BadRequestException, InternalServerErrorException, ForbiddenException, UnprocessableEntityException,
} from '@nestjs/common'
import { ACCOUNT_PLANS } from '../user/entities/user.entity'
@@ -50,6 +52,9 @@ interface customsCHResponse {
'count()': number
}
+const validPeriods = ['1d', '7d', '4w', '3M', '12M', '24M']
+const validTimebuckets = ['hour', 'day', 'week', 'month']
+
// Smaller than 64 characters, must start with an English letter and contain only letters (a-z A-Z), numbers (0-9), underscores (_) and dots (.)
const customEVvalidate = /^[a-zA-Z](?:[\w\.]){0,62}$/
@@ -174,6 +179,25 @@ export class AnalyticsService {
if (!customEVvalidate.test(ev)) {
throw new BadRequestException('An incorrect event name (ev) is provided')
}
+ } else { // the type is 'log'
+ // 'tz' does not need validation as it's based on getCountryForTimezone detection
+ // @ts-ignore
+ const { lc } = logDTO
+ // TODO: IMPORTANT!: validate pg param
+
+ // validate locale ('lc' param)
+ if (_isEmpty(lc)) {
+ if (isLocale(lc)) {
+ // uppercase the locale after '-' char, so for example both 'en-gb' and 'en-GB' in result will be 'en-GB'
+ const lcParted = _split(lc, '-')
+ lcParted[1] = _toUpper(lcParted[1])
+ // @ts-ignore
+ logDTO.lc = _join(lcParted, '')
+ } else {
+ // @ts-ignore
+ logDTO.lc = 'NULL'
+ }
+ }
}
const project = await this.getRedisProject(pid)
@@ -209,6 +233,18 @@ export class AnalyticsService {
return sessionHash
}
+ validatePeriod(period: string): void {
+ if (!_includes(validPeriods, period)) {
+ throw new UnprocessableEntityException('The provided period is incorrect')
+ }
+ }
+
+ validateTimebucket(tb: string): void {
+ if (!_includes(validTimebuckets, tb)) {
+ throw new UnprocessableEntityException('The provided timebucket is incorrect')
+ }
+ }
+
async isUnique(hash: string) {
const session = await redis.get(hash)
await redis.set(hash, 1, 'EX', UNIQUE_SESSION_LIFE_TIME)
diff --git a/src/task-manager/task-manager.module.ts b/src/task-manager/task-manager.module.ts
index 38d9af8d6..6432c4d8a 100644
--- a/src/task-manager/task-manager.module.ts
+++ b/src/task-manager/task-manager.module.ts
@@ -1,4 +1,4 @@
-import { Module, HttpModule, forwardRef } from '@nestjs/common'
+import { Module, forwardRef } from '@nestjs/common'
import { TaskManagerService } from './task-manager.service'
import { MailerModule } from '../mailer/mailer.module'
import { UserModule } from '../user/user.module'
@@ -9,7 +9,6 @@ import { AnalyticsModule } from '../analytics/analytics.module'
imports: [
ProjectModule,
MailerModule,
- HttpModule,
UserModule,
forwardRef(() => AnalyticsModule),
],