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!

banned unnecessary routes and removed all restrictions for the selfhosted edition

Blue Mouse0238a8f3194d
diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.ts
index 2dd85f621..18a2a87b1 100644
--- a/src/analytics/analytics.service.ts
+++ b/src/analytics/analytics.service.ts
@@ -17,7 +17,7 @@ import { ACCOUNT_PLANS } from '../user/entities/user.entity'
import {
redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout,
UNIQUE_SESSION_LIFE_TIME, clickhouse, getPercentageChange, getRedisUserCountKey,
- redisProjectCountCacheTimeout, // REDIS_SESSION_SALT_KEY,
+ redisProjectCountCacheTimeout, isSelfhosted, // REDIS_SESSION_SALT_KEY,
} from '../common/constants'
import { PageviewsDTO } from './dto/pageviews.dto'
import { EventsDTO } from './dto/events.dto'
@@ -130,11 +130,13 @@ export class AnalyticsService {
if (!project.active) throw new BadRequestException('Incoming analytics is disabled for this project')
- const count = await this.getRedisCount(project.admin.id)
- const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
-
- if (count >= maxCount) {
- throw new ForbiddenException('You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.')
+ if (!isSelfhosted) {
+ const count = await this.getRedisCount(project.admin.id)
+ const maxCount = ACCOUNT_PLANS[project.admin.planCode].monthlyUsageLimit || 0
+
+ if (count >= maxCount) {
+ throw new ForbiddenException('You have exceeded the available monthly request limit for your account. Please upgrade your account plan if you need more requests.')
+ }
}
this.checkOrigin(project, origin)
diff --git a/src/app.module.ts b/src/app.module.ts
index 1c4d1afcd..5e708276c 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -26,7 +26,7 @@ import { PingModule } from './ping/ping.module'
username: process.env.MYSQL_USER,
password: process.env.MYSQL_ROOT_PASSWORD,
database: process.env.MYSQL_DATABASE,
- synchronize: true,
+ synchronize: false,
entities: [User, ActionToken, Project],
}),
ScheduleModule.forRoot(),
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts
index 6114d22ec..e900ecb84 100644
--- a/src/auth/auth.controller.ts
+++ b/src/auth/auth.controller.ts
@@ -20,6 +20,7 @@ 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'
+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
// TODO: Add logout endpoint to invalidate the token
@ApiTags('Auth')
@@ -56,6 +57,7 @@ export class AuthController {
return await this.authService.login(user)
}
+ @UseGuards(SelfhostedGuard)
@Post('/register')
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')
@@ -82,6 +84,7 @@ export class AuthController {
}
}
+ @UseGuards(SelfhostedGuard)
@Get('/verify/:id')
async verify(@Param('id') id: string): Promise<User> {
this.logger.log({ id }, 'GET /auth/verify/:id')
@@ -100,6 +103,7 @@ export class AuthController {
}
}
+ @UseGuards(SelfhostedGuard)
@Get('/change-email/:id')
async changeEmail(@Param('id') id: string): Promise<User> {
this.logger.log({ id }, 'GET /auth/change-email/:id')
@@ -121,6 +125,7 @@ export class AuthController {
}
}
+ @UseGuards(SelfhostedGuard)
@Post('/reset-password')
async requestReset(@Body() body: RequestPasswordChangeDTO, @Req() request: Request, @Headers() headers, @Ip() reqIP): Promise<string> {
this.logger.log({ body }, 'POST /auth/password-reset')
@@ -142,6 +147,7 @@ export class AuthController {
return 'A password reset URL has been sent to your email'
}
+ @UseGuards(SelfhostedGuard)
@Post('/password-reset/:id')
async reset(@Param('id') id: string, @Body() body: PasswordChangeDTO): Promise<User> {
this.logger.log({ id }, 'POST /auth/password-reset/:id')
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 11e6af7bc..27cdc4251 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -36,6 +36,8 @@ const clickhouse = new ClickHouse({
},
})
+const isSelfhosted = process.env.SELFHOSTED
+
/**
* Calculates in percent, the change between 2 numbers.
* e.g from 1000 to 500 = 50%
@@ -92,5 +94,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, REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME,
+ STRIPE_SECRET, STRIPE_WH_SECRET, REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME, isSelfhosted,
}
diff --git a/src/common/guards/selfhosted.guard.ts b/src/common/guards/selfhosted.guard.ts
new file mode 100644
index 000000000..10c00acf8
--- /dev/null
+++ b/src/common/guards/selfhosted.guard.ts
@@ -0,0 +1,13 @@
+import { Injectable, CanActivate, ForbiddenException } from '@nestjs/common'
+import { isSelfhosted } from '../constants'
+
+@Injectable()
+export class SelfhostedGuard implements CanActivate {
+ canActivate(): boolean {
+ if (isSelfhosted) {
+ throw new ForbiddenException('This API route is disabled in selfhosted edition')
+ }
+
+ return true
+ }
+}
diff --git a/src/ping/ping.controller.ts b/src/ping/ping.controller.ts
index 68b8ade64..486c8a127 100644
--- a/src/ping/ping.controller.ts
+++ b/src/ping/ping.controller.ts
@@ -1,5 +1,6 @@
-import { Controller, Get } from '@nestjs/common'
+import { Controller, Get, UseGuards } from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
@ApiTags('Ping')
@Controller('ping')
@@ -7,6 +8,7 @@ export class PingController {
constructor() {}
@Get('/')
+ @UseGuards(SelfhostedGuard)
async get(): Promise<any> {
return
}
diff --git a/src/project/project.controller.ts b/src/project/project.controller.ts
index 3a4bd0210..3e94b27d3 100644
--- a/src/project/project.controller.ts
+++ b/src/project/project.controller.ts
@@ -19,7 +19,7 @@ import { UserService } from '../user/user.service'
import { ProjectDTO } from './dto/project.dto'
import { AppLoggerService } from '../logger/logger.service'
import {
- redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout, clickhouse,
+ redis, isValidPID, getRedisProjectKey, redisProjectCacheTimeout, clickhouse, isSelfhosted,
} from '../common/constants'
@ApiTags('Project')
@@ -72,7 +72,7 @@ export class ProjectController {
throw new ForbiddenException('Please, verify your email address first')
}
- if (_size(user.projects) >= (maxProjects || 5)) {
+ 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.`)
}
diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.ts
index 4e7b6dc0e..b2e8b1239 100644
--- a/src/task-manager/task-manager.service.ts
+++ b/src/task-manager/task-manager.service.ts
@@ -15,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, // REDIS_SESSION_SALT_KEY,
+ clickhouse, redis, REDIS_LOG_DATA_CACHE_KEY, REDIS_LOG_CUSTOM_CACHE_KEY, isSelfhosted, // REDIS_SESSION_SALT_KEY,
} from '../common/constants'
import { getRandomTip } from '../common/utils'
@@ -64,6 +64,10 @@ export class TaskManagerService {
// EVERY SUNDAY AT 2:30 AM
@Cron('30 02 * * 0')
async weeklyReportsHandler(): Promise<void> {
+ if (isSelfhosted) {
+ return
+ }
+
const users = await this.userService.find({
where: {
reportFrequency: ReportFrequency.Weekly,
@@ -102,6 +106,10 @@ export class TaskManagerService {
// ON THE FIRST DAY OF EVERY MONTH AT 2 AM
@Cron('0 02 1 * *')
async monthlyReportsHandler(): Promise<void> {
+ if (isSelfhosted) {
+ return
+ }
+
const users = await this.userService.find({
where: {
reportFrequency: ReportFrequency.Monthly,
diff --git a/src/user/user.controller.ts b/src/user/user.controller.ts
index e3d3a741a..86d3828ff 100644
--- a/src/user/user.controller.ts
+++ b/src/user/user.controller.ts
@@ -21,6 +21,7 @@ import {
GDPR_EXPORT_TIMEFRAME, clickhouse, STRIPE_SECRET,
} from '../common/constants'
import { RolesGuard } from 'src/common/guards/roles.guard'
+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
import { UpdateUserProfileDTO } from './dto/update-user.dto'
import { UpgradeUserProfileDTO } from './dto/upgrade-user.dto'
import { CurrentUserId } from 'src/common/decorators/current-user-id.decorator'
@@ -53,6 +54,7 @@ export class UserController {
@ApiQuery({ name: 'take', required: false })
@ApiQuery({ name: 'skip', required: false })
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.ADMIN)
async get(@Query('take') take: number | undefined, @Query('skip') skip: number | undefined): Promise<Pagination<User> | User[]> {
this.logger.log({ take, skip }, 'GET /user')
@@ -62,6 +64,7 @@ export class UserController {
@Get('/search')
@ApiQuery({ name: 'query', required: false })
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.ADMIN)
async searchUsers(@Query('query') query: string | undefined): Promise<User[]> {
this.logger.log({ query }, 'GET /user/search')
@@ -70,6 +73,7 @@ export class UserController {
@Post('/')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.ADMIN)
async create(@Body() userDTO: UserProfileDTO): Promise<User> {
this.logger.log({ userDTO }, 'POST /user')
@@ -91,6 +95,7 @@ export class UserController {
@Delete('/:id')
@HttpCode(204)
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.ADMIN)
async delete(@Param('id') id: string, @CurrentUserId() uid: string): Promise<any> {
this.logger.log({ id, uid }, 'DELETE /user/:id')
@@ -123,6 +128,7 @@ export class UserController {
@Delete('/')
@HttpCode(204)
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async deleteSelf(@CurrentUserId() id: string): Promise<any> {
this.logger.log({ id }, 'DELETE /user')
@@ -152,6 +158,7 @@ export class UserController {
@Post('/confirm_email')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async sendEmailConfirmation(@CurrentUserId() id: string, @Req() request: Request): Promise<boolean> {
this.logger.log({ id }, 'POST /confirm_email')
@@ -170,6 +177,7 @@ export class UserController {
@Put('/:id')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.ADMIN)
async update(@Body() userDTO: UpdateUserProfileDTO, @Param('id') id: string): Promise<User> {
this.logger.log({ userDTO, id }, 'DELETE /user/:id')
@@ -200,6 +208,7 @@ export class UserController {
@Put('/')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async updateCurrentUser(@Body() userDTO: UpdateUserProfileDTO, @CurrentUserId() id: string, @Req() request: Request): Promise<User> {
this.logger.log({ userDTO, id }, 'PUT /user')
@@ -233,6 +242,7 @@ export class UserController {
@Post('/upgrade')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async upgradePlan(@Body() body: UpgradeUserProfileDTO, @CurrentUserId() user_id: string): Promise<object> {
this.logger.log({ body, user_id }, 'POST /user/upgrade')
@@ -312,6 +322,7 @@ export class UserController {
@Get('/export')
@UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard)
@Roles(UserType.CUSTOMER, UserType.ADMIN)
async exportUserData(@CurrentUserId() user_id: string): Promise<User> {
this.logger.log({ user_id }, 'GET /user/export')
diff --git a/src/webhook/webhook.controller.ts b/src/webhook/webhook.controller.ts
index ecff7dfc6..9a69cf6a3 100644
--- a/src/webhook/webhook.controller.ts
+++ b/src/webhook/webhook.controller.ts
@@ -1,5 +1,5 @@
import {
- Controller, Body, Post, Headers, BadRequestException, NotFoundException,
+ Controller, Body, Post, Headers, BadRequestException, NotFoundException, UseGuards,
} from '@nestjs/common'
import { ApiTags } from '@nestjs/swagger'
import * as _isEmpty from 'lodash/isEmpty'
@@ -11,6 +11,7 @@ import {
} from '../user/entities/user.entity'
import { UserService } from '../user/user.service'
import { AppLoggerService } from '../logger/logger.service'
+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
import { STRIPE_WH_SECRET, STRIPE_SECRET } from '../common/constants'
const stripe = require('stripe')(STRIPE_SECRET)
@@ -25,6 +26,7 @@ export class WebhookController {
private readonly userService: UserService,
) { }
+ @UseGuards(SelfhostedGuard)
@Post('/')
async stripeWebhook(@Body() body: Buffer, @Headers() headers): Promise<any> {
let event