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!

Added 2FA support

Blue Mouse13f4b81c187c
diff --git a/.env.example b/.env.example
index ae9a1a411..b6a09aa1f 100644
--- a/.env.example
+++ b/.env.example
@@ -1,5 +1,6 @@
# Auth
JWT_SECRET=SOME_SECRET_TOKEN
+TWO_FACTOR_AUTHENTICATION_APP_NAME=Swetrix
# Database
MYSQL_HOST=localhost
diff --git a/package.json b/package.json
index fdcdf87b4..45abb1daf 100644
--- a/package.json
+++ b/package.json
@@ -51,10 +51,12 @@
"lodash": "^4.17.21",
"mysql": "^2.18.1",
"nodemailer": "^6.7.3",
+ "otplib": "^12.0.1",
"passport": "^0.5.2",
"passport-jwt": "^4.0.0",
"php-serialize": "^4.0.2",
"postmark": "^3.0.1",
+ "qrcode": "^1.5.0",
"reflect-metadata": "^0.1.13",
"rimraf": "^3.0.2",
"rxjs": "^7.5.5",
diff --git a/src/app.module.ts b/src/app.module.ts
index 05ecbfd6b..1a9c873bb 100644
--- a/src/app.module.ts
+++ b/src/app.module.ts
@@ -11,6 +11,7 @@ import { Project } from './project/entity/project.entity'
import { ProjectModule } from './project/project.module'
import { MailerModule } from './mailer/mailer.module'
import { ActionTokensModule } from './action-tokens/action-tokens.module'
+import { TwoFactorAuthModule } from './twoFactorAuth/twoFactorAuth.module'
import { ActionToken } from './action-tokens/action-token.entity'
import { ProjectShare } from './project/entity/project-share.entity'
import { TaskManagerModule } from './task-manager/task-manager.module'
@@ -36,6 +37,7 @@ import { PingModule } from './ping/ping.module'
UserModule,
MailerModule,
ActionTokensModule,
+ TwoFactorAuthModule,
ProjectModule,
AnalyticsModule,
WebhookModule,
diff --git a/src/auth/auth.controller.ts b/src/auth/auth.controller.ts
index b5efd6ec2..e9d51f5e2 100644
--- a/src/auth/auth.controller.ts
+++ b/src/auth/auth.controller.ts
@@ -1,7 +1,7 @@
import {
Controller, Post, Body, Req, Get, Param, BadRequestException, UseGuards, Ip, Headers, UnprocessableEntityException,
} from '@nestjs/common'
-import e, { Request } from 'express'
+import { Request } from 'express'
import { ApiTags } from '@nestjs/swagger'
import { AuthService } from './auth.service'
diff --git a/src/auth/auth.service.ts b/src/auth/auth.service.ts
index 65832d45d..0672b5e16 100644
--- a/src/auth/auth.service.ts
+++ b/src/auth/auth.service.ts
@@ -110,7 +110,7 @@ export class AuthService {
return userData
}
- login(user: User | object): object {
+ login(user: User | object, isSecondFactorAuthenticated = false): object {
let userData = user
if (isSelfhosted) {
@@ -125,7 +125,7 @@ export class AuthService {
}
// @ts-ignore
- const token = sign({ user_id: userData.id }, process.env.JWT_SECRET, {
+ const token = sign({ user_id: userData.id, isSecondFactorAuthenticated }, process.env.JWT_SECRET, {
expiresIn: JWT_LIFE_TIME,
})
diff --git a/src/common/constants.ts b/src/common/constants.ts
index 61844ea0d..ddaa7ac23 100644
--- a/src/common/constants.ts
+++ b/src/common/constants.ts
@@ -103,6 +103,7 @@ const SELFHOSTED_EMAIL = process.env.EMAIL
const SELFHOSTED_PASSWORD = process.env.PASSWORD
const UUIDV5_NAMESPACE = '912c64c1-73fd-42b6-859f-785f839a9f68'
const SELFHOSTED_UUID = isSelfhosted ? uuidv5(SELFHOSTED_EMAIL, UUIDV5_NAMESPACE) : ''
+const TWO_FACTOR_AUTHENTICATION_APP_NAME = process.env.TWO_FACTOR_AUTHENTICATION_APP_NAME
/**
* Calculates in percent, the change between 2 numbers.
@@ -167,5 +168,5 @@ export {
GDPR_EXPORT_TIMEFRAME, getRedisUserCountKey, redisProjectCountCacheTimeout, REDIS_LOG_CUSTOM_CACHE_KEY,
REDIS_SESSION_SALT_KEY, HEARTBEAT_SID_LIFE_TIME, isSelfhosted, UUIDV5_NAMESPACE, SELFHOSTED_EMAIL,
SELFHOSTED_PASSWORD, SELFHOSTED_UUID, CLICKHOUSE_INIT_QUERIES, REDIS_USERS_COUNT_KEY, REDIS_PROJECTS_COUNT_KEY,
- REDIS_PAGEVIEWS_COUNT_KEY, SEND_WARNING_AT_PERC, PROJECT_INVITE_EXPIRE,
+ REDIS_PAGEVIEWS_COUNT_KEY, SEND_WARNING_AT_PERC, PROJECT_INVITE_EXPIRE, TWO_FACTOR_AUTHENTICATION_APP_NAME,
}
diff --git a/src/common/decorators/2fa-disabled.decorator.ts b/src/common/decorators/2fa-disabled.decorator.ts
new file mode 100644
index 000000000..cb5e944f8
--- /dev/null
+++ b/src/common/decorators/2fa-disabled.decorator.ts
@@ -0,0 +1,6 @@
+import { SetMetadata, CustomDecorator } from '@nestjs/common'
+
+/**
+ * Should be applied to controllers where user has to be authenticated but 2FA is not required.
+ */
+export const TwoFaNotRequired = (): CustomDecorator<string> => SetMetadata('twoFaNotRequired', true)
diff --git a/src/common/guards/roles.guard.ts b/src/common/guards/roles.guard.ts
index 1c95552b0..4b17ddff5 100644
--- a/src/common/guards/roles.guard.ts
+++ b/src/common/guards/roles.guard.ts
@@ -18,6 +18,7 @@ export class RolesGuard implements CanActivate {
async canActivate(context: ExecutionContext): Promise<boolean> {
const secret = process.env.JWT_SECRET
const roles = this.reflector.get<string[]>('roles', context.getHandler())
+ const twoFaNotRequired = this.reflector.get<boolean>('twoFaNotRequired', context.getHandler())
if (!roles || isSelfhosted) {
return true
}
@@ -36,7 +37,16 @@ export class RolesGuard implements CanActivate {
if (decoded) {
let user: User = await this.userService.findOneWhere({ id: decoded.user_id })
const hasRole = user.roles.some(role => !!roles.find(item => item === role))
- return hasRole
+
+ if (!hasRole) {
+ throw new Error()
+ }
+
+ if (!twoFaNotRequired && user.isTwoFactorAuthenticationEnabled && !decoded.isSecondFactorAuthenticated) {
+ throw new Error()
+ }
+
+ return true
}
} catch {
throw new UnauthorizedException()
diff --git a/src/twoFactorAuth/dto/2fa-auth.dto.ts b/src/twoFactorAuth/dto/2fa-auth.dto.ts
new file mode 100644
index 000000000..e6ae4013d
--- /dev/null
+++ b/src/twoFactorAuth/dto/2fa-auth.dto.ts
@@ -0,0 +1,8 @@
+import { ApiProperty } from '@nestjs/swagger'
+import { IsNotEmpty } from 'class-validator'
+
+export class TwoFactorAuthDTO {
+ @ApiProperty({ example: '123456', required: true })
+ @IsNotEmpty()
+ twoFactorAuthenticationCode: string
+}
diff --git a/src/twoFactorAuth/twoFactorAuth.controller.spec.ts b/src/twoFactorAuth/twoFactorAuth.controller.spec.ts
new file mode 100644
index 000000000..22d6f2292
--- /dev/null
+++ b/src/twoFactorAuth/twoFactorAuth.controller.spec.ts
@@ -0,0 +1,18 @@
+import { Test, TestingModule } from '@nestjs/testing'
+import { TwoFactorAuthController } from './twoFactorAuth.controller'
+
+describe('TwoFactorAuthController', () => {
+ let controller: TwoFactorAuthController
+
+ beforeEach(async () => {
+ const module: TestingModule = await Test.createTestingModule({
+ controllers: [TwoFactorAuthController],
+ }).compile()
+
+ controller = module.get<TwoFactorAuthController>(TwoFactorAuthController)
+ })
+
+ it('should be defined', () => {
+ expect(controller).toBeDefined()
+ })
+})
diff --git a/src/twoFactorAuth/twoFactorAuth.controller.ts b/src/twoFactorAuth/twoFactorAuth.controller.ts
new file mode 100644
index 000000000..ec291cd21
--- /dev/null
+++ b/src/twoFactorAuth/twoFactorAuth.controller.ts
@@ -0,0 +1,92 @@
+import {
+ Controller, Post, Res, UseGuards, HttpCode, Body, UnauthorizedException,
+} from '@nestjs/common'
+import { ApiTags } from '@nestjs/swagger'
+import { Response } from 'express'
+
+import { TwoFactorAuthService } from './twoFactorAuth.service'
+import { UserService } from '../user/user.service'
+import { AuthService } from 'src/auth/auth.service'
+import { UserType } from '../user/entities/user.entity'
+import { ActionTokensService } from '../action-tokens/action-tokens.service'
+import { AppLoggerService } from '../logger/logger.service'
+import { CurrentUserId } from 'src/common/decorators/current-user-id.decorator'
+import { SelfhostedGuard } from '../common/guards/selfhosted.guard'
+import { Roles } from '../common/decorators/roles.decorator'
+import { TwoFaNotRequired } from '../common/decorators/2fa-disabled.decorator'
+import { RolesGuard } from 'src/common/guards/roles.guard'
+import { TwoFactorAuthDTO } from './dto/2fa-auth.dto'
+import {
+ isSelfhosted, SELFHOSTED_EMAIL, SELFHOSTED_PASSWORD, SELFHOSTED_UUID,
+} from 'src/common/constants'
+
+@ApiTags('2fa')
+@Controller('2fa')
+export class TwoFactorAuthController {
+ constructor(
+ private twoFactorAuthService: TwoFactorAuthService,
+ private userService: UserService,
+ private authService: AuthService,
+ private actionTokensService: ActionTokensService,
+ private readonly logger: AppLoggerService
+ ) {}
+
+ @Post('generate')
+ @UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @TwoFaNotRequired()
+ async register(@Res() response: Response, @CurrentUserId() id: string) {
+ const user = await this.userService.findOneWhere({ id })
+
+ const { otpauthUrl } = await this.twoFactorAuthService.generateTwoFactorAuthenticationSecret(user)
+
+ return this.twoFactorAuthService.pipeQrCodeStream(response, otpauthUrl)
+ }
+
+ @Post('enable')
+ @HttpCode(200)
+ @UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @TwoFaNotRequired()
+ async turnOnTwoFactorAuthentication(@Body() body: TwoFactorAuthDTO, @CurrentUserId() id: string) {
+ this.logger.log({ body }, 'POST /2fa/enable')
+ const user = await this.userService.findOneWhere({ id })
+ const { twoFactorAuthenticationCode } = body
+
+ const isCodeValid = this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode, user,
+ )
+
+ if (!isCodeValid) {
+ throw new UnauthorizedException('Wrong authentication code')
+ }
+
+ await this.userService.update(user.id, {
+ isTwoFactorAuthenticationEnabled: true,
+ })
+ }
+
+ @Post('authenticate')
+ @HttpCode(200)
+ @UseGuards(RolesGuard)
+ @UseGuards(SelfhostedGuard) // temporary this feature is not available for selfhosted
+ @Roles(UserType.CUSTOMER, UserType.ADMIN)
+ @TwoFaNotRequired()
+ async authenticate(@Body() body: TwoFactorAuthDTO, @CurrentUserId() id: string) {
+ this.logger.log({ body }, 'POST /2fa/authenticate')
+ const user = await this.userService.findOneWhere({ id })
+ const { twoFactorAuthenticationCode } = body
+
+ const isCodeValid = this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode, user,
+ )
+
+ if (!isCodeValid) {
+ throw new UnauthorizedException('Wrong authentication code')
+ }
+
+ return this.authService.login(user, true)
+ }
+}
diff --git a/src/twoFactorAuth/twoFactorAuth.module.ts b/src/twoFactorAuth/twoFactorAuth.module.ts
new file mode 100644
index 000000000..215f835b9
--- /dev/null
+++ b/src/twoFactorAuth/twoFactorAuth.module.ts
@@ -0,0 +1,20 @@
+import { Module } from '@nestjs/common'
+import { TwoFactorAuthService } from './twoFactorAuth.service'
+import { UserModule } from '../user/user.module'
+import { AuthModule } from 'src/auth/auth.module'
+import { TwoFactorAuthController } from './twoFactorAuth.controller'
+import { ActionTokensModule } from '../action-tokens/action-tokens.module'
+import { AppLoggerModule } from '../logger/logger.module'
+
+@Module({
+ imports: [
+ UserModule,
+ ActionTokensModule,
+ AppLoggerModule,
+ AuthModule,
+ ],
+ controllers: [TwoFactorAuthController],
+ providers: [TwoFactorAuthService],
+ exports: [TwoFactorAuthService],
+})
+export class TwoFactorAuthModule {}
diff --git a/src/twoFactorAuth/twoFactorAuth.service.ts b/src/twoFactorAuth/twoFactorAuth.service.ts
new file mode 100644
index 000000000..65b6e2c09
--- /dev/null
+++ b/src/twoFactorAuth/twoFactorAuth.service.ts
@@ -0,0 +1,44 @@
+import { Injectable } from '@nestjs/common'
+import { authenticator } from 'otplib'
+import { toFileStream } from 'qrcode'
+import { Response } from 'express'
+
+import { UserService } from '../user/user.service'
+import { User } from '../user/entities/user.entity'
+import { AppLoggerService } from '../logger/logger.service'
+import {
+ TWO_FACTOR_AUTHENTICATION_APP_NAME,
+} from '../common/constants'
+
+@Injectable()
+export class TwoFactorAuthService {
+ constructor(
+ private userService: UserService,
+ private readonly logger: AppLoggerService
+ ) { }
+
+ async generateTwoFactorAuthenticationSecret(user: User) {
+ const secret = authenticator.generateSecret()
+ const otpauthUrl = authenticator.keyuri(user.id, TWO_FACTOR_AUTHENTICATION_APP_NAME, secret)
+
+ await this.userService.update(user.id, {
+ twoFactorAuthenticationSecret: secret,
+ })
+
+ return {
+ secret,
+ otpauthUrl,
+ }
+ }
+
+ async pipeQrCodeStream(stream: Response, otpauthUrl: string) {
+ return toFileStream(stream, otpauthUrl)
+ }
+
+ isTwoFactorAuthenticationCodeValid(twoFactorAuthenticationCode: string, user: User) {
+ return authenticator.verify({
+ token: twoFactorAuthenticationCode,
+ secret: user.twoFactorAuthenticationSecret,
+ })
+ }
+}
diff --git a/src/user/entities/user.entity.ts b/src/user/entities/user.entity.ts
index 46f24f0e0..adada4351 100644
--- a/src/user/entities/user.entity.ts
+++ b/src/user/entities/user.entity.ts
@@ -126,6 +126,12 @@ export class User {
@Column('varchar', { length: 50, default: DEFAULT_TIMEZONE })
timezone: string
+ @Column('varchar', { length: 32, nullable: true })
+ twoFactorAuthenticationSecret: string
+
+ @Column({ default: false })
+ isTwoFactorAuthenticationEnabled: boolean
+
@BeforeUpdate()
updateTimestamp() {
this.updated = new Date