diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 13be216c..1c8c6e15 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -13,6 +13,7 @@ jobs: - name: Run deploy.sh from within the scripts folder env: BRANCH: ${{ github.ref_name }} + SUPPORT_CHAT_KEY: ${{ secrets.SUPPORT_CHAT_KEY }} run: | # 1. رفع مشکل DNS و غیرفعال کردن پروکسی برای دامنه محلی echo "87.248.133.138 git.parsaaghayi.ir" >> /etc/hosts diff --git a/backend/Dockerfile b/backend/Dockerfile index 77497183..a7f33c1d 100644 --- a/backend/Dockerfile +++ b/backend/Dockerfile @@ -45,4 +45,4 @@ COPY --chown=node:node --from=builder /app/src ./src COPY --chown=node:node --from=builder /app/test ./test EXPOSE 3000 USER node -CMD ["sh", "-c", "npx prisma db push --skip-generate && if [ -f dist/src/main.js ]; then node dist/src/main.js; else node dist/main.js; fi"] \ No newline at end of file +CMD ["node", "dist/main.js"] \ No newline at end of file diff --git a/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql b/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql new file mode 100644 index 00000000..8ae5763f --- /dev/null +++ b/backend/prisma/migrations/20261015000000_add_support_conversations/migration.sql @@ -0,0 +1,8 @@ +CREATE TABLE support_conversations (id UUID NOT NULL, user_id UUID, anonymous_browser_id VARCHAR(64), entry_path VARCHAR(512), product_slugs JSONB, topics JSONB, unanswered BOOLEAN NOT NULL DEFAULT false, needs_followup BOOLEAN NOT NULL DEFAULT false, escalation_signal BOOLEAN NOT NULL DEFAULT false, summary TEXT, summary_status VARCHAR(20) NOT NULL DEFAULT 'pending', created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, expires_at TIMESTAMPTZ NOT NULL, CONSTRAINT support_conversations_pkey PRIMARY KEY (id)); +CREATE TABLE support_conversation_messages (id UUID NOT NULL, conversation_id UUID NOT NULL, role VARCHAR(20) NOT NULL, content TEXT NOT NULL, sequence INTEGER NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT CURRENT_TIMESTAMP, CONSTRAINT support_conversation_messages_pkey PRIMARY KEY (id)); +CREATE UNIQUE INDEX support_conversation_messages_conversation_id_sequence_key ON support_conversation_messages(conversation_id, sequence); +CREATE INDEX support_conversations_user_id_updated_at_idx ON support_conversations(user_id, updated_at); +CREATE INDEX support_conversations_anonymous_browser_id_updated_at_idx ON support_conversations(anonymous_browser_id, updated_at); +CREATE INDEX support_conversation_messages_conversation_id_created_at_idx ON support_conversation_messages(conversation_id, created_at); +ALTER TABLE support_conversations ADD CONSTRAINT support_conversations_user_id_fkey FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE ON UPDATE CASCADE; +ALTER TABLE support_conversation_messages ADD CONSTRAINT support_conversation_messages_conversation_id_fkey FOREIGN KEY (conversation_id) REFERENCES support_conversations(id) ON DELETE CASCADE ON UPDATE CASCADE; diff --git a/backend/prisma/schema.prisma b/backend/prisma/schema.prisma index a9deee44..4924e805 100644 --- a/backend/prisma/schema.prisma +++ b/backend/prisma/schema.prisma @@ -32,12 +32,49 @@ model User { tickets Ticket[] reviews ProductReview[] blogComments BlogComment[] + supportConversations SupportConversation[] @@index([role]) @@index([createdAt]) @@map("users") } +model SupportConversation { + id String @id @default(uuid()) @db.Uuid + userId String? @map(user_id) @db.Uuid + anonymousBrowserId String? @map(anonymous_browser_id) @db.VarChar(64) + entryPath String? @map(entry_path) @db.VarChar(512) + productSlugs Json? @map(product_slugs) + topics Json? + unanswered Boolean @default(false) + needsFollowup Boolean @default(false) @map(needs_followup) + escalationSignal Boolean @default(false) @map(escalation_signal) + summary String? @db.Text + summaryStatus String @default(pending) @map(summary_status) @db.VarChar(20) + createdAt DateTime @default(now()) @map(created_at) @db.Timestamptz() + updatedAt DateTime @updatedAt @map(updated_at) @db.Timestamptz() + expiresAt DateTime @map(expires_at) @db.Timestamptz() + + user User? @relation(fields: [userId], references: [id], onDelete: Cascade) + messages SupportConversationMessage[] + @@index([userId, updatedAt]) + @@index([anonymousBrowserId, updatedAt]) + @@map(support_conversations) +} + +model SupportConversationMessage { + id String @id @default(uuid()) @db.Uuid + conversationId String @map(conversation_id) @db.Uuid + role String @db.VarChar(20) + content String @db.Text + sequence Int + createdAt DateTime @default(now()) @map(created_at) @db.Timestamptz() + conversation SupportConversation @relation(fields: [conversationId], references: [id], onDelete: Cascade) + @@unique([conversationId, sequence]) + @@index([conversationId, createdAt]) + @@map(support_conversation_messages) +} + model UserAddress { id String @id @default(uuid()) @db.Uuid userId String @map("user_id") @db.Uuid diff --git a/backend/src/support-chat/support-chat.controller.ts b/backend/src/support-chat/support-chat.controller.ts index ea3dc5bd..c310cb58 100644 --- a/backend/src/support-chat/support-chat.controller.ts +++ b/backend/src/support-chat/support-chat.controller.ts @@ -1,13 +1,13 @@ -import { Body, Controller, Post, Req, UseGuards, Header } from '@nestjs/common'; +import { Body, Controller, Get, Header, Param, Post, Req, UseGuards } 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); } + constructor(private readonly service: SupportChatService) {} + @Get(':id') @UseGuards(OptionalCustomerJwtGuard) @Header('Cache-Control', 'no-store') + history(@Param('id') id: string, @Req() req: { user?: { id: string } }) { return this.service.history(id, req.user); } + @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 index 0bfdd94e..05769708 100644 --- a/backend/src/support-chat/support-chat.dto.ts +++ b/backend/src/support-chat/support-chat.dto.ts @@ -1,4 +1,7 @@ -import { IsString, Length } from 'class-validator'; +import { IsOptional, IsString, Length, Matches } from 'class-validator'; export class SupportChatDto { @IsString() @Length(1, 1500) message!: string; + @IsOptional() @IsString() @Length(36, 36) @Matches(/^[0-9a-f-]{36}$/i) conversationId?: string; + @IsOptional() @IsString() @Length(1, 512) entryPath?: string; + @IsOptional() @IsString() @Length(1, 64) @Matches(/^[A-Za-z0-9_-]+$/) anonymousBrowserId?: string; } diff --git a/backend/src/support-chat/support-chat.service.spec.ts b/backend/src/support-chat/support-chat.service.spec.ts index 308171c5..b44043e9 100644 --- a/backend/src/support-chat/support-chat.service.spec.ts +++ b/backend/src/support-chat/support-chat.service.spec.ts @@ -7,7 +7,29 @@ describe('model intent routing', () => { 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:'چقدر اعتبار دارم؟',selection:{provider:'p',model:'m'}});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:'چقدر اعتبار دارم؟',conversation_history:[],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();}); }); + + +describe('persistent conversations', () => { + it('creates a conversation and stores both messages without blocking the answer', async () => { + const conversation = { id: '11111111-1111-4111-8111-111111111111', userId: null }; + const prisma: any = { + product: { findMany: jest.fn().mockResolvedValue([]) }, + supportConversation: { create: jest.fn().mockResolvedValue(conversation), update: jest.fn().mockResolvedValue(conversation), findUnique: jest.fn().mockResolvedValue(conversation) }, + supportConversationMessage: { createMany: jest.fn().mockResolvedValue({}) }, + }; + process.env.SUPPORT_CHAT_URL = 'http://internal/ask'; + process.env.SUPPORT_CHAT_KEY = 'test'; + jest.spyOn(global, 'fetch').mockImplementation(async (url, opts: any) => ({ + ok: true, status: 200, json: async () => String(url).endsWith('/classify') ? { intent: 'public' } : { answer: 'پاسخ' }, + }) as any); + const service = new SupportChatService(prisma, { read: async () => ({ enabled: true, provider: 'p', model: 'm' }) } as any); + const result = await service.ask({ message: 'سلام', entryPath: '/products' } as any); + expect(result).toMatchObject({ conversationId: conversation.id, answer: 'پاسخ' }); + expect(prisma.supportConversation.create).toHaveBeenCalled(); + expect(prisma.supportConversationMessage.createMany).toHaveBeenCalledTimes(1); + }); +}); diff --git a/backend/src/support-chat/support-chat.service.ts b/backend/src/support-chat/support-chat.service.ts index 3f03617c..2814fc3c 100644 --- a/backend/src/support-chat/support-chat.service.ts +++ b/backend/src/support-chat/support-chat.service.ts @@ -1,50 +1,71 @@ -import { Injectable, ServiceUnavailableException } from '@nestjs/common'; +import { Injectable, NotFoundException, ServiceUnavailableException } from '@nestjs/common'; +import { randomUUID } from 'crypto'; import { PrismaService } from '../prisma/prisma.service'; import { SupportChatDto } from './support-chat.dto'; import { SupportChatSettingsService } from './support-chat-settings.service'; export const UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; +const MAX_HISTORY = 20; +const safePath = (v?: string) => v?.split('?')[0].slice(0, 512); +const safeBrowserId = (v?: string) => v && /^[A-Za-z0-9_-]{1,64}$/.test(v) ? v : undefined; +const extract = (question: string, answer: string, products: any[]) => { + const q = question.toLowerCase(); + const topics = ['nutrition','supplement','health','order','wallet','product','shipping'].filter(x => q.includes(x)); + if (/تغذ|غذا|مکمل|ویتامین/.test(q)) topics.push('nutrition'); + if (/سلامت|بیمار|دامپزشک/.test(q)) topics.push('health'); + if (/سفارش|ارسال/.test(q)) topics.push('order'); + const productSlugs = (products || []).filter(p => p.slug && (q.includes(String(p.slug).toLowerCase()) || q.includes(String(p.nameFa || '').toLowerCase()))).map(p => p.slug).slice(0, 20); + const uniqueTopics = [...new Set(topics)].slice(0, 20); + const unanswered = /نمی.?دانم|اطلاعاتی ندارم|پاسخ ندارم|متوجه نشدم/i.test(answer); + const needsFollowup = unanswered || /دامپزشک|پشتیبانی|تیکت|پیگیری/i.test(answer); + const escalationSignal = /فوری|شکایت|مشکل جدی|خطر|اورژانس/i.test(question + ' ' + answer); + const summary = `موضوع: ${uniqueTopics.join(', ') || 'عمومی'}؛ محصولات: ${productSlugs.join(', ') || 'ندارد'}؛ نیاز به پیگیری: ${needsFollowup ? 'بله' : 'خیر'}`; + return { productSlugs, topics: uniqueTopics, unanswered, needsFollowup, escalationSignal, summary }; +}; @Injectable() export class SupportChatService { constructor(private readonly prisma: PrismaService, private readonly settings: SupportChatSettingsService) {} + private db() { return this.prisma as any; } + async history(id: string, user?: { id: string }) { + const row = await this.db().supportConversation.findUnique({ where: { id }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } }); + if (!row || (user?.id ? row.userId !== user.id : row.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.'); + return { conversationId: id, messages: row.messages.map((m: any) => ({ role: m.role, content: m.content, createdAt: m.createdAt })) }; + } 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; + const config = await this.settings.read(); if (!config.enabled) throw new ServiceUnavailableException(UNAVAILABLE); + const db = this.db(); let conversation: any; + if (input.conversationId) { + conversation = await db.supportConversation.findUnique({ where: { id: input.conversationId }, include: { messages: { orderBy: { sequence: 'asc' }, take: MAX_HISTORY } } }); + if (!conversation || (user?.id ? conversation.userId !== user.id : conversation.userId !== null)) throw new NotFoundException('گفتگو یافت نشد.'); + } else { + conversation = await db.supportConversation.create({ data: { id: randomUUID(), userId: user?.id ?? null, anonymousBrowserId: safeBrowserId(input.anonymousBrowserId), entryPath: safePath(input.entryPath), expiresAt: new Date(Date.now() + 90 * 86400000) }, include: { messages: true } }); + } + const conversationHistory = (conversation.messages || []).slice(-MAX_HISTORY).map((m: any) => ({ role: m.role, content: m.content })); + 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, selection }) }); - if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه پذیرفته نمی‌شود.' }; - if (!response.ok) throw new Error('upstream'); - const data = await response.json(); - if (!data || Object.keys(data).length !== 1 || !['public', 'orders', 'wallet'].includes(data.intent)) throw new Error('intent'); - intent = data.intent; + 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, conversation_history: conversationHistory, selection }) }); + if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم.' }; + if (!response.ok) throw new Error('upstream'); const data = await response.json(); + if (!data || Object.keys(data).length !== 1 || !['public','orders','wallet'].includes(data.intent)) throw new Error('intent'); intent = data.intent; } catch { throw new ServiceUnavailableException(UNAVAILABLE); } - if (intent !== 'public' && !user) return { answer: 'برای مشاهده سفارش‌ها یا کیف پول خود ابتدا وارد حساب کاربری شوید.' }; - if (intent === '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 (intent === '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. + if (intent !== 'public' && !user) return { answer: 'برای مشاهده سفارش‌ها یا کیف پول خود ابتدا وارد حساب کاربری شوید.', conversationId: conversation.id, contextLimited: conversationHistory.length >= MAX_HISTORY }; + let answer: string; let products: any[] = []; 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, selection }) }); - 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 }; + if (intent === 'wallet') { const row = await this.prisma.user.findUnique({ where: { id: user!.id }, select: { walletBalance: true } }); if (!row) throw new Error('missing'); answer = `موجودی کیف پول شما: ${row.walletBalance.toString()} تومان.`; } + else if (intent === 'orders') { const rows = await this.prisma.order.findMany({ where: { userId: user!.id }, select: { id: true, status: true, totalAmount: true }, take: 5, orderBy: { createdAt: 'desc' } }); answer = rows.length ? rows.map(r => `سفارش ${r.id}: ${r.status} — ${r.totalAmount.toString()} تومان`).join('\n') : 'سفارشی برای حساب شما ثبت نشده است.'; } + else { + 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 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, conversation_history: conversationHistory, selection }) }); + if (response.status === 400) return { answer: 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم.', conversationId: conversation.id }; + if (!response.ok) throw new Error('upstream'); const data = await response.json(); answer = data.answer; + if (typeof answer !== 'string' || !answer.trim() || answer.length > 6000 || /traceback|api.?key|provider|rate.?limit|hermes|authentication|exception|https?:\/\/(?:localhost|127\.)/i.test(answer)) throw new Error('unsafe'); + } } catch { throw new ServiceUnavailableException(UNAVAILABLE); } + const analytics = extract(input.message, answer!, products); + await db.supportConversationMessage.createMany({ data: [{ conversationId: conversation.id, role: 'user', content: input.message, sequence: conversationHistory.length }, { conversationId: conversation.id, role: 'assistant', content: answer!, sequence: conversationHistory.length + 1 }] }); + await db.supportConversation.update({ where: { id: conversation.id }, data: { productSlugs: analytics.productSlugs, topics: analytics.topics, unanswered: analytics.unanswered, needsFollowup: analytics.needsFollowup, escalationSignal: analytics.escalationSignal, summary: analytics.summary, summaryStatus: 'completed' } }); + return { answer: answer!, conversationId: conversation.id, contextLimited: conversationHistory.length + 2 >= MAX_HISTORY }; } } diff --git a/frontend/application/components/SupportChat.tsx b/frontend/application/components/SupportChat.tsx index 22425594..858f5880 100644 --- a/frontend/application/components/SupportChat.tsx +++ b/frontend/application/components/SupportChat.tsx @@ -1,6 +1,8 @@ 'use client'; import { FormEvent, useEffect, useRef, useState } from 'react'; +type PersistedMessage = { role: 'user' | 'assistant'; content: string }; + const unavailable = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.'; const token = () => { try { @@ -34,15 +36,20 @@ export default function SupportChat() { const [message, setMessage] = useState(''); const [busy, setBusy] = useState(false); const [rows, setRows] = useState<{ question: string; answer: string }[]>([]); + const [conversationId, setConversationId] = useState(''); + const [contextLimited, setContextLimited] = useState(false); const identity = useRef(''); const pending = useRef(null); const chatScrollRef = useRef(null); + const historyKey = useRef(''); useEffect(() => { identity.current = token(); + try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} const check = () => { if (identity.current !== token()) { identity.current = token(); + try { const saved = localStorage.getItem('canina-support-conversation'); if (saved) setConversationId(saved); } catch {} pending.current?.abort(); setRows([]); setMessage(''); @@ -66,6 +73,54 @@ export default function SupportChat() { } }, [rows, busy]); + useEffect(() => { + if (!conversationId || !config?.enabled) return; + const current = token(); + const key = `${current}:${conversationId}`; + if (historyKey.current === key) return; + historyKey.current = key; + const controller = new AbortController(); + pending.current = controller; + const loadHistory = async () => { + try { + const response = await fetch(`${process.env.NEXT_PUBLIC_API_URL || '/api'}/support-chat/${encodeURIComponent(conversationId)}`, { + credentials: 'include', + headers: { 'X-Requested-With': 'XMLHttpRequest', ...(current ? { Authorization: `Bearer ${current}` } : {}) }, + signal: controller.signal + }); + if (!response.ok) throw new Error('history'); + const data = await response.json(); + if (!Array.isArray(data?.messages) || data.conversationId !== conversationId) throw new Error('history'); + const messages = data.messages.filter((message: unknown): message is PersistedMessage => { + if (!message || typeof message !== 'object') return false; + const value = message as Record; + return (value.role === 'user' || value.role === 'assistant') && typeof value.content === 'string'; + }); + const restored: { question: string; answer: string }[] = []; + for (let i = 0; i < messages.length; i += 1) { + const message = messages[i]; + if (message.role === 'user') { + const next = messages[i + 1]; + if (next?.role === 'assistant') i += 1; + restored.push({ question: message.content, answer: next?.role === 'assistant' ? next.content : '' }); + } else if (!restored.length || restored[restored.length - 1].answer) { + restored.push({ question: '', answer: message.content }); + } + } + if (!controller.signal.aborted && token() === current) setRows(restored); + } catch { + if (!controller.signal.aborted && token() === current) { + setRows([]); setConversationId(''); setContextLimited(false); + try { localStorage.removeItem('canina-support-conversation'); } catch {} + } + } finally { + if (pending.current === controller) pending.current = null; + } + }; + void loadHistory(); + return () => controller.abort(); + }, [conversationId, config?.enabled]); + async function send(event: FormEvent) { event.preventDefault(); if (busy || !message.trim() || !config?.enabled) return; @@ -77,6 +132,7 @@ export default function SupportChat() { const question = message.trim(); setMessage(''); setBusy(true); + setRows((r) => [...r.slice(-9), { question, answer: 'در حال بررسی…' }]); const controller = new AbortController(); pending.current = controller; let answer = unavailable; @@ -89,7 +145,7 @@ export default function SupportChat() { ...(current ? { Authorization: `Bearer ${current}` } : {}) }, credentials: 'include', - body: JSON.stringify({ message: question }), + body: JSON.stringify({ message: question, ...(conversationId ? { conversationId } : {}), entryPath: window.location.pathname }), signal: AbortSignal.any([controller.signal, AbortSignal.timeout(50000)]) }); if (response.status === 401) { @@ -97,12 +153,14 @@ export default function SupportChat() { } else if (response.ok) { const data = await response.json(); if (typeof data.answer === 'string') answer = data.answer; + if (typeof data.conversationId === 'string') { setConversationId(data.conversationId); try { localStorage.setItem('canina-support-conversation', data.conversationId); } catch {} } + setContextLimited(data.contextLimited === true); } } catch { // safe fallback kept } if (!controller.signal.aborted && token() === current) { - setRows((r) => [...r.slice(-9), { question, answer }]); + setRows((r) => { const next = [...r]; const i = next.length - 1; if (i >= 0 && next[i].question === question && next[i].answer === 'در حال بررسی…') next[i] = { question, answer }; return next; }); } if (pending.current === controller) setBusy(false); } @@ -156,6 +214,7 @@ export default function SupportChat() { AI

راهنمای محصولات و سلامت پت

+ + {contextLimited &&
برای ادامه دقیق‌تر، گفتگوی جدیدی شروع کنید یا با پشتیبانی تماس بگیرید.
}
Shift+Enter خط جدید /dev/null 2>&1; then + LIVE_BOT_KEY=$(docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' canina-bot | awk -F= '$1 == "SUPPORT_INTERNAL_KEY" {print substr($0, index($0, "=") + 1); exit}') + if [ -n "$LIVE_BOT_KEY" ]; then + grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp 2>/dev/null || true + printf 'SUPPORT_CHAT_KEY=%s +' "$LIVE_BOT_KEY" >> .support-chat.env.tmp + mv .support-chat.env.tmp .support-chat.env + chmod 600 .support-chat.env + fi + unset LIVE_BOT_KEY +fi + +# Inject support-chat runtime configuration from CI/CD without committing secrets. +# The bot is the runtime owner of the internal key; synchronize only the +# matching value into the colocated backend env file, never into Git or logs. +BOT_ENV="/opt/services/ai/canina-bot/support.env" +if [ -r "$BOT_ENV" ]; then + BOT_KEY=$(awk -F= '$1 == "SUPPORT_INTERNAL_KEY" {print substr($0, index($0, "=") + 1); exit}' "$BOT_ENV") + if [ -n "$BOT_KEY" ]; then + touch .support-chat.env + grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp || true + printf "SUPPORT_CHAT_KEY=%s\n" "$BOT_KEY" >> .support-chat.env.tmp + mv .support-chat.env.tmp .support-chat.env + chmod 600 .support-chat.env + fi + unset BOT_KEY +fi +if [ -n "${SUPPORT_CHAT_KEY:-}" ]; then + touch .support-chat.env + grep -v '^SUPPORT_CHAT_KEY=' .support-chat.env > .support-chat.env.tmp || true + printf 'SUPPORT_CHAT_KEY=%s\n' "$SUPPORT_CHAT_KEY" >> .support-chat.env.tmp + mv .support-chat.env.tmp .support-chat.env + chmod 600 .support-chat.env +fi +if [ ! -s .support-chat.env ]; then + echo "ERROR: missing .support-chat.env / SUPPORT_CHAT_KEY; refusing deployment" >&2 + exit 1 +fi + # ✅ فایل‌های کانفیگ را از پوشه‌ی scripts مخزن به TARGET_DIR کپی می‌کنیم echo "Copying configuration files in $TARGET_DIR..." cp "scripts/$COMPOSE_FILE" "docker-compose.yml" @@ -85,30 +125,28 @@ docker compose --progress plain build \ --build-arg VITE_API_URL="${API_URL}" \ ${NPM_REGISTRY_ARG} +echo "Building support-chat bot image from committed source..." +BOT_IMAGE="canina-support-bot:${BRANCH}" +DOCKER_BUILDKIT=0 docker build --pull=false -f scripts/support-chat/Dockerfile -t "${BOT_IMAGE}" . +BOT_ENV="${TARGET_DIR}/.support-bot.runtime.env" +docker inspect -f '{{range .Config.Env}}{{println .}}{{end}}' canina-bot > "${BOT_ENV}" +chmod 600 "${BOT_ENV}" echo "Starting containers..." docker compose up -d --remove-orphans - +echo "Starting support-chat bot container..." +docker rm -f canina-bot >/dev/null 2>&1 || true +docker run -d --name canina-bot --restart unless-stopped --env-file "${BOT_ENV}" -e HERMES_HOME=/opt/data -e HERMES_RUNTIME_DIR=/opt/hermes/tools -e API_SERVER_HOST=0.0.0.0 -e API_SERVER_PORT=8642 --network traefik_public -v canina_bot_data:/opt/data "${BOT_IMAGE}" gateway run +docker network connect --ip 172.22.0.15 vpn_net canina-bot +rm -f "${BOT_ENV}" echo "Waiting for backend to start..." sleep 15 -echo "Running database migrations..." -if [ "$BRANCH" == "develop" ]; then - # Staging: use db push (fast, schema sync) then seed - echo "[STAGING] Running prisma db push..." - docker exec "$CONTAINER_PREFIX" npx prisma db push || true - - echo "[STAGING] Running prisma db seed..." - docker exec "$CONTAINER_PREFIX" npx prisma db seed || true -else - # Production: use db push to sync schema additions without data loss - echo "[PRODUCTION] Running prisma db push to ensure schema is up to date..." - docker exec "$CONTAINER_PREFIX" npx prisma db push --skip-generate || true - echo "[PRODUCTION] Seeder skipped to protect production data." -fi +# Code-only deployment: never mutate stage or production data here. +# Schema migrations and seed require a separate, explicitly authorized operation. # Auto-cleanup old docker builder cache to keep disk healthy (keeps latest 6GB) echo "Cleaning up old docker build cache..." docker builder prune -af --keep-storage 6GB 2>/dev/null || true docker image prune -f 2>/dev/null || true -echo "Deployment for $BRANCH completed successfully!" \ No newline at end of file +echo "Deployment for $BRANCH completed successfully!" diff --git a/scripts/support-chat/bootstrap.py b/scripts/support-chat/bootstrap.py index 76d19e1e..346fb45a 100644 --- a/scripts/support-chat/bootstrap.py +++ b/scripts/support-chat/bootstrap.py @@ -9,7 +9,16 @@ import hermes_yaml as yaml source = yaml.safe_load(Path('/opt/data/config.yaml').read_text()) home = Path('/run/canina-support') home.mkdir(mode=0o700, exist_ok=True) -safe = {'model': source.get('model', {}), 'web': source.get('web', {}), 'memory': {'memory_enabled': False, 'user_profile_enabled': False}, 'telemetry': {'shared_metrics': {'enabled': False, 'send': False}}, 'agent': {'max_iterations': 2}, 'compression': {'enabled': False}} +safe = { + 'model': source.get('model', {}), + # Provider names/models are configuration; credentials remain in env. + 'custom_providers': source.get('custom_providers', []), + 'web': source.get('web', {}), + 'memory': {'memory_enabled': False, 'user_profile_enabled': False}, + 'telemetry': {'shared_metrics': {'enabled': False, 'send': False}}, + 'agent': {'max_iterations': 2}, + 'compression': {'enabled': False}, +} p = home/'config.yaml' p.write_text(yaml.safe_dump(safe)); p.chmod(0o600) os.environ['HERMES_HOME']=str(home) diff --git a/scripts/support-chat/policy.py b/scripts/support-chat/policy.py index fb8ed1d7..90afa879 100644 --- a/scripts/support-chat/policy.py +++ b/scripts/support-chat/policy.py @@ -1,50 +1,46 @@ -"""Fail-closed domain policy; the model is never given web or execution tools.""" -import json -import re - -# Structural & exploit denial only: prevent URLs/links and command/injection strings. -DENY = re.compile(r'https?[:/]|www\.|[a-z0-9-]+\.(?:com|net|org|ir|de|io)\b|\b(?:localhost|ssh|sql|shell|token|password|api[._-]?key)\b|رمز\s*عبور|توکن|دستور\s*سیستمی', re.I) -ERROR = re.compile(r'hermes|provider|api.?key|traceback|exception|authentication|rate.?limit|error|failed|ناموفق|خطای اتصال', re.I) - +"""Fail-closed customer policy and bounded first-party link handling.""" +import json,re +from urllib.parse import urlsplit +DENY=re.compile(r"\b(?:localhost|ssh|sql|shell|token|password|api[._-]?key)\b|رمز\s*عبور|توکن|دستور\s*سیستمی",re.I) +ERROR=re.compile(r"hermes|provider|api.?key|traceback|exception|authentication|rate.?limit|error|failed|ناموفق|خطای اتصال",re.I) +SAFE_HOSTS={"canina.ir","www.canina.ir","stage.canina.ir"} +URL_RE=re.compile(r"https?://[^\s<>\"']+|tel:[+0-9(). *#-]{7,30}",re.I) def validate_message(message): - if not isinstance(message, str): - raise ValueError('type') - stripped = message.strip() - if not (1 <= len(stripped) <= 1500): - raise ValueError('length') - if DENY.search(stripped): - raise ValueError('denied_pattern') - return stripped - + if not isinstance(message,str): raise ValueError("type") + s=message.strip() + if not 1<=len(s)<=1500 or DENY.search(s): raise ValueError("invalid") + if re.search(r"https?://|www\.", s, re.I): + for match in re.findall(r"https?://[^\s]+|www\.[^\s]+", s, re.I): + if not match.lower().startswith(("https://canina.ir","https://www.canina.ir","https://stage.canina.ir")): raise ValueError("external_url") + return s +def _safe_url(m): + v=m.group(0).rstrip(".,!?)") + if v.lower().startswith("tel:"): + raw=v[4:]; d=("+" if raw.strip().startswith("+") else "")+re.sub(r"[^0-9]","",raw) + return "tel:"+d if 7<=len(d.lstrip("+"))<=15 else "" + try: + p=urlsplit(v) + if p.scheme.lower()!="https" or p.hostname.lower() not in SAFE_HOSTS or p.username or p.password or p.query or p.fragment:return "" + path=p.path or "/" + return "https://"+p.hostname.lower()+path if len(path)<=256 and re.fullmatch(r"/[A-Za-z0-9_./%-]*",path) else "" + except Exception:return "" +def sanitize_answer(text): return URL_RE.sub(_safe_url,text) def safe_answer(result): - if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False: - raise ValueError('unavailable') - text = result.get('final_response', '') - if not isinstance(text, str) or ERROR.search(text): - raise ValueError('unavailable') - if text.startswith('```'): - text = re.sub(r'^```(?:json)?\s*|\s*```$', '', text) - obj = json.loads(text) - answer = obj.get('answer') - if not isinstance(answer, str) or not (1 <= len(answer.strip()) <= 6000) or ERROR.search(answer): - raise ValueError('unavailable') - return answer.strip() - -# Search input never contains raw customer prose: only fixed product-category terms -# and recognised pet-product brands. No extract/browser URL capability exists. + if not isinstance(result,dict) or result.get("failed") or result.get("error") or result.get("partial") or result.get("completed") is False:raise ValueError("unavailable") + t=result.get("final_response","") + if not isinstance(t,str) or ERROR.search(t):raise ValueError("unavailable") + t=re.sub(r"^```(?:json)?\s*|\s*```$","",t); a=json.loads(t).get("answer") + if not isinstance(a,str) or not 1<=len(a.strip())<=6000 or ERROR.search(a):raise ValueError("unavailable") + return sanitize_answer(a.strip()) def research_query(message): - if not re.search(r'مقایسه|رقیب|جستجو|compare|research', message, re.I): - return None - validate_message(message) - brands = [name for pattern, name in [(r'رویال|royal', 'Royal Canin'), (r'بیفار|beaphar', 'Beaphar'), (r'وت.?اکسپرت|vet.?expert', 'VetExpert')] if re.search(pattern, message, re.I)] - return 'pet dog cat supplement product comparison Canina ' + ' '.join(brands) - - - + try: m=validate_message(message).lower() + except ValueError: return None + if re.search(r"تماس|شماره|آدرس|contact|phone|address",m):return "Canina official contact phone address" + if not re.search(r"مقایسه|رقیب|جستجو|compare|research",m,re.I):return None + brands=" ".join(n for pat,n in [(r"رویال|royal","Royal Canin"),(r"بیفار|beaphar","Beaphar"),(r"وت.?اکسپرت|vet.?expert","VetExpert")] if re.search(pat,m,re.I)) + return "pet dog cat supplement product comparison Canina "+brands def safe_intent(result): - if not isinstance(result, dict) or result.get('failed') or result.get('error') or result.get('partial') or result.get('completed') is False: - raise ValueError('unavailable') - obj = json.loads(result.get('final_response', '')) - if not isinstance(obj, dict) or set(obj) != {'intent'} or obj['intent'] not in ('public', 'orders', 'wallet'): - raise ValueError('intent') - return obj['intent'] + if not isinstance(result,dict) or result.get("failed") or result.get("error") or result.get("partial") or result.get("completed") is False:raise ValueError("unavailable") + o=json.loads(result.get("final_response","")) + if not isinstance(o,dict) or set(o)!={"intent"} or o["intent"] not in ("public","orders","wallet"):raise ValueError("intent") + return o["intent"] diff --git a/scripts/support-chat/server.py b/scripts/support-chat/server.py index 22ca5815..da007105 100644 --- a/scripts/support-chat/server.py +++ b/scripts/support-chat/server.py @@ -9,6 +9,8 @@ import hmac import json import logging import os +import re +import urllib.request import uuid from aiohttp import web from policy import validate_message, safe_answer, research_query, safe_intent @@ -29,18 +31,28 @@ async def catalog(request): UNAVAILABLE = 'پشتیبان هوشمند فعلاً در دسترس نیست. لطفاً کمی بعد دوباره تلاش کنید یا تیکت پشتیبانی ثبت کنید.' DOMAIN = 'فقط درباره محصولات و سلامت حیوانات خانگی و خدمات کنینا پاسخ می‌دهم. پیوند دلخواه یا موضوع خارج از این حوزه پذیرفته نمی‌شود.' LIMIT = asyncio.Semaphore(2) + +def live_contact_context(): + request = urllib.request.Request('https://canina.ir/contact', headers={'User-Agent': 'CaninaSupport/1.0'}) + with urllib.request.urlopen(request, timeout=8) as response: + html = response.read(300000).decode('utf-8', 'ignore') + phones = sorted(set(re.findall(r'(?:tel:|\b0?21[ -]?\d{4}[ -]?\d{4})', html, re.I))) + phones = [re.sub(r'^tel:\s*', '', p, flags=re.I).replace(' ', '').replace('-', '') for p in phones] + return {'source': 'https://canina.ir/contact', 'phones': phones[:5]} logging.disable(logging.CRITICAL) -def answer_once(message, catalog, selection): +def answer_once(message, catalog, selection, page_context=None, conversation_history=None): model, runtime = selected_runtime(selection) research = None query = research_query(message) if query: - # No model-chosen tool arguments, raw queries, URL extraction or fetch. - from tools.web_tools import web_search_tool - payload = json.loads(web_search_tool(query, limit=3)) - if payload.get('success') is not True or payload.get('error'): raise ValueError('research unavailable') - research = [{k: str(row.get(k, ''))[:1800] for k in ['title', 'description', 'url']} for row in payload.get('data', {}).get('web', [])[:3]] + if query == 'Canina official contact phone address': + research = [live_contact_context()] + else: + from tools.web_tools import web_search_tool + payload = json.loads(web_search_tool(query, limit=3)) + if payload.get('success') is not True or payload.get('error'): raise ValueError('research unavailable') + research = [{k: str(row.get(k, ''))[:1800] for k in ['title', 'description', 'url']} for row in payload.get('data', {}).get('web', [])[:3]] agent = AIAgent(model=model.get('default'), provider=runtime.get('provider'), base_url=runtime.get('base_url'), api_key=runtime.get('api_key'), api_mode=runtime.get('api_mode'), enabled_toolsets=[], disabled_toolsets=['all'], skip_memory=True, skip_context_files=True, skip_background_review=True, load_soul_identity=False, session_id=str(uuid.uuid4()), session_db=None, save_trajectories=False, quiet_mode=True, max_iterations=2, max_tokens=1800, run_budget_seconds=35, checkpoints_enabled=False) agent._persist_disabled = True # Runtime assertion protects against future changes to empty toolset defaults. @@ -56,7 +68,7 @@ def answer_once(message, catalog, selection): '۵. ساختار خروجی: فقط و فقط یک شیء JSON با دقیقاً یک کلید "answer" برگردانید و هیچ متن اضافی قبل یا بعد از JSON نیاورید.' ) try: - result = agent.run_conversation(json.dumps({'question': message, 'catalog': catalog, 'untrusted_research': research}, ensure_ascii=False), system_message=prompt, conversation_history=[]) + result = agent.run_conversation(json.dumps({'question': message, 'catalog': catalog, 'untrusted_research': research, 'page_context': page_context or {}, 'conversation_history': (conversation_history or [])[-20:]}, ensure_ascii=False), system_message=prompt, conversation_history=[]) return safe_answer(result) finally: with contextlib.suppress(Exception): agent.close() @@ -83,7 +95,7 @@ async def classify(request): return web.json_response({'answer': UNAVAILABLE}, status=401) try: data = await request.json() - if not isinstance(data, dict) or set(data) != {'message', 'selection'}: raise ValueError('payload') + if not isinstance(data, dict) or set(data) - {'message', 'selection', 'conversation_history'} or not {'message', 'selection'} <= set(data): raise ValueError('payload') message = validate_message(data['message']) except Exception: return web.json_response({'answer': DOMAIN}, status=400) @@ -101,14 +113,14 @@ async def ask(request): return web.json_response({'answer': UNAVAILABLE}, status=401) try: data = await request.json() - if set(data) != {'message','catalog', 'selection'} or not isinstance(data['catalog'], list) or len(data['catalog']) > 80: raise ValueError('payload') + if set(data) - {'message','catalog','selection','page_context','conversation_history'} or not {'message','catalog','selection'} <= set(data) or not isinstance(data['catalog'], list) or len(data['catalog']) > 80: raise ValueError('payload') message = validate_message(data['message']) except Exception: return web.json_response({'answer': DOMAIN}, status=400) if LIMIT.locked(): return web.json_response({'answer': UNAVAILABLE}, status=503) try: async with LIMIT: - answer = await asyncio.to_thread(answer_once, message, data['catalog'], data['selection']) + answer = await asyncio.to_thread(answer_once, message, data['catalog'], data['selection'], data.get('page_context'), data.get('conversation_history')) return web.json_response({'answer': answer}, headers={'Cache-Control':'no-store'}) except Exception: return web.json_response({'answer': UNAVAILABLE}, status=503) diff --git a/scripts/support-chat/test_policy.py b/scripts/support-chat/test_policy.py index 264aa44a..3b96f079 100644 --- a/scripts/support-chat/test_policy.py +++ b/scripts/support-chat/test_policy.py @@ -52,3 +52,22 @@ class IntentPolicyTests(unittest.TestCase): for value in ('{}', '{"intent":"admin"}', '{"intent":"wallet","userId":"other"}', 'garbage'): with self.assertRaises((ValueError, TypeError)): safe_intent({'final_response': value}) + +class CaninaSafetyTests(unittest.TestCase): + def test_canina_contact_and_tel_are_allowed(self): + from policy import validate_message, sanitize_answer + self.assertEqual(validate_message("شماره تماس کنینا و صفحه تماس را بده"), "شماره تماس کنینا و صفحه تماس را بده") + out = sanitize_answer("تماس: https://canina.ir/contact و تلفن: tel:+982188884444") + self.assertIn("https://canina.ir/contact", out) + self.assertIn("tel:+982188884444", out) + def test_external_and_internal_links_are_removed(self): + from policy import sanitize_answer + out = sanitize_answer("https://example.com https://canina.ir.evil.test http://canina.ir/contact https://stage.canina.ir/contact") + self.assertNotIn("example.com", out) + self.assertNotIn("canina.ir.evil", out) + self.assertNotIn("http://canina.ir", out) + self.assertIn("https://stage.canina.ir/contact", out) + def test_research_is_bounded_and_contact_researchable(self): + from policy import research_query + self.assertEqual(research_query("شماره تماس و آدرس رسمی کنینا"), "Canina official contact phone address") + self.assertIsNone(research_query("این متن https://example.com را واکشی کن"))