if-proxy/app/main.py
boyko_vn 1f380e3d27 1
2026-10-30 23:37:28 +03:00

320 lines
11 KiB
Python

import ipaddress
import json
import os
import re
import sqlite3
import tomllib
from contextlib import contextmanager
from pathlib import Path
from urllib.parse import urlsplit
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import HTMLResponse, JSONResponse, PlainTextResponse
from pydantic import BaseModel, Field, field_validator
ROOT = Path(__file__).resolve().parent.parent
DB_PATH = Path(os.environ.get("PAC_ROUTER_DB", str(ROOT / "router.db")))
DEFAULT_HOST = os.environ.get("PAC_UPSTREAM_HOST", "127.0.0.1")
DEFAULT_PORT = int(os.environ.get("PAC_UPSTREAM_PORT", "3128"))
DOMAIN_RE = re.compile(r"^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$")
def server_config():
with (ROOT / "config.toml").open("rb") as f:
config = tomllib.load(f)
server = config["server"]
host = os.environ.get("PAC_UI_HOST", server["host"])
port = int(os.environ.get("PAC_UI_PORT", server["port"]))
if not isinstance(host, str) or not host:
raise ValueError("server.host must be a nonempty string")
if type(port) is not int or not 1 <= port <= 65535:
raise ValueError("server.port must be an integer between 1 and 65535")
return host, port
def proxy_server_config():
with (ROOT / "config.toml").open("rb") as f:
config = tomllib.load(f)
proxy = config.get("proxy_server", {"host": "127.0.0.1", "port": 25667})
host = os.environ.get("PAC_PROXY_HOST", proxy["host"])
port = int(os.environ.get("PAC_PROXY_PORT", proxy["port"]))
if host not in ("127.0.0.1", "localhost", "::1") and os.environ.get("PAC_ALLOW_NON_LOOPBACK") != "1":
raise ValueError("proxy_server.host must be a loopback address")
if type(port) is not int or not 1 <= port <= 65535:
raise ValueError("proxy_server.port must be an integer between 1 and 65535")
return host, port
app = FastAPI(title="PAC Router", docs_url=None, redoc_url=None, openapi_url=None)
def validate_domain(raw: str) -> str:
value = raw.strip().lower().rstrip(".")
if value.startswith("*."):
base = value[2:]
else:
base = value
if not base or len(base) > 253 or not DOMAIN_RE.fullmatch(base):
raise ValueError("Use a hostname or *.hostname (ASCII/IDNA); no URLs or ports")
if "." not in base and base != "localhost":
raise ValueError("Domain must contain a dot")
return value
def validate_proxy(host: str, port: int):
try:
ipaddress.ip_address(host)
except ValueError:
if not DOMAIN_RE.fullmatch(host) or len(host) > 253:
raise ValueError("Invalid proxy host")
if not 1 <= port <= 65535:
raise ValueError("Invalid proxy port")
class RuleIn(BaseModel):
domain: str = Field(min_length=1, max_length=260)
route: str = "PROXY"
enabled: bool = True
@field_validator("domain")
@classmethod
def domain_valid(cls, v):
return validate_domain(v)
@field_validator("route")
@classmethod
def route_valid(cls, v):
if v not in ("PROXY", "DIRECT"):
raise ValueError("Route must be PROXY or DIRECT")
return v
class SettingsIn(BaseModel):
proxy_host: str
proxy_port: int
default_route: str = "DIRECT"
@field_validator("default_route")
@classmethod
def route_valid(cls, v):
if v not in ("DIRECT", "PROXY"):
raise ValueError("Invalid route")
return v
@field_validator("proxy_host")
@classmethod
def host_valid(cls, v):
v = v.strip().lower()
validate_proxy(v, 1)
return v
@field_validator("proxy_port")
@classmethod
def port_valid(cls, v):
validate_proxy("127.0.0.1", v)
return v
@contextmanager
def db():
DB_PATH.parent.mkdir(parents=True, exist_ok=True)
con = sqlite3.connect(DB_PATH, timeout=10)
con.row_factory = sqlite3.Row
try:
yield con
con.commit()
finally:
con.close()
def initialize():
validate_proxy(DEFAULT_HOST, DEFAULT_PORT)
with db() as con:
con.execute("CREATE TABLE IF NOT EXISTS rules (id INTEGER PRIMARY KEY, domain TEXT NOT NULL UNIQUE, route TEXT NOT NULL, enabled INTEGER NOT NULL DEFAULT 1)")
con.execute("CREATE TABLE IF NOT EXISTS settings (key TEXT PRIMARY KEY, value TEXT NOT NULL)")
con.execute("INSERT OR IGNORE INTO settings VALUES ('proxy_host', ?)", (DEFAULT_HOST,))
con.execute("INSERT OR IGNORE INTO settings VALUES ('proxy_port', ?)", (str(DEFAULT_PORT),))
con.execute("INSERT OR IGNORE INTO settings VALUES ('default_route', 'DIRECT')")
initialize()
def settings():
with db() as con:
d = {r["key"]: r["value"] for r in con.execute("SELECT key, value FROM settings")}
return {"proxy_host": d["proxy_host"], "proxy_port": int(d["proxy_port"]), "default_route": d["default_route"]}
def rules():
with db() as con:
return [dict(r) | {"enabled": bool(r["enabled"])} for r in con.execute("SELECT * FROM rules ORDER BY id")]
def match(pattern, host):
if pattern.startswith("*."):
base = pattern[2:]
return host.endswith("." + base)
return pattern == host
def route_for(host):
host = host.strip().lower().rstrip(".")
active = [r for r in rules() if r["enabled"] and match(r["domain"], host)]
# Exact matches outrank wildcards; longer suffix outranks shorter; id breaks ties.
active.sort(key=lambda r: (not r["domain"].startswith("*."), len(r["domain"]), -r["id"]), reverse=True)
selected = active[0] if active else None
return {"route": selected["route"] if selected else settings()["default_route"], "rule": selected}
def pac():
s = settings()
proxy = f'PROXY {s["proxy_host"]}:{s["proxy_port"]}'
active = [r for r in rules() if r["enabled"]]
active.sort(key=lambda r: (not r["domain"].startswith("*."), len(r["domain"]), -r["id"]), reverse=True)
lines = [
"// Generated by PAC Router. No fallback to DIRECT for PROXY routes.",
"function FindProxyForURL(url, host) {",
" host = host.toLowerCase().replace(/\\.$/, '');",
]
for r in active:
domain = r["domain"]
if domain.startswith("*."):
base = domain[2:]
condition = f'dnsDomainIs(host, {json.dumps("." + base)})'
else:
condition = f'host === {json.dumps(domain)}'
target = proxy if r["route"] == "PROXY" else "DIRECT"
lines.append(f" if ({condition}) return {json.dumps(target)};")
target = proxy if s["default_route"] == "PROXY" else "DIRECT"
lines += [f" return {json.dumps(target)};", "}", ""]
return "\n".join(lines)
@app.middleware("http")
async def protect(request: Request, call_next):
# Localhost-only deployment, plus reject cross-site browser writes.
if request.method not in ("GET", "HEAD", "OPTIONS"):
origin = request.headers.get("origin")
if origin:
try:
parsed = urlsplit(origin)
valid = parsed.scheme == "http" and parsed.hostname in ("127.0.0.1", "localhost") and parsed.port == server_config()[1]
except ValueError:
valid = False
if not valid:
return JSONResponse({"detail": "Cross-origin write rejected"}, status_code=403)
elif request.headers.get("sec-fetch-site") == "cross-site":
return JSONResponse({"detail": "Cross-site write rejected"}, status_code=403)
return await call_next(request)
@app.get("/", response_class=HTMLResponse)
def home():
return (ROOT / "app" / "index.html").read_text(encoding="utf-8")
@app.get("/proxy.pac")
def get_pac():
return PlainTextResponse(pac(), media_type="application/x-ns-proxy-autoconfig", headers={"Cache-Control": "no-store, max-age=0"})
@app.get("/api/state")
def state():
return {"settings": settings(), "rules": rules()}
@app.put("/api/settings")
def update_settings(data: SettingsIn):
with db() as con:
for k, v in data.model_dump().items():
con.execute("INSERT OR REPLACE INTO settings (key,value) VALUES (?,?)", (k, str(v)))
return settings()
@app.post("/api/rules", status_code=201)
def create_rule(data: RuleIn):
try:
with db() as con:
cur = con.execute("INSERT INTO rules(domain,route,enabled) VALUES (?,?,?)", (data.domain, data.route, int(data.enabled)))
return {"id": cur.lastrowid}
except sqlite3.IntegrityError:
raise HTTPException(409, "Domain already exists")
@app.put("/api/rules/{rule_id}")
def update_rule(rule_id: int, data: RuleIn):
try:
with db() as con:
cur = con.execute("UPDATE rules SET domain=?, route=?, enabled=? WHERE id=?", (data.domain, data.route, int(data.enabled), rule_id))
if not cur.rowcount:
raise HTTPException(404, "Rule not found")
except sqlite3.IntegrityError:
raise HTTPException(409, "Domain already exists")
return {"ok": True}
@app.delete("/api/rules/{rule_id}")
def delete_rule(rule_id: int):
with db() as con:
cur = con.execute("DELETE FROM rules WHERE id=?", (rule_id,))
if not cur.rowcount:
raise HTTPException(404, "Rule not found")
return {"ok": True}
@app.get("/api/test")
def test(host: str):
try:
host = validate_domain(host)
if host.startswith("*."):
raise ValueError("Enter an actual hostname")
except ValueError as exc:
raise HTTPException(422, str(exc))
return route_for(host)
@app.get("/api/export")
def export():
return {"version": 1, "settings": settings(), "rules": [{k: r[k] for k in ("domain", "route", "enabled")} for r in rules()]}
class ImportIn(BaseModel):
version: int
settings: SettingsIn
rules: list[RuleIn] = Field(max_length=10000)
@app.post("/api/import")
def import_data(data: ImportIn):
if data.version != 1:
raise HTTPException(422, "Unsupported export version")
names = [r.domain for r in data.rules]
if len(names) != len(set(names)):
raise HTTPException(422, "Duplicate domains")
with db() as con:
con.execute("DELETE FROM rules")
for r in data.rules:
con.execute("INSERT INTO rules(domain,route,enabled) VALUES (?,?,?)", (r.domain, r.route, int(r.enabled)))
for k, v in data.settings.model_dump().items():
con.execute("INSERT OR REPLACE INTO settings(key,value) VALUES (?,?)", (k, str(v)))
return {"ok": True}
def main():
import asyncio
import uvicorn
from app.proxy import start_proxy
host, port = server_config()
if host not in ("127.0.0.1", "localhost", "::1") and os.environ.get("PAC_ALLOW_NON_LOOPBACK") != "1":
raise ValueError("Only loopback binding is supported for security reasons")
proxy_host, proxy_port = proxy_server_config()
async def serve():
proxy = await start_proxy(proxy_host, proxy_port, route_for, settings)
web = uvicorn.Server(uvicorn.Config(app, host=host, port=port))
print(f"Routing proxy listening on http://{proxy_host}:{proxy_port}")
async with proxy:
await web.serve()
asyncio.run(serve())