fix(security): resolve all critical, high, and medium security vulnerabilities
This commit is contained in:
1 parent
da26dd1c8d
commit
dc88677169
33 files changed
+438
-85
No files matched your search
@@ -1,11 +1,29 @@
|
||||
export const DEFAULT_JWT_SECRET =
|
||||
'canina_jwt_fallback_access_secret_32_characters_minimum_len_2026';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
export const DEFAULT_JWT_REFRESH_SECRET =
|
||||
'canina_jwt_fallback_refresh_secret_32_characters_minimum_len_2026';
|
||||
const devAccessSecret =
|
||||
process.env.NODE_ENV !== 'production'
|
||||
? crypto.randomBytes(32).toString('hex')
|
||||
: undefined;
|
||||
|
||||
export const getJwtSecret = (): string =>
|
||||
process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET || DEFAULT_JWT_SECRET;
|
||||
const devRefreshSecret =
|
||||
process.env.NODE_ENV !== 'production'
|
||||
? crypto.randomBytes(32).toString('hex')
|
||||
: undefined;
|
||||
|
||||
export const getJwtRefreshSecret = (): string =>
|
||||
process.env.JWT_REFRESH_SECRET || DEFAULT_JWT_REFRESH_SECRET;
|
||||
export const getJwtSecret = (): string => {
|
||||
const secret = process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET;
|
||||
if (secret) return secret;
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('FATAL SECURITY ERROR: JWT_ACCESS_SECRET must be defined in production!');
|
||||
}
|
||||
return devAccessSecret!;
|
||||
};
|
||||
|
||||
export const getJwtRefreshSecret = (): string => {
|
||||
const secret = process.env.JWT_REFRESH_SECRET;
|
||||
if (secret) return secret;
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('FATAL SECURITY ERROR: JWT_REFRESH_SECRET must be defined in production!');
|
||||
}
|
||||
return devRefreshSecret!;
|
||||
};
|
||||
@@ -92,6 +92,7 @@ export class AuthController {
|
||||
return this.authService.login(loginDto);
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 300000 } }) // 5 attempts per 5 minutes
|
||||
@Post('admin-login')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'ورود ادمین به پنل مدیریت' })
|
||||
@@ -116,11 +117,18 @@ export class AuthController {
|
||||
return this.authService.refresh(req.user);
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@UseGuards(JwtAuthGuard)
|
||||
@Post('logout')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'خروج از حساب کاربری' })
|
||||
@ApiOperation({ summary: 'خروج از حساب کاربری و ابطال توکن' })
|
||||
@ApiOkResponse({ description: 'با موفقیت خارج شدید' })
|
||||
logout() {
|
||||
async logout(@Req() req: any) {
|
||||
const authHeader = req.headers?.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const token = authHeader.replace('Bearer ', '').trim();
|
||||
await this.authService.blacklistToken(token);
|
||||
}
|
||||
return { success: true, message: 'با موفقیت خارج شدید' };
|
||||
}
|
||||
}
|
||||
@@ -8,11 +8,14 @@ import { UsersModule } from '../users/users.module';
|
||||
import { AdminModule } from '../admin/admin.module';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
|
||||
import { RedisModule } from '../redis/redis.module';
|
||||
|
||||
@Module({
|
||||
imports: [
|
||||
UsersModule,
|
||||
forwardRef(() => AdminModule),
|
||||
PassportModule,
|
||||
RedisModule,
|
||||
JwtModule.registerAsync({
|
||||
useFactory: () => ({
|
||||
secret: getJwtSecret(),
|
||||
|
||||
@@ -155,10 +155,11 @@ export class AuthService {
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user,
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
},
|
||||
};
|
||||
@@ -210,10 +211,11 @@ export class AuthService {
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const { password: _p, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user,
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
},
|
||||
};
|
||||
@@ -251,18 +253,17 @@ export class AuthService {
|
||||
const payload = { sub: user.id, phoneNumber: user.mobile };
|
||||
const accessToken = this.jwtService.sign(payload);
|
||||
|
||||
const { password: _pw, ...safeUser } = user;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user,
|
||||
user: safeUser,
|
||||
accessToken,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async adminLogin(body: AdminLoginInput) {
|
||||
const adminEmail = process.env.ADMIN_EMAIL || 'admin@canina.ir';
|
||||
const adminPassword = process.env.ADMIN_PASSWORD || 'admin123';
|
||||
|
||||
// First check database for user with role 'Admin' or 'SUPER_ADMIN'
|
||||
const dbAdmin = await this.prisma.user.findFirst({
|
||||
@@ -280,34 +281,59 @@ export class AuthService {
|
||||
email: dbAdmin.email,
|
||||
role: dbAdmin.role,
|
||||
};
|
||||
const { password: _p, ...safeUser } = dbAdmin;
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: dbAdmin,
|
||||
user: safeUser,
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
},
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback to validated environment variable credentials
|
||||
if (body.email === adminEmail && body.password === adminPassword) {
|
||||
const payload = {
|
||||
sub: '12345678-1234-1234-1234-123456789012',
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
};
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
// Fallback to validated environment variable credentials only if configured securely
|
||||
const adminEmail = process.env.ADMIN_EMAIL;
|
||||
const adminPassword = process.env.ADMIN_PASSWORD;
|
||||
|
||||
if (
|
||||
adminEmail &&
|
||||
adminPassword &&
|
||||
adminPassword.length >= 8 &&
|
||||
body.email &&
|
||||
body.password
|
||||
) {
|
||||
const emailMatches =
|
||||
body.email.length === adminEmail.length &&
|
||||
crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.email).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminEmail).digest()),
|
||||
);
|
||||
|
||||
const passwordMatches =
|
||||
crypto.timingSafeEqual(
|
||||
Buffer.from(crypto.createHash('sha256').update(body.password).digest()),
|
||||
Buffer.from(crypto.createHash('sha256').update(adminPassword).digest()),
|
||||
);
|
||||
|
||||
if (emailMatches && passwordMatches) {
|
||||
const payload = {
|
||||
sub: '12345678-1234-1234-1234-123456789012',
|
||||
email: adminEmail,
|
||||
role: 'Admin',
|
||||
};
|
||||
return {
|
||||
success: true,
|
||||
data: {
|
||||
user: {
|
||||
id: '12345678-1234-1234-1234-123456789012',
|
||||
email: body.email,
|
||||
role: 'Admin',
|
||||
},
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
},
|
||||
accessToken: this.jwtService.sign(payload),
|
||||
},
|
||||
};
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
throw new BadRequestException({
|
||||
@@ -336,4 +362,21 @@ export class AuthService {
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async blacklistToken(token: string) {
|
||||
try {
|
||||
const decoded: any = this.jwtService.decode(token);
|
||||
let ttl = 7 * 24 * 3600; // default 7 days
|
||||
if (decoded && decoded.exp) {
|
||||
const remaining = decoded.exp - Math.floor(Date.now() / 1000);
|
||||
if (remaining > 0) {
|
||||
ttl = remaining;
|
||||
}
|
||||
}
|
||||
await this.redisService.set(`bl_token:${token}`, '1', ttl);
|
||||
} catch {
|
||||
// Fallback: cache for 7 days
|
||||
await this.redisService.set(`bl_token:${token}`, '1', 7 * 24 * 3600);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,6 +4,9 @@ import { Injectable, UnauthorizedException } from '@nestjs/common';
|
||||
import { UsersService } from '../users/users.service';
|
||||
import { getJwtSecret } from './auth.constants';
|
||||
|
||||
import { RedisService } from '../redis/redis.service';
|
||||
import type { Request } from 'express';
|
||||
|
||||
export interface JwtPayload {
|
||||
sub: string;
|
||||
email?: string;
|
||||
@@ -13,18 +16,37 @@ export interface JwtPayload {
|
||||
|
||||
@Injectable()
|
||||
export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
constructor(private readonly usersService: UsersService) {
|
||||
constructor(
|
||||
private readonly usersService: UsersService,
|
||||
private readonly redisService: RedisService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: getJwtSecret(),
|
||||
passReqToCallback: true,
|
||||
});
|
||||
}
|
||||
|
||||
async validate(payload: JwtPayload) {
|
||||
// Bypass DB lookup for local admin user to prevent UUID casting errors
|
||||
async validate(req: Request, payload: JwtPayload) {
|
||||
const rawToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
|
||||
if (rawToken) {
|
||||
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
|
||||
if (isBlacklisted) {
|
||||
throw new UnauthorizedException('این توکن باطل شده است. لطفاً مجدداً وارد شوید');
|
||||
}
|
||||
}
|
||||
// Handle fallback admin ID only if ADMIN_EMAIL is configured and matches payload
|
||||
if (payload.sub === '12345678-1234-1234-1234-123456789012') {
|
||||
return { id: payload.sub, email: payload.email, role: payload.role };
|
||||
const adminEmail = process.env.ADMIN_EMAIL;
|
||||
if (adminEmail && payload.email === adminEmail) {
|
||||
return {
|
||||
id: payload.sub,
|
||||
email: adminEmail,
|
||||
role: 'Admin',
|
||||
};
|
||||
}
|
||||
throw new UnauthorizedException('حساب کاربری مدیریت معتبر نیست');
|
||||
}
|
||||
|
||||
const user = await this.usersService.findById(payload.sub);
|
||||
|
||||
Reference in new issue
Block a user