fix(security): remediate audit vulnerabilities SEC-001 through SEC-023
This commit is contained in:
1 parent
dc88677169
commit
bd49fbc4a0
31 files changed
+867
-114
No files matched your search
@@ -24,6 +24,7 @@ import {
|
||||
} from '@nestjs/swagger';
|
||||
|
||||
import { AdminLoginDto } from './dto/admin-login.dto';
|
||||
import { RefreshTokenDto } from './dto/refresh-token.dto';
|
||||
|
||||
@ApiTags('Auth - احراز هویت')
|
||||
@Controller('auth')
|
||||
@@ -72,6 +73,7 @@ export class AuthController {
|
||||
return this.authService.verifyOtp(verifyOtpDto);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post('register')
|
||||
@HttpCode(HttpStatus.CREATED)
|
||||
@ApiOperation({ summary: 'ثبتنام با ایمیل/موبایل و رمز عبور' })
|
||||
@@ -83,6 +85,7 @@ export class AuthController {
|
||||
return this.authService.register(registerDto);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@Post('login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ورود با موبایل و رمز عبور' })
|
||||
@@ -102,6 +105,16 @@ export class AuthController {
|
||||
return this.authService.adminLogin(body);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post('refresh-token')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'دریافت جفت توکن جدید با استفاده از توکن تازهسازی' })
|
||||
@ApiOkResponse({ description: 'توکنهای جدید با موفقیت صادر شدند' })
|
||||
@ApiBadRequestResponse({ description: 'توکن نامعتبر یا منقضی است' })
|
||||
refreshToken(@Body() body: RefreshTokenDto) {
|
||||
return this.authService.refreshToken(body.refreshToken);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('refresh')
|
||||
|
||||
@@ -19,7 +19,7 @@ import { RedisModule } from '../redis/redis.module';
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
secret: getJwtSecret(),
|
||||
signOptions: { expiresIn: '7d' },
|
||||
signOptions: { expiresIn: '15m' },
|
||||
}),
|
||||
}),
|
||||
],
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import {
|
||||
Injectable,
|
||||
BadRequestException,
|
||||
UnauthorizedException,
|
||||
HttpException,
|
||||
HttpStatus,
|
||||
} from '@nestjs/common';
|
||||
@@ -13,6 +14,7 @@ import { SmsService } from '../common/services/sms.service';
|
||||
import * as bcrypt from 'bcryptjs';
|
||||
import * as crypto from 'crypto';
|
||||
import { normalizeMobile } from '../common/utils/phone.utils';
|
||||
import { getJwtRefreshSecret } from './auth.constants';
|
||||
|
||||
export class RegisterInput {
|
||||
firstName!: string;
|
||||
@@ -42,6 +44,28 @@ export class AuthService {
|
||||
private smsService: SmsService,
|
||||
) {}
|
||||
|
||||
private async generateTokens(payload: Record<string, any>) {
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
// Refresh token with 30-day lifetime signed by refresh secret
|
||||
const refreshSecret = getJwtRefreshSecret();
|
||||
const tokenId = crypto.randomUUID();
|
||||
const refreshPayload = { ...payload, jti: tokenId };
|
||||
const refreshToken = this.jwtService.sign(refreshPayload, {
|
||||
secret: refreshSecret,
|
||||
expiresIn: '30d',
|
||||
});
|
||||
|
||||
// Store active refresh token in Redis (30 days TTL = 2,592,000s)
|
||||
await this.redisService.set(
|
||||
`refresh_token:${payload.sub}:${tokenId}`,
|
||||
'1',
|
||||
30 * 24 * 3600,
|
||||
);
|
||||
|
||||
return { accessToken, refreshToken };
|
||||
}
|
||||
|
||||
async sendOtp(sendOtpDto: SendOtpDto) {
|
||||
const phoneNumber = normalizeMobile(sendOtpDto.phoneNumber);
|
||||
|
||||
@@ -152,15 +176,16 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -208,15 +233,16 @@ export class AuthService {
|
||||
},
|
||||
});
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -250,21 +276,21 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile, role: user.role };
|
||||
const tokens = await this.generateTokens(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async adminLogin(body: AdminLoginInput) {
|
||||
|
||||
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
|
||||
const dbAdmin = await this.prisma.user.findFirst({
|
||||
where: {
|
||||
@@ -281,18 +307,28 @@ export class AuthService {
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: safeUser,
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to validated environment variable credentials only if configured securely
|
||||
// In production, fallback credentials MUST NOT be accepted
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new BadRequestException({
|
||||
message: 'ایمیل یا رمز عبور مدیریت اشتباه است',
|
||||
error: 'INVALID_ADMIN_CREDENTIALS',
|
||||
});
|
||||
}
|
||||
|
||||
// Fallback to validated environment variable credentials only in non-production
|
||||
const adminEmail = process.env.ADMIN_EMAIL;
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
|
||||
@@ -322,6 +358,7 @@ export class AuthService {
|
||||
email: adminEmail,
|
||||
role: 'Admin',
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
@@ -330,7 +367,8 @@ export class AuthService {
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
},
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -342,7 +380,83 @@ export class AuthService {
|
||||
});
|
||||
}
|
||||
|
||||
refresh(user: {
|
||||
async refreshToken(rawRefreshToken: string) {
|
||||
if (!rawRefreshToken) {
|
||||
throw new UnauthorizedException('توکن تازهسازی یافت نشد');
|
||||
}
|
||||
|
||||
let decoded: any;
|
||||
try {
|
||||
decoded = this.jwtService.verify(rawRefreshToken, {
|
||||
secret: getJwtRefreshSecret(),
|
||||
});
|
||||
} catch {
|
||||
throw new UnauthorizedException('توکن تازهسازی نامعتبر یا منقضی شده است');
|
||||
}
|
||||
|
||||
const userId = decoded.sub;
|
||||
const tokenId = decoded.jti;
|
||||
|
||||
if (!userId || !tokenId) {
|
||||
throw new UnauthorizedException('اطلاعات توکن نامعتبر است');
|
||||
}
|
||||
|
||||
// Check if token exists in Redis
|
||||
const tokenKey = `refresh_token:${userId}:${tokenId}`;
|
||||
const tokenValid = await this.redisService.get(tokenKey);
|
||||
if (!tokenValid) {
|
||||
throw new UnauthorizedException('توکن تازهسازی باطل شده است. لطفاً مجدداً وارد شوید');
|
||||
}
|
||||
|
||||
// Invalidate old token (Rotation)
|
||||
await this.redisService.del(tokenKey);
|
||||
|
||||
let userPayload: Record<string, any>;
|
||||
let safeUser: any;
|
||||
|
||||
if (userId === '12345678-1234-1234-1234-123456789012') {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new UnauthorizedException('حساب کاربری مدیریت معتبر نیست');
|
||||
}
|
||||
userPayload = {
|
||||
sub: userId,
|
||||
email: decoded.email,
|
||||
role: 'Admin',
|
||||
};
|
||||
safeUser = {
|
||||
id: userId,
|
||||
email: decoded.email,
|
||||
role: 'Admin',
|
||||
};
|
||||
} else {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) {
|
||||
throw new UnauthorizedException('کاربر یافت نشد');
|
||||
}
|
||||
userPayload = {
|
||||
sub: user.id,
|
||||
email: user.email,
|
||||
phoneNumber: user.mobile,
|
||||
role: user.role,
|
||||
};
|
||||
const { password: _p, ...restUser } = user;
|
||||
safeUser = restUser;
|
||||
}
|
||||
|
||||
// Issue new pair of tokens
|
||||
const tokens = await this.generateTokens(userPayload);
|
||||
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: safeUser,
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async refresh(user: {
|
||||
id: string;
|
||||
email?: string;
|
||||
role?: string;
|
||||
@@ -354,11 +468,13 @@ export class AuthService {
|
||||
role: user.role,
|
||||
phoneNumber: user.mobile,
|
||||
};
|
||||
const tokens = await this.generateTokens(payload);
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user,
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
accessToken: tokens.accessToken,
|
||||
refreshToken: tokens.refreshToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -366,7 +482,7 @@ export class AuthService {
|
||||
async blacklistToken(token: string) {
|
||||
try {
|
||||
const decoded: any = this.jwtService.decode(token);
|
||||
let ttl = 7 * 24 * 3600; // default 7 days
|
||||
let ttl = 15 * 60; // 15 minutes default for access token
|
||||
if (decoded && decoded.exp) {
|
||||
const remaining = decoded.exp - Math.floor(Date.now() / 1000);
|
||||
if (remaining > 0) {
|
||||
@@ -374,9 +490,13 @@ export class AuthService {
|
||||
}
|
||||
}
|
||||
await this.redisService.set(`bl_token:${token}`, '1', ttl);
|
||||
|
||||
// If token payload has jti and sub, also invalidate the refresh token in Redis
|
||||
if (decoded && decoded.sub && decoded.jti) {
|
||||
await this.redisService.del(`refresh_token:${decoded.sub}:${decoded.jti}`);
|
||||
}
|
||||
} catch {
|
||||
// Fallback: cache for 7 days
|
||||
await this.redisService.set(`bl_token:${token}`, '1', 7 * 24 * 3600);
|
||||
await this.redisService.set(`bl_token:${token}`, '1', 15 * 60);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
import { IsNotEmpty, IsString } from 'class-validator';
|
||||
import { ApiProperty } from '@nestjs/swagger';
|
||||
|
||||
export class RefreshTokenDto {
|
||||
@ApiProperty({
|
||||
description: 'توکن تازهسازی (Refresh Token)',
|
||||
example: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...',
|
||||
})
|
||||
@IsNotEmpty({ message: 'ارسال توکن تازهسازی الزامی است' })
|
||||
@IsString({ message: 'توکن تازهسازی باید رشته متنی باشد' })
|
||||
refreshToken: string;
|
||||
}
|
||||
@@ -36,8 +36,11 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
throw new UnauthorizedException('این توکن باطل شده است. لطفاً مجدداً وارد شوید');
|
||||
}
|
||||
}
|
||||
// Handle fallback admin ID only if ADMIN_EMAIL is configured and matches payload
|
||||
// Handle fallback admin ID only in non-production environments if ADMIN_EMAIL matches
|
||||
if (payload.sub === '12345678-1234-1234-1234-123456789012') {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new UnauthorizedException('حساب کاربری مدیریت معتبر نیست');
|
||||
}
|
||||
const adminEmail = process.env.ADMIN_EMAIL;
|
||||
if (adminEmail && payload.email === adminEmail) {
|
||||
return {
|
||||
|
||||
Reference in new issue
Block a user