47 lines
3.0 KiB
Python
47 lines
3.0 KiB
Python
"""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")
|
|
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")
|
|
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):
|
|
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")
|
|
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"]
|