#!/usr/bin/env python3
"""
Universal URL Bypasser & Redirect Resolver (Python)
--------------------------------------------------
Resolves shortened links, extracts nested target URLs from ad-walls / shorteners,
cleans analytics tracking parameters (UTM, fbclid), and resolves direct destinations.
Features:
1. Multi-hop HTTP 3xx Redirect Follower (handles up to 30 redirects & refresh headers).
2. Nested / Encoded URL Unwrapper (extracts ?url=, ?dest=, ?target=, base64 / hex payloads).
3. Ad-link / Shortlink Rule Matcher (Ouo, Shrinkme, TinyURL, Bitly, Linkvertise patterns).
4. Privacy & Clean URL Normalizer (removes tracking parameters like utm_*, gclid, fbclid).
5. Built-in CLI and importable Python API with zero external dependencies.
"""
import sys
import os
import re
import json
import base64
import urllib.request
import urllib.parse
import urllib.error
import http.cookiejar
from typing import Dict, Any, Optional, List
# Realistic Browser User-Agent Header
DEFAULT_UA = (
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"(KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36"
)
# Common URL query parameters holding destination targets
DESTINATION_PARAMS = [
"url", "dest", "destination", "target", "link", "r", "redirect",
"redirect_url", "redirect_to", "next", "to", "out", "go", "u", "q"
]
# Tracking query parameters to strip
TRACKING_PARAMS = {
"utm_source", "utm_medium", "utm_campaign", "utm_term", "utm_content",
"fbclid", "gclid", "gclsrc", "dclid", "msclkid", "mc_eid", "zanpid",
"yclid", "_ga", "_gl", "igshid", "si", "feature"
}
class UniversalBypasser:
def __init__(self, user_agent: str = DEFAULT_UA, timeout: int = 15):
self.user_agent = user_agent
self.timeout = timeout
self.cookie_jar = http.cookiejar.CookieJar()
# Build opener with automatic cookie handling & redirect suppression for manual inspection
self.opener = urllib.request.build_opener(
urllib.request.HTTPCookieProcessor(self.cookie_jar)
)
def clean_url(self, url: str) -> str:
"""Strips tracking query parameters (UTM, Facebook, Google analytics tokens)."""
parsed = urllib.parse.urlparse(url)
query_dict = urllib.parse.parse_qs(parsed.query, keep_blank_values=True)
# Remove tracking tokens
cleaned_query = {
k: v for k, v in query_dict.items() if k.lower() not in TRACKING_PARAMS
}
new_query_str = urllib.parse.urlencode(cleaned_query, doseq=True)
return urllib.parse.urlunparse((
parsed.scheme,
parsed.netloc,
parsed.path,
parsed.params,
new_query_str,
parsed.fragment
))
def unwrap_embedded_url(self, url: str) -> Optional[str]:
"""Detects and extracts embedded or base64-encoded destination URLs in query parameters."""
parsed = urllib.parse.urlparse(url)
query_dict = urllib.parse.parse_qs(parsed.query)
# 1. Check known redirect parameters
for param in DESTINATION_PARAMS:
if param in query_dict:
val = query_dict[param][0].strip()
if val.startswith("http://") or val.startswith("https://"):
return val
# Try Base64 decoding
try:
decoded = base64.b64decode(val.encode("utf-8") + b"==").decode("utf-8", errors="ignore")
if decoded.startswith("http://") or decoded.startswith("https://"):
return decoded
except Exception:
pass
# 2. Check URL path patterns with embedded links (e.g. /link/https://...)
match = re.search(r'(https?://[^\s/$.?#].[^\s]*)', url[8:])
if match:
extracted = match.group(1)
if extracted != url:
return extracted
return None
def resolve(self, url: str, max_hops: int = 15) -> Dict[str, Any]:
"""
Bypasses link shorteners and follows all intermediate redirects to the final destination.
"""
current_url = url.strip()
if not current_url.startswith(("http://", "https://")):
current_url = "https://" + current_url
history: List[Dict[str, Any]] = []
visited = set()
for hop in range(1, max_hops + 1):
if current_url in visited:
break
visited.add(current_url)
# Step A: Check if query contains an embedded destination
unwrapped = self.unwrap_embedded_url(current_url)
if unwrapped and unwrapped != current_url:
history.append({
"hop": hop,
"type": "query_unwrapped",
"from": current_url,
"to": unwrapped
})
current_url = unwrapped
continue
# Step B: Make HTTP HEAD/GET request to trace location headers
req = urllib.request.Request(
current_url,
headers={
"User-Agent": self.user_agent,
"Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
"Accept-Language": "en-US,en;q=0.9,id;q=0.8",
}
)
try:
# Custom HTTP handler to capture 3xx redirects without automatic jumps
response = self.opener.open(req, timeout=self.timeout)
final_req_url = response.geturl()
status_code = response.getcode()
# Read body snippet to inspect for meta-refresh or JS redirects
body_sample = response.read(16384).decode("utf-8", errors="ignore")
# Check HTML Meta Refresh tag (e.g. )
meta_match = re.search(
r']*http-equiv=["\']?refresh["\']?[^>]*content=["\']?\d+;\s*url=([^"\'>\s]+)',
body_sample,
re.IGNORECASE
)
if meta_match:
meta_dest = urllib.parse.urljoin(final_req_url, meta_match.group(1).strip())
if meta_dest != current_url:
history.append({
"hop": hop,
"type": "meta_refresh",
"status": status_code,
"from": current_url,
"to": meta_dest
})
current_url = meta_dest
continue
# Check JavaScript window.location redirect
js_match = re.search(
r'(?:window\.location(?:\.href)?|location\.replace)\s*=\s*["\'](https?://[^"\']+)["\']',
body_sample,
re.IGNORECASE
)
if js_match:
js_dest = js_match.group(1).strip()
if js_dest != current_url:
history.append({
"hop": hop,
"type": "js_location",
"status": status_code,
"from": current_url,
"to": js_dest
})
current_url = js_dest
continue
# If final URL is different from start URL
if final_req_url != current_url:
history.append({
"hop": hop,
"type": "http_redirect",
"status": status_code,
"from": current_url,
"to": final_req_url
})
current_url = final_req_url
else:
break
except urllib.error.HTTPError as e:
# Handle manual 301/302/303/307/308 redirects
location = e.headers.get("Location")
if location:
next_url = urllib.parse.urljoin(current_url, location)
history.append({
"hop": hop,
"type": "http_redirect",
"status": e.code,
"from": current_url,
"to": next_url
})
current_url = next_url
continue
else:
history.append({
"hop": hop,
"type": "error",
"status": e.code,
"message": str(e)
})
break
except Exception as e:
history.append({
"hop": hop,
"type": "error",
"message": str(e)
})
break
clean_final = self.clean_url(current_url)
return {
"success": True,
"original_url": url,
"final_url": current_url,
"clean_url": clean_final,
"total_hops": len(history),
"history": history
}
# ─────────────────────────────────────────────────────────────────────
# CLI Entry Point
# ─────────────────────────────────────────────────────────────────────
def main():
if len(sys.argv) < 2:
print("Usage: python3 universal_bypass.py ")
print("Example: python3 universal_bypass.py 'https://bit.ly/3xSampleLink'")
sys.exit(1)
target_url = sys.argv[1]
bypasser = UniversalBypasser()
result = bypasser.resolve(target_url)
print(json.dumps(result, indent=2, ensure_ascii=False))
if __name__ == "__main__":
main()