Reaper1909 commited on
Commit
8dd75e2
·
verified ·
1 Parent(s): 6d6be31

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +31 -29
app.py CHANGED
@@ -1,11 +1,10 @@
1
  import os
2
  import json
3
  import asyncio
4
- import concurrent.futures
5
  from functools import lru_cache
6
  from urllib.parse import urlparse
7
 
8
- import whois
9
  from fastapi import FastAPI
10
  from fastapi.middleware.cors import CORSMiddleware
11
  from pydantic import BaseModel
@@ -24,8 +23,7 @@ app.add_middleware(
24
  allow_headers=["*"],
25
  )
26
 
27
- # Initialize Groq Client (Ensure your API key is set in your environment variables)
28
- # Example: export GROQ_API_KEY="gsk_your_api_key_here"
29
  GROQ_API_KEY = os.getenv("GROQ_API_KEY", "your_groq_api_key_here")
30
  groq_client = Groq(api_key=GROQ_API_KEY)
31
 
@@ -34,7 +32,7 @@ class ScanRequest(BaseModel):
34
  url: str
35
 
36
  # ---------------------------------------------------------
37
- # 2. Helper Functions (Domain Extraction & OSINT)
38
  # ---------------------------------------------------------
39
  def extract_domain(url: str) -> str:
40
  """Safely extracts the domain name from a full URL."""
@@ -46,28 +44,33 @@ def extract_domain(url: str) -> str:
46
  except Exception:
47
  return url
48
 
49
- def get_whois_data(domain: str, timeout_seconds: int = 2) -> str:
50
- """Executes WHOIS lookup with a strict timeout to prevent API hanging."""
51
- with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
52
- future = executor.submit(whois.whois, domain)
53
- try:
54
- result = future.result(timeout=timeout_seconds)
55
- if result.creation_date:
56
- # Some registries return a list of dates, some return a single date
57
- if isinstance(result.creation_date, list):
58
- return str(result.creation_date[0])
59
- return str(result.creation_date)
60
- return "Unknown"
61
- except concurrent.futures.TimeoutError:
62
- print(f"[WADE] WHOIS timeout for {domain}. Bypassing.")
63
- return "Unknown (Timeout)"
64
- except Exception as e:
65
- print(f"[WADE] WHOIS error for {domain}: {e}")
66
- return "Unknown (Error)"
 
 
 
 
 
67
 
68
  @lru_cache(maxsize=1000)
69
  def cached_whois_lookup(domain: str) -> str:
70
- """Caches the result to prevent redundant WHOIS lookups for the same domain."""
71
  return get_whois_data(domain)
72
 
73
  # ---------------------------------------------------------
@@ -78,7 +81,7 @@ async def analyze_url(payload: ScanRequest):
78
  target_url = payload.url
79
  target_domain = extract_domain(target_url)
80
 
81
- # A. Execute Non-Blocking, Cached OSINT Lookup
82
  domain_age = await asyncio.to_thread(cached_whois_lookup, target_domain)
83
 
84
  # B. Construct the System Prompt for the LLM
@@ -105,9 +108,9 @@ async def analyze_url(payload: ScanRequest):
105
  messages=[
106
  {"role": "system", "content": system_prompt}
107
  ],
108
- model="llama3-70b-8192", # You can change this to llama3-8b-8192 for faster/cheaper tests
109
- temperature=0.1, # Low temperature for highly analytical/deterministic outputs
110
- response_format={"type": "json_object"} # Forces the LLM to return strict JSON
111
  )
112
 
113
  # Parse the JSON response from Groq
@@ -130,5 +133,4 @@ async def analyze_url(payload: ScanRequest):
130
  # ---------------------------------------------------------
131
  if __name__ == "__main__":
132
  import uvicorn
133
- # Run the server on port 8000
134
  uvicorn.run(app, host="0.0.0.0", port=8000)
 
1
  import os
2
  import json
3
  import asyncio
4
+ import requests
5
  from functools import lru_cache
6
  from urllib.parse import urlparse
7
 
 
8
  from fastapi import FastAPI
9
  from fastapi.middleware.cors import CORSMiddleware
10
  from pydantic import BaseModel
 
23
  allow_headers=["*"],
24
  )
25
 
26
+ # Initialize Groq Client (Ensure GROQ_API_KEY is in your HF Secrets)
 
27
  GROQ_API_KEY = os.getenv("GROQ_API_KEY", "your_groq_api_key_here")
28
  groq_client = Groq(api_key=GROQ_API_KEY)
29
 
 
32
  url: str
33
 
34
  # ---------------------------------------------------------
35
+ # 2. Helper Functions (Domain Extraction & RDAP OSINT)
36
  # ---------------------------------------------------------
37
  def extract_domain(url: str) -> str:
38
  """Safely extracts the domain name from a full URL."""
 
44
  except Exception:
45
  return url
46
 
47
+ def get_whois_data(domain: str, timeout_seconds: int = 3) -> str:
48
+ """Executes an RDAP (HTTPS) lookup to bypass Cloud Port 43 blocks."""
49
+ try:
50
+ # Query the global RDAP bootstrap server over standard HTTPS
51
+ response = requests.get(f"https://rdap.org/domain/{domain}", timeout=timeout_seconds)
52
+
53
+ if response.status_code == 200:
54
+ data = response.json()
55
+ # Extract the 'registration' event from the RDAP JSON
56
+ for event in data.get("events", []):
57
+ if event.get("eventAction") == "registration":
58
+ # Returns format like: 2001-01-13T00:00:00Z
59
+ date_str = event.get("eventDate", "Unknown")
60
+ return date_str.split("T")[0] # Clean up time, just return YYYY-MM-DD
61
+
62
+ return "Unknown (No Database Match)"
63
+
64
+ except requests.exceptions.Timeout:
65
+ print(f"[WADE] RDAP timeout for {domain}. Bypassing.")
66
+ return "Unknown (Timeout)"
67
+ except Exception as e:
68
+ print(f"[WADE] RDAP error for {domain}: {e}")
69
+ return "Unknown (Error)"
70
 
71
  @lru_cache(maxsize=1000)
72
  def cached_whois_lookup(domain: str) -> str:
73
+ """Caches the result to prevent redundant lookups for the same domain."""
74
  return get_whois_data(domain)
75
 
76
  # ---------------------------------------------------------
 
81
  target_url = payload.url
82
  target_domain = extract_domain(target_url)
83
 
84
+ # A. Execute Non-Blocking, Cached OSINT Lookup via RDAP
85
  domain_age = await asyncio.to_thread(cached_whois_lookup, target_domain)
86
 
87
  # B. Construct the System Prompt for the LLM
 
108
  messages=[
109
  {"role": "system", "content": system_prompt}
110
  ],
111
+ model="llama3-70b-8192",
112
+ temperature=0.1,
113
+ response_format={"type": "json_object"}
114
  )
115
 
116
  # Parse the JSON response from Groq
 
133
  # ---------------------------------------------------------
134
  if __name__ == "__main__":
135
  import uvicorn
 
136
  uvicorn.run(app, host="0.0.0.0", port=8000)