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
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user