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
@@ -151,7 +151,8 @@ export class ApiKeysService {
|
||||
.catch(() => {});
|
||||
|
||||
const scopes = key.scopes.split(',').map((s) => s.trim().toLowerCase());
|
||||
const hasAdminScope = scopes.includes('*') || scopes.includes('admin') || scopes.includes('all');
|
||||
// SEC-016: Disallow wildcard '*' from granting admin role; require explicit 'admin' scope
|
||||
const hasAdminScope = scopes.includes('admin');
|
||||
|
||||
return {
|
||||
id: key.id,
|
||||
|
||||
@@ -51,7 +51,11 @@ export class MediaService {
|
||||
}
|
||||
|
||||
const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
|
||||
const ext = path.extname(originalname);
|
||||
const ext = path.extname(originalname).toLowerCase();
|
||||
const ALLOWED_EXTENSIONS = ['.jpg', '.jpeg', '.png', '.webp', '.gif', '.pdf'];
|
||||
if (!ALLOWED_EXTENSIONS.includes(ext)) {
|
||||
throw new BadRequestException('پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایلهای اجرایی مسدود هستند).');
|
||||
}
|
||||
const filename = `${uniqueSuffix}${ext}`;
|
||||
const filePath = path.join(uploadDir, filename);
|
||||
|
||||
|
||||
@@ -179,7 +179,27 @@ export class SslService {
|
||||
const cleanDomain = domain
|
||||
.replace(/^https?:\/\//, '')
|
||||
.replace(/\/.*$/, '')
|
||||
.trim();
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
|
||||
// SEC-009: Strict domain validation preventing SSRF
|
||||
const DOMAIN_REGEX = /^(?!-)[a-zA-Z0-9-]{1,63}(?<!-)(\.[a-zA-Z0-9-]{1,63})*\.[a-zA-Z]{2,}$/;
|
||||
const IP_REGEX = /^(?:\d{1,3}\.){3}\d{1,3}$|^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/;
|
||||
|
||||
if (
|
||||
!cleanDomain ||
|
||||
!DOMAIN_REGEX.test(cleanDomain) ||
|
||||
IP_REGEX.test(cleanDomain) ||
|
||||
cleanDomain === 'localhost' ||
|
||||
cleanDomain.endsWith('.local') ||
|
||||
cleanDomain.endsWith('.internal')
|
||||
) {
|
||||
return resolve({
|
||||
onlineCheck: false,
|
||||
error: 'فرمت نام دامنه نامعتبر است یا آدرسهای IP و داخلی مجاز نیستند.',
|
||||
});
|
||||
}
|
||||
|
||||
const socket = tls.connect(
|
||||
{
|
||||
host: cleanDomain,
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -38,10 +38,7 @@ export class RolesGuard implements CanActivate {
|
||||
// If request originates from an API key, verify it has admin scope for admin-guarded routes
|
||||
if (user.isApiKey) {
|
||||
const scopes = Array.isArray(user.scopes) ? user.scopes : [];
|
||||
const hasAdminScope =
|
||||
scopes.includes('*') ||
|
||||
scopes.includes('admin') ||
|
||||
scopes.includes('all');
|
||||
const hasAdminScope = scopes.includes('admin');
|
||||
if (!hasAdminScope) {
|
||||
throw new ForbiddenException(
|
||||
'کلید API ارائهشده فاقد اسکوپ مدیریتی لازم برای این عملیات است',
|
||||
|
||||
@@ -13,9 +13,15 @@ export class RevalidationService {
|
||||
}
|
||||
|
||||
private get secret(): string {
|
||||
return (
|
||||
process.env.REVALIDATION_SECRET || 'canina_revalidation_secret_key_2026'
|
||||
);
|
||||
const secret = process.env.REVALIDATION_SECRET;
|
||||
if (!secret) {
|
||||
if (process.env.NODE_ENV === 'production') {
|
||||
throw new Error('REVALIDATION_SECRET is required in production environment.');
|
||||
}
|
||||
this.logger.warn('REVALIDATION_SECRET is not defined in environment variables.');
|
||||
return '';
|
||||
}
|
||||
return secret;
|
||||
}
|
||||
|
||||
async revalidateTag(tag: string): Promise<boolean> {
|
||||
|
||||
+4
-2
@@ -49,12 +49,14 @@ async function bootstrap() {
|
||||
contentSecurityPolicy: process.env.NODE_ENV === 'production' ? {
|
||||
directives: {
|
||||
defaultSrc: ["'self'"],
|
||||
scriptSrc: ["'self'", "'unsafe-inline'"],
|
||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||
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,
|
||||
|
||||
@@ -147,6 +147,25 @@ export class OrdersController {
|
||||
return this.ordersService.findAllByUser(req.user.id, query);
|
||||
}
|
||||
|
||||
@Post(':id/retry-payment')
|
||||
@ApiOperation({
|
||||
summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت',
|
||||
})
|
||||
@ApiOkResponse({
|
||||
description: 'درخواست پرداخت مجدد با موفقیت پردازش شد',
|
||||
})
|
||||
retryPayment(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Param('id') id: string,
|
||||
@Body() body: { paymentMethod?: string },
|
||||
) {
|
||||
return this.ordersService.retryPayment(
|
||||
req.user.id,
|
||||
id,
|
||||
body?.paymentMethod,
|
||||
);
|
||||
}
|
||||
|
||||
@Get(':id')
|
||||
@ApiOperation({ summary: 'دریافت جزئیات یک سفارش خاص' })
|
||||
@ApiOkResponse({
|
||||
@@ -186,25 +205,6 @@ export class OrdersController {
|
||||
},
|
||||
},
|
||||
})
|
||||
@Post(':id/retry-payment')
|
||||
@ApiOperation({
|
||||
summary: 'پرداخت مجدد و تکمیل سفارش با امکان انتخاب روش پرداخت',
|
||||
})
|
||||
@ApiOkResponse({
|
||||
description: 'درخواست پرداخت مجدد با موفقیت پردازش شد',
|
||||
})
|
||||
retryPayment(
|
||||
@Req() req: { user: { id: string } },
|
||||
@Param('id') id: string,
|
||||
@Body() body: { paymentMethod?: string },
|
||||
) {
|
||||
return this.ordersService.retryPayment(
|
||||
req.user.id,
|
||||
id,
|
||||
body?.paymentMethod,
|
||||
);
|
||||
}
|
||||
|
||||
findOne(@Req() req: { user: { id: string } }, @Param('id') id: string) {
|
||||
return this.ordersService.findOne(id, req.user.id);
|
||||
}
|
||||
|
||||
@@ -196,20 +196,20 @@ export class OrdersService {
|
||||
if (!user) {
|
||||
throw new NotFoundException('کاربر یافت نشد');
|
||||
}
|
||||
const userBalance = new Prisma.Decimal(user.walletBalance || 0);
|
||||
if (userBalance.lessThan(finalAmount)) {
|
||||
throw new BadRequestException(
|
||||
'موجودی کیف پول برای پرداخت این سفارش کافی نیست',
|
||||
);
|
||||
}
|
||||
|
||||
const createdWalletOrder = await this.prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: {
|
||||
walletBalance: { decrement: Number(finalAmount) },
|
||||
},
|
||||
});
|
||||
// SEC-002: Atomic decrement preventing race condition & overdraft
|
||||
const updatedCount = await tx.$executeRaw`
|
||||
UPDATE "users"
|
||||
SET "wallet_balance" = "wallet_balance" - ${Number(finalAmount)}::decimal
|
||||
WHERE "id" = ${userId}::uuid AND "wallet_balance" >= ${Number(finalAmount)}::decimal
|
||||
`;
|
||||
|
||||
if (updatedCount === 0) {
|
||||
throw new BadRequestException(
|
||||
'موجودی کیف پول برای پرداخت این سفارش کافی نیست',
|
||||
);
|
||||
}
|
||||
|
||||
await tx.walletTransaction.create({
|
||||
data: {
|
||||
@@ -581,18 +581,19 @@ export class OrdersService {
|
||||
const user = await this.prisma.user.findUnique({ where: { id: userId } });
|
||||
if (!user) throw new NotFoundException('کاربر یافت نشد');
|
||||
|
||||
const userBalance = Number(user.walletBalance || 0);
|
||||
if (userBalance < finalAmount) {
|
||||
throw new BadRequestException(
|
||||
`موجودی کیف پول شما (${userBalance.toLocaleString('fa-IR')} تومان) کمتر از مبلغ سفارش (${finalAmount.toLocaleString('fa-IR')} تومان) است.`,
|
||||
);
|
||||
}
|
||||
|
||||
await this.prisma.$transaction(async (tx) => {
|
||||
await tx.user.update({
|
||||
where: { id: userId },
|
||||
data: { walletBalance: { decrement: finalAmount } },
|
||||
});
|
||||
// SEC-002: Atomic decrement preventing race condition & overdraft
|
||||
const updatedCount = await tx.$executeRaw`
|
||||
UPDATE "users"
|
||||
SET "wallet_balance" = "wallet_balance" - ${finalAmount}::decimal
|
||||
WHERE "id" = ${userId}::uuid AND "wallet_balance" >= ${finalAmount}::decimal
|
||||
`;
|
||||
|
||||
if (updatedCount === 0) {
|
||||
throw new BadRequestException(
|
||||
`موجودی کیف پول شما برای پرداخت این سفارش (${finalAmount.toLocaleString('fa-IR')} تومان) کافی نیست.`,
|
||||
);
|
||||
}
|
||||
|
||||
await tx.walletTransaction.create({
|
||||
data: {
|
||||
|
||||
Reference in new issue
Block a user