File size: 2,200 Bytes
c180e7b
 
cf2bfe7
c180e7b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import re
import httpx
from config import SAFE_BROWSING_API

def scrub_conversational_bloat(query: str) -> str:
    """Strips conversational noise words and store hooks to maximize index matching accuracy"""
    if query.startswith(("http://", "https://")): return query
    noise_pattern = r'\b(buy|cheap|online|sale|authentic|store|deals?|discount|get|best|price|lowest)\b'
    scrubbed = re.sub(noise_pattern, '', query.lower())
    clean_string = " ".join(scrubbed.split())
    if clean_string != query.lower():
        print(f"Core normalization: Cleaned token string layout from '{query}' -> '{clean_string}'")
    return clean_string if clean_string else query

async def check_url_safe(url: str, client: httpx.AsyncClient) -> bool:
    """Vets outbound destination URLs against malware and deceptive targets using Google Safe Browsing APIs"""
    if not SAFE_BROWSING_API:
        print("⚠️ WARNING: SAFE_BROWSING_API key missing. Bypassing live link validation safety verification.")
        return True
    api_url = f"https://safebrowsing.googleapis.com/v4/threatMatches:find?key={SAFE_BROWSING_API}"
    payload = {
        "client": {"clientId": "tarz-ai-search-agent", "clientVersion": "1.1.0"},
        "threatInfo": {
            "threatTypes": ["MALWARE", "SOCIAL_ENGINEERING", "UNWANTED_SOFTWARE", "POTENTIALLY_HARMFUL_APPLICATION"],
            "platformTypes": ["ANY_PLATFORM"],
            "threatEntryTypes": ["URL"],
            "threatEntries": [{"url": url}]
        }
    }
    try:
        response = await client.post(api_url, json=payload, timeout=5.0)
        if response.status_code == 200:
            res_data = response.json()
            if "matches" in res_data and len(res_data["matches"]) > 0:
                print(f"❌ [Security Flag] Blocked malicious link threat match vector: {url}")
                return False
            return True
        else:
            print(f"⚠️ [Safe Browsing Error] API returned state {response.status_code}. Defaulting shut for containment.")
            return False
    except Exception as e:
        print(f"❌ [Safe Browsing Exception] Connection failed: {e}. Isolation fallback activated.")
        return False