fix(support-chat): allow safe Canina research and contact links
Deploy Canina / deploy (push) Failing after 31s

This commit is contained in:
devops committed 2026-10-15 15:39:06 +00:00
1 parent f292195edf
commit 043488fe55
3 files changed
+83 -56

No files matched your search

+42 -46
View File
@@ -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"]