Upload 5 files
Browse files- Dockerfile (2) +13 -0
- README (1).md +35 -0
- app (2).py +332 -0
- requirements (1).txt +4 -0
- shim.js +238 -0
Dockerfile (2)
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
FROM python:3.11-slim
|
| 2 |
+
|
| 3 |
+
WORKDIR /app
|
| 4 |
+
|
| 5 |
+
COPY requirements.txt .
|
| 6 |
+
RUN pip install --no-cache-dir -r requirements.txt
|
| 7 |
+
|
| 8 |
+
COPY . .
|
| 9 |
+
|
| 10 |
+
EXPOSE 7860
|
| 11 |
+
|
| 12 |
+
# One worker: per-visitor cookie jars live in memory. Threads handle concurrency/streaming.
|
| 13 |
+
CMD ["gunicorn", "-w", "1", "--threads", "64", "--timeout", "120", "-b", "0.0.0.0:7860", "app:app"]
|
README (1).md
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
title: Simple Browser
|
| 3 |
+
emoji: 🌐
|
| 4 |
+
colorFrom: blue
|
| 5 |
+
colorTo: gray
|
| 6 |
+
sdk: docker
|
| 7 |
+
app_port: 7860
|
| 8 |
+
---
|
| 9 |
+
|
| 10 |
+
# Simple Browser
|
| 11 |
+
|
| 12 |
+
A rewriting proxy. Your browser renders everything (real JS, video, audio,
|
| 13 |
+
hover, scrolling, full resolution); this server makes the network requests.
|
| 14 |
+
|
| 15 |
+
- HTML/CSS are rewritten so every link, image, script, stylesheet and form
|
| 16 |
+
goes through `/p?u=<url>`.
|
| 17 |
+
- `shim.js` patches `fetch`, `XMLHttpRequest`, `sendBeacon`, `history`,
|
| 18 |
+
`window.open` and DOM URL setters so JS-made requests go through too.
|
| 19 |
+
- Cookies from sites are kept server-side, one jar per visitor.
|
| 20 |
+
- Private/loopback addresses are blocked (SSRF protection).
|
| 21 |
+
|
| 22 |
+
## Limits
|
| 23 |
+
- WebSockets, service workers, `document.cookie` and `location = ...` set in
|
| 24 |
+
JS are not proxied. Sites that rely on them may break or leak a direct request.
|
| 25 |
+
- Heavy sites (YouTube, Google sign-in, anything with bot detection) may still
|
| 26 |
+
fail. Google also distrusts datacenter IPs regardless of the browser.
|
| 27 |
+
- Open the Space's direct `*.hf.space` URL, not the huggingface.co page
|
| 28 |
+
(the embedded iframe can block the session cookie).
|
| 29 |
+
- This is an open proxy. Keep the Space private.
|
| 30 |
+
|
| 31 |
+
## Local run
|
| 32 |
+
```
|
| 33 |
+
pip install -r requirements.txt
|
| 34 |
+
python app.py
|
| 35 |
+
```
|
app (2).py
ADDED
|
@@ -0,0 +1,332 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ipaddress
|
| 2 |
+
import json
|
| 3 |
+
import os
|
| 4 |
+
import re
|
| 5 |
+
import socket
|
| 6 |
+
import threading
|
| 7 |
+
import time
|
| 8 |
+
import uuid
|
| 9 |
+
from urllib.parse import parse_qs, quote, urldefrag, urlencode, urljoin, urlparse
|
| 10 |
+
|
| 11 |
+
import requests
|
| 12 |
+
from bs4 import BeautifulSoup
|
| 13 |
+
from bs4.element import Doctype
|
| 14 |
+
from flask import Flask, Response, g, redirect, request, send_from_directory
|
| 15 |
+
|
| 16 |
+
app = Flask(__name__)
|
| 17 |
+
|
| 18 |
+
HERE = os.path.dirname(os.path.abspath(__file__))
|
| 19 |
+
ALLOW_PRIVATE = os.environ.get("PX_ALLOW_PRIVATE") == "1" # testing only
|
| 20 |
+
DEFAULT_UA = (
|
| 21 |
+
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
| 22 |
+
"(KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36"
|
| 23 |
+
)
|
| 24 |
+
METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]
|
| 25 |
+
URL_ATTRS = ("href", "src", "action", "poster", "data", "formaction", "background")
|
| 26 |
+
SKIP_PREFIXES = ("#", "data:", "blob:", "javascript:", "mailto:", "tel:", "about:")
|
| 27 |
+
|
| 28 |
+
# ---------------------------------------------------------------- sessions
|
| 29 |
+
# One server-side cookie jar per visitor, so logins made through the proxy
|
| 30 |
+
# stick. Cookies from sites never reach the visitor's browser.
|
| 31 |
+
SESSIONS = {}
|
| 32 |
+
S_LOCK = threading.Lock()
|
| 33 |
+
MAX_SESSIONS = 200
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
def get_session(sid):
|
| 37 |
+
now = time.time()
|
| 38 |
+
with S_LOCK:
|
| 39 |
+
if len(SESSIONS) > MAX_SESSIONS:
|
| 40 |
+
for k in sorted(SESSIONS, key=lambda k: SESSIONS[k][1])[:50]:
|
| 41 |
+
del SESSIONS[k]
|
| 42 |
+
entry = SESSIONS.get(sid)
|
| 43 |
+
if entry is None:
|
| 44 |
+
sess = requests.Session()
|
| 45 |
+
sess.trust_env = False
|
| 46 |
+
entry = SESSIONS[sid] = [sess, now]
|
| 47 |
+
entry[1] = now
|
| 48 |
+
return entry[0]
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
@app.before_request
|
| 52 |
+
def assign_sid():
|
| 53 |
+
g.sid = request.cookies.get("px_sid")
|
| 54 |
+
g.new_sid = False
|
| 55 |
+
if not g.sid:
|
| 56 |
+
g.sid = uuid.uuid4().hex
|
| 57 |
+
g.new_sid = True
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
@app.after_request
|
| 61 |
+
def persist_sid(resp):
|
| 62 |
+
if g.get("new_sid"):
|
| 63 |
+
resp.set_cookie(
|
| 64 |
+
"px_sid", g.sid, max_age=60 * 60 * 24 * 30,
|
| 65 |
+
httponly=True, secure=True, samesite="None",
|
| 66 |
+
)
|
| 67 |
+
return resp
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
# ---------------------------------------------------------------- safety
|
| 71 |
+
_DNS = {}
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def host_is_public(host, port):
|
| 75 |
+
key = (host, port)
|
| 76 |
+
hit = _DNS.get(key)
|
| 77 |
+
if hit and time.time() - hit[1] < 300:
|
| 78 |
+
return hit[0]
|
| 79 |
+
try:
|
| 80 |
+
infos = socket.getaddrinfo(host, port)
|
| 81 |
+
ok = all(ipaddress.ip_address(i[4][0]).is_global for i in infos)
|
| 82 |
+
except (socket.gaierror, ValueError):
|
| 83 |
+
ok = False
|
| 84 |
+
if len(_DNS) > 5000:
|
| 85 |
+
_DNS.clear()
|
| 86 |
+
_DNS[key] = (ok, time.time())
|
| 87 |
+
return ok
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
def is_safe(url):
|
| 91 |
+
"""Refuse non-http(s) and anything that resolves to a non-public address."""
|
| 92 |
+
p = urlparse(url)
|
| 93 |
+
if p.scheme not in ("http", "https") or not p.hostname:
|
| 94 |
+
return False
|
| 95 |
+
if ALLOW_PRIVATE:
|
| 96 |
+
return True
|
| 97 |
+
return host_is_public(p.hostname, p.port or (443 if p.scheme == "https" else 80))
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
# ---------------------------------------------------------------- rewriting
|
| 101 |
+
def px(url, base):
|
| 102 |
+
if not url or not url.strip():
|
| 103 |
+
return url
|
| 104 |
+
u = url.strip()
|
| 105 |
+
if u.lower().startswith(SKIP_PREFIXES):
|
| 106 |
+
return url
|
| 107 |
+
absu = urljoin(base, u)
|
| 108 |
+
if not absu.startswith(("http://", "https://")):
|
| 109 |
+
return url
|
| 110 |
+
absu, frag = urldefrag(absu)
|
| 111 |
+
return "/p?u=" + quote(absu, safe="") + ("#" + frag if frag else "")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
CSS_URL = re.compile(r"""url\(\s*(['"]?)(.*?)\1\s*\)""", re.I)
|
| 115 |
+
CSS_IMPORT = re.compile(r"""@import\s+(['"])(.*?)\1""", re.I)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def rewrite_css(css, base):
|
| 119 |
+
css = CSS_URL.sub(lambda m: "url(%s%s%s)" % (m.group(1), px(m.group(2), base), m.group(1)), css)
|
| 120 |
+
css = CSS_IMPORT.sub(lambda m: "@import %s%s%s" % (m.group(1), px(m.group(2), base), m.group(1)), css)
|
| 121 |
+
return css
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
def rewrite_srcset(value, base):
|
| 125 |
+
out = []
|
| 126 |
+
for part in value.split(","):
|
| 127 |
+
bits = part.strip().split(None, 1)
|
| 128 |
+
if bits:
|
| 129 |
+
out.append(" ".join([px(bits[0], base)] + bits[1:]))
|
| 130 |
+
return ", ".join(out)
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def rewrite_html(raw, doc_url, nojs=False):
|
| 134 |
+
soup = BeautifulSoup(raw, "html.parser")
|
| 135 |
+
base = doc_url
|
| 136 |
+
|
| 137 |
+
if nojs:
|
| 138 |
+
# Serve the server-rendered page only: drop scripts, show <noscript> content.
|
| 139 |
+
for s in soup.find_all("script"):
|
| 140 |
+
s.extract()
|
| 141 |
+
for n in soup.find_all("noscript"):
|
| 142 |
+
n.unwrap()
|
| 143 |
+
|
| 144 |
+
b = soup.find("base", href=True)
|
| 145 |
+
if b:
|
| 146 |
+
base = urljoin(doc_url, b["href"])
|
| 147 |
+
b.extract()
|
| 148 |
+
|
| 149 |
+
for m in soup.find_all("meta"):
|
| 150 |
+
equiv = (m.get("http-equiv") or "").lower()
|
| 151 |
+
if equiv == "content-security-policy":
|
| 152 |
+
m.extract()
|
| 153 |
+
elif equiv == "refresh" and m.get("content"):
|
| 154 |
+
mm = re.match(r"\s*(\d+)\s*;\s*url=(.*)", m["content"], re.I)
|
| 155 |
+
if mm:
|
| 156 |
+
m["content"] = "%s;url=%s" % (mm.group(1), px(mm.group(2).strip(" '\""), base))
|
| 157 |
+
|
| 158 |
+
for tag in soup.find_all(True):
|
| 159 |
+
if tag.name == "link" and {"preconnect", "dns-prefetch", "prefetch", "prerender"} & set(tag.get("rel") or []):
|
| 160 |
+
tag.extract() # these would make the visitor's browser contact the origin directly
|
| 161 |
+
continue
|
| 162 |
+
for attr in ("integrity", "nonce", "ping"):
|
| 163 |
+
tag.attrs.pop(attr, None)
|
| 164 |
+
if nojs:
|
| 165 |
+
for attr in [a for a in tag.attrs if a.lower().startswith("on")]:
|
| 166 |
+
del tag.attrs[attr]
|
| 167 |
+
|
| 168 |
+
if tag.name == "form" and (tag.get("method") or "get").lower() == "get":
|
| 169 |
+
# Browsers drop the query string of a GET form's action, so carry the
|
| 170 |
+
# real destination in a hidden field instead.
|
| 171 |
+
dest = urljoin(base, tag.get("action") or "")
|
| 172 |
+
tag["action"] = "/p"
|
| 173 |
+
tag.insert(0, soup.new_tag("input", attrs={"type": "hidden", "name": "__px_u", "value": dest}))
|
| 174 |
+
else:
|
| 175 |
+
for attr in URL_ATTRS:
|
| 176 |
+
v = tag.get(attr)
|
| 177 |
+
if isinstance(v, str) and v:
|
| 178 |
+
tag[attr] = px(v, base)
|
| 179 |
+
|
| 180 |
+
for attr in ("srcset", "imagesrcset"):
|
| 181 |
+
if isinstance(tag.get(attr), str):
|
| 182 |
+
tag[attr] = rewrite_srcset(tag[attr], base)
|
| 183 |
+
if isinstance(tag.get("style"), str):
|
| 184 |
+
tag["style"] = rewrite_css(tag["style"], base)
|
| 185 |
+
if tag.name == "style" and tag.string:
|
| 186 |
+
tag.string = rewrite_css(tag.string, base)
|
| 187 |
+
|
| 188 |
+
boot = soup.new_tag("script")
|
| 189 |
+
boot.string = "window.__PX_BASE__=%s;" % json.dumps(doc_url).replace("</", "<\\/")
|
| 190 |
+
shim = soup.new_tag("script", src="/shim.js")
|
| 191 |
+
|
| 192 |
+
head = soup.find("head")
|
| 193 |
+
if head is None:
|
| 194 |
+
head = soup.new_tag("head")
|
| 195 |
+
html = soup.find("html")
|
| 196 |
+
if html:
|
| 197 |
+
html.insert(0, head)
|
| 198 |
+
else:
|
| 199 |
+
soup.insert(1 if soup.contents and isinstance(soup.contents[0], Doctype) else 0, head)
|
| 200 |
+
head.insert(0, shim)
|
| 201 |
+
head.insert(0, boot)
|
| 202 |
+
return str(soup)
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
SHELL = """<!DOCTYPE html><html><head><meta charset="utf-8">
|
| 206 |
+
<meta name="viewport" content="width=device-width,initial-scale=1"><title>%(title)s</title>
|
| 207 |
+
<style>body{margin:0;background:#111;color:#ddd;font-family:-apple-system,Helvetica,Arial,sans-serif;
|
| 208 |
+
display:flex;align-items:center;justify-content:center;min-height:100vh}
|
| 209 |
+
main{text-align:center;max-width:460px;padding:24px;line-height:1.5}a{color:#7aa7ff}</style>
|
| 210 |
+
<script>window.__PX_BASE__="";</script><script src="/shim.js"></script></head>
|
| 211 |
+
<body><main>%(body)s</main></body></html>"""
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def shell(title, body, status=200):
|
| 215 |
+
return Response(SHELL % {"title": title, "body": body}, status=status, content_type="text/html; charset=utf-8")
|
| 216 |
+
|
| 217 |
+
|
| 218 |
+
# ---------------------------------------------------------------- routes
|
| 219 |
+
@app.route("/")
|
| 220 |
+
def home():
|
| 221 |
+
links = " · ".join(
|
| 222 |
+
'<a href="/p?u=%s">%s</a>' % (quote(u, safe=""), n)
|
| 223 |
+
for n, u in [
|
| 224 |
+
("DuckDuckGo", "https://duckduckgo.com/html/"),
|
| 225 |
+
("Wikipedia", "https://en.wikipedia.org/"),
|
| 226 |
+
("Hacker News", "https://news.ycombinator.com/"),
|
| 227 |
+
]
|
| 228 |
+
)
|
| 229 |
+
return shell(
|
| 230 |
+
"Browser",
|
| 231 |
+
"<h2>Type a URL or search in the bar</h2>"
|
| 232 |
+
"<p>Every request is made by this server. Rendering happens in your browser.</p><p>%s</p>" % links,
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@app.route("/shim.js")
|
| 237 |
+
def shim_js():
|
| 238 |
+
resp = send_from_directory(HERE, "shim.js", mimetype="application/javascript")
|
| 239 |
+
resp.headers["Cache-Control"] = "no-cache"
|
| 240 |
+
return resp
|
| 241 |
+
|
| 242 |
+
|
| 243 |
+
@app.route("/p", methods=METHODS)
|
| 244 |
+
def proxy():
|
| 245 |
+
args = request.args
|
| 246 |
+
if "__px_u" in args: # GET form submission
|
| 247 |
+
fields = [(k, v) for k, v in args.items(multi=True) if k != "__px_u"]
|
| 248 |
+
target = urlparse(args["__px_u"])._replace(query=urlencode(fields), fragment="").geturl()
|
| 249 |
+
else:
|
| 250 |
+
target = args.get("u", "").strip()
|
| 251 |
+
if not target:
|
| 252 |
+
return redirect("/")
|
| 253 |
+
if not is_safe(target):
|
| 254 |
+
return shell("Blocked", "<h3>Blocked</h3><p>That address isn't reachable through this proxy.</p>", 403)
|
| 255 |
+
|
| 256 |
+
origin = "%s://%s" % (urlparse(target).scheme, urlparse(target).netloc)
|
| 257 |
+
headers = {
|
| 258 |
+
"User-Agent": request.headers.get("User-Agent", DEFAULT_UA),
|
| 259 |
+
"Accept": request.headers.get("Accept", "*/*"),
|
| 260 |
+
"Accept-Language": request.headers.get("Accept-Language", "en-US,en;q=0.9"),
|
| 261 |
+
"Accept-Encoding": "identity",
|
| 262 |
+
"Referer": origin + "/",
|
| 263 |
+
}
|
| 264 |
+
for h in ("Content-Type", "Range"):
|
| 265 |
+
if request.headers.get(h):
|
| 266 |
+
headers[h] = request.headers[h]
|
| 267 |
+
body = None
|
| 268 |
+
if request.method not in ("GET", "HEAD"):
|
| 269 |
+
headers["Origin"] = origin
|
| 270 |
+
body = request.get_data()
|
| 271 |
+
|
| 272 |
+
try:
|
| 273 |
+
r = get_session(g.sid).request(
|
| 274 |
+
request.method, target, headers=headers, data=body,
|
| 275 |
+
allow_redirects=False, stream=True, timeout=(10, 30),
|
| 276 |
+
)
|
| 277 |
+
except requests.RequestException as e:
|
| 278 |
+
return shell("Error", "<h3>Couldn't load that page</h3><p>%s</p>" % str(e).replace("<", "<"), 502)
|
| 279 |
+
|
| 280 |
+
if r.status_code in (301, 302, 303, 307, 308) and r.headers.get("Location"):
|
| 281 |
+
resp = Response(status=r.status_code)
|
| 282 |
+
resp.headers["Location"] = px(urljoin(target, r.headers["Location"]), target)
|
| 283 |
+
r.close()
|
| 284 |
+
return resp
|
| 285 |
+
|
| 286 |
+
ctype = r.headers.get("Content-Type", "")
|
| 287 |
+
kind = ctype.split(";")[0].strip().lower()
|
| 288 |
+
|
| 289 |
+
if kind in ("text/html", "application/xhtml+xml"):
|
| 290 |
+
out = rewrite_html(r.content, target, request.cookies.get("px_nojs") == "1")
|
| 291 |
+
resp = Response(out, status=r.status_code, content_type="text/html; charset=utf-8")
|
| 292 |
+
resp.headers["Cache-Control"] = "no-store"
|
| 293 |
+
return resp
|
| 294 |
+
|
| 295 |
+
if kind == "text/css":
|
| 296 |
+
out = rewrite_css(r.content.decode(r.encoding or "utf-8", "replace"), target)
|
| 297 |
+
return Response(out, status=r.status_code, content_type="text/css; charset=utf-8")
|
| 298 |
+
|
| 299 |
+
keep = {}
|
| 300 |
+
for h in ("Content-Type", "Content-Range", "Accept-Ranges", "Content-Disposition", "Cache-Control"):
|
| 301 |
+
if r.headers.get(h):
|
| 302 |
+
keep[h] = r.headers[h]
|
| 303 |
+
if r.headers.get("Content-Length") and r.headers.get("Content-Encoding", "identity") == "identity":
|
| 304 |
+
keep["Content-Length"] = r.headers["Content-Length"]
|
| 305 |
+
|
| 306 |
+
def stream():
|
| 307 |
+
try:
|
| 308 |
+
for chunk in r.iter_content(65536):
|
| 309 |
+
if chunk:
|
| 310 |
+
yield chunk
|
| 311 |
+
finally:
|
| 312 |
+
r.close()
|
| 313 |
+
|
| 314 |
+
return Response(stream(), status=r.status_code, headers=keep)
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
@app.route("/<path:path>", methods=METHODS)
|
| 318 |
+
def fallback(path):
|
| 319 |
+
"""Catch root-relative requests that escaped rewriting (e.g. built in JS)
|
| 320 |
+
and re-aim them using the page they came from."""
|
| 321 |
+
ref = urlparse(request.headers.get("Referer", ""))
|
| 322 |
+
q = parse_qs(ref.query)
|
| 323 |
+
if ref.path == "/p":
|
| 324 |
+
page = (q.get("__px_u") or q.get("u") or [None])[0]
|
| 325 |
+
if page:
|
| 326 |
+
real = urljoin(page, request.full_path.rstrip("?"))
|
| 327 |
+
return redirect(px(real, page), code=307)
|
| 328 |
+
return shell("Not found", "<h3>Not found</h3>", 404)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
if __name__ == "__main__":
|
| 332 |
+
app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 7860)), threaded=True)
|
requirements (1).txt
ADDED
|
@@ -0,0 +1,4 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
flask==3.0.3
|
| 2 |
+
requests==2.32.3
|
| 3 |
+
beautifulsoup4==4.12.3
|
| 4 |
+
gunicorn==22.0.0
|
shim.js
ADDED
|
@@ -0,0 +1,238 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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owing through the server proxy, and draws the small URL bar. */
|
| 3 |
+
(function () {
|
| 4 |
+
if (window.__PX_INSTALLED__) return;
|
| 5 |
+
window.__PX_INSTALLED__ = true;
|
| 6 |
+
|
| 7 |
+
var ORIGIN = location.origin;
|
| 8 |
+
var base = window.__PX_BASE__ || "";
|
| 9 |
+
|
| 10 |
+
function isProxied(s) {
|
| 11 |
+
return /^(https?:\/\/[^\/]+)?\/p\?(u|__px_u)=/.test(s) &&
|
| 12 |
+
(s.charAt(0) === "/" || s.indexOf(ORIGIN) === 0);
|
| 13 |
+
}
|
| 14 |
+
function toProxy(abs) {
|
| 15 |
+
var i = abs.indexOf("#"), hash = "";
|
| 16 |
+
if (i >= 0) { hash = abs.slice(i); abs = abs.slice(0, i); }
|
| 17 |
+
return "/p?u=" + encodeURIComponent(abs) + hash;
|
| 18 |
+
}
|
| 19 |
+
function px(url) {
|
| 20 |
+
if (!base || url == null) return url;
|
| 21 |
+
var s = String(url).trim();
|
| 22 |
+
if (!s || /^(#|data:|blob:|javascript:|mailto:|tel:|about:)/i.test(s) || isProxied(s)) return url;
|
| 23 |
+
try {
|
| 24 |
+
var u = new URL(s, base);
|
| 25 |
+
// Code that built a URL from location.origin points at the proxy itself;
|
| 26 |
+
// re-aim it at the real site.
|
| 27 |
+
if (u.origin === ORIGIN) u = new URL(u.pathname + u.search + u.hash, base);
|
| 28 |
+
if (u.protocol !== "http:" && u.protocol !== "https:") return url;
|
| 29 |
+
return toProxy(u.href);
|
| 30 |
+
} catch (e) { return url; }
|
| 31 |
+
}
|
| 32 |
+
function pxSrcset(v) {
|
| 33 |
+
return String(v).split(",").map(function (part) {
|
| 34 |
+
var bits = part.trim().split(/\s+/);
|
| 35 |
+
if (bits[0]) bits[0] = px(bits[0]);
|
| 36 |
+
return bits.join(" ");
|
| 37 |
+
}).join(", ");
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
/* ---------------------------------------------------------- patches */
|
| 41 |
+
if (base) {
|
| 42 |
+
var _fetch = window.fetch;
|
| 43 |
+
if (_fetch) {
|
| 44 |
+
window.fetch = function (input, init) {
|
| 45 |
+
try {
|
| 46 |
+
if (typeof input === "string" || input instanceof URL) input = px(String(input));
|
| 47 |
+
else if (input && input.url) input = new Request(px(input.url), input);
|
| 48 |
+
} catch (e) {}
|
| 49 |
+
return _fetch.call(this, input, init);
|
| 50 |
+
};
|
| 51 |
+
}
|
| 52 |
+
|
| 53 |
+
var _xhrOpen = XMLHttpRequest.prototype.open;
|
| 54 |
+
XMLHttpRequest.prototype.open = function (method, url) {
|
| 55 |
+
var a = Array.prototype.slice.call(arguments);
|
| 56 |
+
a[1] = px(url);
|
| 57 |
+
return _xhrOpen.apply(this, a);
|
| 58 |
+
};
|
| 59 |
+
|
| 60 |
+
if (navigator.sendBeacon) {
|
| 61 |
+
var _beacon = navigator.sendBeacon;
|
| 62 |
+
navigator.sendBeacon = function (url, data) { return _beacon.call(this, px(url), data); };
|
| 63 |
+
}
|
| 64 |
+
|
| 65 |
+
var _open = window.open;
|
| 66 |
+
window.open = function () {
|
| 67 |
+
var a = Array.prototype.slice.call(arguments);
|
| 68 |
+
if (a.length) a[0] = px(a[0]);
|
| 69 |
+
return _open.apply(window, a);
|
| 70 |
+
};
|
| 71 |
+
|
| 72 |
+
["pushState", "replaceState"].forEach(function (fn) {
|
| 73 |
+
var orig = history[fn];
|
| 74 |
+
history[fn] = function (state, title, url) {
|
| 75 |
+
if (url != null) {
|
| 76 |
+
try {
|
| 77 |
+
var abs = new URL(String(url), base).href;
|
| 78 |
+
base = abs;
|
| 79 |
+
window.__PX_BASE__ = abs;
|
| 80 |
+
url = toProxy(abs);
|
| 81 |
+
} catch (e) {}
|
| 82 |
+
}
|
| 83 |
+
var r = orig.call(this, state, title, url);
|
| 84 |
+
syncBar();
|
| 85 |
+
return r;
|
| 86 |
+
};
|
| 87 |
+
});
|
| 88 |
+
function syncBase() {
|
| 89 |
+
var u = new URLSearchParams(location.search).get("u");
|
| 90 |
+
if (u) base = u + location.hash;
|
| 91 |
+
syncBar();
|
| 92 |
+
}
|
| 93 |
+
window.addEventListener("popstate", syncBase);
|
| 94 |
+
window.addEventListener("hashchange", syncBase);
|
| 95 |
+
|
| 96 |
+
[[HTMLImageElement, "src"], [HTMLScriptElement, "src"], [HTMLIFrameElement, "src"],
|
| 97 |
+
[HTMLMediaElement, "src"], [HTMLSourceElement, "src"], [HTMLEmbedElement, "src"],
|
| 98 |
+
[HTMLInputElement, "src"], [HTMLLinkElement, "href"], [HTMLAnchorElement, "href"],
|
| 99 |
+
[HTMLFormElement, "action"], [HTMLVideoElement, "poster"]
|
| 100 |
+
].forEach(function (pair) {
|
| 101 |
+
var d = Object.getOwnPropertyDescriptor(pair[0].prototype, pair[1]);
|
| 102 |
+
if (!d || !d.set) return;
|
| 103 |
+
Object.defineProperty(pair[0].prototype, pair[1], {
|
| 104 |
+
configurable: true, enumerable: d.enumerable, get: d.get,
|
| 105 |
+
set: function (v) { d.set.call(this, px(v)); }
|
| 106 |
+
});
|
| 107 |
+
});
|
| 108 |
+
|
| 109 |
+
var URL_ATTR = { src: 1, href: 1, action: 1, poster: 1, data: 1, formaction: 1 };
|
| 110 |
+
var _setAttr = Element.prototype.setAttribute;
|
| 111 |
+
Element.prototype.setAttribute = function (name, value) {
|
| 112 |
+
var n = String(name).toLowerCase();
|
| 113 |
+
if (URL_ATTR[n]) value = px(value);
|
| 114 |
+
else if (n === "srcset") value = pxSrcset(value);
|
| 115 |
+
return _setAttr.call(this, name, value);
|
| 116 |
+
};
|
| 117 |
+
|
| 118 |
+
// Markup injected as a string: rewrite URLs on the new nodes right after
|
| 119 |
+
// insertion (before image loads start), without re-parsing the HTML.
|
| 120 |
+
var SEL = "[src],[href],[action],[poster],[srcset]";
|
| 121 |
+
function fixTree(root) {
|
| 122 |
+
if (!root || !root.querySelectorAll) return;
|
| 123 |
+
var list = root.querySelectorAll(SEL);
|
| 124 |
+
for (var i = 0; i < list.length; i++) {
|
| 125 |
+
var el = list[i];
|
| 126 |
+
["src", "href", "action", "poster"].forEach(function (a) {
|
| 127 |
+
var v = el.getAttribute(a);
|
| 128 |
+
if (v != null) { var nv = px(v); if (nv !== v) _setAttr.call(el, a, nv); }
|
| 129 |
+
});
|
| 130 |
+
var ss = el.getAttribute("srcset");
|
| 131 |
+
if (ss != null) { var ns = pxSrcset(ss); if (ns !== ss) _setAttr.call(el, "srcset", ns); }
|
| 132 |
+
}
|
| 133 |
+
}
|
| 134 |
+
var innerDesc = Object.getOwnPropertyDescriptor(Element.prototype, "innerHTML");
|
| 135 |
+
Object.defineProperty(Element.prototype, "innerHTML", {
|
| 136 |
+
configurable: true, enumerable: innerDesc.enumerable, get: innerDesc.get,
|
| 137 |
+
set: function (v) { innerDesc.set.call(this, v); fixTree(this); }
|
| 138 |
+
});
|
| 139 |
+
var _iah = Element.prototype.insertAdjacentHTML;
|
| 140 |
+
Element.prototype.insertAdjacentHTML = function (pos, html) {
|
| 141 |
+
var r = _iah.call(this, pos, html);
|
| 142 |
+
fixTree(/^(beforebegin|afterend)$/i.test(pos) ? this.parentNode : this);
|
| 143 |
+
return r;
|
| 144 |
+
};
|
| 145 |
+
}
|
| 146 |
+
|
| 147 |
+
/* ---------------------------------------------------------- URL bar */
|
| 148 |
+
var ICON = {
|
| 149 |
+
back: '<path d="M15 18l-6-6 6-6"/>',
|
| 150 |
+
fwd: '<path d="M9 18l6-6-6-6"/>',
|
| 151 |
+
reload: '<path d="M21 12a9 9 0 1 1-3-6.7"/><path d="M21 4v5h-5"/>',
|
| 152 |
+
go: '<path d="M5 12h14"/><path d="M13 6l6 6-6 6"/>',
|
| 153 |
+
up: '<path d="M6 15l6-6 6 6"/>',
|
| 154 |
+
down: '<path d="M6 9l6 6 6-6"/>',
|
| 155 |
+
code: '<path d="M8 6l-6 6 6 6"/><path d="M16 6l6 6-6 6"/>'
|
| 156 |
+
};
|
| 157 |
+
function svg(name) {
|
| 158 |
+
return '<svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" ' +
|
| 159 |
+
'stroke-width="2" stroke-linecap="round" stroke-linejoin="round">' + ICON[name] + "</svg>";
|
| 160 |
+
}
|
| 161 |
+
|
| 162 |
+
var input, barHost;
|
| 163 |
+
function syncBar() {
|
| 164 |
+
if (input && document.activeElement !== barHost) input.value = base.split("#")[0];
|
| 165 |
+
}
|
| 166 |
+
function normalize(v) {
|
| 167 |
+
v = v.trim();
|
| 168 |
+
if (!v) return null;
|
| 169 |
+
if (/^https?:\/\//i.test(v)) return v;
|
| 170 |
+
if (!/\s/.test(v) && /^[^\s\/]+\.[^\s\/]{2,}(\/.*)?$/.test(v)) return "https://" + v;
|
| 171 |
+
return "https://duckduckgo.com/html/?q=" + encodeURIComponent(v);
|
| 172 |
+
}
|
| 173 |
+
function navigate() {
|
| 174 |
+
var url = normalize(input.value);
|
| 175 |
+
if (url) location.href = "/p?u=" + encodeURIComponent(url);
|
| 176 |
+
}
|
| 177 |
+
function mountBar() {
|
| 178 |
+
if (document.getElementById("__px_bar")) return;
|
| 179 |
+
barHost = document.createElement("div");
|
| 180 |
+
barHost.id = "__px_bar";
|
| 181 |
+
var root = barHost.attachShadow({ mode: "open" });
|
| 182 |
+
root.innerHTML =
|
| 183 |
+
"<style>" +
|
| 184 |
+
".bar{position:fixed;top:0;left:0;right:0;height:40px;box-sizing:border-box;display:flex;gap:6px;" +
|
| 185 |
+
"align-items:center;padding:0 8px;background:#1e1e1e;z-index:2147483647;font:14px system-ui,sans-serif}" +
|
| 186 |
+
"button{flex:none;width:28px;height:28px;border:0;border-radius:6px;background:#2d2d2d;color:#ddd;" +
|
| 187 |
+
"display:grid;place-items:center;cursor:pointer;padding:0}button:hover{background:#3a3a3a}" +
|
| 188 |
+
"input{flex:1;min-width:0;height:28px;border:0;border-radius:6px;padding:0 10px;background:#2d2d2d;" +
|
| 189 |
+
"color:#fff;font:inherit;outline:none}input:focus{box-shadow:0 0 0 1px #4f8cff}" +
|
| 190 |
+
"button.on{background:#4f8cff;color:#fff}" +
|
| 191 |
+
".tab{position:fixed;top:6px;right:6px;z-index:2147483647;display:none;background:#1e1e1e}" +
|
| 192 |
+
"</style>" +
|
| 193 |
+
'<div class="bar"><button id="b" title="Back">' + svg("back") + "</button>" +
|
| 194 |
+
'<button id="f" title="Forward">' + svg("fwd") + "</button>" +
|
| 195 |
+
'<button id="r" title="Reload">' + svg("reload") + "</button>" +
|
| 196 |
+
'<input id="u" spellcheck="false" autocapitalize="off" placeholder="Search or enter address">' +
|
| 197 |
+
'<button id="g" title="Go">' + svg("go") + "</button>" +
|
| 198 |
+
'<button id="j">' + svg("code") + "</button>" +
|
| 199 |
+
'<button id="c" title="Hide bar">' + svg("up") + "</button></div>" +
|
| 200 |
+
'<button class="tab" id="t" title="Show bar">' + svg("down") + "</button>";
|
| 201 |
+
document.documentElement.appendChild(barHost);
|
| 202 |
+
document.documentElement.style.setProperty("margin-top", "40px", "important");
|
| 203 |
+
|
| 204 |
+
input = root.getElementById("u");
|
| 205 |
+
barHost = root.host;
|
| 206 |
+
input.value = base.split("#")[0];
|
| 207 |
+
var bar = root.querySelector(".bar"), tab = root.getElementById("t");
|
| 208 |
+
root.getElementById("b").onclick = function () { history.back(); };
|
| 209 |
+
root.getElementById("f").onclick = function () { history.forward(); };
|
| 210 |
+
root.getElementById("r").onclick = function () { location.reload(); };
|
| 211 |
+
root.getElementById("g").onclick = navigate;
|
| 212 |
+
input.addEventListener("keydown", function (e) { if (e.key === "Enter") navigate(); });
|
| 213 |
+
input.addEventListener("focus", function () { input.select(); });
|
| 214 |
+
var jsBtn = root.getElementById("j");
|
| 215 |
+
function nojsOn() { return /(^|;\s*)px_nojs=1/.test(document.cookie); }
|
| 216 |
+
function paintJs() {
|
| 217 |
+
var off = nojsOn();
|
| 218 |
+
jsBtn.className = off ? "on" : "";
|
| 219 |
+
jsBtn.title = off ? "Page scripts are OFF (click to turn on)" : "Page scripts are on (click to turn off)";
|
| 220 |
+
}
|
| 221 |
+
paintJs();
|
| 222 |
+
jsBtn.onclick = function () {
|
| 223 |
+
document.cookie = "px_nojs=" + (nojsOn() ? "0" : "1") +
|
| 224 |
+
"; path=/; max-age=31536000; SameSite=None; Secure";
|
| 225 |
+
location.reload();
|
| 226 |
+
};
|
| 227 |
+
root.getElementById("c").onclick = function () {
|
| 228 |
+
bar.style.display = "none"; tab.style.display = "grid";
|
| 229 |
+
document.documentElement.style.setProperty("margin-top", "0", "important");
|
| 230 |
+
};
|
| 231 |
+
tab.onclick = function () {
|
| 232 |
+
bar.style.display = "flex"; tab.style.display = "none";
|
| 233 |
+
document.documentElement.style.setProperty("margin-top", "40px", "important");
|
| 234 |
+
};
|
| 235 |
+
}
|
| 236 |
+
if (document.readyState === "loading") document.addEventListener("DOMContentLoaded", mountBar);
|
| 237 |
+
else mountBar();
|
| 238 |
+
})();
|