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!

2FA support for community edition

Blue Mousec083631c5740
diff --git a/backend/apps/community/src/app.module.ts b/backend/apps/community/src/app.module.ts
index 05526d7f8..73481f249 100644
--- a/backend/apps/community/src/app.module.ts
+++ b/backend/apps/community/src/app.module.ts
@@ -15,6 +15,7 @@ import { FeatureFlagModule } from './feature-flag/feature-flag.module'
import { CaptchaModule } from './captcha/captcha.module'
import { getI18nConfig } from './configs'
import { AuthModule } from './auth/auth.module'
+import { TwoFactorAuthModule } from './twoFactorAuth/twoFactorAuth.module'
import { AppController } from './app.controller'
import { isPrimaryNode } from './common/utils'
import { MailerModule } from './mailer/mailer.module'
@@ -71,6 +72,7 @@ const modules = [
FeatureFlagModule,
CaptchaModule,
AuthModule,
+ TwoFactorAuthModule,
]
@Module({
diff --git a/backend/apps/community/src/auth/auth.controller.ts b/backend/apps/community/src/auth/auth.controller.ts
index 20a164eb2..b15980876 100644
--- a/backend/apps/community/src/auth/auth.controller.ts
+++ b/backend/apps/community/src/auth/auth.controller.ts
@@ -161,6 +161,15 @@ export class AuthController {
throw new ConflictException(i18n.t('auth.invalidCredentials'))
}
+ if (user.isTwoFactorAuthenticationEnabled) {
+ const jwtTokens = await this.authService.generateJwtTokens(user.id, false)
+
+ return {
+ ...jwtTokens,
+ user: this.userService.omitSensitiveData(user),
+ }
+ }
+
const jwtTokens = await this.authService.generateJwtTokens(user.id, true)
return {
@@ -328,7 +337,10 @@ export class AuthController {
throw new ConflictException(i18n.t('auth.invalidRefreshToken'))
}
- const accessToken = await this.authService.generateJwtAccessToken(user.id)
+ const accessToken = await this.authService.generateJwtAccessToken(
+ user.id,
+ true,
+ )
return { accessToken }
}
diff --git a/backend/apps/community/src/auth/auth.service.ts b/backend/apps/community/src/auth/auth.service.ts
index e4e9f4da8..22edf8dee 100644
--- a/backend/apps/community/src/auth/auth.service.ts
+++ b/backend/apps/community/src/auth/auth.service.ts
@@ -550,7 +550,8 @@ export class AuthService {
throw new BadRequestException('Invalid user ID')
}
- const tokens = await this.generateJwtTokens(id, true)
+ const is2FAAuthenticated = !user.isTwoFactorAuthenticationEnabled
+ const tokens = await this.generateJwtTokens(id, is2FAAuthenticated)
return {
...tokens,
diff --git a/backend/apps/community/src/auth/decorators/index.ts b/backend/apps/community/src/auth/decorators/index.ts
index 4d9bad96c..896246617 100644
--- a/backend/apps/community/src/auth/decorators/index.ts
+++ b/backend/apps/community/src/auth/decorators/index.ts
@@ -2,3 +2,4 @@ export * from './current-user-id.decorator'
export * from './public.decorator'
export * from './current-user.decorator'
export * from './auth.decorator'
+export * from './two-fa-not-required.decorator'
diff --git a/backend/apps/community/src/auth/decorators/two-fa-not-required.decorator.ts b/backend/apps/community/src/auth/decorators/two-fa-not-required.decorator.ts
new file mode 100644
index 000000000..7f0839d32
--- /dev/null
+++ b/backend/apps/community/src/auth/decorators/two-fa-not-required.decorator.ts
@@ -0,0 +1,5 @@
+import { SetMetadata } from '@nestjs/common'
+
+export const IS_TWO_FA_NOT_REQUIRED_KEY = 'isTwoFaNotRequired'
+export const TwoFaNotRequired = () =>
+ SetMetadata(IS_TWO_FA_NOT_REQUIRED_KEY, true)
diff --git a/backend/apps/community/src/auth/guards/authentication.guard.ts b/backend/apps/community/src/auth/guards/authentication.guard.ts
index d8d6f812f..b4a71c7cd 100644
--- a/backend/apps/community/src/auth/guards/authentication.guard.ts
+++ b/backend/apps/community/src/auth/guards/authentication.guard.ts
@@ -1,12 +1,33 @@
-import { Injectable, CanActivate } from '@nestjs/common'
+import { Injectable, CanActivate, ExecutionContext } from '@nestjs/common'
+import { Reflector } from '@nestjs/core'
+import { IS_TWO_FA_NOT_REQUIRED_KEY } from '../decorators'
@Injectable()
export class AuthenticationGuard implements CanActivate {
- constructor() {}
+ constructor(private readonly reflector: Reflector) {}
+
+ async canActivate(context: ExecutionContext) {
+ const isTwoFaNotRequired = this.reflector.get<boolean>(
+ IS_TWO_FA_NOT_REQUIRED_KEY,
+ context.getHandler(),
+ )
+
+ const request = context.switchToHttp().getRequest()
+ const user = request.user
+
+ if (isTwoFaNotRequired) {
+ return true
+ }
+
+ if (!user) return true
+
+ if (
+ user?.isTwoFactorAuthenticationEnabled &&
+ !user?.isSecondFactorAuthenticated
+ ) {
+ return false
+ }
- async canActivate() {
- // If upstream guards authenticated a user, they set request.user.
- // If unauthenticated (including API-key or optional auth cases), allow pass-through here.
return true
}
}
diff --git a/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts b/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
index a9b8c6f09..83d788e9f 100644
--- a/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
+++ b/backend/apps/community/src/auth/strategies/jwt-access-token.strategy.ts
@@ -33,6 +33,9 @@ export class JwtAccessTokenStrategy extends PassportStrategy(
throw new UnauthorizedException()
}
- return user
+ return {
+ ...user,
+ isSecondFactorAuthenticated: payload.isSecondFactorAuthenticated,
+ }
}
}
diff --git a/backend/apps/community/src/common/constants.ts b/backend/apps/community/src/common/constants.ts
index e1f4ed70c..13a7bb4c4 100644
--- a/backend/apps/community/src/common/constants.ts
+++ b/backend/apps/community/src/common/constants.ts
@@ -50,6 +50,9 @@ export const IS_REGISTRATION_DISABLED =
const SELFHOSTED_GEOIP_DB_PATH = process.env.IP_GEOLOCATION_DB_PATH
// OIDC configuration
+const TWO_FACTOR_AUTHENTICATION_APP_NAME =
+ process.env.TWO_FACTOR_AUTHENTICATION_APP_NAME || 'Swetrix'
+
const OIDC_ENABLED = process.env.OIDC_ENABLED === 'true'
const OIDC_ONLY_AUTH = process.env.OIDC_ONLY_AUTH === 'true'
@@ -138,6 +141,7 @@ export {
PID_REGEX,
ALL_COLUMNS,
SELFHOSTED_GEOIP_DB_PATH,
+ TWO_FACTOR_AUTHENTICATION_APP_NAME,
OIDC_ENABLED,
OIDC_ONLY_AUTH,
REDIS_OIDC_SESSION_KEY,
diff --git a/backend/apps/community/src/common/templates/en/2fa-turned-off.html b/backend/apps/community/src/common/templates/en/2fa-turned-off.html
new file mode 100644
index 000000000..947d5d0ab
--- /dev/null
+++ b/backend/apps/community/src/common/templates/en/2fa-turned-off.html
@@ -0,0 +1,2 @@
+This is an email to let you know the 2FA (two-factor authentication) has been
+turned off for your Swetrix account.
diff --git a/backend/apps/community/src/common/templates/en/2fa-turned-on.html b/backend/apps/community/src/common/templates/en/2fa-turned-on.html
new file mode 100644
index 000000000..65028e06e
--- /dev/null
+++ b/backend/apps/community/src/common/templates/en/2fa-turned-on.html
@@ -0,0 +1,2 @@
+This is an email to let you know the 2FA (two-factor authentication) has been
+turned on for your Swetrix account.
diff --git a/backend/apps/community/src/common/types.ts b/backend/apps/community/src/common/types.ts
index 980e28ae8..ad1e0dd05 100644
--- a/backend/apps/community/src/common/types.ts
+++ b/backend/apps/community/src/common/types.ts
@@ -10,6 +10,9 @@ export interface ClickhouseInputUser {
onboardingStep: OnboardingStep
hasCompletedOnboarding: number
apiKey: string | null
+ twoFactorAuthenticationSecret: string | null
+ twoFactorRecoveryCode: string | null
+ isTwoFactorAuthenticationEnabled: number
}
export interface User {
@@ -22,6 +25,9 @@ export interface User {
onboardingStep: OnboardingStep
hasCompletedOnboarding: boolean
apiKey: string | null
+ twoFactorAuthenticationSecret: string | null
+ twoFactorRecoveryCode: string | null
+ isTwoFactorAuthenticationEnabled: boolean
}
export interface ClickhouseFunnel {
diff --git a/backend/apps/community/src/common/utils.ts b/backend/apps/community/src/common/utils.ts
index 386f8c723..6c6c7b5bc 100644
--- a/backend/apps/community/src/common/utils.ts
+++ b/backend/apps/community/src/common/utils.ts
@@ -109,6 +109,12 @@ export const generateRandomId = (alphabet: string, size: number) => {
export const generateRandomString = (length: number): string =>
randomstring.generate(length)
+export const generateRecoveryCode = () =>
+ randomstring.generate({
+ length: 30,
+ charset: 'alphabetic',
+ })
+
const RATE_LIMIT_REQUESTS_AMOUNT = 3
const RATE_LIMIT_TIMEOUT = 86400 // 24 hours
diff --git a/backend/apps/community/src/mailer/letter.ts b/backend/apps/community/src/mailer/letter.ts
index 2ba13b296..198b1a379 100644
--- a/backend/apps/community/src/mailer/letter.ts
+++ b/backend/apps/community/src/mailer/letter.ts
@@ -4,4 +4,6 @@ export enum LetterTemplate {
MailAddressChangeConfirmation = 'mailaddress-change_confirmation',
MailAddressHadChanged = 'mailaddress-change_information',
ProjectInvitation = 'customer_project-invitation',
+ TwoFAOn = '2fa-turned-on',
+ TwoFAOff = '2fa-turned-off',
}
diff --git a/backend/apps/community/src/mailer/mailer.service.ts b/backend/apps/community/src/mailer/mailer.service.ts
index 55b564fc7..3e08cbf3e 100644
--- a/backend/apps/community/src/mailer/mailer.service.ts
+++ b/backend/apps/community/src/mailer/mailer.service.ts
@@ -35,6 +35,16 @@ const metaInfoJson = {
en: () => 'You have been invited to join the project',
},
},
+ [LetterTemplate.TwoFAOn]: {
+ subject: {
+ en: () => '2FA has been enabled on your account',
+ },
+ },
+ [LetterTemplate.TwoFAOff]: {
+ subject: {
+ en: () => '2FA has been disabled on your account',
+ },
+ },
}
interface Params {
diff --git a/backend/apps/community/src/twoFactorAuth/dto/2fa-auth.dto.ts b/backend/apps/community/src/twoFactorAuth/dto/2fa-auth.dto.ts
new file mode 100644
index 000000000..e6ae4013d
--- /dev/null
+++ b/backend/apps/community/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/backend/apps/community/src/twoFactorAuth/twoFactorAuth.controller.ts b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.controller.ts
new file mode 100644
index 000000000..763fcb029
--- /dev/null
+++ b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.controller.ts
@@ -0,0 +1,215 @@
+import {
+ Controller,
+ Post,
+ HttpCode,
+ Body,
+ BadRequestException,
+ Headers,
+ Ip,
+} from '@nestjs/common'
+import { ApiBearerAuth, ApiTags } from '@nestjs/swagger'
+
+import { Auth } from '../auth/decorators'
+import { TwoFactorAuthService } from './twoFactorAuth.service'
+import { UserService } from '../user/user.service'
+import { AuthService } from '../auth/auth.service'
+import { AppLoggerService } from '../logger/logger.service'
+import { MailerService } from '../mailer/mailer.service'
+import { LetterTemplate } from '../mailer/letter'
+import { TwoFaNotRequired, CurrentUserId } from '../auth/decorators'
+import { TwoFactorAuthDTO } from './dto/2fa-auth.dto'
+import {
+ generateRecoveryCode,
+ checkRateLimit,
+ getIPFromHeaders,
+} from '../common/utils'
+
+@ApiTags('2fa')
+@Controller('2fa')
+export class TwoFactorAuthController {
+ constructor(
+ private twoFactorAuthService: TwoFactorAuthService,
+ private userService: UserService,
+ private authService: AuthService,
+ private readonly logger: AppLoggerService,
+ private readonly mailerService: MailerService,
+ ) {}
+
+ @ApiBearerAuth()
+ @Post('generate')
+ @Auth()
+ @TwoFaNotRequired()
+ async register(@CurrentUserId() id: string) {
+ const user = await this.userService.findOne({ id })
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ throw new BadRequestException(
+ 'Two-factor authentication is already enabled',
+ )
+ }
+
+ return this.twoFactorAuthService.generateTwoFactorAuthenticationSecret(user)
+ }
+
+ @ApiBearerAuth()
+ @Post('enable')
+ @Auth()
+ @TwoFaNotRequired()
+ async turnOnTwoFactorAuthentication(
+ @Body() body: TwoFactorAuthDTO,
+ @CurrentUserId() id: string,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ this.logger.log({}, 'POST /2fa/enable')
+
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+ await checkRateLimit(ip, '2fa-enable', 5, 1800)
+ await checkRateLimit(id, '2fa-enable', 5, 1800)
+
+ const user = await this.userService.findOne({ id })
+ const { twoFactorAuthenticationCode } = body
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ if (user.isTwoFactorAuthenticationEnabled) {
+ throw new BadRequestException(
+ 'Two-factor authentication is already enabled',
+ )
+ }
+
+ if (!user.twoFactorAuthenticationSecret) {
+ throw new BadRequestException(
+ 'Two-factor authentication is not initialised',
+ )
+ }
+
+ const isCodeValid =
+ this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode,
+ user,
+ )
+
+ if (!isCodeValid) {
+ throw new BadRequestException('Wrong authentication code')
+ }
+
+ const twoFactorRecoveryCode = generateRecoveryCode()
+
+ await this.userService.update(user.id, {
+ isTwoFactorAuthenticationEnabled: 1,
+ twoFactorRecoveryCode,
+ })
+
+ await this.mailerService.sendEmail(user.email, LetterTemplate.TwoFAOn)
+
+ const authData = await this.authService.generateJwtTokens(user.id, true)
+
+ return {
+ twoFactorRecoveryCode,
+ ...authData,
+ }
+ }
+
+ @ApiBearerAuth()
+ @Post('disable')
+ @HttpCode(200)
+ @Auth()
+ async turnOffTwoFactorAuthentication(
+ @Body() body: TwoFactorAuthDTO,
+ @CurrentUserId() id: string,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ this.logger.log({}, 'POST /2fa/disable')
+
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+ await checkRateLimit(ip, '2fa-disable', 5, 1800)
+ await checkRateLimit(id, '2fa-disable', 5, 1800)
+
+ const user = await this.userService.findOne({ id })
+ const { twoFactorAuthenticationCode } = body
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ const isRecoveryCodeValid =
+ !!user.twoFactorRecoveryCode &&
+ user.twoFactorRecoveryCode === twoFactorAuthenticationCode
+ const isTotpValid =
+ this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode,
+ user,
+ )
+ const isCodeValid = isRecoveryCodeValid || isTotpValid
+
+ if (!isCodeValid) {
+ throw new BadRequestException('Wrong authentication code')
+ }
+
+ await this.mailerService.sendEmail(user.email, LetterTemplate.TwoFAOff)
+
+ await this.userService.update(user.id, {
+ isTwoFactorAuthenticationEnabled: 0,
+ twoFactorRecoveryCode: null,
+ twoFactorAuthenticationSecret: null,
+ })
+ }
+
+ @ApiBearerAuth()
+ @Post('authenticate')
+ @HttpCode(200)
+ @Auth()
+ @TwoFaNotRequired()
+ async authenticate(
+ @Body() body: TwoFactorAuthDTO,
+ @CurrentUserId() id: string,
+ @Headers() headers,
+ @Ip() reqIP,
+ ) {
+ this.logger.log({}, 'POST /2fa/authenticate')
+
+ const ip = getIPFromHeaders(headers) || reqIP || ''
+ await checkRateLimit(ip, '2fa-auth', 10, 1800)
+ await checkRateLimit(id, '2fa-auth', 10, 1800)
+
+ const user = await this.userService.findOne({ id })
+ const { twoFactorAuthenticationCode } = body
+
+ if (!user) {
+ throw new BadRequestException('User not found')
+ }
+
+ if (!user.isTwoFactorAuthenticationEnabled) {
+ throw new BadRequestException('Two-factor authentication is not enabled')
+ }
+
+ const isRecoveryCodeValid =
+ !!user.twoFactorRecoveryCode &&
+ user.twoFactorRecoveryCode === twoFactorAuthenticationCode
+ const isTotpValid =
+ this.twoFactorAuthService.isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode,
+ user,
+ )
+ const isCodeValid = isRecoveryCodeValid || isTotpValid
+
+ if (!isCodeValid) {
+ throw new BadRequestException('Wrong authentication code')
+ }
+
+ const tokens = await this.authService.generateJwtTokens(user.id, true)
+
+ return {
+ ...tokens,
+ user: this.userService.omitSensitiveData(user),
+ }
+ }
+}
diff --git a/backend/apps/community/src/twoFactorAuth/twoFactorAuth.module.ts b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.module.ts
new file mode 100644
index 000000000..364563720
--- /dev/null
+++ b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.module.ts
@@ -0,0 +1,20 @@
+import { forwardRef, Module } from '@nestjs/common'
+import { TwoFactorAuthService } from './twoFactorAuth.service'
+import { UserModule } from '../user/user.module'
+import { AuthModule } from '../auth/auth.module'
+import { TwoFactorAuthController } from './twoFactorAuth.controller'
+import { AppLoggerModule } from '../logger/logger.module'
+import { MailerModule } from '../mailer/mailer.module'
+
+@Module({
+ imports: [
+ forwardRef(() => UserModule),
+ AppLoggerModule,
+ forwardRef(() => AuthModule),
+ MailerModule,
+ ],
+ controllers: [TwoFactorAuthController],
+ providers: [TwoFactorAuthService],
+ exports: [TwoFactorAuthService],
+})
+export class TwoFactorAuthModule {}
diff --git a/backend/apps/community/src/twoFactorAuth/twoFactorAuth.service.ts b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.service.ts
new file mode 100644
index 000000000..d73fc5e8a
--- /dev/null
+++ b/backend/apps/community/src/twoFactorAuth/twoFactorAuth.service.ts
@@ -0,0 +1,42 @@
+import { Injectable } from '@nestjs/common'
+import { authenticator } from 'otplib'
+
+import { UserService } from '../user/user.service'
+import { User } from '../common/types'
+import { TWO_FACTOR_AUTHENTICATION_APP_NAME } from '../common/constants'
+
+@Injectable()
+export class TwoFactorAuthService {
+ constructor(private userService: UserService) {}
+
+ async generateTwoFactorAuthenticationSecret(user: User) {
+ const secret = authenticator.generateSecret()
+ const otpauthUrl = authenticator.keyuri(
+ user.email,
+ TWO_FACTOR_AUTHENTICATION_APP_NAME,
+ secret,
+ )
+
+ await this.userService.update(user.id, {
+ twoFactorAuthenticationSecret: secret,
+ })
+
+ return {
+ secret,
+ otpauthUrl,
+ }
+ }
+
+ isTwoFactorAuthenticationCodeValid(
+ twoFactorAuthenticationCode: string,
+ user: User,
+ ) {
+ if (!twoFactorAuthenticationCode) return false
+ if (!user?.twoFactorAuthenticationSecret) return false
+
+ return authenticator.verify({
+ token: twoFactorAuthenticationCode,
+ secret: user.twoFactorAuthenticationSecret,
+ })
+ }
+}
diff --git a/backend/apps/community/src/user/user.service.ts b/backend/apps/community/src/user/user.service.ts
index 157c4ab55..c7c63c8d3 100644
--- a/backend/apps/community/src/user/user.service.ts
+++ b/backend/apps/community/src/user/user.service.ts
@@ -24,6 +24,9 @@ export class UserService {
onboardingStep: 'String',
hasCompletedOnboarding: 'Int8',
apiKey: 'String',
+ twoFactorAuthenticationSecret: 'String',
+ twoFactorRecoveryCode: 'String',
+ isTwoFactorAuthenticationEnabled: 'Int8',
}
const entries = Object.entries(options).filter(
@@ -64,6 +67,9 @@ export class UserService {
'onboardingStep',
'hasCompletedOnboarding',
'apiKey',
+ 'twoFactorAuthenticationSecret',
+ 'twoFactorRecoveryCode',
+ 'isTwoFactorAuthenticationEnabled',
]
const rawEntries = Object.entries(update) as [
@@ -84,8 +90,13 @@ export class UserService {
for (const [key, value] of entries) {
// Support explicit clearing of the nullable apiKey column
if (value === null) {
- if (key === 'apiKey') {
- assignments.push('apiKey = NULL')
+ const nullableKeys: Array<keyof ClickhouseInputUser> = [
+ 'apiKey',
+ 'twoFactorAuthenticationSecret',
+ 'twoFactorRecoveryCode',
+ ]
+ if (nullableKeys.includes(key)) {
+ assignments.push(`${String(key)} = NULL`)
}
continue
}
@@ -93,6 +104,7 @@ export class UserService {
const type = [
'showLiveVisitorsInTitle',
'hasCompletedOnboarding',
+ 'isTwoFactorAuthenticationEnabled',
].includes(key)
? 'Int8'
: 'String'
@@ -144,6 +156,9 @@ export class UserService {
onboardingStep: OnboardingStep.LANGUAGE,
hasCompletedOnboarding: 0,
apiKey: null,
+ twoFactorAuthenticationSecret: null,
+ twoFactorRecoveryCode: null,
+ isTwoFactorAuthenticationEnabled: 0,
},
],
})
@@ -163,7 +178,11 @@ export class UserService {
}
omitSensitiveData(user: Partial<User>): Partial<User> {
- return _omit(user, ['password'])
+ return _omit(user, [
+ 'password',
+ 'twoFactorAuthenticationSecret',
+ 'twoFactorRecoveryCode',
+ ])
}
validatePassword(pass: string): void {
@@ -194,6 +213,9 @@ export class UserService {
...user,
showLiveVisitorsInTitle: Boolean(user.showLiveVisitorsInTitle),
hasCompletedOnboarding: Boolean(user.hasCompletedOnboarding),
+ isTwoFactorAuthenticationEnabled: Boolean(
+ user.isTwoFactorAuthenticationEnabled,
+ ),
}
}
}
diff --git a/backend/migrations/clickhouse/initialise_selfhosted.js b/backend/migrations/clickhouse/initialise_selfhosted.js
index 6a9762114..f0b6eff39 100644
--- a/backend/migrations/clickhouse/initialise_selfhosted.js
+++ b/backend/migrations/clickhouse/initialise_selfhosted.js
@@ -13,7 +13,10 @@ const CLICKHOUSE_INIT_QUERIES = [
showLiveVisitorsInTitle Int8,
onboardingStep String CODEC(ZSTD(3)),
hasCompletedOnboarding Int8,
- apiKey Nullable(String) CODEC(ZSTD(3))
+ apiKey Nullable(String) CODEC(ZSTD(3)),
+ twoFactorAuthenticationSecret Nullable(String) CODEC(ZSTD(3)),
+ twoFactorRecoveryCode Nullable(String) CODEC(ZSTD(3)),
+ isTwoFactorAuthenticationEnabled Int8 DEFAULT 0
)
ENGINE = MergeTree()
PRIMARY KEY id;`,
diff --git a/backend/migrations/clickhouse/selfhosted_2026_03_04_2fa.js b/backend/migrations/clickhouse/selfhosted_2026_03_04_2fa.js
new file mode 100644
index 000000000..a159d6dcd
--- /dev/null
+++ b/backend/migrations/clickhouse/selfhosted_2026_03_04_2fa.js
@@ -0,0 +1,18 @@
+const { queriesRunner, dbName } = require('./setup')
+
+const queries = [
+ `ALTER TABLE ${dbName}.user ADD COLUMN IF NOT EXISTS twoFactorAuthenticationSecret Nullable(String) CODEC(ZSTD(3))`,
+ `ALTER TABLE ${dbName}.user ADD COLUMN IF NOT EXISTS twoFactorRecoveryCode Nullable(String) CODEC(ZSTD(3))`,
+ `ALTER TABLE ${dbName}.user ADD COLUMN IF NOT EXISTS isTwoFactorAuthenticationEnabled Int8 DEFAULT 0`,
+]
+
+async function run() {
+ try {
+ await queriesRunner(queries)
+ console.log('[INFO] Selfhosted 2FA migration finished')
+ } catch (reason) {
+ console.error('[ERROR] 2FA migration failed:', reason)
+ }
+}
+
+run()
diff --git a/docs/package.json b/docs/package.json
index 9629e1b9e..114f099e8 100644
--- a/docs/package.json
+++ b/docs/package.json
@@ -4,7 +4,7 @@
"private": true,
"scripts": {
"dev": "next dev -p 5007",
- "build": "next build",
+ "build": "next build --no-turbopack",
"start": "next start -p 5007 -H 0.0.0.0",
"format": "oxfmt",
"format:check": "oxfmt --check"
diff --git a/web/app/pages/UserSettings/UserSettings.tsx b/web/app/pages/UserSettings/UserSettings.tsx
index 1b77e84b6..7f5193b3f 100644
--- a/web/app/pages/UserSettings/UserSettings.tsx
+++ b/web/app/pages/UserSettings/UserSettings.tsx
@@ -1093,14 +1093,12 @@ const UserSettings = () => {
</SettingsSection>
{/* 2FA setting */}
- {!isSelfhosted ? (
- <SettingsSection
- title={t('profileSettings.2fa')}
- description={t('profileSettings.2faSectionDesc')}
- >
- <TwoFA />
- </SettingsSection>
- ) : null}
+ <SettingsSection
+ title={t('profileSettings.2fa')}
+ description={t('profileSettings.2faSectionDesc')}
+ >
+ <TwoFA />
+ </SettingsSection>
{/* Logout from all devices */}
<SettingsSection
diff --git a/web/app/ui/Dropdown.tsx b/web/app/ui/Dropdown.tsx
index 00d3aeda8..0bc9fa1ea 100644
--- a/web/app/ui/Dropdown.tsx
+++ b/web/app/ui/Dropdown.tsx
@@ -77,7 +77,7 @@ function Dropdown<T>({
{
'justify-between': aside,
'justify-center': !aside,
- 'inline-flex w-full rounded-md border-0 bg-white px-3 py-2 text-sm font-medium ring-1 ring-inset ring-gray-300 hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:outline-hidden md:px-4 dark:bg-slate-950 dark:text-gray-50 dark:ring-slate-700/80 dark:hover:bg-slate-800 dark:focus:ring-slate-300':
+ 'inline-flex w-full rounded-md border-0 bg-white px-3 py-2 text-sm font-medium ring-1 ring-gray-300 ring-inset hover:bg-gray-50 focus:ring-2 focus:ring-slate-900 focus:outline-hidden md:px-4 dark:bg-slate-950 dark:text-gray-50 dark:ring-slate-700/80 dark:hover:bg-slate-800 dark:focus:ring-slate-300':
!headless,
'group inline-flex w-full px-3 py-2 text-sm font-medium outline-hidden md:px-4':
headless,
diff --git a/web/app/ui/Tooltip.tsx b/web/app/ui/Tooltip.tsx
index 4b2f5ae73..b71dbcc8e 100644
--- a/web/app/ui/Tooltip.tsx
+++ b/web/app/ui/Tooltip.tsx
@@ -57,13 +57,18 @@ const Tooltip = ({
disableHoverableContent={disableHoverableContent}
>
<TooltipRoot>
- <TooltipTrigger className={className} aria-label={t('common.learnMore')}>
+ <TooltipTrigger
+ className={className}
+ aria-label={t('common.learnMore')}
+ >
{tooltipNode || (
<QuestionIcon className='size-4.5 fill-slate-700 stroke-gray-50 dark:fill-slate-200 dark:stroke-slate-800' />
)}
</TooltipTrigger>
<TooltipContent
- className={disableHoverableContent ? 'pointer-events-none' : undefined}
+ className={
+ disableHoverableContent ? 'pointer-events-none' : undefined
+ }
>
{text}
</TooltipContent>