📈 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
Added support for heartbeat events; fixed a bug when any user was able to view stats of any of existing projects; general code improvements & optimisations
Blue Mousea693b2b37bdd
diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex 1eb174a50..0617f19b0 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -3,21 +3,22 @@ import * as _isNumber from 'lodash/isNumber'import * as _isArray from 'lodash/isArray'import * as _size from 'lodash/size'import * as _last from 'lodash/last'+import * as _map from 'lodash/map'import * as _countBy from 'lodash/countBy'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'import { v4 as uuidv4 } from 'uuid'import { hash } from 'blake3'import {- Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException,- InternalServerErrorException, NotImplementedException, UnprocessableEntityException, PreconditionFailedException,+ Controller, Body, Query, UseGuards, Get, Post, Headers, BadRequestException, InternalServerErrorException,+ NotImplementedException, UnprocessableEntityException, PreconditionFailedException, Ip,} from '@nestjs/common'import { ApiTags } from '@nestjs/swagger'import * as UAParser from 'ua-parser-js'-import { AnalyticsService } from './analytics.service'-import { ProjectService } from '../project/project.service'+import { AnalyticsService, getSessionKey } from './analytics.service'import { UserType } from '../user/entities/user.entity'+import { CurrentUserId } from '../common/decorators/current-user-id.decorator'import { Roles } from '../common/decorators/roles.decorator'import { RolesGuard } from 'src/common/guards/roles.guard'import { PageviewsDTO } from './dto/pageviews.dto'@@ -26,16 +27,13 @@ import { AnalyticsGET_DTO } from './dto/getData.dto'import { AppLoggerService } from '../logger/logger.service'import {clickhouse, isValidPID, REDIS_LOG_DATA_CACHE_KEY, redis, REDIS_LOG_CUSTOM_CACHE_KEY,+ HEARTBEAT_SID_LIFE_TIME, // REDIS_SESSION_SALT_KEY,} from '../common/constants'import ct from '../common/countriesTimezones'dayjs.extend(utc)-// todo: implement random salts-// store them in redis storage and reset every 24 hours-const getSessionKey = (ip: string, ua: string, pid: string, salt: string = '') => hash(`${ua}${ip}${pid}${salt}`).toString('hex')--const getSessionKeyCustom = (ip: string, ua: string, pid: string, ev: string, salt: string = '') => hash(`${ua}${ip}${pid}${ev}${salt}`).toString('hex')+const getSessionKeyCustom = (ip: string, ua: string, pid: string, ev: string, salt: string = '') => `cses_${hash(`${ua}${ip}${pid}${ev}${salt}`).toString('hex')}`const analyticsDTO = (pid: string, pg: string, dv: string, br: string, os: string, lc: string, ref: string, so: string, me: string, ca: string, lt: number | string, cc: string, unique: number): Array<string | number> => {return [uuidv4(), pid, pg, dv, br, os, lc, ref, so, me, ca, lt, cc, unique, dayjs.utc().format('YYYY-MM-DD HH:mm:ss')]@@ -56,18 +54,16 @@ const getElValue = (el) => {export class AnalyticsController {constructor(private readonly analyticsService: AnalyticsService,- private readonly projectService: ProjectService,private readonly logger: AppLoggerService,) { }@Get('/')@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)- async getData(@Query() data: AnalyticsGET_DTO): Promise<any> {- // this.logger.log({ ...data }, 'GET /log')-+ async getData(@Query() data: AnalyticsGET_DTO, @CurrentUserId() uid: string): Promise<any> {const { pid, period, timeBucket, from, to } = data- if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+ this.analyticsService.validatePID(pid)+ await this.analyticsService.checkProjectAccess(pid, uid)let groupFrom = from, groupTo = to// TODO: data validation@@ -114,9 +110,7 @@ export class AnalyticsController {@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)// returns overall short statistics per project- async getOverallStats(@Query() data): Promise<any> {- // this.logger.log({ ...data }, 'GET /birdseye')-+ async getOverallStats(@Query() data, @CurrentUserId() uid: string): Promise<any> {let { pids, pid } = dataconst pidsEmpty = _isEmpty(pids)const pidEmpty = _isEmpty(pid)@@ -136,21 +130,39 @@ export class AnalyticsController {throw new UnprocessableEntityException('An array of Project ID\'s has to be provided as a \'pids\' param')}+ for (let i = 0; i < _size(pids); ++i) {+ this.analyticsService.validatePID(pids[i])+ await this.analyticsService.checkProjectAccess(pids[i], uid)+ }+return this.analyticsService.getSummary(pids, 'w', true)}+ @Get('/hb')+ // @UseGuards(RolesGuard)+ // @Roles(UserType.CUSTOMER, UserType.ADMIN)+ async getHeartBeatStats(@Query() data, @CurrentUserId() uid: string): Promise<object> {+ const { pid } = data+ this.analyticsService.validatePID(pid)+ // await this.analyticsService.checkProjectAccess(pid, uid)++ const result = await redis.countKeysByPattern(`hb:${pid}:*`)+ return {+ result,+ }+ }+// Log custom event@Post('/custom')async logCustom(@Body() eventsDTO: EventsDTO, @Headers() headers): Promise<any> {- // this.logger.log({ eventsDTO, headers }, 'POST /log/custom')-const { 'user-agent': userAgent, origin } = headersawait this.analyticsService.validate(eventsDTO, origin)const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || ''if (eventsDTO.unique) {- const sessionHash = getSessionKeyCustom(ip, userAgent, eventsDTO.pid, eventsDTO.ev)+ // const salt = await redis.get(REDIS_SESSION_SALT_KEY)+ const sessionHash = getSessionKeyCustom(ip, userAgent, eventsDTO.pid, eventsDTO.ev/*, salt */)const unique = await this.analyticsService.isUnique(sessionHash)if (!unique) {@@ -171,19 +183,27 @@ export class AnalyticsController {}}+ @Post('/hb')+ async heartbeat(@Body() logDTO: PageviewsDTO, @Headers() headers, @Ip() reqIP): Promise<any> {+ const { 'user-agent': userAgent } = headers+ const { pid } = logDTO+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''++ const sessionID = await this.analyticsService.validateHB(logDTO, userAgent, ip)+ await redis.set(`hb:${pid}:${sessionID}`, 1, 'EX', HEARTBEAT_SID_LIFE_TIME)+ return+ }+// Log pageview event@Post('/')- async log(@Body() logDTO: PageviewsDTO, @Headers() headers): Promise<any> {- // this.logger.log({ logDTO }, 'POST /log')-+ async log(@Body() logDTO: PageviewsDTO, @Headers() headers, @Ip() reqIP): Promise<any> {const { 'user-agent': userAgent, origin } = headersawait this.analyticsService.validate(logDTO, origin)- // the NestJS server HAS TO be proxied either by Cloudflare or by NGINX, which are setting the request IP- // if the app is hosted raw, @nestjs/common @Ip module should be used to retreive the request IP address- const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || ''+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''- const sessionHash = getSessionKey(ip, userAgent, logDTO.pid)+ // const salt = await redis.get(REDIS_SESSION_SALT_KEY)+ const sessionHash = getSessionKey(ip, userAgent, logDTO.pid/*, salt */)const unique = await this.analyticsService.isUnique(sessionHash)let dto: Array<string | number>diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex 0f0f3b2ba..2dd85f621 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -8,6 +8,7 @@ import * as _join from 'lodash/join'import * as _keys from 'lodash/keys'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'+import { hash } from 'blake3'import {Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,} from '@nestjs/common'@@ -16,7 +17,7 @@ import { ACCOUNT_PLANS } from '../user/entities/user.entity'import {redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout,UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisUserCountKey,- redisProjectCountCacheTimeout,+ redisProjectCountCacheTimeout, // REDIS_SESSION_SALT_KEY,} from '../common/constants'import { PageviewsDTO } from './dto/pageviews.dto'import { EventsDTO } from './dto/events.dto'@@ -26,6 +27,8 @@ import { TimeBucketType } from './dto/getData.dto'dayjs.extend(utc)+export const getSessionKey = (ip: string, ua: string, pid: string, salt: string = '') => `ses_${hash(`${ua}${ip}${pid}${salt}`).toString('hex')}`+@Injectable()export class AnalyticsService {constructor(@@ -54,6 +57,11 @@ export class AnalyticsService {return project}+ async checkProjectAccess(pid: string, uid: string): Promise<void> {+ const project = await this.getRedisProject(pid)+ this.projectService.allowedToManage(project, uid)+ }+// Returns amount of existing events starting from monthasync getRedisCount(uid: string): Promise<number | null> {const countKey = getRedisUserCountKey(uid)@@ -103,13 +111,16 @@ export class AnalyticsService {}}- // TODO: Remove unnecessary checks (because some of them are already checked in the DTO)+ validatePID(pid: string): void {+ if (_isEmpty(pid)) throw new BadRequestException('The Project ID (pid) has to be provided')+ if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+ }+async validate(logDTO: PageviewsDTO | EventsDTO, origin: string): Promise<string | null> {if (_isEmpty(logDTO)) throw new BadRequestException('The request cannot be empty')- const { pid } = logDTO- if (_isEmpty(pid)) throw new BadRequestException('The Project ID (pid) has to be provided')- if (!isValidPID(pid)) throw new BadRequestException('The provided Project ID (pid) is incorrect')+ const { pid } = logDTO+ this.validatePID(pid)if (logDTO instanceof EventsDTO && !_isEmpty(logDTO.ev) && _size(logDTO.ev) > 64) {throw new BadRequestException('An incorrect event name (ev) is provided')@@ -131,12 +142,32 @@ export class AnalyticsService {return null}+ async validateHB(logDTO: PageviewsDTO, userAgent: string, ip: string): Promise<string | null> {+ if (_isEmpty(logDTO)) throw new BadRequestException('The request cannot be empty')++ const { pid } = logDTO+ this.validatePID(pid)++ // const salt = await redis.get(REDIS_SESSION_SALT_KEY)+ const sessionHash = getSessionKey(ip, userAgent, pid/*, salt */)+ const sessionExists = await this.isSessionOpen(sessionHash)++ if (!sessionExists) throw new ForbiddenException('The Heartbeat session does not exist')++ return sessionHash+ }+async isUnique(hash: string) {const session = await redis.get(hash)await redis.set(hash, 1, 'EX', UNIQUE_SESSION_LIFE_TIME)return !Boolean(session)}+ async isSessionOpen(hash: string) {+ const session = await redis.get(hash)+ return Boolean(session)+ }+processData(data: object): object {const res = {cc: {},@@ -221,7 +252,7 @@ export class AnalyticsService {return result}- // TODO: Refactor; check if there's no date/time shifts+ // TODO: REFACTOR THE FUNCTION; check if there's no date/time shiftsasync groupByTimeBucket(data: Object[], timeBucket: TimeBucketType, from: string, to: string): Promise<object | void> {if (_isEmpty(data)) return Promise.resolve()let groupDateIteratordiff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex 4537a1d2f..eeb3f5056 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -6,6 +6,8 @@ import { UserService } from '../user/user.service'import { User } from '../user/entities/user.entity'import { JWT_LIFE_TIME } from '../common/constants'+const BCRYPT_SALT_ROUNDS = 10+@Injectable()export class AuthService {constructor(@@ -13,7 +15,7 @@ export class AuthService {) {}async hashPassword(pass: string): Promise<string> {- const salt = await bcrypt.genSalt(10)+ const salt = await bcrypt.genSalt(BCRYPT_SALT_ROUNDS)return await bcrypt.hash(pass, salt)}diff --git a/src/common/constants.ts b/src/common/constants.tsindex f265cbc5d..11e6af7bc 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -11,6 +11,11 @@ const redis = new Redis({host: process.env.REDIS_HOST,})+redis.defineCommand('countKeysByPattern', {+ numberOfKeys: 0,+ lua: "return #redis.call('keys', ARGV[1])",+})+const clickhouse = new ClickHouse({url: process.env.CLICKHOUSE_HOST,port: _toNumber(process.env.CLICKHOUSE_PORT),@@ -62,8 +67,8 @@ const getRedisProjectKey = (pid: string) => `pid_${pid}`const getRedisUserCountKey = (uid: string) => `user_c_${uid}`const REDIS_LOG_DATA_CACHE_KEY = 'log_cache'-const REDIS_LOG_CUSTOM_CACHE_KEY = 'log_custom_cache'+const REDIS_SESSION_SALT_KEY = 'log_salt' // is updated every 24 hours// 3600 sec -> 1 hourconst redisProjectCacheTimeout = 3600@@ -74,6 +79,9 @@ const redisProjectCountCacheTimeout = 900// 30 minues -> the amount of time analytics requests within one session are counted as non-uniqueconst UNIQUE_SESSION_LIFE_TIME = 1800+// 35 seconds+const HEARTBEAT_SID_LIFE_TIME = 35+// how often can user request a fresh GDPR export of their data; in days.const GDPR_EXPORT_TIMEFRAME = 14@@ -84,5 +92,5 @@ export {clickhouse, JWT_LIFE_TIME, HISTORY_LIFE_TIME_DAYS, redis, isValidPID, getRedisProjectKey,redisProjectCacheTimeout, getPercentageChange, UNIQUE_SESSION_LIFE_TIME, REDIS_LOG_DATA_CACHE_KEY,GDPR_EXPORT_TIMEFRAME, getRedisUserCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,- STRIPE_SECRET, STRIPE_WH_SECRET,+ STRIPE_SECRET, STRIPE_WH_SECRET, REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME,}diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex 6e9b8b9b4..f093fd1ea 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -118,12 +118,12 @@ export class ProjectController {if (_isEmpty(project)) {throw new NotFoundException()}+ this.projectService.allowedToManage(project, userId)project.active = projectDTO.activeproject.origins = _map(projectDTO.origins, _trim)project.name = projectDTO.name- await this.projectService.allowedToManage(project, userId)await this.projectService.update(id, project)const key = getRedisProjectKey(id)@@ -154,7 +154,7 @@ export class ProjectController {if (_isEmpty(project)) {throw new NotFoundException(`Project with ID ${id} does not exist`)}- await this.projectService.allowedToManage(project, userId)+ this.projectService.allowedToManage(project, userId)const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex 0ecb4a0ad..23fdd7052 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -9,15 +9,13 @@ import * as _join from 'lodash/join'import { Pagination, PaginationOptionsInterface } from '../common/pagination'import { Project } from './entity/project.entity'import { ProjectDTO } from './dto/project.dto'-import { UserService } from '../user/user.service'import { isValidPID } from '../common/constants'@Injectable()export class ProjectService {constructor(@InjectRepository(Project)- private projectsRepository: Repository<Project>,- private readonly userService: UserService+ private projectsRepository: Repository<Project>) {}async paginate(options: PaginationOptionsInterface, where: Record<string, unknown> | undefined): Promise<Pagination<Project>> {@@ -79,17 +77,15 @@ export class ProjectService {return this.projectsRepository.findOne({ where, ...params })}- ifAllowedToManage(userId: string, project: Project): boolean {- return userId === project.admin.id+ ifAllowedToManage(uid: string, project: Project): boolean {+ return uid === project.admin.id}- async allowedToManage(project: Project, userId: string): Promise<void> {- const user = await this.userService.findOne(userId)-- if (this.ifAllowedToManage(user.id, project)) {+ allowedToManage(project: Project, uid: string): void {+ if (this.ifAllowedToManage(uid, project)) {return} else {- throw new ForbiddenException('Not allowed to manage this project')+ throw new ForbiddenException('You are not allowed to access this project')}}diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.tsindex 95e39b7ea..79bfccfad 100644--- a/src/task-manager/task-manager.service.ts+++ b/src/task-manager/task-manager.service.ts@@ -1,5 +1,6 @@import { Injectable, HttpService } from '@nestjs/common'import { Cron, CronExpression } from '@nestjs/schedule'+// import * as bcrypt from 'bcrypt'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'import * as _isEmpty from 'lodash/isEmpty'@@ -14,7 +15,7 @@ import { LetterTemplate } from '../mailer/letter'import { AnalyticsService } from '../analytics/analytics.service'import { ReportFrequency } from '../user/entities/user.entity'import {- clickhouse, redis, REDIS_LOG_DATA_CACHE_KEY, REDIS_LOG_CUSTOM_CACHE_KEY,+ clickhouse, redis, REDIS_LOG_DATA_CACHE_KEY, REDIS_LOG_CUSTOM_CACHE_KEY, REDIS_SESSION_SALT_KEY,} from '../common/constants'dayjs.extend(utc)@@ -54,6 +55,12 @@ export class TaskManagerService {}}+ // @Cron(CronExpression.EVERY_DAY_AT_MIDNIGHT)+ // async generateSessionSalt(): Promise<void> {+ // const salt = await bcrypt.genSalt(10)+ // await redis.set(REDIS_SESSION_SALT_KEY, salt, 'EX', 87000)+ // }+// EVERY SUNDAY AT 2:30 AM@Cron('30 02 * * 0')async weeklyReportsHandler(): Promise<void> {