Spaces:
Sleeping

File size: 3,267 Bytes
1e8121d
 
 
 
c22da75
1e8121d
 
 
 
c22da75
1e8121d
 
 
 
ae48344
c22da75
 
1e8121d
c22da75
ae48344
c22da75
 
 
ae48344
c22da75
 
ae48344
 
 
1e8121d
c22da75
 
1e8121d
 
 
ae48344
1e8121d
ae48344
c22da75
ae48344
c22da75
 
959cd28
ae48344
959cd28
c22da75
1e8121d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
959cd28
1e8121d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c22da75
1e8121d
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#!/usr/bin/env python3
import os
import sys
import re
from fastapi import FastAPI, Query, Response, HTTPException
import requests
from bs4 import BeautifulSoup
import uvicorn

app = FastAPI(title="Secure DuckDuckGo SearXNG Proxy")

def log(message: str):
    print(f"[SEARCH-PROXY] {message}", file=sys.stdout, flush=True)

# Secure Token Configuration from HF Secrets
AUTH_TOKEN = os.getenv("INTERNAL_SEARCH_KEY", "your-super-secure-search-password")

@app.get("/")
def home():
    """Public root landing page."""
    return {
        "status": "healthy",
        "engine": "DuckDuckGo-SearXNG-Proxy",
        "security": "Enabled (Root path locked)"
    }

# CRITICAL FIX: Capture the token immediately after the root domain slash
@app.get("/{token}")
@app.get("/{token}/")
def searxng_compat_endpoint(
    token: str,
    q: str = Query(None),
    format: str = Query("json")
):
    """
    Catches Open WebUI's direct root-level password paths cleanly.
    """
    # Validate the token directly
    if token != AUTH_TOKEN:
        log(f"Unauthorized search attempt rejected. Received token: '{token}' does not match.")
        raise HTTPException(status_code=401, detail="Unauthorized: Invalid Token.")

    if not q:
        return {"results": [], "note": f"Token '{token}' verified successfully. Add 'q' parameter to search."}

    log(f"Authorized search request received: '{q}'")
    
    headers = {
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
        "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
        "Accept-Language": "en-US,en;q=0.5"
    }
    
    url = f"https://html.duckduckgo.com/html/?q={requests.utils.quote(q)}"
    
    try:
        response = requests.get(url, headers=headers, timeout=5)
        if response.status_code != 200:
            log(f"Error: DuckDuckGo returned status code {response.status_code}")
            return {"results": []}
            
        soup = BeautifulSoup(response.text, "html.parser")
        results = []
        
        for row in soup.find_all('div', class_='result')[:8]:
            title_node = row.find('a', class_='result__url')
            snippet_node = row.find('a', class_='result__snippet')
            
            if title_node and snippet_node:
                raw_url = title_node.get('href', '')
                
                clean_url = raw_url
                if "//duckduckgo.com/l/?" in raw_url:
                    match = re.search(r'uddg=([^&]+)', raw_url)
                    if match:
                        clean_url = requests.utils.unquote(match.group(1))
                
                results.append({
                    "title": title_node.text.strip(),
                    "url": clean_url,
                    "content": snippet_node.text.strip()
                })
        
        log(f"Successfully returned {len(results)} secured results.")
        return {"results": results}

    except Exception as e:
        log(f"Exception triggered during execution: {str(e)}")
        return {"results": []}

if __name__ == "__main__":
    port = int(os.getenv("PORT", 7860))
    uvicorn.run(app, host="0.0.0.0", port=port, workers=1)