import os
import requests
from urllib.parse import urlparse, urljoin
from flask import Flask, request, Response, render_template_string
app = Flask(__name__)
HTML_FORM = '''
Proxy Browser
Proxy Browser
{% if error %}
{{ error }}
{% endif %}
'''
def smart_url(user_url):
if not user_url:
return None
u = user_url.strip()
if not (u.startswith("http://") or u.startswith("https://")):
if "." in u:
u = "https://" + u
else:
return None
return u
def rewrite_html(html, base_url):
from bs4 import BeautifulSoup
soup = BeautifulSoup(html, "html.parser")
tags = [("a", "href"), ("img", "src"), ("script", "src"), ("link", "href")]
for tag, attr in tags:
for t in soup.find_all(tag):
asset_url = t.get(attr)
if asset_url:
if asset_url.startswith("http"):
t[attr] = "/proxy?url=" + asset_url
elif asset_url.startswith("//"):
t[attr] = "/proxy?url=https:" + asset_url
elif asset_url.startswith("/"):
domain = f"{urlparse(base_url).scheme}://{urlparse(base_url).netloc}"
t[attr] = "/proxy?url=" + urljoin(domain, asset_url)
else:
t[attr] = "/proxy?url=" + urljoin(base_url, asset_url)
return str(soup)
@app.route("/", methods=["GET"])
def index():
raw_url = request.args.get("url", "").strip()
if not raw_url:
return render_template_string(HTML_FORM)
url = smart_url(raw_url)
if not url:
return render_template_string(HTML_FORM, error="Invalid URL. Try entering a domain like google.com")
# Show the result in an iframe, with a back button
return f'''
'''
@app.route("/proxy", methods=["GET"])
def proxy():
raw_url = request.args.get("url", "").strip()
url = smart_url(raw_url)
if not url:
return render_template_string(HTML_FORM, error="Invalid or missing URL.")
try:
resp = requests.get(url, headers={"User-Agent": "Mozilla/5.0"}, timeout=10)
content_type = resp.headers.get("Content-Type", "")
if "text/html" in content_type:
rewritten = rewrite_html(resp.text, url)
return Response(rewritten, content_type=content_type)
elif any(x in content_type for x in ["image", "javascript", "css"]):
return Response(resp.content, content_type=content_type)
else:
return Response(resp.content, content_type=content_type)
except Exception as e:
return render_template_string(HTML_FORM, error=f"Error: {e}")
if __name__ == "__main__":
port = int(os.environ.get("PORT", 5000))
app.run(host="0.0.0.0", port=port)