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!

removing old refresh tokens on password reset & other improvements (#189)

Andrii Romasiun2ce8c1b487e3
diff --git a/.env.example b/.env.example
index d2408cb19..8b7caada0 100644
--- a/.env.example
+++ b/.env.example
@@ -8,6 +8,12 @@ CLIENT_URL='http://localhost:3000'
JWT_ACCESS_TOKEN_SECRET='jwt-access-token-secret'
JWT_REFRESH_TOKEN_SECRET='jwt-refresh-token-secret'
+# Time in seconds
+# 30 minutes
+JWT_ACCESS_TOKEN_LIFETIME=1800
+# 30 days
+JWT_REFRESH_TOKEN_LIFETIME=2592000
+
# Database
MYSQL_HOST=localhost
MYSQL_USER=root
diff --git a/apps/production/src/auth/auth.service.ts b/apps/production/src/auth/auth.service.ts
index 9dc8e38ef..94f34bdc6 100644
--- a/apps/production/src/auth/auth.service.ts
+++ b/apps/production/src/auth/auth.service.ts
@@ -39,6 +39,8 @@ import {
PRODUCTION_ORIGIN,
isDevelopment,
JWT_ACCESS_TOKEN_SECRET,
+ JWT_ACCESS_TOKEN_LIFETIME,
+ JWT_REFRESH_TOKEN_LIFETIME,
} from '../common/constants'
import { getGeoDetails } from '../common/utils'
import { TelegramService } from '../integrations/telegram/telegram.service'
@@ -170,7 +172,7 @@ export class AuthService {
},
{
algorithm: 'HS256',
- expiresIn: 60 * 30,
+ expiresIn: JWT_ACCESS_TOKEN_LIFETIME,
secret: JWT_ACCESS_TOKEN_SECRET,
},
)
@@ -326,10 +328,16 @@ export class AuthService {
): Promise<void> {
const hashedPassword = await this.hashPassword(password)
+ // Update user password
await this.userService.updateUser(actionToken.user.id, {
password: hashedPassword,
})
+
+ // Delete current 'reset password' action token
await this.actionTokensService.deleteActionToken(actionToken.id)
+
+ // Delete all user refresh tokens
+ await this.logoutAll(actionToken.user.id)
}
public async changePassword(userId: string, password: string): Promise<void> {
@@ -414,7 +422,7 @@ export class AuthService {
},
{
algorithm: 'HS256',
- expiresIn: 60 * 60 * 24 * 30,
+ expiresIn: JWT_REFRESH_TOKEN_LIFETIME,
secret: this.configService.get('JWT_REFRESH_TOKEN_SECRET'),
},
)
diff --git a/apps/production/src/common/constants.ts b/apps/production/src/common/constants.ts
index 1cf6fe92b..a55b6d83d 100644
--- a/apps/production/src/common/constants.ts
+++ b/apps/production/src/common/constants.ts
@@ -42,7 +42,13 @@ const clickhouse = new ClickHouse({
},
})
-const { JWT_ACCESS_TOKEN_SECRET } = process.env
+const {
+ JWT_ACCESS_TOKEN_SECRET,
+ // 30 days
+ JWT_REFRESH_TOKEN_LIFETIME = 60 * 60 * 24 * 30,
+ // 30 minutes
+ JWT_ACCESS_TOKEN_LIFETIME = 60 * 30,
+} = process.env
const isDevelopment = process.env.NODE_ENV === 'development'
const isProxiedByCloudflare = process.env.CLOUDFLARE_PROXY_ENABLED === 'true'
const PRODUCTION_ORIGIN = process.env.CLIENT_URL || 'https://swetrix.com'
@@ -155,6 +161,9 @@ const sentryIgnoreErrors: (string | RegExp)[] = [
'HttpException', // at the moment, these are either rate-limiting or payment required errors, so no need to track them
]
+const NUMBER_JWT_REFRESH_TOKEN_LIFETIME = Number(JWT_REFRESH_TOKEN_LIFETIME)
+const NUMBER_JWT_ACCESS_TOKEN_LIFETIME = Number(JWT_ACCESS_TOKEN_LIFETIME)
+
export {
clickhouse,
redis,
@@ -189,6 +198,8 @@ export {
PRODUCTION_ORIGIN,
REDIS_SSO_UUID,
JWT_ACCESS_TOKEN_SECRET,
+ NUMBER_JWT_REFRESH_TOKEN_LIFETIME as JWT_REFRESH_TOKEN_LIFETIME,
+ NUMBER_JWT_ACCESS_TOKEN_LIFETIME as JWT_ACCESS_TOKEN_LIFETIME,
getRedisUserUsageInfoKey,
redisUserUsageinfoCacheTimeout,
TRAFFIC_COLUMNS,
diff --git a/apps/production/src/task-manager/task-manager.module.ts b/apps/production/src/task-manager/task-manager.module.ts
index ea785f378..5a9acc3d8 100644
--- a/apps/production/src/task-manager/task-manager.module.ts
+++ b/apps/production/src/task-manager/task-manager.module.ts
@@ -1,8 +1,8 @@
import { Module, forwardRef } from '@nestjs/common'
-import { AlertModule } from 'src/alert/alert.module'
-import { ExtensionsModule } from 'src/marketplace/extensions/extensions.module'
-import { TelegramService } from 'src/integrations/telegram/telegram.service'
import { TypeOrmModule } from '@nestjs/typeorm'
+import { AlertModule } from '../alert/alert.module'
+import { ExtensionsModule } from '../marketplace/extensions/extensions.module'
+import { TelegramService } from '../integrations/telegram/telegram.service'
import { TaskManagerService } from './task-manager.service'
import { MailerModule } from '../mailer/mailer.module'
import { UserModule } from '../user/user.module'
diff --git a/apps/production/src/task-manager/task-manager.service.ts b/apps/production/src/task-manager/task-manager.service.ts
index a732af174..ee97deb04 100644
--- a/apps/production/src/task-manager/task-manager.service.ts
+++ b/apps/production/src/task-manager/task-manager.service.ts
@@ -44,6 +44,7 @@ import {
SEND_WARNING_AT_PERC,
PROJECT_INVITE_EXPIRE,
REDIS_LOG_CAPTCHA_CACHE_KEY,
+ JWT_REFRESH_TOKEN_LIFETIME,
} from '../common/constants'
import { getRandomTip } from '../common/utils'
import { AppLoggerService } from '../logger/logger.service'
@@ -1086,4 +1087,19 @@ export class TaskManagerService {
)
})
}
+
+ // Delete old refresh tokens
+ @Cron(CronExpression.EVERY_DAY_AT_1AM)
+ async deleteOldRefreshTokens(): Promise<void> {
+ const minDate = dayjs
+ .utc()
+ .subtract(JWT_REFRESH_TOKEN_LIFETIME, 's')
+ .format('YYYY-MM-DD HH:mm:ss')
+
+ const where: Record<string, unknown> = {
+ created: LessThan(minDate),
+ }
+
+ await this.userService.deleteRefreshTokensWhere(where)
+ }
}
diff --git a/apps/production/src/user/entities/refresh-token.entity.ts b/apps/production/src/user/entities/refresh-token.entity.ts
index f97e5218a..5347b2236 100644
--- a/apps/production/src/user/entities/refresh-token.entity.ts
+++ b/apps/production/src/user/entities/refresh-token.entity.ts
@@ -23,4 +23,7 @@ export class RefreshToken {
})
@JoinColumn()
user: User
+
+ @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
+ created: Date
}
diff --git a/apps/production/src/user/user.controller.ts b/apps/production/src/user/user.controller.ts
index 250be9203..a545a33b9 100644
--- a/apps/production/src/user/user.controller.ts
+++ b/apps/production/src/user/user.controller.ts
@@ -498,13 +498,15 @@ export class UserController {
this.logger.log({ userDTO, id }, 'PUT /user')
const user = await this.userService.findOneWhere({ id })
- if (!_isEmpty(userDTO.password) && _isString(userDTO.password)) {
+ const shouldUpdatePassword =
+ !_isEmpty(userDTO.password) && _isString(userDTO.password)
+
+ if (shouldUpdatePassword) {
+ // Validate new password
this.userService.validatePassword(userDTO.password)
+
+ // Hash new password
userDTO.password = await this.authService.hashPassword(userDTO.password)
- await this.mailerService.sendEmail(
- userDTO.email,
- LetterTemplate.PasswordChanged,
- )
}
try {
@@ -606,6 +608,18 @@ export class UserController {
])
await this.userService.update(id, userToUpdate)
+ // If password should have been updated and there were no issues doing so, then...
+ if (shouldUpdatePassword) {
+ // Send 'Password changed' email notification
+ await this.mailerService.sendEmail(
+ userDTO.email,
+ LetterTemplate.PasswordChanged,
+ )
+
+ // Log out all user sessions
+ await this.authService.logoutAll(id)
+ }
+
const updatedUser = await this.userService.findOneWhere({ id })
return this.userService.omitSensitiveData(updatedUser)
} catch (e) {
diff --git a/apps/production/src/user/user.service.ts b/apps/production/src/user/user.service.ts
index 6b1ec9429..db1ebe52b 100644
--- a/apps/production/src/user/user.service.ts
+++ b/apps/production/src/user/user.service.ts
@@ -297,6 +297,10 @@ export class UserService {
})
}
+ public async deleteRefreshTokensWhere(where: Record<string, unknown>) {
+ await this.refreshTokenRepository.delete(where)
+ }
+
public async findUserByApiKey(apiKey: string) {
return this.usersRepository.findOne({ where: { apiKey } })
}
diff --git a/apps/selfhosted/src/auth/auth.service.ts b/apps/selfhosted/src/auth/auth.service.ts
index bafd0bc04..5284b63f9 100644
--- a/apps/selfhosted/src/auth/auth.service.ts
+++ b/apps/selfhosted/src/auth/auth.service.ts
@@ -13,6 +13,8 @@ import {
SELFHOSTED_EMAIL,
SELFHOSTED_PASSWORD,
JWT_ACCESS_TOKEN_SECRET,
+ JWT_ACCESS_TOKEN_LIFETIME,
+ JWT_REFRESH_TOKEN_LIFETIME,
} from '../common/constants'
import { getSelfhostedUser, SelfhostedUser } from '../user/entities/user.entity'
@@ -39,7 +41,7 @@ export class AuthService {
},
{
algorithm: 'HS256',
- expiresIn: 60 * 30,
+ expiresIn: JWT_ACCESS_TOKEN_LIFETIME,
secret: JWT_ACCESS_TOKEN_SECRET,
},
)
@@ -67,7 +69,7 @@ export class AuthService {
},
{
algorithm: 'HS256',
- expiresIn: 60 * 60 * 24 * 30,
+ expiresIn: JWT_REFRESH_TOKEN_LIFETIME,
secret: this.configService.get('JWT_REFRESH_TOKEN_SECRET'),
},
)
diff --git a/apps/selfhosted/src/common/constants.ts b/apps/selfhosted/src/common/constants.ts
index f9cb8de4c..72a942b6b 100644
--- a/apps/selfhosted/src/common/constants.ts
+++ b/apps/selfhosted/src/common/constants.ts
@@ -43,7 +43,13 @@ const clickhouse = new ClickHouse({
},
})
-const { JWT_ACCESS_TOKEN_SECRET } = process.env
+const {
+ JWT_ACCESS_TOKEN_SECRET,
+ // 30 days
+ JWT_REFRESH_TOKEN_LIFETIME = 60 * 60 * 24 * 30,
+ // 30 minutes
+ JWT_ACCESS_TOKEN_LIFETIME = 60 * 30,
+} = process.env
const isProxiedByCloudflare = process.env.CLOUDFLARE_PROXY_ENABLED === 'true'
const isDevelopment = process.env.NODE_ENV === 'development'
@@ -98,6 +104,9 @@ const TRAFFIC_COLUMNS = [
const PERFORMANCE_COLUMNS = ['cc', 'rg', 'ct', 'pg', 'dv', 'br']
+const NUMBER_JWT_REFRESH_TOKEN_LIFETIME = Number(JWT_REFRESH_TOKEN_LIFETIME)
+const NUMBER_JWT_ACCESS_TOKEN_LIFETIME = Number(JWT_ACCESS_TOKEN_LIFETIME)
+
export {
clickhouse,
redis,
@@ -122,6 +131,8 @@ export {
isDevelopment,
DEFAULT_SELFHOSTED_UUID,
JWT_ACCESS_TOKEN_SECRET,
+ NUMBER_JWT_REFRESH_TOKEN_LIFETIME as JWT_REFRESH_TOKEN_LIFETIME,
+ NUMBER_JWT_ACCESS_TOKEN_LIFETIME as JWT_ACCESS_TOKEN_LIFETIME,
TRAFFIC_COLUMNS,
PERFORMANCE_COLUMNS,
isProxiedByCloudflare,
diff --git a/migrations/mysql/2023_09_11.sql b/migrations/mysql/2023_09_11.sql
new file mode 100644
index 000000000..436c0616f
--- /dev/null
+++ b/migrations/mysql/2023_09_11.sql
@@ -0,0 +1 @@
+alter table refresh_token add column `created` timestamp NOT NULL DEFAULT current_timestamp() after `refreshToken`;