📈 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
remove selfhosted stuff from the production source code
Blue Mouse35fa50df2f55
diff --git a/src/alert/alert.controller.ts b/src/alert/alert.controller.tsindex b7aee7593..321221e7b 100644--- a/src/alert/alert.controller.ts+++ b/src/alert/alert.controller.ts@@ -33,7 +33,6 @@ import { Roles } from '../auth/decorators/roles.decorator'import { Alert } from './entity/alert.entity'import { AlertDTO, CreateAlertDTO } from './dto/alert.dto'import { RolesGuard } from '../auth/guards/roles.guard'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import { AlertService } from './alert.service'const ALERTS_MAXIMUM = ACCOUNT_PLANS[PlanCode.free].maxAlerts@@ -49,7 +48,6 @@ export class AlertController {) {}@Get('/')- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN, UserType.CUSTOMER)@ApiResponse({ status: 200, type: Alert })@@ -83,7 +81,6 @@ export class AlertController {}@Post('/')- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN, UserType.CUSTOMER)@ApiResponse({ status: 201, type: Alert })@@ -158,7 +155,6 @@ export class AlertController {}@Put('/:id')- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN, UserType.CUSTOMER)@ApiResponse({ status: 200, type: Alert })@@ -208,7 +204,6 @@ export class AlertController {}@Delete('/:id')- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN, UserType.CUSTOMER)@ApiResponse({ status: 204, description: 'Empty body' })diff --git a/src/analytics/analytics.controller.ts b/src/analytics/analytics.controller.tsindex 887a2dd80..053f6a6e2 100644--- a/src/analytics/analytics.controller.ts+++ b/src/analytics/analytics.controller.ts@@ -46,7 +46,6 @@ import { EventsDTO } from './dto/events.dto'import { AnalyticsGET_DTO } from './dto/getData.dto'import { GetUserFlowDTO } from './dto/getUserFlow.dto'import { AppLoggerService } from '../logger/logger.service'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import {REDIS_LOG_DATA_CACHE_KEY,REDIS_LOG_PERF_CACHE_KEY,@@ -650,7 +649,6 @@ export class AnalyticsController {return this.analyticsService.getCaptchaSummary(pidsArray, 'w')}- @UseGuards(SelfhostedGuard)@Public()@Get('generalStats')async getGeneralStats(): Promise<object> {diff --git a/src/analytics/analytics.service.ts b/src/analytics/analytics.service.tsindex ca56f2cc0..ffe51e76c 100644--- a/src/analytics/analytics.service.ts+++ b/src/analytics/analytics.service.ts@@ -38,7 +38,6 @@ import {isValidPID,UNIQUE_SESSION_LIFE_TIME,clickhouse,- isSelfhosted,REDIS_SESSION_SALT_KEY,} from '../common/constants'import {@@ -215,10 +214,8 @@ export class AnalyticsService {constructor(private readonly projectService: ProjectService) {}async checkProjectAccess(pid: string, uid: string | null): Promise<void> {- if (!isSelfhosted) {- const project = await this.projectService.getRedisProject(pid)- this.projectService.allowedToView(project, uid)- }+ const project = await this.projectService.getRedisProject(pid)+ this.projectService.allowedToView(project, uid)}checkOrigin(project: Project, origin: string): void {@@ -324,7 +321,6 @@ export class AnalyticsService {)}- if (!isSelfhosted) {if (project.admin.planCode === PlanCode.none) {throw new ForbiddenException('You cannot send analytics to this project due to no active subscription. Please upgrade your account plan to continue sending analytics.',@@ -340,7 +336,6 @@ export class AnalyticsService {'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/auth/auth.controller.ts b/src/auth/auth.controller.tsindex 944617f04..1f87e49d4 100644--- a/src/auth/auth.controller.ts+++ b/src/auth/auth.controller.ts@@ -30,13 +30,10 @@ import { checkRateLimit } from 'src/common/utils'import {UserType,User,- generateSelfhostedUser,} from 'src/user/entities/user.entity'import { UserService } from 'src/user/user.service'-import { isSelfhosted } from 'src/common/constants'import { AuthService } from './auth.service'import { Public, CurrentUserId, CurrentUser, Roles } from './decorators'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import {RegisterResponseDto,RegisterRequestDto,@@ -83,7 +80,6 @@ export class AuthController {description: 'User registered',type: RegisterResponseDto,})- @UseGuards(SelfhostedGuard)@Public()@Post('register')public async register(@@ -158,13 +154,6 @@ export class AuthController {!user.isTwoFactorAuthenticationEnabled,)- if (isSelfhosted) {- return {- ...jwtTokens,- user,- }- }-await this.authService.sendTelegramNotification(user.id, headers, ip)if (user.isTwoFactorAuthenticationEnabled) {@@ -183,7 +172,6 @@ export class AuthController {@ApiOkResponse({description: 'User email verified',})- @UseGuards(SelfhostedGuard)@Public()@Get('verify-email/:token')public async verifyEmail(@@ -205,7 +193,6 @@ export class AuthController {@ApiOkResponse({description: 'Password reset requested',})- @UseGuards(SelfhostedGuard)@Public()@Post('reset-password')public async requestResetPassword(@@ -233,7 +220,6 @@ export class AuthController {@ApiOkResponse({description: 'Password reset',})- @UseGuards(SelfhostedGuard)@Public()@Post('reset-password/confirm/:token')@HttpCode(200)@@ -257,7 +243,6 @@ export class AuthController {@ApiOkResponse({description: 'Password changed',})- @UseGuards(SelfhostedGuard)@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@Post('change-password')@@ -288,7 +273,6 @@ export class AuthController {@ApiOkResponse({description: 'Resend of the verification email requested',})- @UseGuards(SelfhostedGuard)@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@Post('verify-email')@@ -320,7 +304,6 @@ export class AuthController {@ApiOkResponse({description: 'User email changed',})- @UseGuards(SelfhostedGuard)@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@Post('change-email')@@ -357,7 +340,6 @@ export class AuthController {@ApiOkResponse({description: 'User email confirmed',})- @UseGuards(SelfhostedGuard)@Public()@Get('change-email/confirm/:token')public async confirmChangeEmail(@@ -388,9 +370,7 @@ export class AuthController {@CurrentUser('refreshToken') refreshToken: string,@I18n() i18n: I18nContext,): Promise<{ accessToken: string }> {- const user = isSelfhosted- ? generateSelfhostedUser()- : await this.userService.findUserById(userId)+ const user = await this.userService.findUserById(userId)if (!user) {throw new UnauthorizedException()@@ -426,9 +406,7 @@ export class AuthController {@CurrentUser('refreshToken') refreshToken: string,@I18n() i18n: I18nContext,): Promise<void> {- const user = isSelfhosted- ? generateSelfhostedUser()- : await this.userService.findUserById(userId)+ const user = await this.userService.findUserById(userId)if (!user) {throw new UnauthorizedException()@@ -449,7 +427,6 @@ export class AuthController {// SSO section@ApiOperation({ summary: 'Generate SSO authentication URL' })@Post('sso/generate')- @UseGuards(SelfhostedGuard)@Public()async generateAuthURL(@Body() body: SSOGenerateDto,@@ -476,7 +453,6 @@ export class AuthController {@ApiOperation({ summary: 'Process authentication token (or code)' })@Post('sso/process-token')- @UseGuards(SelfhostedGuard)@Public()async processSSOToken(@Body() body: ProcessSSOCodeDto,@@ -495,7 +471,6 @@ export class AuthController {@ApiOperation({ summary: 'Auth user' })@Post('sso/hash')- @UseGuards(SelfhostedGuard)@Public()// Validates the authorisation code and returns the JWT tokensasync getJWTByHash(@@ -515,7 +490,6 @@ export class AuthController {@ApiOkResponse({description: 'SSO provider linked to an existing account',})- @UseGuards(SelfhostedGuard)@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@Post('sso/link_by_hash')@@ -532,7 +506,6 @@ export class AuthController {@ApiOkResponse({description: 'SSO provider unlinked from an existing account',})- @UseGuards(SelfhostedGuard)@UseGuards(RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@Delete('sso/unlink')diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.tsindex ad5810136..b15749f9a 100644--- a/src/auth/auth.service.ts+++ b/src/auth/auth.service.ts@@ -30,8 +30,6 @@ import {MAX_EMAIL_REQUESTS,User,TRIAL_DURATION,- SelfhostedUser,- generateSelfhostedUser,} from 'src/user/entities/user.entity'import { UserService } from 'src/user/user.service'import { ProjectService } from 'src/project/project.service'@@ -45,9 +43,6 @@ import {redis,PRODUCTION_ORIGIN,isDevelopment,- isSelfhosted,- SELFHOSTED_EMAIL,- SELFHOSTED_PASSWORD,JWT_ACCESS_TOKEN_SECRET,} from 'src/common/constants'import { TelegramService } from 'src/integrations/telegram/telegram.service'@@ -188,15 +183,7 @@ export class AuthService {public async validateUser(email: string,password: string,- ): Promise<User | SelfhostedUser | null> {- if (isSelfhosted) {- if (email !== SELFHOSTED_EMAIL || password !== SELFHOSTED_PASSWORD) {- return null- }-- return generateSelfhostedUser()- }-+ ): Promise<User | null> {const user = await this.userService.findUser(email)if (user && (await this.comparePassword(password, user.password))) {@@ -443,11 +430,7 @@ export class AuthService {},)- if (isSelfhosted) {- await saveRefreshTokenClickhouse(userId, refreshToken)- } else {await this.userService.saveRefreshToken(userId, refreshToken)- }return refreshToken}@@ -456,11 +439,6 @@ export class AuthService {userId: string,refreshToken: string,): Promise<boolean> {- if (isSelfhosted) {- const tokens = await findRefreshTokenClickhouse(userId, refreshToken)- return !_isEmpty(tokens)- }-const token = await this.userService.findRefreshToken(userId, refreshToken)return Boolean(token)}@@ -487,11 +465,6 @@ export class AuthService {}async logout(userId: string, refreshToken: string) {- if (isSelfhosted) {- await deleteRefreshTokenClickhouse(userId, refreshToken)- return- }-await this.userService.deleteRefreshToken(userId, refreshToken)}diff --git a/src/auth/guards/roles.guard.ts b/src/auth/guards/roles.guard.tsindex cf75d1045..dac5d324b 100644--- a/src/auth/guards/roles.guard.ts+++ b/src/auth/guards/roles.guard.ts@@ -3,9 +3,9 @@ import { Reflector } from '@nestjs/core'import { ExtractJwt } from 'passport-jwt'import { verify } from 'jsonwebtoken'-import { UserType, generateSelfhostedUser } from 'src/user/entities/user.entity'+import { UserType } from 'src/user/entities/user.entity'import { UserService } from 'src/user/user.service'-import { isSelfhosted, JWT_ACCESS_TOKEN_SECRET } from 'src/common/constants'+import { JWT_ACCESS_TOKEN_SECRET } from 'src/common/constants'import { IS_TWO_FA_NOT_REQUIRED_KEY, ROLES_KEY } from '../decorators'@Injectable()@@ -31,9 +31,7 @@ export class RolesGuard implements CanActivate {const request = context.switchToHttp().getRequest()const userFromRequest = request.user- const user = isSelfhosted- ? generateSelfhostedUser()- : await this.userService.findUserById(userFromRequest.id)+ const user = await this.userService.findUserById(userFromRequest.id)// this is a temp measure as well due to some fucking bug related to undefined user, will revert it when I find the causelet hasRole@@ -55,21 +53,6 @@ export class RolesGuard implements CanActivate {token = extract(request)}- if (isSelfhosted) {- try {- const decoded: any = verify(token, JWT_ACCESS_TOKEN_SECRET)-- // If the token is not decoded, it means it's invalid- if (!decoded) {- return false- }- } catch {- return false- }-- return true- }-if (isTwoFaNotRequired) {return true}diff --git a/src/auth/strategies/jwt-access-token.strategy.ts b/src/auth/strategies/jwt-access-token.strategy.tsindex b2b357ac6..160c51551 100644--- a/src/auth/strategies/jwt-access-token.strategy.ts+++ b/src/auth/strategies/jwt-access-token.strategy.ts@@ -4,11 +4,8 @@ import { PassportStrategy } from '@nestjs/passport'import { Strategy, ExtractJwt } from 'passport-jwt'import {- isSelfhosted,- SELFHOSTED_UUID,JWT_ACCESS_TOKEN_SECRET,} from 'src/common/constants'-import { generateSelfhostedUser } from 'src/user/entities/user.entity'import { UserService } from 'src/user/user.service'import { IJwtPayload } from '../interfaces'@@ -29,14 +26,6 @@ export class JwtAccessTokenStrategy extends PassportStrategy(}public async validate(payload: IJwtPayload) {- if (isSelfhosted) {- if (payload.sub !== SELFHOSTED_UUID) {- throw new UnauthorizedException()- }-- return generateSelfhostedUser()- }-const user = await this.userService.findUserById(payload.sub)if (!user) {diff --git a/src/common/constants.ts b/src/common/constants.tsindex fb60c0988..04de34c05 100644--- a/src/common/constants.ts+++ b/src/common/constants.ts@@ -3,8 +3,6 @@ import Redis from 'ioredis'import { hash } from 'blake3'import * as _toNumber from 'lodash/toNumber'-import { getSelfhostedUUID } from './utils'-// eslint-disable-next-line @typescript-eslint/no-var-requiresrequire('dotenv').config()@@ -45,17 +43,11 @@ const clickhouse = new ClickHouse({})const { JWT_ACCESS_TOKEN_SECRET } = process.env-const isSelfhosted = Boolean(process.env.SELFHOSTED)const isNewRelicEnabled = Boolean(process.env.USE_NEW_RELIC)const isDevelopment = process.env.NODE_ENV === 'development'const PRODUCTION_ORIGIN = process.env.CLIENT_URL || 'https://swetrix.com'-const SELFHOSTED_EMAIL = process.env.EMAIL-const SELFHOSTED_PASSWORD = process.env.PASSWORDconst UUIDV5_NAMESPACE = '912c64c1-73fd-42b6-859f-785f839a9f68'-const DEFAULT_SELFHOSTED_UUID = 'deadbeef-dead-beef-dead-beefdeadbeef'--const SELFHOSTED_UUID = isSelfhosted ? getSelfhostedUUID() : ''const { TWO_FACTOR_AUTHENTICATION_APP_NAME } = process.env@@ -125,11 +117,7 @@ export {REDIS_LOG_CUSTOM_CACHE_KEY,REDIS_SESSION_SALT_KEY,HEARTBEAT_SID_LIFE_TIME,- isSelfhosted,UUIDV5_NAMESPACE,- SELFHOSTED_EMAIL,- SELFHOSTED_PASSWORD,- SELFHOSTED_UUID,REDIS_USERS_COUNT_KEY,REDIS_PROJECTS_COUNT_KEY,REDIS_PAGEVIEWS_COUNT_KEY,@@ -149,7 +137,6 @@ export {CAPTCHA_TOKEN_LIFETIME,CAPTCHA_SECRET_KEY_LENGTH,PRODUCTION_ORIGIN,- DEFAULT_SELFHOSTED_UUID,REDIS_SSO_UUID,JWT_ACCESS_TOKEN_SECRET,}diff --git a/src/common/guards/selfhosted.guard.ts b/src/common/guards/selfhosted.guard.tsdeleted file mode 100644index cc82e13bf..000000000--- a/src/common/guards/selfhosted.guard.ts+++ /dev/null@@ -1,19 +0,0 @@-import {- Injectable,- CanActivate,- NotImplementedException,-} from '@nestjs/common'-import { isSelfhosted } from '../constants'--@Injectable()-export class SelfhostedGuard implements CanActivate {- canActivate(): boolean {- if (isSelfhosted) {- throw new NotImplementedException(- 'This API route is disabled in the Swetrix Selfhosted edition',- )- }-- return true- }-}diff --git a/src/common/utils.ts b/src/common/utils.tsindex 11e1f9df5..fde87bfed 100644--- a/src/common/utils.ts+++ b/src/common/utils.ts@@ -19,8 +19,6 @@ import * as _map from 'lodash/map'import {clickhouse,redis,- DEFAULT_SELFHOSTED_UUID,- SELFHOSTED_EMAIL,UUIDV5_NAMESPACE,isDevelopment,} from './constants'@@ -241,14 +239,6 @@ const millisecondsToSeconds = (milliseconds: number) => milliseconds / 1000const generateRandomString = (length: number): string =>randomstring.generate(length)-const getSelfhostedUUID = (): string => {- try {- return uuidv5(SELFHOSTED_EMAIL, UUIDV5_NAMESPACE)- } catch {- return DEFAULT_SELFHOSTED_UUID- }-}-export {getRandomTip,checkRateLimit,@@ -260,7 +250,6 @@ export {calculateRelativePercentage,millisecondsToSeconds,generateRandomString,- getSelfhostedUUID,saveRefreshTokenClickhouse,findRefreshTokenClickhouse,deleteRefreshTokenClickhouse,diff --git a/src/project/entity/project.entity.ts b/src/project/entity/project.entity.tsindex ff12ad7dc..f98cc3a5d 100644--- a/src/project/entity/project.entity.ts+++ b/src/project/entity/project.entity.ts@@ -15,8 +15,7 @@ import { ExtensionToProject } from '../../marketplace/extensions/entities/extensimport { ProjectSubscriber } from './project-subscriber.entity'import { CAPTCHA_SECRET_KEY_LENGTH } from '../../common/constants'-// In case of modifying some properties here, make sure to also edit them in common/constants.ts -> selfhosted -> clickhouse-// and to add them to the GDPR data export email template+// In case of modifying some properties here add them to the GDPR data export email template@Entity()export class Project {@ApiProperty()diff --git a/src/project/project.controller.ts b/src/project/project.controller.tsindex 747af8629..86bb1a3ab 100644--- a/src/project/project.controller.ts+++ b/src/project/project.controller.ts@@ -43,7 +43,6 @@ import { ActionTokensService } from '../action-tokens/action-tokens.service'import { MailerService } from '../mailer/mailer.service'import { LetterTemplate } from '../mailer/letter'import { Roles } from '../auth/decorators/roles.decorator'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import { RolesGuard } from '../auth/guards/roles.guard'import { Pagination } from '../common/pagination/pagination'import { Project } from './entity/project.entity'@@ -57,7 +56,6 @@ import { AppLoggerService } from '../logger/logger.service'import {isValidPID,clickhouse,- isSelfhosted,PROJECT_INVITE_EXPIRE,CAPTCHA_SECRET_KEY_LENGTH,isDevelopment,@@ -122,16 +120,6 @@ export class ProjectController {this.logger.log({ userId, take, skip }, 'GET /project')const isCaptcha = isCaptchaStr === 'true'- if (isSelfhosted) {- const results = await getProjectsClickhouse()- const formatted = _map(results, this.projectService.formatFromClickhouse)- return {- results: formatted,- page_total: _size(formatted),- total: _size(formatted),- totalMonthlyEvents: 0, // not needed as it's selfhosed- }- }const where = Object()where.admin = userId@@ -162,12 +150,6 @@ export class ProjectController {async getNames(@CurrentUserId() userId: string): Promise<Project[]> {this.logger.log({ userId }, 'GET /project/names')- if (isSelfhosted) {- const results = await getProjectsClickhouse()- const formatted = _map(results, this.projectService.formatFromClickhouse)- return formatted- }-const where = Object()where.admin = userId@@ -185,7 +167,6 @@ export class ProjectController {@ApiQuery({ name: 'skip', required: false })@ApiQuery({ name: 'relatedonly', required: false, type: Boolean })@ApiResponse({ status: 200, type: [Project] })- @UseGuards(SelfhostedGuard)@Auth([UserType.CUSTOMER, UserType.ADMIN], true)async getShared(@CurrentUserId() userId: string,@@ -208,7 +189,6 @@ export class ProjectController {@Get('/all')@ApiQuery({ name: 'take', required: false })@ApiQuery({ name: 'skip', required: false })- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Auth([UserType.ADMIN])@ApiResponse({ status: 200, type: Project })@@ -227,7 +207,6 @@ export class ProjectController {@ApiQuery({ name: 'skip', required: false })@ApiQuery({ name: 'relatedonly', required: false, type: Boolean })@ApiResponse({ status: 200, type: [Project] })- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN)async getUserProject(@@ -251,7 +230,6 @@ export class ProjectController {@Post('/admin/:id')@ApiResponse({ status: 201, type: Project })- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.ADMIN)async createForAdmin(@@ -314,22 +292,6 @@ export class ProjectController {): Promise<Project> {this.logger.log({ projectDTO, userId }, 'POST /project')- if (isSelfhosted) {- const projects = await getProjectsClickhouse()-- this.projectService.validateProject(projectDTO)- this.projectService.checkIfIDUniqueClickhouse(projects, projectDTO.id)-- const project = new Project()- Object.assign(project, projectDTO)- project.origins = _map(projectDTO.origins, _trim)- project.ipBlacklist = _map(projectDTO.ipBlacklist, _trim)- project.active = true-- await createProjectClickhouse(project)-- return project- }const user = await this.userService.findOneWithRelations(userId, ['projects',])@@ -424,19 +386,6 @@ export class ProjectController {)}- if (isSelfhosted) {- const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`- const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`-- try {- await clickhouse.query(query1).toPromise()- await clickhouse.query(query2).toPromise()- return 'Project resetted successfully'- } catch (e) {- this.logger.error(e)- return 'Error while resetting your project'- }- } else {const user = await this.userService.findOne(uid)const project = await this.projectService.findOneWhere({ id },@@ -463,12 +412,11 @@ export class ProjectController {this.logger.error(e)return 'Error while resetting your project'}- }}@Delete('/captcha/reset/:id')@HttpCode(204)- @UseGuards(SelfhostedGuard, JwtAccessTokenGuard, RolesGuard)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 204, description: 'Empty body' })async resetCAPTCHA(@@ -510,7 +458,7 @@ export class ProjectController {@Post('/secret-gen/:pid')@HttpCode(200)- @UseGuards(SelfhostedGuard, JwtAccessTokenGuard, RolesGuard)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 200, description: 'A regenerated CAPTCHA secret key' })async secretGen(@@ -548,7 +496,7 @@ export class ProjectController {@Delete('/captcha/:id')@HttpCode(204)- @UseGuards(SelfhostedGuard, JwtAccessTokenGuard, RolesGuard)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 204, description: 'Empty body' })async deleteCAPTCHA(@@ -639,12 +587,7 @@ export class ProjectController {throw new BadRequestException("The provided 'to' date is incorrect")}- let project-- if (isSelfhosted) {- project = getProjectsClickhouse(pid)- } else {- project = await this.projectService.findOne(pid, {+ const project = await this.projectService.findOne(pid, {relations: ['admin', 'share'],})@@ -653,7 +596,6 @@ export class ProjectController {}this.projectService.allowedToManage(project, uid)- }from = dayjs(from).format('YYYY-MM-DD')to = dayjs(to).format('YYYY-MM-DD 23:59:59')@@ -663,7 +605,7 @@ export class ProjectController {@Post('/:pid/share')@HttpCode(200)- @UseGuards(SelfhostedGuard, JwtAccessTokenGuard, RolesGuard)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 200, type: Project })async share(@@ -785,7 +727,7 @@ export class ProjectController {@Put('/share/:shareId')@HttpCode(200)- @UseGuards(SelfhostedGuard, JwtAccessTokenGuard, RolesGuard)+ @UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 200, type: Project })async updateShare(@@ -824,7 +766,6 @@ export class ProjectController {}@HttpCode(204)- @UseGuards(SelfhostedGuard)// @UseGuards(JwtAccessTokenGuard, RolesGuard)// @Roles(UserType.CUSTOMER, UserType.ADMIN)@Public()@@ -860,7 +801,6 @@ export class ProjectController {}@Post('transfer')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async transferProject(@Body() body: TransferProjectBodyDto,@@ -898,7 +838,6 @@ export class ProjectController {}@Get('transfer')- @UseGuards(SelfhostedGuard)async confirmTransferProject(@Query() queries: ConfirmTransferProjectQueriesDto,) {@@ -932,7 +871,6 @@ export class ProjectController {}@Delete('transfer')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async cancelTransferProject(@Query() queries: CancelTransferProjectQueriesDto,@@ -962,7 +900,6 @@ export class ProjectController {}@Delete(':projectId/subscribers/:subscriberId')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async removeSubscriber(@Param() params: RemoveSubscriberParamsDto,@@ -998,7 +935,6 @@ export class ProjectController {}@Post(':projectId/subscribers')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async addSubscriber(@Param() params: AddSubscriberParamsDto,@@ -1042,7 +978,6 @@ export class ProjectController {}@Get(':projectId/subscribers/invite')- @UseGuards(SelfhostedGuard)@HttpCode(HttpStatus.OK)async confirmSubscriberInvite(@Param() params: ConfirmSubscriberInviteParamsDto,@@ -1087,7 +1022,6 @@ export class ProjectController {}@Get(':projectId/subscribers')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async getSubscribers(@Param() params: GetSubscribersParamsDto,@@ -1108,7 +1042,6 @@ export class ProjectController {}@Patch(':projectId/subscribers/:subscriberId')- @UseGuards(SelfhostedGuard)@Auth([UserType.ADMIN, UserType.CUSTOMER])async updateSubscriber(@Param() params: UpdateSubscriberParamsDto,@@ -1160,22 +1093,6 @@ export class ProjectController {'The provided Project ID (pid) is incorrect',)}-- if (isSelfhosted) {- await deleteProjectClickhouse(id)-- const query1 = `ALTER table analytics DELETE WHERE pid='${id}'`- const query2 = `ALTER table customEV DELETE WHERE pid='${id}'`-- try {- 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 user = await this.userService.findOne(uid)const project = await this.projectService.findOneWhere({ id },@@ -1218,7 +1135,6 @@ export class ProjectController {}return 'Project deleted successfully'- }}@Put('captcha/inherited/:id')@@ -1287,25 +1203,7 @@ export class ProjectController {): Promise<any> {this.logger.log({ projectDTO, uid, id }, 'PUT /project/:id')this.projectService.validateProject(projectDTO)- let project-- if (isSelfhosted) {- const chProject = await getProjectsClickhouse(id)-- if (_isEmpty(chProject)) {- throw new NotFoundException()- }- chProject.active = projectDTO.active- chProject.origins = _map(projectDTO.origins, _trim)- chProject.ipBlacklist = _map(projectDTO.ipBlacklist, _trim)- chProject.name = projectDTO.name- chProject.public = projectDTO.public-- await updateProjectClickhouse(- this.projectService.formatToClickhouse(chProject),- )- } else {- project = await this.projectService.findOne(id, {+ const project = await this.projectService.findOne(id, {relations: ['admin', 'share', 'share.user'],})const user = await this.userService.findOne(uid)@@ -1323,7 +1221,6 @@ export class ProjectController {project.public = projectDTO.publicawait this.projectService.update(id, _omit(project, ['share', 'admin']))- }// await updateProjectRedis(id, project)await deleteProjectRedis(id)@@ -1334,7 +1231,6 @@ export class ProjectController {// The routes related to sharing projects feature@Delete('/:pid/:shareId')@HttpCode(204)- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 204, description: 'Empty body' })@@ -1385,15 +1281,9 @@ export class ProjectController {)}- let project-- if (isSelfhosted) {- project = await getProjectsClickhouse(id)- } else {- project = await this.projectService.findOne(id, {+ const project = await this.projectService.findOne(id, {relations: ['admin'],})- }if (_isEmpty(project)) {throw new NotFoundException('Project was not found in the database')@@ -1401,10 +1291,6 @@ export class ProjectController {this.projectService.allowedToView(project, uid)- if (isSelfhosted) {- return this.projectService.formatFromClickhouse(project)- }-return {..._omit(project, ['admin']),isOwner: uid === project.admin?.id,diff --git a/src/project/project.service.ts b/src/project/project.service.tsindex 939c22c36..7a479bd18 100644--- a/src/project/project.service.ts+++ b/src/project/project.service.ts@@ -41,7 +41,6 @@ import {getRedisUserCountKey,redis,clickhouse,- isSelfhosted,IP_REGEX,ORIGINS_REGEX,getRedisProjectKey,@@ -127,9 +126,6 @@ export class ProjectService {let project: string | Project = await redis.get(pidKey)if (_isEmpty(project)) {- if (isSelfhosted) {- project = this.formatFromClickhouse(await getProjectsClickhouse(pid))- } else {// todo: optimise the relations - select// select only required columns// https://stackoverflow.com/questions/59645009/how-to-return-only-some-columns-of-a-relations-with-typeorm@@ -145,13 +141,11 @@ export class ProjectService {'isCaptchaEnabled',],})- }if (_isEmpty(project))throw new BadRequestException('The provided Project ID (pid) is incorrect',)- if (!isSelfhosted) {const share = await this.findShare({where: {project: pid,@@ -160,7 +154,6 @@ export class ProjectService {})// @ts-ignoreproject = { ...project, share }- }await redis.set(pidKey,@@ -456,10 +449,6 @@ export class ProjectService {.format('YYYY-MM-DD HH:mm:ss')const monthEnd = dayjs.utc().endOf('month').format('YYYY-MM-DD HH:mm:ss')- if (isSelfhosted) {- // selfhosted has no limits- return 0- }const pids = await this.find({where: {admin: uid,diff --git a/src/task-manager/task-manager.service.ts b/src/task-manager/task-manager.service.tsindex 9d6076544..5dfa0722c 100644--- a/src/task-manager/task-manager.service.ts+++ b/src/task-manager/task-manager.service.ts@@ -36,7 +36,6 @@ import {redis,REDIS_LOG_DATA_CACHE_KEY,REDIS_LOG_CUSTOM_CACHE_KEY,- isSelfhosted,REDIS_SESSION_SALT_KEY,REDIS_USERS_COUNT_KEY,REDIS_PROJECTS_COUNT_KEY,@@ -240,10 +239,6 @@ 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,@@ -294,10 +289,6 @@ 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,@@ -347,10 +338,6 @@ export class TaskManagerService {@Cron(CronExpression.EVERY_QUARTER)async quarterlyReportsHandler(): Promise<void> {- if (isSelfhosted) {- return- }-const users = await this.userService.find({where: {reportFrequency: ReportFrequency.QUARTERLY,@@ -530,10 +517,6 @@ export class TaskManagerService {@Cron(CronExpression.EVERY_10_MINUTES)async getGeneralStats(): Promise<object> {- if (isSelfhosted) {- return {}- }-const PVquery = 'SELECT count(*) from analytics'const CEquery = 'SELECT count(*) from customEV'const PFquery = 'SELECT count(*) from performance'diff --git a/src/twoFactorAuth/twoFactorAuth.controller.ts b/src/twoFactorAuth/twoFactorAuth.controller.tsindex 033dcebfa..af880e89a 100644--- a/src/twoFactorAuth/twoFactorAuth.controller.ts+++ b/src/twoFactorAuth/twoFactorAuth.controller.ts@@ -18,7 +18,6 @@ import { UserType } from '../user/entities/user.entity'import { AppLoggerService } from '../logger/logger.service'import { MailerService } from '../mailer/mailer.service'import { LetterTemplate } from '../mailer/letter'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import { TwoFaNotRequired, Roles, CurrentUserId } from '../auth/decorators'import { RolesGuard } from '../auth/guards/roles.guard'import { TwoFactorAuthDTO } from './dto/2fa-auth.dto'@@ -37,7 +36,6 @@ export class TwoFactorAuthController {@Post('generate')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)@TwoFaNotRequired()async register(@CurrentUserId() id: string) {@@ -48,7 +46,6 @@ export class TwoFactorAuthController {@Post('enable')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)@TwoFaNotRequired()async turnOnTwoFactorAuthentication(@@ -98,7 +95,6 @@ export class TwoFactorAuthController {@Post('disable')@HttpCode(200)@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)async turnOffTwoFactorAuthentication(@Body() body: TwoFactorAuthDTO,@@ -138,7 +134,6 @@ export class TwoFactorAuthController {@Post('authenticate')@HttpCode(200)@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted@Roles(UserType.CUSTOMER, UserType.ADMIN)@TwoFaNotRequired()async authenticate(diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.tsindex 1c471371b..293757442 100644--- a/src/user/entities/user.entity.ts+++ b/src/user/entities/user.entity.ts@@ -14,7 +14,6 @@ import { ExtensionToUser } from '../../marketplace/extensions/entities/extensionimport { Comment } from '../../marketplace/comments/entities/comment.entity'import { Complaint } from '../../marketplace/complaints/entities/complaint.entity'import { RefreshToken } from './refresh-token.entity'-import { SELFHOSTED_EMAIL, SELFHOSTED_UUID } from '../../common/constants'export enum PlanCode {none = 'none',@@ -133,24 +132,6 @@ export const DEFAULT_TIMEZONE = 'Etc/GMT'export const TRIAL_DURATION = 14 // days-export interface SelfhostedUser {- id: string- email: string- isTwoFactorAuthenticationEnabled: boolean- planCode: PlanCode- roles: UserType[]- isActive: boolean-}--export const generateSelfhostedUser = (): SelfhostedUser => ({- id: SELFHOSTED_UUID,- email: SELFHOSTED_EMAIL,- isTwoFactorAuthenticationEnabled: false,- planCode: PlanCode.enterprise,- roles: [UserType.ADMIN, UserType.CUSTOMER],- isActive: true,-})-@Entity()export class User {@PrimaryGeneratedColumn('uuid')diff --git a/src/user/user.controller.ts b/src/user/user.controller.tsindex e190d50bf..1309261a9 100644--- a/src/user/user.controller.ts+++ b/src/user/user.controller.ts@@ -40,19 +40,16 @@ import {MAX_EMAIL_REQUESTS,PlanCode,Theme,- generateSelfhostedUser,} from './entities/user.entity'import { Roles } from '../auth/decorators/roles.decorator'import { Pagination } from '../common/pagination/pagination'import {GDPR_EXPORT_TIMEFRAME,clickhouse,- isSelfhosted,isDevelopment,PRODUCTION_ORIGIN,} from '../common/constants'import { RolesGuard } from '../auth/guards/roles.guard'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'import { UpdateUserProfileDTO } from './dto/update-user.dto'import { AdminUpdateUserProfileDTO } from './dto/admin-update-user.dto'import { CurrentUserId } from '../auth/decorators/current-user-id.decorator'@@ -90,9 +87,6 @@ export class UserController {this.logger.log({ user_id }, 'GET /user/me')let user- if (isSelfhosted) {- user = generateSelfhostedUser()- } else {const sharedProjects = await this.projectService.findShare({where: {user: user_id,@@ -104,7 +98,6 @@ export class UserController {)user.sharedProjects = sharedProjects- }return this.userService.omitSensitiveData(user)}@@ -113,7 +106,6 @@ export class UserController {@ApiQuery({ name: 'take', required: false })@ApiQuery({ name: 'skip', required: false })@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.ADMIN)async get(@Query('take') take: number | undefined,@@ -125,7 +117,6 @@ export class UserController {@Put('/theme')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async setTheme(@CurrentUserId() userId: string,@@ -137,7 +128,6 @@ export class UserController {@Get('/search')@ApiQuery({ name: 'query', required: false })@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.ADMIN)async searchUsers(@Query('query') query: string | undefined,@@ -148,7 +138,6 @@ export class UserController {@Post('/')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.ADMIN)async create(@Body() userDTO: UserProfileDTO): Promise<User | null> {this.logger.log({ userDTO }, 'POST /user')@@ -171,7 +160,6 @@ export class UserController {@Post('/api-key')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async generateApiKey(@CurrentUserId() userId: string,@@ -202,7 +190,6 @@ export class UserController {@Delete('/api-key')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async deleteApiKey(@CurrentUserId() userId: string): Promise<void> {this.logger.log({ userId }, 'DELETE /user/api-key')@@ -219,7 +206,6 @@ export class UserController {@Delete('/:id')@HttpCode(204)@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.ADMIN)async delete(@Param('id') id: string,@@ -263,7 +249,6 @@ export class UserController {@Delete('/')@HttpCode(204)@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async deleteSelf(@CurrentUserId() id: string): Promise<any> {this.logger.log({ id }, 'DELETE /user')@@ -301,7 +286,6 @@ export class UserController {@Delete('/share/:shareId')@HttpCode(204)- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 204, description: 'Empty body' })@@ -331,7 +315,6 @@ export class UserController {@Get('/share/:shareId')@HttpCode(204)- @UseGuards(SelfhostedGuard)@UseGuards(JwtAccessTokenGuard, RolesGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@ApiResponse({ status: 204, description: 'Empty body' })@@ -363,7 +346,6 @@ export class UserController {@Post('/confirm_email')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async sendEmailConfirmation(@CurrentUserId() id: string,@@ -399,7 +381,6 @@ export class UserController {@Put('/:id')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.ADMIN)async update(@Body() userDTO: AdminUpdateUserProfileDTO,@@ -435,7 +416,6 @@ export class UserController {@Delete('/tg/:id')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)@HttpCode(204)async deleteTelegramConnection(@@ -456,7 +436,6 @@ export class UserController {@Put('/')@UseGuards(JwtAccessTokenGuard, RolesGuard)- @UseGuards(SelfhostedGuard)@Roles(UserType.CUSTOMER, UserType.ADMIN)async updateCurrentUser(@Body() userDTO: UpdateUserProfileDTO,@@ -581,7 +560,6 @@ export class UserController {@Get('/export')@UseGuards(JwtAccessTokenGuard, 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.tsindex 4db403cca..e0655b449 100644--- a/src/webhook/webhook.controller.ts+++ b/src/webhook/webhook.controller.ts@@ -20,7 +20,6 @@ import {import { UserService } from '../user/user.service'import { AppLoggerService } from '../logger/logger.service'import { WebhookService } from './webhook.service'-import { SelfhostedGuard } from '../common/guards/selfhosted.guard'const MAX_PAYMENT_ATTEMPTS = 5@@ -34,7 +33,6 @@ export class WebhookController {private readonly projectService: ProjectService,) {}- @UseGuards(SelfhostedGuard)@Post('/paddle')async paddleWebhook(@Body() body,