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
@@ -10,6 +10,7 @@ import { OrdersModule } from './orders/orders.module';
|
||||
import { SettingsModule } from './settings/settings.module';
|
||||
import { ThrottlerModule, ThrottlerGuard } from '@nestjs/throttler';
|
||||
import { APP_GUARD } from '@nestjs/core';
|
||||
import { CsrfGuard } from './common/guards/csrf.guard';
|
||||
import { MetricsController } from './common/metrics.controller';
|
||||
import { AdminModule } from './admin/admin.module';
|
||||
import { HomeModule } from './home/home.module';
|
||||
@@ -83,6 +84,10 @@ import { Request, Response, NextFunction } from 'express';
|
||||
provide: APP_GUARD,
|
||||
useClass: ThrottlerGuard,
|
||||
},
|
||||
{
|
||||
provide: APP_GUARD,
|
||||
useClass: CsrfGuard,
|
||||
},
|
||||
RedisService,
|
||||
],
|
||||
})
|
||||
|
||||
@@ -13,11 +13,17 @@ const devRefreshSecret =
|
||||
export const getJwtSecret = (): string => {
|
||||
const secret = process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET;
|
||||
if (secret) return secret;
|
||||
return 'canina_secure_access_token_jwt_secret_production_2026';
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('JWT_ACCESS_SECRET is required in production environment.');
|
||||
}
|
||||
return devAccessSecret || 'canina_dev_access_token_jwt_secret_development_only';
|
||||
};
|
||||
|
||||
export const getJwtRefreshSecret = (): string => {
|
||||
const secret = process.env.JWT_REFRESH_SECRET;
|
||||
if (secret) return secret;
|
||||
return 'canina_secure_refresh_token_jwt_secret_production_2026';
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('JWT_REFRESH_SECRET is required in production environment.');
|
||||
}
|
||||
return devRefreshSecret || 'canina_dev_refresh_token_jwt_secret_development_only';
|
||||
};
|
||||
@@ -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: 'با موفقیت خارج شدید' };
|
||||
}
|
||||
}
|
||||
@@ -21,7 +21,19 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
private readonly redisService: RedisService,
|
||||
) {
|
||||
super({
|
||||
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
jwtFromRequest: ExtractJwt.fromExtractors([
|
||||
ExtractJwt.fromAuthHeaderAsBearerToken(),
|
||||
(req: Request) => {
|
||||
if (!req || !req.headers) return null;
|
||||
// Support parsed cookie object or raw Cookie header
|
||||
const cookieHeader = req.headers.cookie;
|
||||
if (cookieHeader) {
|
||||
const match = cookieHeader.match(/(?:^|;\s*)accessToken=([^;]+)/);
|
||||
if (match) return decodeURIComponent(match[1]);
|
||||
}
|
||||
return (req as any).cookies?.accessToken || null;
|
||||
},
|
||||
]),
|
||||
ignoreExpiration: false,
|
||||
secretOrKey: getJwtSecret(),
|
||||
passReqToCallback: true,
|
||||
@@ -29,7 +41,11 @@ export class JwtStrategy extends PassportStrategy(Strategy) {
|
||||
}
|
||||
|
||||
async validate(req: Request, payload: JwtPayload) {
|
||||
const rawToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
|
||||
let rawToken = ExtractJwt.fromAuthHeaderAsBearerToken()(req);
|
||||
if (!rawToken && req.headers?.cookie) {
|
||||
const match = req.headers.cookie.match(/(?:^|;\s*)accessToken=([^;]+)/);
|
||||
if (match) rawToken = decodeURIComponent(match[1]);
|
||||
}
|
||||
if (rawToken) {
|
||||
const isBlacklisted = await this.redisService.get(`bl_token:${rawToken}`);
|
||||
if (isBlacklisted) {
|
||||
|
||||
@@ -52,15 +52,28 @@ export function validateEnv(config: Record<string, unknown>) {
|
||||
throw new Error(`Environment Validation Error: ${messages}`);
|
||||
}
|
||||
|
||||
const isProduction = validatedConfig.NODE_ENV === 'production';
|
||||
|
||||
if (!validatedConfig.JWT_ACCESS_SECRET) {
|
||||
if (isProduction && !process.env.JWT_SECRET) {
|
||||
throw new Error(
|
||||
'Environment Validation Error: JWT_ACCESS_SECRET is strictly required in production mode.',
|
||||
);
|
||||
}
|
||||
process.env.JWT_ACCESS_SECRET =
|
||||
process.env.JWT_SECRET ||
|
||||
'canina_secure_access_token_jwt_secret_production_2026';
|
||||
'canina_dev_access_token_jwt_secret_development_only';
|
||||
validatedConfig.JWT_ACCESS_SECRET = process.env.JWT_ACCESS_SECRET;
|
||||
}
|
||||
|
||||
if (!validatedConfig.JWT_REFRESH_SECRET) {
|
||||
if (isProduction) {
|
||||
throw new Error(
|
||||
'Environment Validation Error: JWT_REFRESH_SECRET is strictly required in production mode.',
|
||||
);
|
||||
}
|
||||
process.env.JWT_REFRESH_SECRET =
|
||||
'canina_secure_refresh_token_jwt_secret_production_2026';
|
||||
'canina_dev_refresh_token_jwt_secret_development_only';
|
||||
validatedConfig.JWT_REFRESH_SECRET = process.env.JWT_REFRESH_SECRET;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
import {
|
||||
Injectable,
|
||||
CanActivate,
|
||||
ExecutionContext,
|
||||
ForbiddenException,
|
||||
} from '@nestjs/common';
|
||||
import { Request } from 'express';
|
||||
|
||||
@Injectable()
|
||||
export class CsrfGuard implements CanActivate {
|
||||
private readonly stateChangingMethods = new Set([
|
||||
'POST',
|
||||
'PUT',
|
||||
'PATCH',
|
||||
'DELETE',
|
||||
]);
|
||||
|
||||
canActivate(context: ExecutionContext): boolean {
|
||||
const req = context.switchToHttp().getRequest<Request>();
|
||||
const method = (req.method || '').toUpperCase();
|
||||
|
||||
// Safe / Read-only HTTP methods are not subject to CSRF
|
||||
if (!this.stateChangingMethods.has(method)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const path = req.originalUrl || req.url || '';
|
||||
|
||||
// Webhooks & Payment Callbacks (e.g. Zibal gateway callback, MeliPayamak incoming webhooks)
|
||||
if (
|
||||
path.includes('/payment/callback') ||
|
||||
path.includes('/payment/verify') ||
|
||||
path.includes('/webhooks')
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 1. Authorization Bearer Token requests are immune to standard cross-site browser CSRF
|
||||
const authHeader = req.headers['authorization'];
|
||||
if (authHeader && authHeader.startsWith('Bearer ')) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 2. Custom header verification (X-Requested-With or X-CSRF-Token)
|
||||
const customHeader =
|
||||
req.headers['x-requested-with'] ||
|
||||
req.headers['x-csrf-token'] ||
|
||||
req.headers['x-api-key'];
|
||||
|
||||
if (customHeader) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// 3. Same-origin Sec-Fetch-Site check (Modern Browsers Protection)
|
||||
const secFetchSite = req.headers['sec-fetch-site'];
|
||||
if (secFetchSite === 'same-origin' || secFetchSite === 'same-site') {
|
||||
return true;
|
||||
}
|
||||
|
||||
// If request has cookie credentials but lacks any anti-CSRF signature, block it
|
||||
if (req.headers.cookie) {
|
||||
throw new ForbiddenException(
|
||||
'درخواست مشکوک به حمله CSRF است. هدر اعتبارسنجی یافت نشد.',
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
+31
-14
@@ -10,6 +10,7 @@ import { DecimalInterceptor } from './common/interceptors/decimal.interceptor';
|
||||
import { validateEnv } from './common/env.validation';
|
||||
import helmet from 'helmet';
|
||||
import compression from 'compression';
|
||||
import * as crypto from 'crypto';
|
||||
|
||||
// Ensure BigInt can be serialized to JSON across all NestJS / Express responses
|
||||
(BigInt.prototype as any).toJSON = function () {
|
||||
@@ -44,22 +45,38 @@ async function bootstrap() {
|
||||
|
||||
app.use(compression());
|
||||
|
||||
// SEC-013: Dynamic cryptographically-secure nonce per request for CSP
|
||||
app.use((req: any, res: any, next: any) => {
|
||||
res.locals.cspNonce = crypto.randomBytes(16).toString('base64');
|
||||
next();
|
||||
});
|
||||
|
||||
app.use(
|
||||
helmet({
|
||||
contentSecurityPolicy: process.env.NODE_ENV === 'production' ? {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"], // Needed for swagger and UI styling if applicable
|
||||
imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
|
||||
connectSrc: ["'self'", 'https:'],
|
||||
fontSrc: ["'self'", 'data:'],
|
||||
objectSrc: ["'none'"],
|
||||
baseUri: ["'self'"],
|
||||
frameAncestors: ["'none'"],
|
||||
upgradeInsecureRequests: [],
|
||||
},
|
||||
} : false,
|
||||
contentSecurityPolicy:
|
||||
process.env.NODE_ENV === 'production'
|
||||
? {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: [
|
||||
"'self'",
|
||||
(req: any, res: any) => `'nonce-${res.locals.cspNonce}'`,
|
||||
],
|
||||
styleSrc: [
|
||||
"'self'",
|
||||
"'unsafe-inline'", // Needed for inline styles across dashboards/UI
|
||||
(req: any, res: any) => `'nonce-${res.locals.cspNonce}'`,
|
||||
],
|
||||
imgSrc: ["'self'", 'data:', 'blob:', 'https:'],
|
||||
connectSrc: ["'self'", 'https:'],
|
||||
fontSrc: ["'self'", 'data:'],
|
||||
objectSrc: ["'none'"],
|
||||
baseUri: ["'self'"],
|
||||
frameAncestors: ["'none'"],
|
||||
upgradeInsecureRequests: [],
|
||||
},
|
||||
}
|
||||
: false,
|
||||
crossOriginEmbedderPolicy: false,
|
||||
}),
|
||||
);
|
||||
|
||||
Reference in new issue
Block a user