From 8242a1271f4ea01b8ea66f1cd087caf7a6121b57 Mon Sep 17 00:00:00 2001 From: devops Date: Wed, 14 Oct 2026 16:48:56 +0000 Subject: [PATCH] feat(support): isolated stateless customer chat with JWT gatekeeper --- backend/src/app.module.ts | 2 + .../support-chat/support-chat.controller.ts | 13 ++++ backend/src/support-chat/support-chat.dto.ts | 5 ++ .../src/support-chat/support-chat.guard.ts | 17 +++++ .../support-chat/support-chat.http.spec.ts | 41 +++++++++++ .../src/support-chat/support-chat.module.ts | 8 +++ .../support-chat/support-chat.service.spec.ts | 13 ++++ .../src/support-chat/support-chat.service.ts | 34 +++++++++ frontend/application/app/layout.tsx | 2 + .../components/SupportChat.test.tsx | 30 ++++++++ .../application/components/SupportChat.tsx | 42 +++++++++++ scripts/support-chat/Dockerfile | 9 +++ scripts/support-chat/README.md | 20 ++++++ scripts/support-chat/bootstrap.py | 19 +++++ .../compose.bot.override.example.yml | 7 ++ .../compose.stage.override.example.yml | 6 ++ scripts/support-chat/policy.py | 27 ++++++++ scripts/support-chat/run | 7 ++ scripts/support-chat/server.py | 69 +++++++++++++++++++ scripts/support-chat/test_policy.py | 14 ++++ scripts/support-chat/verify-stage.cjs | 28 ++++++++ 21 files changed, 413 insertions(+) create mode 100644 backend/src/support-chat/support-chat.controller.ts create mode 100644 backend/src/support-chat/support-chat.dto.ts create mode 100644 backend/src/support-chat/support-chat.guard.ts create mode 100644 backend/src/support-chat/support-chat.http.spec.ts create mode 100644 backend/src/support-chat/support-chat.module.ts create mode 100644 backend/src/support-chat/support-chat.service.spec.ts create mode 100644 backend/src/support-chat/support-chat.service.ts create mode 100644 frontend/application/components/SupportChat.test.tsx create mode 100644 frontend/application/components/SupportChat.tsx create mode 100644 scripts/support-chat/Dockerfile create mode 100644 scripts/support-chat/README.md create mode 100644 scripts/support-chat/bootstrap.py create mode 100644 scripts/support-chat/compose.bot.override.example.yml create mode 100644 scripts/support-chat/compose.stage.override.example.yml create mode 100644 scripts/support-chat/policy.py create mode 100644 scripts/support-chat/run create mode 100644 scripts/support-chat/server.py create mode 100644 scripts/support-chat/test_policy.py create mode 100644 scripts/support-chat/verify-stage.cjs diff --git a/backend/src/app.module.ts b/backend/src/app.module.ts index 690fbe86..53b5f778 100644 --- a/backend/src/app.module.ts +++ b/backend/src/app.module.ts @@ -1,5 +1,6 @@ import { Module, NestModule, MiddlewareConsumer } from "@nestjs/common"; import { PrismaModule } from "./prisma/prisma.module"; +import { SupportChatModule } from './support-chat/support-chat.module'; import { ProductsModule } from "./products/products.module"; import { UsersModule } from "./users/users.module"; import { RedisModule } from "./redis/redis.module"; @@ -40,6 +41,7 @@ import { Request, Response, NextFunction } from "express"; @Module({ imports: [ + SupportChatModule, RevalidationModule, SmsModule, ContactModule, diff --git a/backend/src/support-chat/support-chat.controller.ts b/backend/src/support-chat/support-chat.controller.ts new file mode 100644 index 00000000..ea3dc5bd --- /dev/null +++ b/backend/src/support-chat/support-chat.controller.ts @@ -0,0 +1,13 @@ +import { Body, Controller, Post, Req, UseGuards, Header } from '@nestjs/common'; +import { Throttle } from '@nestjs/throttler'; +import { SupportChatService } from './support-chat.service'; +import { SupportChatDto } from './support-chat.dto'; +import { OptionalCustomerJwtGuard } from './support-chat.guard'; +@Controller('support-chat') +export class SupportChatController { + constructor(private readonly service: SupportChatService) {} + @Post('ask') @UseGuards(OptionalCustomerJwtGuard) + @Throttle({ default: { limit: 10, ttl: 60000 } }) + @Header('Cache-Control', 'no-store') + ask(@Body() dto: SupportChatDto, @Req() req: { user?: { id: string } }) { return this.service.ask(dto, req.user); } +} diff --git a/backend/src/support-chat/support-chat.dto.ts b/backend/src/support-chat/support-chat.dto.ts new file mode 100644 index 00000000..b4617fdd --- /dev/null +++ b/backend/src/support-chat/support-chat.dto.ts @@ -0,0 +1,5 @@ +import { IsIn, IsString, Length } from 'class-validator'; +export class SupportChatDto { + @IsString() @Length(1, 1500) message!: string; + @IsIn(['public', 'orders', 'wallet']) scope: 'public' | 'orders' | 'wallet' = 'public'; +} diff --git a/backend/src/support-chat/support-chat.guard.ts b/backend/src/support-chat/support-chat.guard.ts new file mode 100644 index 00000000..9c94736b --- /dev/null +++ b/backend/src/support-chat/support-chat.guard.ts @@ -0,0 +1,17 @@ +import { ExecutionContext, Injectable, UnauthorizedException } from '@nestjs/common'; +import { AuthGuard } from '@nestjs/passport'; +@Injectable() +export class OptionalCustomerJwtGuard extends AuthGuard('jwt') { + canActivate(context: ExecutionContext) { + const req = context.switchToHttp().getRequest(); + const supplied = Object.prototype.hasOwnProperty.call(req.headers, 'authorization') || /(?:^|;\s*)accessToken=/.test(req.headers.cookie || ''); + if (!supplied) return true; + if ((process.env.JWT_ACCESS_SECRET || process.env.JWT_SECRET || '').length < 32) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); + if (req.headers.authorization !== undefined && !/^Bearer \S+$/.test(req.headers.authorization)) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); + return super.canActivate(context); + } + handleRequest(err: unknown, user: T | false): T { + if (err || !user) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.'); + return user; + } +} diff --git a/backend/src/support-chat/support-chat.http.spec.ts b/backend/src/support-chat/support-chat.http.spec.ts new file mode 100644 index 00000000..f1a6542c --- /dev/null +++ b/backend/src/support-chat/support-chat.http.spec.ts @@ -0,0 +1,41 @@ +import { Test } from '@nestjs/testing'; +import { INestApplication, ValidationPipe } from '@nestjs/common'; +import { PassportModule, PassportStrategy } from '@nestjs/passport'; +import { Strategy, ExtractJwt } from 'passport-jwt'; +import { JwtService } from '@nestjs/jwt'; +import request from 'supertest'; +import { SupportChatController } from './support-chat.controller'; +import { SupportChatService, UNAVAILABLE } from './support-chat.service'; +import { OptionalCustomerJwtGuard } from './support-chat.guard'; +import { PrismaService } from '../prisma/prisma.service'; +class TestJwt extends PassportStrategy(Strategy) { + constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey: 'test-secret', algorithms: ['HS256'] }); } + validate(payload: any) { return { id: payload.sub }; } +} +describe('support HTTP boundary', () => { + let app: INestApplication; + const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockImplementation(({where}) => [{ id: where.userId + '-order', status: 'processing', totalAmount: '19' }]) }, user: { findUnique: jest.fn().mockImplementation(({where}) => ({ walletBalance: where.id === 'alice' ? '11' : '22' })) } }; + const jwt = new JwtService({ secret: 'test-secret' }); + beforeAll(async () => { + process.env.JWT_ACCESS_SECRET = 'test-secret-with-at-least-32-characters'; + const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard, TestJwt, { provide: PrismaService, useValue: prisma }] }).compile(); + app = mod.createNestApplication(); app.useGlobalPipes(new ValidationPipe({ transform: true, whitelist: true, forbidNonWhitelisted: true })); await app.init(); + }); + afterAll(() => app.close()); + beforeEach(() => { jest.clearAllMocks(); }); + it.each(['userId','history','context','sessionId','conversationId'])('rejects untrusted %s', async field => { await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سلام', [field]:'alice'}).expect(400); }); + it.each(['Bearer broken','Basic abc','', 'Bearer '])('rejects supplied invalid auth %j', async auth => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization',auth).send({message:'سلام'}).expect(401); }); + it('fails closed when configured JWT secret is missing', async () => { const saved=process.env.JWT_ACCESS_SECRET; delete process.env.JWT_ACCESS_SECRET; await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'کیف پول',scope:'wallet'}).expect(401); process.env.JWT_ACCESS_SECRET=saved; }); + it('rejects expired JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'}, {expiresIn:-1})).send({message:'سلام'}).expect(401); }); + it('rejects cookie JWT rather than downgrading to guest', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Cookie','accessToken=broken').send({message:'سلام'}).expect(401); }); + it('guest orders do not touch any private rows', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'سفارش من',scope:'orders'}).expect(201); expect(r.body.answer).toContain('وارد'); expect(prisma.order.findMany).not.toHaveBeenCalled(); }); + it('scopes wallet to validated identity across concurrent callers', async () => { + const replies=await Promise.all(['alice','bob'].map(sub => request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub})).send({message:'کیف پول',scope:'wallet'}).expect(201))); + expect(replies[0].body.answer).toContain('11'); expect(replies[0].body.answer).not.toContain('22'); expect(replies[1].body.answer).toContain('22'); expect(prisma.product.findMany).not.toHaveBeenCalled(); + }); + it('scopes bounded orders to identity', async () => { const r=await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'bob'})).send({message:'سفارش',scope:'orders'}).expect(201); expect(r.body.answer).toContain('bob-order'); expect(prisma.order.findMany).toHaveBeenCalledWith(expect.objectContaining({ where:{userId:'bob'}, take:5 })); }); + it.each(['', 'x'.repeat(1501)])('bounds message length', async message => { await request(app.getHttpServer()).post('/support-chat/ask').send({message}).expect(400); }); + it('does not query private data in public scope even with valid JWT', async () => { await request(app.getHttpServer()).post('/support-chat/ask').set('Authorization','Bearer '+jwt.sign({sub:'alice'})).send({message:'سلام',scope:'public'}); expect(prisma.user.findUnique).not.toHaveBeenCalled(); expect(prisma.order.findMany).not.toHaveBeenCalled(); }); + it.each([{error:'upstream-secret'}, {answer:'Provider authentication failed Hermes'}, {answer:''}])('filters malformed and default upstream failures', async body => { process.env.SUPPORT_CHAT_URL='http://internal/ask'; process.env.SUPPORT_CHAT_KEY='test'; const f=jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>body} as any); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); expect(JSON.stringify(r.body)).not.toContain('upstream-secret'); f.mockRestore(); }); + it('returns safe unavailable on network errors', async () => { const f=jest.spyOn(global,'fetch').mockRejectedValue(new Error('private-secret')); const r=await request(app.getHttpServer()).post('/support-chat/ask').send({message:'مکمل سگ'}).expect(503); expect(r.body.message).toBe(UNAVAILABLE); f.mockRestore(); }); +}); diff --git a/backend/src/support-chat/support-chat.module.ts b/backend/src/support-chat/support-chat.module.ts new file mode 100644 index 00000000..3ad225d0 --- /dev/null +++ b/backend/src/support-chat/support-chat.module.ts @@ -0,0 +1,8 @@ +import { Module } from '@nestjs/common'; +import { AuthModule } from '../auth/auth.module'; +import { PrismaModule } from '../prisma/prisma.module'; +import { SupportChatController } from './support-chat.controller'; +import { SupportChatService } from './support-chat.service'; +import { OptionalCustomerJwtGuard } from './support-chat.guard'; +@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatController], providers: [SupportChatService, OptionalCustomerJwtGuard] }) +export class SupportChatModule {} diff --git a/backend/src/support-chat/support-chat.service.spec.ts b/backend/src/support-chat/support-chat.service.spec.ts new file mode 100644 index 00000000..2eb8736c --- /dev/null +++ b/backend/src/support-chat/support-chat.service.spec.ts @@ -0,0 +1,13 @@ +import { SupportChatService, UNAVAILABLE } from './support-chat.service'; + +describe('SupportChatService', () => { + const prisma: any = { product: { findMany: jest.fn().mockResolvedValue([]) }, order: { findMany: jest.fn().mockResolvedValue([]) }, user: { findUnique: jest.fn().mockResolvedValue({ walletBalance: '17' }) } }; + let service: SupportChatService; + beforeEach(() => { jest.clearAllMocks(); service = new SupportChatService(prisma); }); + it('does not load private rows for a guest asking about wallet', async () => { + const result = await service.ask({ message: 'موجودی کیف پول من', scope: 'wallet' }); + expect(result.answer).toContain('وارد'); + expect(prisma.user.findUnique).not.toHaveBeenCalled(); + expect(prisma.order.findMany).not.toHaveBeenCalled(); + }); +}); diff --git a/backend/src/support-chat/support-chat.service.ts b/backend/src/support-chat/support-chat.service.ts new file mode 100644 index 00000000..11b2fd5a --- /dev/null +++ b/backend/src/support-chat/support-chat.service.ts @@ -0,0 +1,34 @@ +import { Injectable, ServiceUnavailableException } from '@nestjs/common'; +import { PrismaService } from '../prisma/prisma.service'; +import { SupportChatDto } from './support-chat.dto'; + +export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; +@Injectable() +export class SupportChatService { + constructor(private readonly prisma: PrismaService) {} + async ask(input: SupportChatDto, user?: { id: string }) { + if (input.scope !== 'public' && !user) return { answer: 'برای مشاهده سفارش‌ها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' }; + if (input.scope === 'wallet') { + const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); + if (!row) throw new ServiceUnavailableException(UNAVAILABLE); + return { answer: `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.` }; + } + if (input.scope === 'orders') { + const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true, createdAt: true }, take: 5, orderBy: { createdAt: 'desc' } }); + return { answer: rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.' }; + } + // Private account rows never leave the backend, even when the model is compromised. + try { + const products = await this.prisma.product.findMany({ take: 80, orderBy: { nameFa: 'asc' }, select: { nameFa: true, nameEn: true, slug: true, priceValue: true, stock: true, stockStatus: true, suitableFor: true, shortDescription: true } }); + const url = process.env.SUPPORT_CHAT_URL; + const key = process.env.SUPPORT_CHAT_KEY; + if (!url || !key) throw new Error('disabled'); + const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, catalog: products }) }); + if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمی‌شود.' }; + if (!response.ok) throw new Error('upstream'); + const data = await response.json(); + if (typeof data.answer !== 'string' || !data.answer.trim() || data.answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(data.answer)) throw new Error('unsafe'); + return { answer: data.answer }; + } catch { throw new ServiceUnavailableException(UNAVAILABLE); } + } +} diff --git a/frontend/application/app/layout.tsx b/frontend/application/app/layout.tsx index 6cf31a9f..00fbe7a0 100644 --- a/frontend/application/app/layout.tsx +++ b/frontend/application/app/layout.tsx @@ -3,6 +3,7 @@ import './globals.css'; import NextTopLoader from 'nextjs-toploader'; import ClientLayout from './ClientLayout'; import AnalyticsDeferred from '../components/AnalyticsDeferred'; +import SupportChat from '../components/SupportChat'; import { getSeoConfig } from '../lib/seo'; import { vazirmatn, lalezar } from '../lib/fonts'; import { generateOrganizationSchema } from '../lib/schema'; @@ -199,6 +200,7 @@ export default async function RootLayout({ {children} + {/* Deferred Analytics (GTM, GA4, Clarity) to unblock Main Thread */} { cleanup(); vi.restoreAllMocks(); localStorage.clear(); }); +describe('support widget', () => { + it('submits only message and explicit scope, renders text safely', async () => { + const fetcher=vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:''})} as Response); + render(); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'})); + fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'مکمل سگ'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); + await waitFor(()=>expect(screen.getByText('')).toBeTruthy()); + expect(JSON.parse(fetcher.mock.calls[0][1]!.body as string)).toEqual({message:'مکمل سگ',scope:'public'}); + expect(document.querySelector('script')).toBeNull(); + }); + it('does not expose upstream errors', async()=> { + vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:false,status:503,json:async()=>({message:'secret-provider'})} as Response); + render(); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'})); + fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'سلام'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); + await waitFor(()=>expect(screen.getByText(/فعلاً در دسترس نیست/)).toBeTruthy()); expect(screen.queryByText('secret-provider')).toBeNull(); + }); + it('clears transcript on account transition', async()=> { + localStorage.setItem('accessToken','alice'); + vi.spyOn(globalThis,'fetch').mockResolvedValue({ok:true,json:async()=>({answer:'private Alice'})} as Response); + render(); fireEvent.click(screen.getByRole('button',{name:'گفتگو با پشتیبان'})); fireEvent.change(screen.getByLabelText('پیام شما'),{target:{value:'کیف پول'}}); fireEvent.click(screen.getByRole('button',{name:'ارسال'})); + await waitFor(()=>expect(screen.getByText('private Alice')).toBeTruthy()); + localStorage.setItem('accessToken','bob'); fireEvent.focus(window); + await waitFor(()=>expect(screen.queryByText('private Alice')).toBeNull()); + }); +}); diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx new file mode 100644 index 00000000..57a504e6 --- /dev/null +++ b/frontend/application/components/SupportChat.tsx @@ -0,0 +1,42 @@ +'use client'; +import { FormEvent, useEffect, useRef, useState } from 'react'; +const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; +const token = () => { try { return localStorage.getItem('accessToken') || ''; } catch { return ''; } }; +export default function SupportChat() { + const [open,setOpen]=useState(false), [message,setMessage]=useState(''), [scope,setScope]=useState('public'), [busy,setBusy]=useState(false); + const [rows,setRows]=useState<{question:string,answer:string}[]>([]); + const identity=useRef(''), pending=useRef(null); + useEffect(()=>{ + identity.current=token(); + const check=()=>{ if(identity.current!==token()){identity.current=token();pending.current?.abort();setRows([]);setMessage('');setScope('public');setBusy(false);} }; + window.addEventListener('focus',check);window.addEventListener('storage',check); + const interval=window.setInterval(check,500); + return ()=>{window.removeEventListener('focus',check);window.removeEventListener('storage',check);clearInterval(interval);pending.current?.abort();}; + },[]); + async function send(event:FormEvent) { + event.preventDefault();if(busy||!message.trim())return; + const current=token(); if(current!==identity.current){setRows([]);identity.current=current;} + const question=message.trim();setMessage('');setBusy(true); + const controller=new AbortController();pending.current=controller; + let answer=unavailable; + try { + const response=await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/ask`,{method:'POST',headers:{'Content-Type':'application/json','X-Requested-With':'XMLHttpRequest',...(current?{Authorization:`Bearer ${current}`}:{})},credentials:'include',body:JSON.stringify({message:question,scope}),signal:AbortSignal.any([controller.signal,AbortSignal.timeout(50000)])}); + if(response.status===401)answer='لطفاً دوباره وارد حساب کاربری شوید.'; + else if(response.ok){const data=await response.json();if(typeof data.answer==='string')answer=data.answer;} + } catch {} + if(!controller.signal.aborted&&token()===current)setRows(r=>[...r.slice(-9),{question,answer}]); + if(pending.current===controller)setBusy(false); + } + return