feat(support-chat): add admin smart chat settings

This commit is contained in:
devops committed 2026-10-14 19:44:24 +00:00
1 parent fa4f1124e6
commit b6735b5a9c
14 files changed
+285 -25

No files matched your search

+2 -1
View File
@@ -247,7 +247,7 @@ export class SettingsService implements OnModuleInit {
});
// 2. Add from settings and unpack object keys
settings.forEach((s) => {
settings.filter((s) => s.key !== "support_chat").forEach((s) => {
const valStr =
typeof s.value === "string" ? s.value : JSON.stringify(s.value);
mergedMap.set(s.key, valStr);
@@ -276,6 +276,7 @@ export class SettingsService implements OnModuleInit {
}
async updateUiText(key: string, value: string) {
if (key === "support_chat") throw new Error("Use support-chat settings API");
const strVal = String(value ?? "");
const allKeysToUpdate = new Set<string>([key]);
const aliases = CANONICAL_ALIASES[key] || [];
@@ -0,0 +1,17 @@
import { Body, Controller, Get, Put, UseGuards, Header } from '@nestjs/common';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { RolesGuard } from '../common/guards/roles.guard';
import { Roles } from '../common/decorators/roles.decorator';
import { SupportChatSettingsService } from './support-chat-settings.service';
@Controller('support-chat')
export class SupportChatSettingsController {
constructor(private readonly settings: SupportChatSettingsService) {}
@Get('config') @Header('Cache-Control', 'no-store')
config() { return this.settings.publicConfig(); }
@Get('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
read() { return this.settings.read(); }
@Get('catalog') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin') @Header('Cache-Control', 'no-store')
catalog() { return this.settings.catalog(); }
@Put('settings') @UseGuards(JwtAuthGuard, RolesGuard) @Roles('Admin')
save(@Body() body: unknown) { return this.settings.save(body); }
}
@@ -0,0 +1,51 @@
import { BadRequestException, Injectable, ServiceUnavailableException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
export const CHAT_SETTINGS_KEY = 'support_chat';
export type ChatSettings = { enabled: boolean; provider: string; model: string; label: string; icon: string };
const fail = () => new ServiceUnavailableException('تنظیمات پشتیبان هوشمند در دسترس نیست.');
export const ICONS = ['chat', 'paw', 'bot'] as const;
export function validateSettings(value: any): ChatSettings {
if (!value || typeof value !== 'object' || Array.isArray(value) || Object.keys(value).sort().join(',') !== 'enabled,icon,label,model,provider' || typeof value.enabled !== 'boolean' || typeof value.provider !== 'string' || typeof value.model !== 'string' || value.provider.length > 100 || value.model.length > 160 || typeof value.label !== 'string' || !value.label.trim() || value.label.length > 60 || /[<>\x00-\x1f]/.test(value.label) || !ICONS.includes(value.icon)) throw new BadRequestException('تنظیمات پشتیبان نامعتبر است.');
return { enabled: value.enabled, provider: value.provider, model: value.model, label: value.label.trim(), icon: value.icon };
}
@Injectable()
export class SupportChatSettingsService {
constructor(private readonly prisma: PrismaService) {}
async read(): Promise<ChatSettings> {
try {
const row = await this.prisma.setting.findUnique({ where: { key: CHAT_SETTINGS_KEY } });
if (!row) throw fail();
return validateSettings(row.value);
} catch { throw fail(); }
}
async publicConfig() {
const { enabled, label, icon } = await this.read();
return { enabled, label, icon };
}
async catalog(): Promise<{ providers: { id: string; label: string; models: string[] }[] }> {
try {
const url = process.env.SUPPORT_CHAT_URL;
const key = process.env.SUPPORT_CHAT_KEY;
if (!url?.endsWith('/ask') || !key) throw fail();
const response = await fetch(url.replace(/\/ask$/, '/catalog'), { headers: { Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(100000), redirect: 'error' });
if (!response.ok) throw fail();
const data = await response.json();
if (!Array.isArray(data.providers) || !data.providers.length || data.providers.length > 50) throw fail();
const safe = (s: any) => typeof s === 'string' && s.length > 0 && s.length <= 160 && /^[\w .:/@+\[\]()-]+$/.test(s) && !s.includes('://');
return { providers: data.providers.map((p: any) => {
if (!/^configured-[a-f0-9]{16}$/.test(p.id) || !safe(p.label) || !Array.isArray(p.models) || !p.models.length || p.models.length > 2000 || !p.models.every(safe)) throw fail();
return { id: p.id, label: p.label, models: p.models };
}) };
} catch { throw fail(); }
}
async save(input: unknown) {
const value = validateSettings(input);
if (value.provider || value.model || value.enabled) {
const catalog = await this.catalog();
if (!catalog.providers.some(p => p.id === value.provider && p.models.includes(value.model))) throw new BadRequestException('مدل متعلق به ارائه‌دهنده انتخاب‌شده نیست.');
}
await this.prisma.setting.upsert({ where: { key: CHAT_SETTINGS_KEY }, create: { key: CHAT_SETTINGS_KEY, category: 'support-chat', value }, update: { value } });
return this.read();
}
}
@@ -0,0 +1,42 @@
import { SupportChatSettingsService, validateSettings } from './support-chat-settings.service';
import { SupportChatService } from './support-chat.service';
import { SupportChatSettingsController } from './support-chat-settings.controller';
import { Test } from '@nestjs/testing';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
import { ExtractJwt, Strategy } from 'passport-jwt';
import { JwtService } from '@nestjs/jwt';
import request from 'supertest';
class TestJwt extends PassportStrategy(Strategy) {
constructor() { super({ jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(), secretOrKey:'test' }); }
validate(p: any) { return { id:p.sub, role:p.role }; }
}
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()} };
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());
const catalog=()=>jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'Configured',models:[selected.model]}]})} as any);
it('persists and reads exact fields and projects safe public config',async()=>{catalog();expect(await service.save(selected)).toEqual(selected);expect(await service.read()).toEqual(selected);expect(await service.publicConfig()).toEqual({enabled:true,label:selected.label,icon:'paw'});});
it.each([{...selected,model:'unknown'},{...selected,provider:'http://127.0.0.1'},{...selected,provider:'configured-ffffffffffffffff'}])('rejects invalid combination %j',async s=>{catalog();await expect(service.save(s)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
it.each(['https://evil/a.svg','<svg onload=alert(1)>','data:image/svg+xml,abc','/uploads/x.svg'])('rejects unsafe icon %s',icon=>{expect(()=>validateSettings({...selected,icon})).toThrow();});
it('rejects unknown fields and invalid label',()=>{expect(()=>validateSettings({...selected,baseUrl:'https://evil'})).toThrow();expect(()=>validateSettings({...selected,label:'<script>'})).toThrow();});
it('fails closed without configuration',async()=>{await expect(service.read()).rejects.toThrow();});
it('fails closed on catalog outage',async()=>{jest.spyOn(global,'fetch').mockRejectedValue(new Error('secret'));await expect(service.save(selected)).rejects.toThrow();expect(prisma.setting.upsert).not.toHaveBeenCalled();});
it('rejects sanitized catalog violations',async()=>{jest.spyOn(global,'fetch').mockResolvedValue({ok:true,json:async()=>({providers:[{id:selected.provider,label:'https://internal',models:['m'],api_key:'secret'}]})} as any);await expect(service.catalog()).rejects.toThrow();});
it('disabling rejects ask before model and private DB calls',async()=>{stored={value:{...selected,enabled:false}};const f=jest.spyOn(global,'fetch');await expect(new SupportChatService(prisma,service).ask({message:'کیف پول'},{id:'alice'})).rejects.toThrow();expect(f).not.toHaveBeenCalled();expect(prisma.user.findUnique).not.toHaveBeenCalled();expect(prisma.product.findMany).not.toHaveBeenCalled();});
it('uses identical stored selection for classify and answer with no identity leakage',async()=>{stored={value:selected};const f=jest.spyOn(global,'fetch').mockImplementation(async(url)=>({ok:true,json:async()=>String(url).endsWith('/classify')?{intent:'public'}:{answer:'سلام'}} as any));await new SupportChatService(prisma,service).ask({message:'سلام'},{id:'alice'});const bodies=f.mock.calls.map(c=>JSON.parse(c[1]!.body as string));expect(bodies.map(b=>b.selection)).toEqual([{provider:selected.provider,model:selected.model},{provider:selected.provider,model:selected.model}]);expect(JSON.stringify(bodies)).not.toContain('alice');});
});
describe('settings HTTP admin boundary',()=>{
let app:any;
const jwt=new JwtService({secret:'test'});
const service={read:jest.fn(async()=>selected),publicConfig:jest.fn(async()=>({enabled:true,label:'test',icon:'bot'})),save:jest.fn(async()=>selected),catalog:jest.fn(async()=>({providers:[]}))};
beforeAll(async()=>{const mod=await Test.createTestingModule({imports:[PassportModule],controllers:[SupportChatSettingsController],providers:[TestJwt,{provide:SupportChatSettingsService,useValue:service}]}).compile();app=mod.createNestApplication();await app.init();});
afterAll(()=>app.close());
it.each(['settings','catalog'])('rejects anonymous %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).expect(401);});
it.each(['settings','catalog'])('rejects customer %s',async path=>{await request(app.getHttpServer()).get('/support-chat/'+path).set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).expect(403);});
it('rejects anonymous and customer writes',async()=>{await request(app.getHttpServer()).put('/support-chat/settings').send(selected).expect(401);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization','Bearer '+jwt.sign({sub:'customer',role:'Customer'})).send(selected).expect(403);});
it('allows Admin reads and writes',async()=>{const auth='Bearer '+jwt.sign({sub:'admin',role:'Admin'});await request(app.getHttpServer()).get('/support-chat/settings').set('Authorization',auth).expect(200);await request(app.getHttpServer()).get('/support-chat/catalog').set('Authorization',auth).expect(200);await request(app.getHttpServer()).put('/support-chat/settings').set('Authorization',auth).send(selected).expect(200);});
it('public configuration only returns safe fields',async()=>{const r=await request(app.getHttpServer()).get('/support-chat/config').expect(200);expect(Object.keys(r.body).sort()).toEqual(['enabled','icon','label']);});
});
@@ -1,3 +1,4 @@
import { SupportChatSettingsService } from './support-chat-settings.service';
import { Test } from '@nestjs/testing';
import { INestApplication, ValidationPipe } from '@nestjs/common';
import { PassportModule, PassportStrategy } from '@nestjs/passport';
@@ -18,7 +19,7 @@ describe('support HTTP boundary', () => {
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();
const mod = await Test.createTestingModule({ imports: [PassportModule], controllers: [SupportChatController], providers: [{ provide: SupportChatSettingsService, useValue: { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } }, 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());
@@ -1,8 +1,10 @@
import { Module } from '@nestjs/common';
import { SupportChatSettingsService } from './support-chat-settings.service';
import { SupportChatSettingsController } from './support-chat-settings.controller';
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] })
@Module({ imports: [AuthModule, PrismaModule], controllers: [SupportChatController, SupportChatSettingsController], providers: [SupportChatService, SupportChatSettingsService, OptionalCustomerJwtGuard] })
export class SupportChatModule {}
@@ -3,11 +3,11 @@ import { SupportChatService, UNAVAILABLE } from './support-chat.service';
describe('model intent routing', () => {
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();process.env.SUPPORT_CHAT_URL='http://internal/ask';process.env.SUPPORT_CHAT_KEY='test';service=new SupportChatService(prisma);});
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); }
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('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:'چقدر اعتبار دارم؟'});expect(f).toHaveBeenCalledTimes(1);});
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:'چقدر اعتبار دارم؟',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();});
});
@@ -1,18 +1,22 @@
import { Injectable, ServiceUnavailableException } from '@nestjs/common';
import { PrismaService } from '../prisma/prisma.service';
import { SupportChatDto } from './support-chat.dto';
import { SupportChatSettingsService } from './support-chat-settings.service';
export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.';
@Injectable()
export class SupportChatService {
constructor(private readonly prisma: PrismaService) {}
constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {}
async ask(input: SupportChatDto, user?: { id: string }) {
const config = await this.settings.read();
if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE);
const selection = { provider: config.provider, model: config.model };
const url = process.env.SUPPORT_CHAT_URL;
const key = process.env.SUPPORT_CHAT_KEY;
let intent: 'public' | 'orders' | 'wallet';
try {
if (!url || !key || !url.endsWith('/ask')) throw new Error('disabled');
const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message }) });
const response = await fetch(url.replace(/\/ask$/, '/classify'), { method: 'POST', headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` }, signal: AbortSignal.timeout(45000), body: JSON.stringify({ message: input.message, selection }) });
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه پذیرفته نمی‌شود.' };
if (!response.ok) throw new Error('upstream');
const data = await response.json();
@@ -35,7 +39,7 @@ export class SupportChatService {
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 }) });
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, selection }) });
if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمی‌شود.' };
if (!response.ok) throw new Error('upstream');
const data = await response.json();