📈 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 selfhosted projects
Blue Mouseb79981adcd62
diff --git a/.env.example b/.env.exampleindex 696194b90..5fee68433 100644--- a/.env.example+++ b/.env.example@@ -28,5 +28,6 @@ FROM_EMAIL='[email protected]'# Use SMTP_MOCK variable for development, leave empty when in productionSMTP_MOCK=true-# Is selfhosted (true -> will disable all restrictions related to tiers)-API_SELFHOSTED=false+# Selfhosted+PASSWORD=12345678diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex 18a2a87b1..bd084a101 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -9,6 +9,7 @@ import * as _keys from 'lodash/keys'import * as dayjs from 'dayjs'import * as utc from 'dayjs/plugin/utc'import { hash } from 'blake3'+import { promises as fs } from 'fs'import {Injectable, BadRequestException, InternalServerErrorException, ForbiddenException,} from '@nestjs/common'@@ -40,10 +41,22 @@ export class AnalyticsService {let project = await redis.get(pidKey)if (_isEmpty(project)) {- project = await this.projectService.findOne(pid, {- relations: ['admin'],- select: ['origins', 'active', 'admin']- })+ if (isSelfhosted) {+ let projects++ try {+ const rawData = await fs.readFile('../../projects.json', 'utf8')+ projects = JSON.parse(rawData)+ } catch (e) {+ throw new InternalServerErrorException('Error while reading projects data')+ }+ project = projects[pid]+ } else {+ project = await this.projectService.findOne(pid, {+ relations: ['admin'],+ select: ['origins', 'active', 'admin']+ })+ }if (_isEmpty(project)) throw new BadRequestException('The provided Project ID (pid) is incorrect')await redis.set(pidKey, JSON.stringify(project), 'EX', redisProjectCacheTimeout)} else {@@ -58,8 +71,10 @@ export class AnalyticsService {}async checkProjectAccess(pid: string, uid: string): Promise<void> {- const project = await this.getRedisProject(pid)- this.projectService.allowedToManage(project, uid)+ if (!isSelfhosted) {+ const project = await this.getRedisProject(pid)+ this.projectService.allowedToManage(project, uid)+ }}// Returns amount of existing events starting from month@@ -70,12 +85,27 @@ export class AnalyticsService {if (_isEmpty(count)) {const now = dayjs.utc().format('YYYY-MM-DD HH:mm:ss')const monthStart = dayjs.utc().startOf('month').format('YYYY-MM-DD HH:mm:ss')- const pids = await this.projectService.find({- where: {- admin: uid,- },- select: ['id'],- })++ let pids++ if (isSelfhosted) {+ let projects++ try {+ const rawData = await fs.readFile('../../projects.json', 'utf8')+ projects = JSON.parse(rawData)+ } catch (e) {+ throw new InternalServerErrorException('Error while reading projects data')+ }+ pids = _keys(projects)+ } else {+ pids = await this.projectService.find({+ where: {+ admin: uid,+ },+ select: ['id'],+ })+ }const count_query = `SELECT COUNT() FROM analytics WHERE pid IN (${_join(_map(pids, el => `'${el.id}'`), ',')}) AND created BETWEEN '${monthStart}' AND '${now}'`const result = await clickhouse.query(count_query).toPromise()diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex e900ecb84..86c238607 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -1,5 +1,5 @@import {- Controller, Post, Body, Req, Get, Param, BadRequestException, UseGuards, Ip, Headers,+ Controller, Post, Body, Req, Get, Param, BadRequestException, UseGuards, Ip, Headers, UnprocessableEntityException,} from '@nestjs/common'import { Request } from 'express'import { ApiTags } from '@nestjs/swagger'@@ -21,6 +21,9 @@ import { checkRateLimit } from '../common/utils'import { LetterTemplate } from '../mailer/letter'import { AppLoggerService } from '../logger/logger.service'import { SelfhostedGuard } from '../common/guards/selfhosted.guard'+import {+ isSelfhosted, SELFHOSTED_EMAIL, SELFHOSTED_PASSWORD,+} from 'src/common/constants'// TODO: Add logout endpoint to invalidate the token@ApiTags('Auth')@@ -53,8 +56,15 @@ export class AuthController {await checkRateLimit(ip, 'login', 10, 3600)// await this.authService.checkCaptcha(userLoginDTO.recaptcha)- const user = await this.authService.validateUser(userLoginDTO.email, userLoginDTO.password)- return await this.authService.login(user)+ if (isSelfhosted) {+ if (userLoginDTO.email !== SELFHOSTED_EMAIL || userLoginDTO.password !== SELFHOSTED_PASSWORD) {+ throw new UnprocessableEntityException('Email or password is incorrect')+ }+ return await this.authService.login(SELFHOSTED_EMAIL)+ } else {+ const user = await this.authService.validateUser(userLoginDTO.email, userLoginDTO.password)+ return await this.authService.login(user)+ }}@UseGuards(SelfhostedGuard)@@ -67,7 +77,7 @@ export class AuthController {// await this.authService.checkCaptcha(recaptcha)this.userService.validatePassword(userDTO.password)userDTO.password = await this.authService.hashPassword(userDTO.password)-+try {const user = await this.userService.create(userDTO)const actionToken = await this.actionTokensService.createForUser(user, ActionTokenType.EMAIL_VERIFICATION)diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex eeb3f5056..c2ddd42e5 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -4,7 +4,9 @@ import * as bcrypt from 'bcrypt'import { UserService } from '../user/user.service'import { User } from '../user/entities/user.entity'-import { JWT_LIFE_TIME } from '../common/constants'+import {+ isSelfhosted, JWT_LIFE_TIME, SELFHOSTED_UUID,+} from '../common/constants'const BCRYPT_SALT_ROUNDS = 10@@ -33,11 +35,22 @@ export class AuthService {throw new UnprocessableEntityException('Email or password is incorrect')}- async login(user: User): Promise<any> {+ async login(user: User | string): Promise<any> {+ let userData = user++ if (isSelfhosted) {+ // @ts-ignore+ userData = {+ id: SELFHOSTED_UUID,+ }+ }++ // @ts-ignoreconst token = sign({ user_id: user.id }, process.env.JWT_SECRET, {expiresIn: JWT_LIFE_TIME,})+ // @ts-ignoredelete user.passwordreturn { access_token: token, user }}diff --git a/src/common/constants.ts b/src/common/constants.tsindex 32b9127c9..2415ca2f3 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -1,6 +1,7 @@import { ClickHouse } from 'clickhouse'import Redis from 'ioredis'import { v5 as uuidv5 } from 'uuid'+import * as fs from 'fs'import * as _toNumber from 'lodash/toNumber'import * as _size from 'lodash/size'import * as _round from 'lodash/round'@@ -73,6 +74,8 @@ const CLICKHOUSE_INIT_QUERIES = [ORDER BY (id, created, pid);`,]+const isSelfhosted = process.env.SELFHOSTED+const initialiseClickhouse = async () => {console.log('Initialising Clickhouse')@@ -83,9 +86,17 @@ const initialiseClickhouse = async () => {console.log('Initialising Clickhouse: DONE')}+const initialiseSelfhosted = () => {+ if (isSelfhosted) {+ fs.writeFile('../../projects.json', '{}', { flag: 'wx' }, (err) => {+ if (err) console.error(err)+ })+ }+}+initialiseClickhouse()+initialiseSelfhosted()-const isSelfhosted = process.env.SELFHOSTEDconst SELFHOSTED_EMAIL = process.env.EMAILconst SELFHOSTED_PASSWORD = process.env.PASSWORDconst UUIDV5_NAMESPACE = '912c64c1-73fd-42b6-859f-785f839a9f68'diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex 3e94b27d3..c830fb8c7 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -1,8 +1,9 @@import {Controller, Body, Query, Param, UseGuards, Get, Post, Put, Delete,- BadRequestException, HttpCode, NotFoundException, ForbiddenException,+ BadRequestException, HttpCode, NotFoundException, ForbiddenException, InternalServerErrorException,} from '@nestjs/common'import { ApiTags, ApiQuery, ApiResponse } from '@nestjs/swagger'+import { promises as fs } from 'fs'import * as _isEmpty from 'lodash/isEmpty'import * as _map from 'lodash/map'import * as _trim from 'lodash/trim'@@ -65,40 +66,68 @@ export class ProjectController {@Roles(UserType.CUSTOMER, UserType.ADMIN)async create(@Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<Project> {this.logger.log({ projectDTO, userId }, 'POST /project')- const user = await this.userService.findOneWithRelations(userId, ['projects'])- const maxProjects = ACCOUNT_PLANS[user.planCode].maxProjects++ if (isSelfhosted) {+ let projects- if (!user.isActive) {- throw new ForbiddenException('Please, verify your email address first')- }-- if (!isSelfhosted && _size(user.projects) >= (maxProjects || 5)) {- throw new ForbiddenException(`You cannot create more than ${maxProjects} projects on your account plan. Please upgrade to be able to create more projects.`)- }-- this.projectService.validateProject(projectDTO)+ try {+ const rawData = await fs.readFile('../../projects.json', 'utf8')+ projects = JSON.parse(rawData)+ } catch (e) {+ throw new InternalServerErrorException('Error while reading projects data')+ }- await this.projectService.checkIfIDUnique(projectDTO.id)+ this.projectService.validateProject(projectDTO)+ this.projectService.checkIfIDUniqueJSON(projects, projectDTO.id)- try {const project = new Project()Object.assign(project, projectDTO)project.origins = _map(projectDTO.origins, _trim)- const newProject = await this.projectService.create(project)- user.projects.push(project)+ projects[project.id] = project+ try {+ await fs.writeFile('../../projects.json', JSON.stringify(projects), { flag: 'w' })+ } catch (e) {+ throw new InternalServerErrorException('Error while saving project')+ }- await this.userService.create(user)+ return project+ } else {+ const user = await this.userService.findOneWithRelations(userId, ['projects'])+ const maxProjects = ACCOUNT_PLANS[user.planCode].maxProjects- return newProject- } catch(e) {- if (e.code === 'ER_DUP_ENTRY'){- if (e.sqlMessage.includes(projectDTO.id)){- throw new BadRequestException('Project with selected ID already exists')- }+ if (!user.isActive) {+ throw new ForbiddenException('Please, verify your email address first')+ }++ if (!isSelfhosted && _size(user.projects) >= (maxProjects || 5)) {+ throw new ForbiddenException(`You cannot create more than ${maxProjects} projects on your account plan. Please upgrade to be able to create more projects.`)}- throw new BadRequestException(e)+ this.projectService.validateProject(projectDTO)++ await this.projectService.checkIfIDUnique(projectDTO.id)++ try {+ const project = new Project()+ Object.assign(project, projectDTO)+ project.origins = _map(projectDTO.origins, _trim)++ const newProject = await this.projectService.create(project)+ user.projects.push(project)++ await this.userService.create(user)++ return newProject+ } catch(e) {+ if (e.code === 'ER_DUP_ENTRY'){+ if (e.sqlMessage.includes(projectDTO.id)){+ throw new BadRequestException('Project with selected ID already exists')+ }+ }++ throw new BadRequestException(e)+ }}}@@ -110,19 +139,46 @@ export class ProjectController {async update(@Param('id') id: string, @Body() projectDTO: ProjectDTO, @CurrentUserId() userId: string): Promise<any> {this.logger.log({ projectDTO, userId, id }, 'PUT /project/:id')this.projectService.validateProject(projectDTO)+ let project- const project = await this.projectService.findOneWithRelations(id)+ if (isSelfhosted) {+ let projects- if (_isEmpty(project)) {- throw new NotFoundException()- }- this.projectService.allowedToManage(project, userId)+ try {+ const rawData = await fs.readFile('../../projects.json', 'utf8')+ projects = JSON.parse(rawData)+ } catch (e) {+ throw new InternalServerErrorException('Error while reading projects data')+ }++ project = projects[id]+ if (_isEmpty(project)) {+ throw new NotFoundException()+ }+ project.active = projectDTO.active+ project.origins = _map(projectDTO.origins, _trim)+ project.name = projectDTO.name++ projects[project.id] = project+ try {+ await fs.writeFile('../../projects.json', JSON.stringify(projects), { flag: 'w' })+ } catch (e) {+ throw new InternalServerErrorException('Error while saving project')+ }+ } else {+ project = await this.projectService.findOneWithRelations(id)- project.active = projectDTO.active- project.origins = _map(projectDTO.origins, _trim)- project.name = projectDTO.name+ if (_isEmpty(project)) {+ throw new NotFoundException()+ }+ this.projectService.allowedToManage(project, userId)- await this.projectService.update(id, project)+ project.active = projectDTO.active+ project.origins = _map(projectDTO.origins, _trim)+ project.name = projectDTO.name++ await this.projectService.update(id, project)+ }const key = getRedisProjectKey(id)@@ -144,27 +200,62 @@ export class ProjectController {this.logger.log({ userId, id }, 'DELETE /project/:id')if (!isValidPID(id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')- const project = await this.projectService.findOneWhere({ id }, {- relations: ['admin'],- select: ['id'],- })+ if (isSelfhosted) {+ let projects- if (_isEmpty(project)) {- throw new NotFoundException(`Project with ID ${id} does not exist`)- }- this.projectService.allowedToManage(project, userId)+ try {+ const rawData = await fs.readFile('../../projects.json', 'utf8')+ projects = JSON.parse(rawData)+ } catch (e) {+ throw new InternalServerErrorException('Error while reading projects data')+ }- const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`- const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`+ const project = projects[id]+ if (_isEmpty(project)) {+ throw new NotFoundException(`Project with ID ${id} does not exist`)+ }+ delete projects[id]+ try {+ await fs.writeFile('../../projects.json', JSON.stringify(projects), { flag: 'w' })+ } catch (e) {+ throw new InternalServerErrorException('Error while saving project')+ }- try {- await this.projectService.delete(id)- await clickhouse.query(query1).toPromise()- await clickhouse.query(query2).toPromise()- return 'Project deleted successfully'- } catch(e) {- this.logger.error(e)- return 'Error while deleting your project'+ const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`+ const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`++ try {+ await this.projectService.delete(id)+ await clickhouse.query(query1).toPromise()+ await clickhouse.query(query2).toPromise()+ return 'Project deleted successfully'+ } catch(e) {+ this.logger.error(e)+ return 'Error while deleting your project'+ }+ } else {+ const project = await this.projectService.findOneWhere({ id }, {+ relations: ['admin'],+ select: ['id'],+ })++ if (_isEmpty(project)) {+ throw new NotFoundException(`Project with ID ${id} does not exist`)+ }+ this.projectService.allowedToManage(project, userId)++ const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`+ const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`++ try {+ await this.projectService.delete(id)+ await clickhouse.query(query1).toPromise()+ await clickhouse.query(query2).toPromise()+ return 'Project deleted successfully'+ } catch(e) {+ this.logger.error(e)+ return 'Error while deleting your project'+ }}}}diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex 18e3b23d3..08b8e1d9f 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -85,14 +85,20 @@ export class ProjectService {}}- async checkIfIDUnique(projectId: string): Promise<void> {- const project = await this.findOne(projectId)+ async checkIfIDUnique(projectID: string): Promise<void> {+ const project = await this.findOne(projectID)if (project) {throw new BadRequestException('Selected project ID is already in use')}}+ async checkIfIDUniqueJSON(projects: object, projectID: string): Promise<void> {+ if (!_isEmpty(projects?.[projectID])) {+ throw new BadRequestException('Selected project ID is already in use')+ }+ }+validateProject(projectDTO: ProjectDTO) {if (!isValidPID(projectDTO.id)) throw new UnprocessableEntityException('The provided Project ID (pid) is incorrect')if (_size(projectDTO.name) > 50) throw new UnprocessableEntityException('The project name is too long')