📈 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 rate-limiting & other bug fixes and optimisations
Blue Mouse2f1fdb28db5f
diff --git a/src/action-tokens/action-token.entity.ts b/src/action-tokens/action-token.entity.tsindex cfbc289a1..16f188548 100644--- a/src/action-tokens/action-token.entity.ts+++ b/src/action-tokens/action-token.entity.ts@@ -10,20 +10,20 @@ export enum ActionTokenType {@Entity()export class ActionToken {@PrimaryGeneratedColumn('uuid')- id: string;+ id: string@ManyToOne(() => User, user => user.actionTokens, { onDelete: 'CASCADE' })- user: User;+ user: User@CreateDateColumn()created: Timestamp@Column('varchar', { length: 254, default: null })- newValue: string;+ newValue: string@Column({type: 'enum',enum: ActionTokenType,})action: ActionTokenType-}\ No newline at end of file+}diff --git a/src/action-tokens/action-tokens.service.spec.ts b/src/action-tokens/action-tokens.service.spec.tsindex 9e8e70055..ca570be5f 100644--- a/src/action-tokens/action-tokens.service.spec.ts+++ b/src/action-tokens/action-tokens.service.spec.ts@@ -1,18 +1,18 @@-import { Test, TestingModule } from '@nestjs/testing';-import { ActionTokensService } from './action-tokens.service';+import { Test, TestingModule } from '@nestjs/testing'+import { ActionTokensService } from './action-tokens.service'describe('ActionTokensService', () => {- let service: ActionTokensService;+ let service: ActionTokensServicebeforeEach(async () => {const module: TestingModule = await Test.createTestingModule({providers: [ActionTokensService],- }).compile();+ }).compile()- service = module.get<ActionTokensService>(ActionTokensService);- });+ service = module.get<ActionTokensService>(ActionTokensService)+ })it('should be defined', () => {- expect(service).toBeDefined();- });-});+ expect(service).toBeDefined()+ })+})diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex 193cce3ee..c311f3c73 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -26,7 +26,7 @@ import { EventsDTO } from './dto/events.dto'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,+ clickhouse, 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'@@ -170,11 +170,11 @@ export class AnalyticsController {// Log custom event@Post('/custom')- async logCustom(@Body() eventsDTO: EventsDTO, @Headers() headers): Promise<any> {+ async logCustom(@Body() eventsDTO: EventsDTO, @Headers() headers, @Ip() reqIP): Promise<any> {const { 'user-agent': userAgent, origin } = headersawait this.analyticsService.validate(eventsDTO, origin)- const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || ''+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''if (eventsDTO.unique) {// const salt = await redis.get(REDIS_SESSION_SALT_KEY)diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.tsindex c004dbae5..6114d22ec 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,+ Controller, Post, Body, Req, Get, Param, BadRequestException, UseGuards, Ip, Headers,} from '@nestjs/common'import { Request } from 'express'import { ApiTags } from '@nestjs/swagger'@@ -17,10 +17,11 @@ import { RequestPasswordChangeDTO } from './dto/request-pass-change.dto'import { RolesGuard } from '../common/guards/roles.guard'import { Roles } from '../common/decorators/roles.decorator'import { CurrentUserId } from '../common/decorators/current-user-id.decorator'+import { checkRateLimit } from '../common/utils'import { LetterTemplate } from '../mailer/letter'import { AppLoggerService } from '../logger/logger.service'-// TODO: Add logout endpoint to delete the token+// TODO: Add logout endpoint to invalidate the token@ApiTags('Auth')@Controller('auth')export class AuthController {@@ -45,8 +46,10 @@ export class AuthController {}@Post('/login')- async loginUser(@Body() userLoginDTO: UserLoginDTO, @Req() request: Request): Promise<any> {+ async loginUser(@Body() userLoginDTO: UserLoginDTO, @Headers() headers, @Ip() reqIP): Promise<any> {this.logger.log({ userLoginDTO }, 'POST /auth/login')+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''+ await checkRateLimit(ip, 'login', 10, 3600)// await this.authService.checkCaptcha(userLoginDTO.recaptcha)const user = await this.authService.validateUser(userLoginDTO.email, userLoginDTO.password)@@ -54,8 +57,10 @@ export class AuthController {}@Post('/register')- async register(@Body() userDTO: SignupUserDTO, /*@Body('recaptcha') recaptcha: string,*/ @Req() request: Request): Promise<any> {+ async register(@Body() userDTO: SignupUserDTO, /*@Body('recaptcha') recaptcha: string,*/ @Req() request: Request, @Headers() headers, @Ip() reqIP): Promise<any> {this.logger.log({ userDTO }, 'POST /auth/register')+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''+ await checkRateLimit(ip, 'register')// await this.authService.checkCaptcha(recaptcha)this.userService.validatePassword(userDTO.password)@@ -85,7 +90,7 @@ export class AuthController {try {actionToken = await this.actionTokensService.find(id)} catch {- throw new BadRequestException('Wrong token')+ throw new BadRequestException('Incorrect token provided')}if (actionToken.action === ActionTokenType.EMAIL_VERIFICATION) {@@ -103,7 +108,7 @@ export class AuthController {try {actionToken = await this.actionTokensService.find(id)} catch {- throw new BadRequestException('Wrong token')+ throw new BadRequestException('Incorrect token provided')}if (actionToken.action === ActionTokenType.EMAIL_CHANGE) {@@ -117,8 +122,14 @@ export class AuthController {}@Post('/reset-password')- async requestReset(@Body() body: RequestPasswordChangeDTO, @Req() request: Request): Promise<string> {- const user = await this.userService.findOneWhere({ email: body.email })+ async requestReset(@Body() body: RequestPasswordChangeDTO, @Req() request: Request, @Headers() headers, @Ip() reqIP): Promise<string> {+ this.logger.log({ body }, 'POST /auth/password-reset')+ const { email } = body+ const ip = headers['cf-connecting-ip'] || headers['x-forwarded-for'] || reqIP || ''+ await checkRateLimit(ip, 'reset-password')+ await checkRateLimit(email, 'reset-password')++ const user = await this.userService.findOneWhere({ email })if (!user) {return 'A password reset URL has been sent to your email'@@ -127,7 +138,7 @@ export class AuthController {const actionToken = await this.actionTokensService.createForUser(user, ActionTokenType.PASSWORD_RESET)const url = `${request.headers.origin}/password-reset/${actionToken.id}`- await this.mailerService.sendEmail(body.email, LetterTemplate.ConfirmPasswordChange, { url })+ await this.mailerService.sendEmail(email, LetterTemplate.ConfirmPasswordChange, { url })return 'A password reset URL has been sent to your email'}@@ -140,7 +151,7 @@ export class AuthController {try {actionToken = await this.actionTokensService.find(id)} catch {- throw new BadRequestException('Wrong token')+ throw new BadRequestException('Incorrect token provided')}if (actionToken.action === ActionTokenType.PASSWORD_RESET) {diff --git a/src/auth/auth.module.ts b/src/auth/auth.module.tsindex e3d7fe199..fcd2dd6b0 100644--- a/src/auth/auth.module.ts+++ b/src/auth/auth.module.ts@@ -17,4 +17,4 @@ import { AppLoggerModule } from '../logger/logger.module'providers: [AuthService],exports: [AuthService],})-export class AuthModule {}\ No newline at end of file+export class AuthModule {}diff --git a/src/auth/dto/user-signup.dto.ts b/src/auth/dto/user-signup.dto.tsindex 046abd7b5..4d4a8d887 100644--- a/src/auth/dto/user-signup.dto.ts+++ b/src/auth/dto/user-signup.dto.ts@@ -1,5 +1,5 @@import { ApiProperty } from '@nestjs/swagger'-import { IsEmail, IsNotEmpty, IsEmpty, IsDate } from 'class-validator'+import { IsEmail, IsNotEmpty } from 'class-validator'// import { UserRole, Locale } from '../../users/entities/user.entity'export class SignupUserDTO {@@ -17,4 +17,4 @@ export class SignupUserDTO {@ApiProperty()@IsNotEmpty()tos: Date-}\ No newline at end of file+}diff --git a/src/common/pagination/index.ts b/src/common/pagination/index.tsindex 9d91dd9ca..f276090bf 100644--- a/src/common/pagination/index.ts+++ b/src/common/pagination/index.ts@@ -1,3 +1,3 @@export * from './pagination.options.interface'export * from './pagination.results.interface'-export * from './pagination'\ No newline at end of file+export * from './pagination'diff --git a/src/common/pagination/pagination.options.interface.ts b/src/common/pagination/pagination.options.interface.tsindex 2b0d713d8..49f1807b0 100644--- a/src/common/pagination/pagination.options.interface.ts+++ b/src/common/pagination/pagination.options.interface.ts@@ -1,4 +1,4 @@export interface PaginationOptionsInterface {take: number;skip: number;-}\ No newline at end of file+}diff --git a/src/common/pagination/pagination.results.interface.ts b/src/common/pagination/pagination.results.interface.tsindex 53b1c4e96..fff9e2303 100644--- a/src/common/pagination/pagination.results.interface.ts+++ b/src/common/pagination/pagination.results.interface.ts@@ -3,4 +3,4 @@ export interface PaginationResultInterface<PaginationEntity> {total: number;next?: string;previous?: string;-}\ No newline at end of file+}diff --git a/src/common/pagination/pagination.ts b/src/common/pagination/pagination.tsindex b3124ac5b..fd5444d1d 100644--- a/src/common/pagination/pagination.ts+++ b/src/common/pagination/pagination.ts@@ -10,4 +10,4 @@ export class Pagination<PaginationEntity> {this.page_total = paginationResults.results.lengththis.total = paginationResults.total}-}\ No newline at end of file+}diff --git a/src/common/templates/en/project-report.html b/src/common/templates/en/project-report.htmlindex 6ec143124..4d6592fdd 100644--- a/src/common/templates/en/project-report.html+++ b/src/common/templates/en/project-report.html@@ -80,6 +80,14 @@<b>Pageviews:</b> {{data.thisWeek}} ({{#greater data.percChange 0}}<span style="color: #059669;">+{{data.percChange}}%</span>{{else}}<span style="color: #DC2626;">{{data.percChange}}%</span>{{/greater}})<br /><br />{{/each}}++ 💡+ <i>+ {{tip}}+ </i>++ <br /><br />+You can manage email reports preferences in your <a href="https://swetrix.com/settings" target="_blank">account settings</a>.</span></font>diff --git a/src/common/utils.ts b/src/common/utils.tsnew file mode 100644index 000000000..0f14e1461--- /dev/null+++ b/src/common/utils.ts@@ -0,0 +1,34 @@+import * as _sample from 'lodash/sample'+import { ForbiddenException } from '@nestjs/common'+import { hash } from 'blake3'+import * as _toNumber from 'lodash/toNumber'+import { redis } from './constants'++const marketingTips = {+ en: ['Tip 1', 'Tip 2', 'Tip 3'],+}++const RATE_LIMIT_REQUESTS_AMOUNT = 3+const RATE_LIMIT_TIMEOUT = 86400 // 24 hours++const _getRateLimitHash = (ip: string, salt: string = '') => `rl:${hash(`${ip}${salt}`).toString('hex')}`++const getRandomTip = (language: string = 'en'): string => {+ return _sample(marketingTips[language])+}++// 'action' is used as a salt to differ rate limiting routes+const checkRateLimit = async (ip: string, action: string, reqAmount = RATE_LIMIT_REQUESTS_AMOUNT, reqTimeout = RATE_LIMIT_TIMEOUT): Promise<void> => {+ const rlHash = _getRateLimitHash(ip, action)+ let rlCount = await redis.get(rlHash)+ rlCount = _toNumber(rlCount) || 0++ if (rlCount >= reqAmount) {+ throw new ForbiddenException('Too many requests, please try again later')+ }+ await redis.set(rlHash, 1 + rlCount, 'EX', reqTimeout)+}++export {+ getRandomTip, checkRateLimit,+}diff --git a/src/logger/logger.service.ts b/src/logger/logger.service.tsindex 860ebd445..bd6891413 100644--- a/src/logger/logger.service.ts+++ b/src/logger/logger.service.ts@@ -1,8 +1,8 @@import { Logger } from '@nestjs/common'export class AppLoggerService extends Logger {- log(value, route) {- if (process.env.NODE_ENV === 'development') {+ log(value, route, forceLog: boolean = false) {+ if (process.env.NODE_ENV === 'development' || forceLog) {Logger.log(value, route)}}diff --git a/src/mailer/mailer.service.ts b/src/mailer/mailer.service.tsindex 64ceb4f3d..27e4ad154 100644--- a/src/mailer/mailer.service.ts+++ b/src/mailer/mailer.service.ts@@ -103,7 +103,7 @@ export class MailerService {}if (process.env.SMTP_MOCK) {- this.logger.log(message, 'sendEmail')+ this.logger.log(message, 'sendEmail', true)} else {transporter.sendMail(message, (err, info) => {if (err) {diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex f093fd1ea..3a4bd0210 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -40,9 +40,7 @@ export class ProjectController {@Roles(UserType.CUSTOMER, UserType.ADMIN)async get(@CurrentUserId() userId: string, @Query('take') take: number | undefined, @Query('skip') skip: number | undefined): Promise<Pagination<Project> | Project[]> {this.logger.log({ userId, take, skip }, 'GET /project')- // const user = await this.userService.findOne(userId)const where = Object()-where.admin = userIdreturn await this.projectService.paginate({ take, skip }, where)@@ -57,7 +55,7 @@ export class ProjectController {if (!isValidPID(id)) throw new BadRequestException('The provided Project ID (pid) is incorrect')const project = await this.projectService.findOne(id)- if (_isEmpty(project)) throw new NotFoundException()+ if (_isEmpty(project)) throw new NotFoundException('Project was not found in the database')return project}diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex 23fdd7052..18e3b23d3 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -77,12 +77,8 @@ export class ProjectService {return this.projectsRepository.findOne({ where, ...params })}- ifAllowedToManage(uid: string, project: Project): boolean {- return uid === project.admin.id- }-allowedToManage(project: Project, uid: string): void {- if (this.ifAllowedToManage(uid, project)) {+ if (uid === project.admin.id) {return} else {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 79bfccfad..4e7b6dc0e 100644--- a/src/task-manager/task-manager.service.ts+++ b/src/task-manager/task-manager.service.ts@@ -1,4 +1,4 @@-import { Injectable, HttpService } from '@nestjs/common'+import { Injectable } from '@nestjs/common'import { Cron, CronExpression } from '@nestjs/schedule'// import * as bcrypt from 'bcrypt'import * as dayjs from 'dayjs'@@ -15,8 +15,9 @@ 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, REDIS_SESSION_SALT_KEY,+ clickhouse, redis, REDIS_LOG_DATA_CACHE_KEY, REDIS_LOG_CUSTOM_CACHE_KEY, // REDIS_SESSION_SALT_KEY,} from '../common/constants'+import { getRandomTip } from '../common/utils'dayjs.extend(utc)@@ -24,7 +25,6 @@ dayjs.extend(utc)export class TaskManagerService {constructor(private readonly mailerService: MailerService,- private readonly httpService: HttpService,private readonly userService: UserService,private readonly analyticsService: AnalyticsService,) {}@@ -74,6 +74,7 @@ export class TaskManagerService {const now = dayjs.utc().format('DD.MM.YYYY')const weekAgo = dayjs.utc().subtract(1, 'w').format('DD.MM.YYYY')const date = `${weekAgo} - ${now}`+ const tip = getRandomTip()for (let i = 0; i < _size(users); ++i) {if (_isEmpty(users[i]?.projects) || _isNull(users[i]?.projects)) {@@ -90,6 +91,7 @@ export class TaskManagerService {data: data[pid],name: users[i].projects[index].name,})),+ tip,}// todo: maybe this should be sent as a broadcast stream@@ -110,6 +112,7 @@ export class TaskManagerService {const now = dayjs.utc().format('DD.MM.YYYY')const weekAgo = dayjs.utc().subtract(1, 'M').format('DD.MM.YYYY')const date = `${weekAgo} - ${now}`+ const tip = getRandomTip()for (let i = 0; i < _size(users); ++i) {if (_isEmpty(users[i]?.projects) || _isNull(users[i]?.projects)) {@@ -126,6 +129,7 @@ export class TaskManagerService {data: data[pid],name: users[i].projects[index].name,})),+ tip,}// todo: maybe this should be sent as a broadcast streamdiff --git a/src/user/dto/update-user.dto.ts b/src/user/dto/update-user.dto.tsindex 53f095c70..f90d5c817 100644--- a/src/user/dto/update-user.dto.ts+++ b/src/user/dto/update-user.dto.ts@@ -1,5 +1,5 @@import { ApiProperty } from '@nestjs/swagger'-import { IsEmail, IsNotEmpty } from 'class-validator'+import { IsEmail } from 'class-validator'export class UpdateUserProfileDTO {@ApiProperty({ example: '[email protected]', required: true })diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 06086c587..b1487b1a1 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -87,20 +87,20 @@ export class User {emailRequests: number@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })- created: Date;+ created: Date@Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })- updated: Date;+ updated: Date@Column({ type: 'timestamp', nullable: true })- exportedAt: Date;+ exportedAt: Date@Column('varchar', { length: 28, nullable: true })stripeSubID: string@BeforeUpdate()updateTimestamp() {- this.updated = new Date;+ this.updated = new Date}// @Column('datetime', { nullable: true, default: null })@@ -111,4 +111,4 @@ export class User {@OneToMany(() => ActionToken, actionToken => actionToken.user)actionTokens: ActionToken[]-}\ No newline at end of file+}diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex 53976d615..e3d3a741a 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -155,7 +155,7 @@ export class UserController {@Roles(UserType.CUSTOMER, UserType.ADMIN)async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {this.logger.log({ id }, 'POST /confirm_email')-+const user = await this.userService.findOneWhere({ id })if (!user || !user.email || user.isActive || user.emailRequests >= MAX_EMAIL_REQUESTS) return falsediff --git a/src/user/user.service.ts b/src/user/user.service.tsindex e23a9ea0d..38d23678c 100644--- a/src/user/user.service.ts+++ b/src/user/user.service.ts@@ -1,6 +1,8 @@import { Injectable, BadRequestException } from '@nestjs/common'import { InjectRepository } from '@nestjs/typeorm'import { Repository } from 'typeorm'+import * as _isEmpty from 'lodash/isEmpty'+import * as _size from 'lodash/size'import { Pagination, PaginationOptionsInterface } from '../common/pagination'import { User } from './entities/user.entity'@@ -69,16 +71,20 @@ export class UserService {return this.usersRepository.find({ where })}- validatePassword(pass: string): string | null {- if(!pass) {- return null+ validatePassword(pass: string): void {+ const err = []+ if (_isEmpty(pass)) {+ err.push('Password cannot be empty')}- const err = []- if(pass.length > 50)+ if(_size(pass) > 50) {err.push('Maximum password length is 50 letters')- if(pass.length < 8)+ }++ if(_size(pass) < 8) {err.push('at least 8 characters')+ }+// if(!/[a-z]/.test(pass))// err.push('should contain at least one lower case')// if(!/[A-Z]/.test(pass))@@ -86,10 +92,8 @@ export class UserService {// if(!(/[!@#$%^&*(),.?":{}|<>]/g.test(pass)))// err.push('should contain at least one symbol')- if (err.length > 0)+ if (!_isEmpty(err)) {throw new BadRequestException(err)- else {- return null}}