fix(security): complete full security remediation - httpOnly cookies, CsrfGuard, nonce-based CSP, and strict JWT production validation
This commit is contained in:
1 parent
8a3adacd38
commit
abc957ba75
8 files changed
+352
-34
No files matched your search
@@ -6,7 +6,9 @@ import {
|
||||
HttpStatus,
|
||||
UseGuards,
|
||||
Req,
|
||||
Res,
|
||||
} from '@nestjs/common';
|
||||
import type { Response } from 'express';
|
||||
import { Throttle } from '@nestjs/throttler';
|
||||
import { AuthService } from './auth.service';
|
||||
import { SendOtpDto } from './dto/send-otp.dto';
|
||||
@@ -61,6 +63,46 @@ export class AuthController {
|
||||
return this.authService.sendOtp(sendOtpDto);
|
||||
}
|
||||
|
||||
private setAuthCookies(res?: Response, accessToken?: string, refreshToken?: string) {
|
||||
if (!res || typeof res.cookie !== 'function') return;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
if (accessToken) {
|
||||
res.cookie('accessToken', accessToken, {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
maxAge: 15 * 60 * 1000, // 15 mins
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
if (refreshToken) {
|
||||
res.cookie('refreshToken', refreshToken, {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
maxAge: 30 * 24 * 60 * 60 * 1000, // 30 days
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
private clearAuthCookies(res?: Response) {
|
||||
if (!res || typeof res.clearCookie !== 'function') return;
|
||||
const isProd = process.env.NODE_ENV === 'production';
|
||||
res.clearCookie('accessToken', {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
res.clearCookie('refreshToken', {
|
||||
httpOnly: true,
|
||||
secure: isProd,
|
||||
sameSite: 'lax',
|
||||
path: '/',
|
||||
});
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@Post('verify-otp')
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@@ -69,8 +111,15 @@ export class AuthController {
|
||||
@ApiBadRequestResponse({
|
||||
description: 'کد تایید اشتباه است یا منقضی شده است',
|
||||
})
|
||||
verifyOtp(@Body() verifyOtpDto: VerifyOtpDto) {
|
||||
return this.authService.verifyOtp(verifyOtpDto);
|
||||
async verifyOtp(
|
||||
@Body() verifyOtpDto: VerifyOtpDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
const result = await this.authService.verifyOtp(verifyOtpDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@@ -81,8 +130,15 @@ export class AuthController {
|
||||
@ApiBadRequestResponse({
|
||||
description: 'اطلاعات ثبتنام نامعتبر است یا کاربر از قبل وجود دارد',
|
||||
})
|
||||
register(@Body() registerDto: RegisterDto) {
|
||||
return this.authService.register(registerDto);
|
||||
async register(
|
||||
@Body() registerDto: RegisterDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
const result = await this.authService.register(registerDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 60000 } })
|
||||
@@ -91,8 +147,15 @@ export class AuthController {
|
||||
@ApiOperation({ summary: 'ورود با موبایل و رمز عبور' })
|
||||
@ApiOkResponse({ description: 'ورود موفق به همراه توکن دسترسی' })
|
||||
@ApiBadRequestResponse({ description: 'نام کاربری یا رمز عبور اشتباه است' })
|
||||
login(@Body() loginDto: LoginDto) {
|
||||
return this.authService.login(loginDto);
|
||||
async login(
|
||||
@Body() loginDto: LoginDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
const result = await this.authService.login(loginDto);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 5, ttl: 300000 } }) // 5 attempts per 5 minutes
|
||||
@@ -101,8 +164,15 @@ export class AuthController {
|
||||
@ApiOperation({ summary: 'ورود ادمین به پنل مدیریت' })
|
||||
@ApiOkResponse({ description: 'ورود موفق ادمین به همراه توکن' })
|
||||
@ApiBadRequestResponse({ description: 'اطلاعات ورود ادمین اشتباه است' })
|
||||
adminLogin(@Body() body: AdminLoginDto) {
|
||||
return this.authService.adminLogin(body);
|
||||
async adminLogin(
|
||||
@Body() body: AdminLoginDto,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
const result = await this.authService.adminLogin(body);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@Throttle({ default: { limit: 10, ttl: 60000 } })
|
||||
@@ -111,8 +181,21 @@ export class AuthController {
|
||||
@ApiOperation({ summary: 'دریافت جفت توکن جدید با استفاده از توکن تازهسازی' })
|
||||
@ApiOkResponse({ description: 'توکنهای جدید با موفقیت صادر شدند' })
|
||||
@ApiBadRequestResponse({ description: 'توکن نامعتبر یا منقضی است' })
|
||||
refreshToken(@Body() body: RefreshTokenDto) {
|
||||
return this.authService.refreshToken(body.refreshToken);
|
||||
async refreshToken(
|
||||
@Body() body: RefreshTokenDto,
|
||||
@Req() req: any,
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
let token = body?.refreshToken;
|
||||
if (!token && req.headers?.cookie) {
|
||||
const match = req.headers.cookie.match(/(?:^|;\s*)refreshToken=([^;]+)/);
|
||||
if (match) token = decodeURIComponent(match[1]);
|
||||
}
|
||||
const result = await this.authService.refreshToken(token);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@@ -121,13 +204,18 @@ export class AuthController {
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'تازهسازی توکن دسترسی (Refresh Token)' })
|
||||
@ApiOkResponse({ description: 'توکن جدید با موفقیت صادر شد' })
|
||||
refresh(
|
||||
async refresh(
|
||||
@Req()
|
||||
req: {
|
||||
user: { id: string; email?: string; role?: string; mobile?: string };
|
||||
},
|
||||
@Res({ passthrough: true }) res?: Response,
|
||||
) {
|
||||
return this.authService.refresh(req.user);
|
||||
const result = await this.authService.refresh(req.user);
|
||||
if (result?.data) {
|
||||
this.setAuthCookies(res, result.data.accessToken, result.data.refreshToken);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
@ApiBearerAuth()
|
||||
@@ -136,12 +224,19 @@ export class AuthController {
|
||||
@HttpCode(HttpStatus.OK)
|
||||
@ApiOperation({ summary: 'خروج از حساب کاربری و ابطال توکن' })
|
||||
@ApiOkResponse({ description: 'با موفقیت خارج شدید' })
|
||||
async logout(@Req() req: any) {
|
||||
async logout(@Req() req: any, @Res({ passthrough: true }) res?: Response) {
|
||||
let token: string | undefined;
|
||||
const authHeader = req.headers?.authorization;
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
const token = authHeader.replace('Bearer ', '').trim();
|
||||
token = authHeader.replace('Bearer ', '').trim();
|
||||
} else if (req.headers?.cookie) {
|
||||
const match = req.headers.cookie.match(/(?:^|;\s*)accessToken=([^;]+)/);
|
||||
if (match) token = decodeURIComponent(match[1]);
|
||||
}
|
||||
if (token) {
|
||||
await this.authService.blacklistToken(token);
|
||||
}
|
||||
this.clearAuthCookies(res);
|
||||
return { success: true, message: 'با موفقیت خارج شدید' };
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user