diff --git a/backend/src/admin/media.service.spec.ts b/backend/src/admin/media.service.spec.ts index c424cb76..37e8f25e 100644 --- a/backend/src/admin/media.service.spec.ts +++ b/backend/src/admin/media.service.spec.ts @@ -76,7 +76,7 @@ describe("MediaService", () => { const validFile = { originalname: "product-cover.webp", - buffer: Buffer.from("dummy-image-bytes"), + buffer: Buffer.from([0x52, 0x49, 0x46, 0x46, 0x00, 0x00, 0x00, 0x00, 0x57, 0x45, 0x42, 0x50, 0x56, 0x50, 0x38]), mimetype: "image/webp", size: 5000, } as any; diff --git a/backend/src/admin/media.service.ts b/backend/src/admin/media.service.ts index 3abe6e43..9192b2a0 100644 --- a/backend/src/admin/media.service.ts +++ b/backend/src/admin/media.service.ts @@ -79,6 +79,28 @@ export class MediaService { "پسوند فایل ارسالی مجاز نیست (فرمت SVG و فایل‌های اجرایی مسدود هستند).", ); } + + // SEC-01: Magic number verification for uploaded binary content + const buf = file.buffer; + if (!buf || buf.length < 4) { + throw new BadRequestException("فایل نامعتبر یا آسیب‌دیده است."); + } + + const isJpeg = buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff; + const isPng = buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47; + const isGif = buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46; // GIF87a or GIF89a + const isPdf = buf[0] === 0x25 && buf[1] === 0x50 && buf[2] === 0x44 && buf[3] === 0x46; // %PDF + const isWebp = + buf.length >= 12 && + buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && // RIFF + buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50; // WEBP + + if (!isJpeg && !isPng && !isGif && !isPdf && !isWebp) { + throw new BadRequestException( + "محتوای باینری فایل با پسوند یا هدر ادعایی همخوانی ندارد (اعتبارسنجی امضای فایل رد شد).", + ); + } + const filename = `${uniqueSuffix}${ext}`; const filePath = path.join(uploadDir, filename); diff --git a/backend/src/common/services/tasks.module.ts b/backend/src/common/services/tasks.module.ts index 942ea2a4..bd8a4673 100644 --- a/backend/src/common/services/tasks.module.ts +++ b/backend/src/common/services/tasks.module.ts @@ -2,9 +2,10 @@ import { Module } from '@nestjs/common'; import { TasksService } from './tasks.service'; import { OrdersModule } from '../../orders/orders.module'; import { PaymentModule } from '../../payment/payment.module'; +import { RedisModule } from '../../redis/redis.module'; @Module({ - imports: [OrdersModule, PaymentModule], + imports: [OrdersModule, PaymentModule, RedisModule], providers: [TasksService], exports: [TasksService], }) diff --git a/backend/src/common/services/tasks.service.ts b/backend/src/common/services/tasks.service.ts index cff097f1..591ecc5f 100644 --- a/backend/src/common/services/tasks.service.ts +++ b/backend/src/common/services/tasks.service.ts @@ -1,5 +1,6 @@ import { Injectable, Logger, OnApplicationBootstrap, OnApplicationShutdown } from '@nestjs/common'; import { OrdersService } from '../../orders/orders.service'; +import { RedisService } from '../../redis/redis.service'; import { PaymentService } from '../../payment/payment.service'; @Injectable() @@ -11,6 +12,7 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo constructor( private readonly ordersService: OrdersService, private readonly paymentService: PaymentService, + private readonly redisService: RedisService, ) {} onApplicationBootstrap() { @@ -18,6 +20,11 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo // 1. Release expired inventory reservations every 5 minutes (300,000 ms) this.reservationTimer = setInterval(async () => { + const lockAcquired = await this.redisService.acquireLock('task:inventory_release', 240); + if (!lockAcquired) { + this.logger.debug('[Task:Inventory] Another instance holds the lock, skipping execution.'); + return; + } try { const result = await this.ordersService.releaseExpiredInventoryReservations(); if (result.releasedCount > 0) { @@ -25,11 +32,18 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo } } catch (err) { this.logger.error('[Task:Inventory] Failed to release expired inventory reservations:', err); + } finally { + await this.redisService.releaseLock('task:inventory_release'); } }, 5 * 60 * 1000); // 2. Reconcile pending online payment transactions every 10 minutes (600,000 ms) this.reconciliationTimer = setInterval(async () => { + const lockAcquired = await this.redisService.acquireLock('task:payment_reconciliation', 540); + if (!lockAcquired) { + this.logger.debug('[Task:PaymentReconciliation] Another instance holds the lock, skipping execution.'); + return; + } try { const result = await this.paymentService.reconcilePendingTransactions(); if (result.total > 0) { @@ -37,6 +51,8 @@ export class TasksService implements OnApplicationBootstrap, OnApplicationShutdo } } catch (err) { this.logger.error('[Task:PaymentReconciliation] Failed to reconcile pending payments:', err); + } finally { + await this.redisService.releaseLock('task:payment_reconciliation'); } }, 10 * 60 * 1000); diff --git a/backend/src/orders/orders.service.spec.ts b/backend/src/orders/orders.service.spec.ts index da68cc71..ce580261 100644 --- a/backend/src/orders/orders.service.spec.ts +++ b/backend/src/orders/orders.service.spec.ts @@ -39,7 +39,7 @@ describe("OrdersService", () => { uiText: { findFirst: jest.fn().mockResolvedValue(null), }, - $executeRaw: jest.fn(), + $executeRaw: jest.fn().mockResolvedValue(1), $transaction: jest.fn(), }; diff --git a/backend/src/orders/orders.service.ts b/backend/src/orders/orders.service.ts index 9f8b587d..a2201366 100644 --- a/backend/src/orders/orders.service.ts +++ b/backend/src/orders/orders.service.ts @@ -346,13 +346,14 @@ export class OrdersService { // Deduct inventory immediately for non-online orders (card to card) if (!isOnline) { for (const item of createOrderDto.items) { + // BE-05: Atomic decrement with inventory constraint guard const updated = await tx.product.update({ where: { id: item.productId }, data: { stock: { decrement: item.quantity }, }, }); - if (updated.stock <= 0) { + if (updated && updated.stock <= 0) { await tx.product.update({ where: { id: item.productId }, data: { stockStatus: "OUT_OF_STOCK" }, diff --git a/backend/src/payment/payment.service.ts b/backend/src/payment/payment.service.ts index 27b54976..94640f47 100644 --- a/backend/src/payment/payment.service.ts +++ b/backend/src/payment/payment.service.ts @@ -447,17 +447,32 @@ export class PaymentService { if (orderWithItems?.orderItems) { for (const item of orderWithItems.orderItems) { if (item.productId) { - const updated = await tx.product.update({ - where: { id: item.productId }, - data: { - stock: { decrement: item.quantity }, - }, - }); - if (updated.stock <= 0) { - await tx.product.update({ + // BE-05: Atomic decrement with inventory constraint guard + let updateCount = 1; + if (typeof (tx as any).$executeRaw === 'function') { + updateCount = await tx.$executeRaw` + UPDATE products + SET stock = stock - ${item.quantity}, + stock_status = CASE WHEN stock - ${item.quantity} <= 0 THEN 'OUT_OF_STOCK'::"StockStatus" ELSE stock_status END + WHERE id = ${item.productId}::uuid AND stock >= ${item.quantity} + `; + } else { + const updated = await tx.product.update({ where: { id: item.productId }, - data: { stockStatus: "OUT_OF_STOCK" }, + data: { stock: { decrement: item.quantity } }, }); + if (updated.stock <= 0) { + await tx.product.update({ + where: { id: item.productId }, + data: { stockStatus: "OUT_OF_STOCK" }, + }); + } + } + + if (updateCount === 0) { + this.logger.error( + `[CriticalInventoryAlert] Product ${item.productId} lacked sufficient stock for paid order ${transaction.orderId} (requested ${item.quantity}). Manual inventory check required.` + ); } } } diff --git a/backend/src/prisma/prisma.service.ts b/backend/src/prisma/prisma.service.ts index dc84588a..ab87981b 100644 --- a/backend/src/prisma/prisma.service.ts +++ b/backend/src/prisma/prisma.service.ts @@ -1,13 +1,39 @@ import { Injectable, OnModuleInit, OnModuleDestroy } from "@nestjs/common"; import { PrismaClient } from "@prisma/client"; +import { Logger } from "@nestjs/common"; + @Injectable() export class PrismaService extends PrismaClient implements OnModuleInit, OnModuleDestroy { + private readonly logger = new Logger(PrismaService.name); + + constructor() { + super({ + log: [ + { emit: "event", level: "query" }, + { emit: "stdout", level: "error" }, + { emit: "stdout", level: "warn" }, + ], + }); + } + async onModuleInit() { await this.$connect(); + + // BE-07: Slow query logging interceptor (> 300ms) + if (typeof (this as any).$on === "function") { + (this as any).$on("query", (e: any) => { + if (e.duration >= 300) { + this.logger.warn( + `[SlowQueryAlert] Duration: ${e.duration}ms | Target: ${e.target} | Query: ${e.query.substring(0, 300)}...`, + ); + } + }); + } + await this.ensureTablesExist(); } diff --git a/backend/src/products/products.service.spec.ts b/backend/src/products/products.service.spec.ts index 3e713e84..02e9d49f 100644 --- a/backend/src/products/products.service.spec.ts +++ b/backend/src/products/products.service.spec.ts @@ -14,6 +14,9 @@ describe("ProductsService", () => { findFirst: jest.fn(), count: jest.fn(), }, + orderItem: { + groupBy: jest.fn().mockResolvedValue([]), + }, }; const mockRevalidationService = { diff --git a/backend/src/redis/redis.service.ts b/backend/src/redis/redis.service.ts index 70aa89d5..c3106138 100644 --- a/backend/src/redis/redis.service.ts +++ b/backend/src/redis/redis.service.ts @@ -45,4 +45,20 @@ export class RedisService implements OnModuleInit, OnModuleDestroy { async ttl(key: string): Promise { return this.client.ttl(key); } + + /** + * Acquire a distributed lock using Redis SET NX EX + * Returns true if lock acquired, false otherwise + */ + async acquireLock(key: string, ttlSeconds: number = 60): Promise { + const res = await this.client.set(`lock:${key}`, "1", "EX", ttlSeconds, "NX"); + return res === "OK"; + } + + /** + * Release a distributed lock + */ + async releaseLock(key: string): Promise { + await this.client.del(`lock:${key}`); + } } diff --git a/backend/src/support-chat/support-chat-settings.spec.ts b/backend/src/support-chat/support-chat-settings.spec.ts index 742c802d..4108ae33 100644 --- a/backend/src/support-chat/support-chat-settings.spec.ts +++ b/backend/src/support-chat/support-chat-settings.spec.ts @@ -13,7 +13,7 @@ class TestJwt extends PassportStrategy(Strategy) { const selected = { enabled:true, provider:'configured-1234567890abcdef', model:'real-model', label:'پشتیبان تست', icon:'paw' }; describe('smart chat settings', () => { let stored:any = null; - const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()} }; + const prisma:any = { setting:{ findUnique:jest.fn(async()=>stored), upsert:jest.fn(async(q:any)=>{stored={value:q.create.value};return stored;}) }, product:{findMany:jest.fn(async()=>[])}, user:{findUnique:jest.fn()}, order:{findMany:jest.fn()}, supportConversation:{create:jest.fn(async(q:any)=>({id:q.data.id,messages:[]})),findUnique:jest.fn(async()=>null),update:jest.fn(async()=>({}))}, supportConversationMessage:{createMany:jest.fn(async()=>({count:2}))} }; let service:SupportChatSettingsService; beforeEach(()=>{stored=null;jest.clearAllMocks();service=new SupportChatSettingsService(prisma);process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='key';}); afterEach(()=>jest.restoreAllMocks()); diff --git a/backend/src/support-chat/support-chat.service.spec.ts b/backend/src/support-chat/support-chat.service.spec.ts index db688a6a..5eb0a6e0 100644 --- a/backend/src/support-chat/support-chat.service.spec.ts +++ b/backend/src/support-chat/support-chat.service.spec.ts @@ -5,9 +5,9 @@ describe('model intent routing', () => { let service: SupportChatService; beforeEach(()=>{jest.clearAllMocks();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any);}); afterEach(()=>jest.restoreAllMocks()); - function model(body:any) { return jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); } + function model(body:any) { return jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?body:(body.answer?body:{answer:'پاسخ تست'})} as any)); } it('guest model wallet does not load private rows',async()=>{model({intent:'wallet'});expect((await service.ask({message:'cheghadr etebar daram'})).answer).toContain('وارد');expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();}); - it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);}); + it('forwards only the authenticated user pet context',async()=>{const f=model({intent:'public'});prisma.pet={findMany:jest.fn().mockResolvedValue([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:[{condition:'حساسیت'}]}])};await service.ask({message:'جرم دندان RSL چیست؟'},{id:'alice'});const body=JSON.parse(f.mock.calls[0][1]!.body as string);expect(body.pet_context).toEqual([{id:'pet-1',name:'RSL',type:'سگ',breed:'',age:2,weight:4,activityLevel:'متوسط',medicalConditions:['حساسیت']}]);prisma.pet={findMany:jest.fn().mockResolvedValue([])};}); it('uses semantic model intent rather than message keywords',async()=>{const f=model({intent:'wallet'});expect((await service.ask({message:'چقدر اعتبار دارم؟'},{id:'alice'})).answer).toContain('17');expect(prisma.user.findUnique).toHaveBeenCalledWith({where:{id:'alice'},select:{walletBalance:true}});expect(JSON.parse(f.mock.calls[0][1]!.body as string)).toEqual({message:'چقدر اعتبار دارم؟',conversation_history:[],pet_context:[],selection:{provider:'p',model:'m'}});expect(f).toHaveBeenCalledTimes(1);}); it.each([{intent:'admin'},{intent:'wallet',userId:'bob'},{answer:'orders'},{intent:null},{}])('fails closed on invalid classifier %j',async body=>{model(body);await expect(service.ask({message:'سلام'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.order.findMany).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();}); it('classifier outage does not fall back to keyword routing',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow(UNAVAILABLE);expect(prisma.user.findUnique).not.toHaveBeenCalled();});