feat(support): isolated stateless customer chat with JWT gatekeeper
This commit is contained in:
1 parent
8bf1843b9b
commit
8242a1271f
21 files changed
+413
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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); }
|
||||
}
|
||||
@@ -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';
|
||||
}
|
||||
@@ -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<T>(err: unknown, user: T | false): T {
|
||||
if (err || !user) throw new UnauthorizedException('لطفاً دوباره وارد حساب کاربری شوید.');
|
||||
return user;
|
||||
}
|
||||
}
|
||||
@@ -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(); });
|
||||
});
|
||||
@@ -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 {}
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -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); }
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user