fix: fix otp security issue and race condition

This commit is contained in:
2026-11-06 19:00:37 +03:30
parent 2051090d3d
commit 48e9ab5531
5 changed files with 156 additions and 17 deletions
+41 -17
View File
@@ -1,5 +1,6 @@
import { HttpStatus, Injectable, UnauthorizedException } from '@nestjs/common';
import { LessThan, MoreThanOrEqual, Repository } from 'typeorm';
import { LessThan, Repository } from 'typeorm';
import { randomInt } from 'crypto';
import { OTP } from '../entities/otp.entity';
import { InjectRepository } from '@nestjs/typeorm';
import { Cron, CronExpression } from '@nestjs/schedule';
@@ -9,6 +10,7 @@ import { AppTimeoutException } from '@/common/exceptions/app-timeout.exception';
@Injectable()
export class OtpService {
private readonly maxFailedAttempts = 10;
constructor(
/**
* Inject OTP Repository
@@ -26,7 +28,7 @@ export class OtpService {
* Generate OTP 5-digit code
*/
private generateOTPCode(): string {
return Math.floor(10_000 + Math.random() * 90_000).toString();
return randomInt(10_000, 100_000).toString();
}
/**
@@ -38,7 +40,7 @@ export class OtpService {
// OTP request Rate limit
const lastOTP = await this.otpRepository.findOne({
where: { phone },
order: { createdAt: 'DESC' },
order: { createdAt: 'DESC', id: 'DESC' },
});
if (lastOTP && Date.now() - lastOTP.createdAt.getTime() < 60_000) {
@@ -63,29 +65,51 @@ export class OtpService {
* Verify OTP
*/
public async verifyOTP(phone: string, code: string): Promise<OTP> {
let otp: OTP | null = null;
let verifiedOTP: OTP | null;
try {
otp = await this.otpRepository.findOne({
where: { phone, used: false, expiresAt: MoreThanOrEqual(new Date()) },
order: { createdAt: 'DESC' },
});
verifiedOTP = await this.otpRepository.manager.transaction(
async (manager) => {
const repository = manager.getRepository(OTP);
const otp = await repository.findOne({
where: { phone },
order: { createdAt: 'DESC', id: 'DESC' },
lock: { mode: 'pessimistic_write' },
});
if (
!otp ||
otp.used ||
otp.failedAttempts >= this.maxFailedAttempts ||
otp.expiresAt.getTime() <= Date.now()
) {
return null;
}
const matches = await this.hashingProvider.compare(code, otp.code);
if (!matches) {
otp.failedAttempts += 1;
await repository.save(otp);
return null;
}
if (otp.expiresAt.getTime() <= Date.now()) return null;
otp.used = true;
await repository.save(otp);
return otp;
},
);
} catch (err) {
throw new AppTimeoutException(err);
}
if (!otp) throw new UnauthorizedException('auth.errors.invalidOTP');
const isOTPCorrect = await this.hashingProvider.compare(code, otp.code);
if (!isOTPCorrect) {
if (!verifiedOTP) {
throw new UnauthorizedException('auth.errors.invalidOTP');
}
otp.used = true;
await this.otpRepository.save(otp);
return otp;
return verifiedOTP;
}
@Cron(CronExpression.EVERY_10_MINUTES)