feat: 账号可配置 HTTP/HTTPS/SOCKS 代理

This commit is contained in:
2026-11-15 01:21:17 +08:00
parent 1141df17f7
commit e9a1e9b315
15 changed files with 848 additions and 55 deletions
+51 -1
View File
@@ -9,7 +9,17 @@ from sqlalchemy.orm import Session
from admin.identity import identity
from admin.session import admin_session_active, clear_admin_session
from admin.settings import SettingsError, load_config, login_config_view, save_settings, settings_view
from admin.users import check_all, check_employee, delete_user, list_users, read_credentials, set_paused
from admin.users import (
check_all,
check_employee,
clear_proxy,
delete_user,
list_users,
read_credentials,
read_proxy,
set_paused,
set_proxy,
)
from euniv.courses import course_page, request_course_sync_now
from euniv.db import get_db
@@ -34,6 +44,19 @@ class PauseBody(BaseModel):
paused: bool
class AdminProxyBody(BaseModel):
employee_ids: list[str]
scheme: str
host: str
port: int
username: str = ""
password: str | None = None
class AdminProxyClearBody(BaseModel):
employee_ids: list[str]
def require_admin(request: Request) -> str:
if not admin_session_active(request.cookies):
raise HTTPException(status_code=401, detail="未登录")
@@ -114,6 +137,33 @@ def post_refresh(
return set_paused(db, employee_id, body.paused)
@admin_router.put("/users/proxy")
def put_users_proxy(body: AdminProxyBody, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
return set_proxy(
db,
body.employee_ids,
body.scheme,
body.host,
body.port,
body.username,
body.password,
)
@admin_router.post("/users/proxy/clear")
def post_users_proxy_clear(
body: AdminProxyClearBody,
db: Session = Depends(get_db),
_: str = Depends(require_admin),
) -> dict:
return clear_proxy(db, body.employee_ids)
@admin_router.get("/users/{employee_id}/proxy")
def get_user_proxy(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
return read_proxy(db, employee_id)
@admin_router.get("/users/{employee_id}/credentials")
def get_credentials(employee_id: str, db: Session = Depends(get_db), _: str = Depends(require_admin)) -> dict:
return read_credentials(db, employee_id)
+66 -3
View File
@@ -11,6 +11,7 @@ from sqlalchemy.orm import Session
from euniv.crypto import decrypt_secret
from euniv.models import Account
from euniv.proxy import ProxyError, apply, clear, summary_of, url_of, view_of
_TOKEN_KEYS = (
"ucs_token",
@@ -22,10 +23,17 @@ _TOKEN_KEYS = (
)
def build_client(login_name: str, password: str):
def build_client(login_name: str, password: str, proxy: str | None = None):
from euniv.client import EunivClient
return EunivClient(login_name, password)
return EunivClient(login_name, password, proxy=proxy)
def _open_client(login_name: str, password: str, proxy: str | None = None):
try:
return build_client(login_name, password, proxy)
except TypeError:
return build_client(login_name, password)
def record_outcome(account: Account, valid: bool | None) -> None:
@@ -57,6 +65,8 @@ def list_users(db: Session) -> list[dict]:
"last_refresh_at": _iso_time(account.last_refresh_at),
"credential_valid": _optional_bool(account.credential_valid),
"month_hours": account.month_hours or "",
"has_proxy": bool(account.proxy_scheme and account.proxy_host and account.proxy_port),
"proxy": summary_of(account),
}
for account in accounts
]
@@ -79,7 +89,7 @@ def check_employee(db: Session, employee_id: str) -> dict:
result = "检查失败"
valid: bool | None = None
try:
client = build_client(employee_id, decrypt_secret(account.password_cipher))
client = _open_client(employee_id, decrypt_secret(account.password_cipher), url_of(account))
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
alive = bool(client.credential_alive())
result = "有效" if alive else "已失效"
@@ -154,6 +164,59 @@ def read_credentials(db: Session, employee_id: str) -> dict:
return payload
def _accounts_by_ids(db: Session, employee_ids: list[str]) -> list[Account]:
ids = []
seen: set[str] = set()
for raw in employee_ids:
employee_id = str(raw or "").strip()
if not employee_id or employee_id in seen:
continue
seen.add(employee_id)
ids.append(employee_id)
if not ids:
raise HTTPException(status_code=400, detail="请选择账号")
if len(ids) > 200:
raise HTTPException(status_code=400, detail="一次最多选择 200 个账号")
accounts = db.scalars(select(Account).where(Account.employee_id.in_(ids))).all()
found = {account.employee_id for account in accounts}
missing = [employee_id for employee_id in ids if employee_id not in found]
if missing:
raise HTTPException(status_code=404, detail="用户不存在")
return accounts
def read_proxy(db: Session, employee_id: str) -> dict:
return view_of(_require(db, employee_id))
def set_proxy(
db: Session,
employee_ids: list[str],
scheme: str,
host: str,
port: int,
username: str = "",
password: str | None = None,
) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
try:
for account in accounts:
apply(account, scheme, host, port, username, password)
except ProxyError as exc:
db.rollback()
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return {"ok": True, "count": len(accounts)}
def clear_proxy(db: Session, employee_ids: list[str]) -> dict:
accounts = _accounts_by_ids(db, employee_ids)
for account in accounts:
clear(account)
db.commit()
return {"ok": True, "count": len(accounts)}
def delete_user(db: Session, employee_id: str) -> dict:
account = _require(db, employee_id)
db.delete(account)
+27
View File
@@ -0,0 +1,27 @@
"""账号 HTTP/SOCKS 代理。"""
from alembic import op
import sqlalchemy as sa
revision = "0008_proxy"
down_revision = "0007_autostudy"
branch_labels = None
depends_on = None
def upgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.add_column(sa.Column("proxy_scheme", sa.String(length=16), nullable=False, server_default=""))
batch.add_column(sa.Column("proxy_host", sa.String(length=255), nullable=False, server_default=""))
batch.add_column(sa.Column("proxy_port", sa.Integer(), nullable=True))
batch.add_column(sa.Column("proxy_username", sa.String(length=128), nullable=False, server_default=""))
batch.add_column(sa.Column("proxy_password_cipher", sa.Text(), nullable=False, server_default=""))
def downgrade() -> None:
with op.batch_alter_table("accounts") as batch:
batch.drop_column("proxy_password_cipher")
batch.drop_column("proxy_username")
batch.drop_column("proxy_port")
batch.drop_column("proxy_host")
batch.drop_column("proxy_scheme")
+45
View File
@@ -38,6 +38,14 @@ class MonthlyTargetBody(_BaseModel):
monthly_target: int
class ProxyBody(_BaseModel):
scheme: str
host: str
port: int
username: str = ""
password: str | None = None
@asynccontextmanager
async def lifespan(_app: FastAPI):
init_db()
@@ -217,6 +225,43 @@ def put_monthly_target(body: MonthlyTargetBody, request: Request, db: Session =
return {"monthly_target": account.monthly_target}
@app.get("/api/settings/proxy")
def get_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
return view_of(account)
@app.put("/api/settings/proxy")
def put_proxy(body: ProxyBody, request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import ProxyError, apply, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
try:
apply(account, body.scheme, body.host, body.port, body.username, body.password)
except ProxyError as exc:
raise HTTPException(status_code=400, detail=str(exc)) from exc
db.commit()
return view_of(account)
@app.delete("/api/settings/proxy")
def delete_proxy(request: Request, db: Session = Depends(get_db)) -> dict:
from euniv.proxy import clear, view_of
account = db.get(Account, _signed_in(request, db))
if account is None:
raise HTTPException(status_code=401, detail="未登录")
clear(account)
db.commit()
return view_of(account)
@app.get("/api/autostudy/status")
def autostudy_state(request: Request, db: Session = Depends(get_db)) -> dict:
_signed_in(request, db)
+20 -30
View File
@@ -600,32 +600,33 @@ class AutoStudyWorker:
}
with SessionLocal() as db:
users = db.execute(
select(Account.employee_id, Account.monthly_target, Account.month_hours,
Account.credential_cipher, Account.password_cipher)
from euniv.proxy import url_of
users = db.scalars(
select(Account)
.where(Account.credential_cipher != "")
.where(Account.credential_valid == True)
.order_by(Account.employee_id)
).all()
courses = db.scalars(select(Course).order_by(Course.title)).all()
course_list = [(c.path, c.title, c.kind) for c in courses]
eligible = []
for row in users:
target = row.monthly_target or 600
current = _parse_minutes(row.month_hours)
if target > 0 and current < target:
try:
password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher))
proxy = url_of(row)
except Exception:
continue
eligible.append((row.employee_id, target, password, credential, proxy))
if not users or not course_list:
if not course_list:
_set_status(running=False, message="没有可用的用户或课程")
return
eligible = []
for row in users:
target = row.monthly_target or 600
current = _parse_minutes(row.month_hours)
if target > 0 and current < target:
try:
password = decrypt_secret(row.password_cipher)
credential = json.loads(decrypt_secret(row.credential_cipher))
except Exception:
continue
eligible.append((row.employee_id, target, password, credential))
if not eligible:
_set_status(running=False, message="所有用户已达标或无有效凭据")
return
@@ -634,8 +635,8 @@ class AutoStudyWorker:
sem = asyncio.Semaphore(_MAX_CONCURRENT_USERS)
tasks = [
self._study_user(emp_id, target, pw, cred, course_list, intervals, auto_mode, sem)
for emp_id, target, pw, cred in eligible
self._study_user(emp_id, target, pw, cred, proxy, course_list, intervals, auto_mode, sem)
for emp_id, target, pw, cred, proxy in eligible
]
results = await asyncio.gather(*tasks, return_exceptions=True)
for emp_id_tuple, result in zip(eligible, results):
@@ -646,24 +647,13 @@ class AutoStudyWorker:
_set_status(running=False, message="本轮完成")
async def _study_user(self, employee_id: str, target: int,
password: str, credential: dict,
password: str, credential: dict, proxy: str | None,
course_list: list, intervals: dict,
auto_mode: bool, sem: asyncio.Semaphore) -> None:
assert self._async_stop is not None
async with sem:
_set_user_status(employee_id, state="准备", course="")
# 后续从账号读取 HTTP/SOCKS 代理 URL 和同时学习门数
from euniv.proxy import parse_proxy
proxy = None
max_courses = _MAX_COURSE_PER_USER
try:
proxy = parse_proxy(proxy)
except ValueError:
_set_user_status(employee_id, state="代理无效")
return
loop = asyncio.get_event_loop()
token, user_id, org_id, cookies = await loop.run_in_executor(
None, _prepare_session, employee_id, password, credential, proxy)
+4 -1
View File
@@ -173,7 +173,10 @@ def _fetch_and_store(trigger: str) -> bool:
return False
password = decrypt_secret(account.password_cipher)
credential = json.loads(decrypt_secret(account.credential_cipher))
client = EunivClient(employee_id, password)
from euniv.proxy import url_of
proxy = url_of(account)
client = EunivClient(employee_id, password, proxy=proxy)
try:
client.restore(credential)
if not client.credential_alive():
+5
View File
@@ -47,3 +47,8 @@ class Account(Base):
credential_valid: Mapped[bool | None] = mapped_column(Boolean, nullable=True)
month_hours: Mapped[str] = mapped_column(String(32), nullable=False, default="", server_default="")
monthly_target: Mapped[int] = mapped_column(nullable=False, default=600, server_default="600")
proxy_scheme: Mapped[str] = mapped_column(String(16), nullable=False, default="", server_default="")
proxy_host: Mapped[str] = mapped_column(String(255), nullable=False, default="", server_default="")
proxy_port: Mapped[int | None] = mapped_column(nullable=True)
proxy_username: Mapped[str] = mapped_column(String(128), nullable=False, default="", server_default="")
proxy_password_cipher: Mapped[str] = mapped_column(Text, nullable=False, default="", server_default="")
+108 -6
View File
@@ -1,10 +1,14 @@
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。不处理 VPN 或隧道。"""
"""账号级 HTTP/HTTPS/SOCKS4/SOCKS5 代理。账号密码可选。"""
from __future__ import annotations
from urllib.parse import urlparse
from urllib.parse import quote, urlparse
_SCHEMES = {"http", "https", "socks4", "socks5", "socks5h"}
SCHEMES = ("http", "https", "socks4", "socks5", "socks5h")
class ProxyError(ValueError):
"""代理配置不符合要求。"""
def parse_proxy(value: str | None) -> str | None:
@@ -16,8 +20,106 @@ def parse_proxy(value: str | None) -> str | None:
text = "http://" + text
parsed = urlparse(text)
scheme = (parsed.scheme or "").lower()
if scheme not in _SCHEMES:
raise ValueError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if scheme not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
if not parsed.hostname:
raise ValueError("代理地址不完整")
raise ProxyError("代理地址不完整")
return text
def build_proxy_url(
scheme: str,
host: str,
port: int,
username: str = "",
password: str = "",
) -> str:
scheme, host, port, username = validate_parts(scheme, host, port, username)
if username or password:
user = quote(username, safe="")
secret = quote(password, safe="")
auth = f"{user}:{secret}@"
else:
auth = ""
return f"{scheme}://{auth}{host}:{port}"
def validate_parts(scheme: str, host: str, port: object, username: str = "") -> tuple[str, str, int, str]:
kind = (scheme or "").strip().lower()
if kind not in SCHEMES:
raise ProxyError("代理只支持 HTTP、HTTPS、SOCKS4、SOCKS5")
address = (host or "").strip()
if not address or "://" in address or any(ch.isspace() for ch in address):
raise ProxyError("请填写代理地址")
if len(address) > 255:
raise ProxyError("代理地址过长")
if not isinstance(port, int) or isinstance(port, bool) or not 1 <= port <= 65535:
raise ProxyError("代理端口须为 1 到 65535 的整数")
user = (username or "").strip()
if len(user) > 128:
raise ProxyError("代理账号过长")
return kind, address, port, user
def enabled(account) -> bool:
return bool(account.proxy_scheme and account.proxy_host and account.proxy_port)
def view_of(account) -> dict:
return {
"enabled": enabled(account),
"scheme": account.proxy_scheme or "http",
"host": account.proxy_host or "",
"port": int(account.proxy_port) if account.proxy_port else None,
"username": account.proxy_username or "",
"has_password": bool(account.proxy_password_cipher),
}
def summary_of(account) -> str:
if not enabled(account):
return ""
return f"{account.proxy_scheme.upper()} {account.proxy_host}:{account.proxy_port}"
def url_of(account) -> str | None:
if not enabled(account):
return None
password = ""
if account.proxy_password_cipher:
from euniv.crypto import decrypt_secret
password = decrypt_secret(account.proxy_password_cipher)
return build_proxy_url(
account.proxy_scheme,
account.proxy_host,
int(account.proxy_port),
account.proxy_username or "",
password,
)
def apply(account, scheme: str, host: str, port: object, username: str = "", password: str | None = None) -> None:
kind, address, number, user = validate_parts(scheme, host, port, username)
if password is not None and len(str(password)) > 256:
raise ProxyError("代理密码过长")
account.proxy_scheme = kind
account.proxy_host = address
account.proxy_port = number
account.proxy_username = user
if password is None:
return
if password == "":
account.proxy_password_cipher = ""
return
from euniv.crypto import encrypt_secret
account.proxy_password_cipher = encrypt_secret(str(password))
def clear(account) -> None:
account.proxy_scheme = ""
account.proxy_host = ""
account.proxy_port = None
account.proxy_username = ""
account.proxy_password_cipher = ""
+14 -4
View File
@@ -68,6 +68,16 @@ def _persist(db: Session, employee_id: str, password: str, client: EunivClient,
db.commit()
def _client(factory, employee_id: str, password: str, account: Account | None = None):
from euniv.proxy import url_of
proxy = url_of(account) if account is not None else None
try:
return factory(employee_id, password, proxy)
except TypeError:
return factory(employee_id, password)
def login_and_store(
db: Session,
employee_id: str,
@@ -83,7 +93,7 @@ def login_and_store(
_request_course_sync(employee_id)
return {"employee_id": employee_id}
_drop_employee(employee_id)
client = client_factory(employee_id, password)
client = _client(client_factory, employee_id, password, account)
held = False
try:
try:
@@ -102,7 +112,7 @@ def login_and_store(
def _credential_still_valid(account: Account, client_factory) -> bool:
client = client_factory(account.employee_id, decrypt_secret(account.password_cipher))
client = _client(client_factory, account.employee_id, decrypt_secret(account.password_cipher), account)
try:
client.restore(json.loads(decrypt_secret(account.credential_cipher)))
return bool(client.credential_alive())
@@ -172,7 +182,7 @@ def _live(db: Session, employee_id: str, client_factory, read):
raise RuntimeError("请先登录")
credential = json.loads(decrypt_secret(account.credential_cipher)) if account.credential_cipher else {}
attempts = _auto_attempts(db)
client = client_factory(employee_id, decrypt_secret(account.password_cipher))
client = _client(client_factory, employee_id, decrypt_secret(account.password_cipher), account)
try:
if credential.get("yxt_token"):
client.restore(credential)
@@ -237,7 +247,7 @@ def _refresh_one(employee_id: str, attempts: int, client_factory) -> None:
try:
password = decrypt_secret(account.password_cipher)
previous = json.loads(decrypt_secret(account.credential_cipher))
client = client_factory(employee_id, password)
client = _client(client_factory, employee_id, password, account)
client.restore(previous)
if client.credential_alive():
updated = client.export_credential()
+59 -1
View File
@@ -291,9 +291,10 @@ def test_saving_new_interval_restarts_wait_without_refresh(monkeypatch) -> None:
class _Alive:
def __init__(self, login_name: str, password: str) -> None:
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
self.login_name = login_name
self.password = password
self.proxy = proxy
self.login_called = False
def close(self) -> None:
@@ -444,6 +445,8 @@ def test_check_skips_empty_credential_and_updates_saved_one() -> None:
"last_refresh_at",
"credential_valid",
"month_hours",
"has_proxy",
"proxy",
}
assert saved["has_credential"] is True
assert saved["refresh_paused"] is False
@@ -632,3 +635,58 @@ def test_settings_do_not_expose_process_switches() -> None:
}
assert identity.password_cipher()
assert decrypt_secret(identity.password_cipher()) == INITIAL_PASSWORD
def test_admin_can_set_and_clear_proxy_for_selected_users() -> None:
_add_account("p1-user")
_add_account("p2-user")
api = _app()
client = TestClient(api.app)
assert client.post("/api/login", json={"employee_id": "admin", "password": INITIAL_PASSWORD}).status_code == 200
saved = client.put(
"/api/admin/users/proxy",
json={
"employee_ids": ["p1-user", "p2-user"],
"scheme": "socks5",
"host": "127.0.0.1",
"port": 1080,
"username": "u",
"password": "secret",
},
)
assert saved.status_code == 200
assert saved.json()["count"] == 2
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "p1-user")
assert one["has_proxy"] is True
assert one["proxy"] == "SOCKS5 127.0.0.1:1080"
detail = client.get("/api/admin/users/p1-user/proxy")
assert detail.status_code == 200
assert detail.json()["username"] == "u"
assert detail.json()["has_password"] is True
assert "password" not in detail.json()
cleared = client.post("/api/admin/users/proxy/clear", json={"employee_ids": ["p1-user"]})
assert cleared.status_code == 200
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "p1-user")
two = next(item for item in listed if item["employee_id"] == "p2-user")
assert one["has_proxy"] is False
assert two["has_proxy"] is True
no_auth = client.put(
"/api/admin/users/proxy",
json={
"employee_ids": ["p1-user"],
"scheme": "http",
"host": "10.0.0.1",
"port": 8080,
"username": "",
"password": "",
},
)
assert no_auth.status_code == 200
listed = client.get("/api/admin/users").json()
one = next(item for item in listed if item["employee_id"] == "p1-user")
assert one["proxy"] == "HTTP 10.0.0.1:8080"
detail = client.get("/api/admin/users/p1-user/proxy")
assert detail.json()["has_password"] is False
assert detail.json()["username"] == ""
+55 -1
View File
@@ -10,9 +10,10 @@ from euniv.models import Account
class FakeClient:
def __init__(self, login_name: str, password: str) -> None:
def __init__(self, login_name: str, password: str, proxy: str | None = None) -> None:
self.login_name = login_name
self.password = password
self.proxy = proxy
self._token = "yxt-1"
self._profile = {
"token": "ucs-1",
@@ -111,6 +112,11 @@ def test_login_stores_password_and_credential_only() -> None:
"credential_valid",
"month_hours",
"monthly_target",
"proxy_scheme",
"proxy_host",
"proxy_port",
"proxy_username",
"proxy_password_cipher",
}
home = client.get("/api/home")
@@ -434,6 +440,54 @@ def test_period_page_is_not_fetched_twice() -> None:
assert len(calls) == 1
def test_user_can_set_proxy_with_or_without_password() -> None:
import euniv.api as api_module
import euniv.service as service_module
api_module.login_and_store = lambda db, employee_id, password, manual=False, auto_attempts=3: service_module.login_and_store(
db, employee_id, password, FakeClient, manual=manual, auto_attempts=auto_attempts
)
client = TestClient(api_module.app)
assert client.post("/api/login", json={"employee_id": "6650000146", "password": "secret-pass"}).status_code == 200
empty = client.get("/api/settings/proxy")
assert empty.status_code == 200
assert empty.json()["enabled"] is False
assert "password" not in empty.json()
saved = client.put(
"/api/settings/proxy",
json={"scheme": "http", "host": "10.0.0.1", "port": 8080, "username": "", "password": ""},
)
assert saved.status_code == 200
assert saved.json() == {
"enabled": True,
"scheme": "http",
"host": "10.0.0.1",
"port": 8080,
"username": "",
"has_password": False,
}
with_auth = client.put(
"/api/settings/proxy",
json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": "p@ss"},
)
assert with_auth.status_code == 200
assert with_auth.json()["has_password"] is True
assert "password" not in with_auth.json()
kept = client.put(
"/api/settings/proxy",
json={"scheme": "socks5", "host": "127.0.0.1", "port": 1080, "username": "u", "password": None},
)
assert kept.status_code == 200
assert kept.json()["has_password"] is True
with SessionLocal() as db:
account = db.get(Account, "6650000146")
assert account is not None
assert decrypt_secret(account.proxy_password_cipher) == "p@ss"
cleared = client.delete("/api/settings/proxy")
assert cleared.status_code == 200
assert cleared.json()["enabled"] is False
def test_exam_list_rejects_unrecognized_page() -> None:
from euniv.client import EunivClient
+10 -1
View File
@@ -3,7 +3,7 @@ import asyncio
import pytest
from euniv.autostudy import HoursWatcher, _parse_minutes, _study_video, wait_stop
from euniv.proxy import parse_proxy
from euniv.proxy import ProxyError, build_proxy_url, parse_proxy
def test_parse_proxy_accepts_http_and_socks() -> None:
@@ -16,6 +16,15 @@ def test_parse_proxy_accepts_http_and_socks() -> None:
assert parse_proxy("socks5://user:pass@127.0.0.1:1080") == "socks5://user:pass@127.0.0.1:1080"
def test_build_proxy_url_auth_is_optional_and_quoted() -> None:
assert build_proxy_url("http", "10.0.0.1", 8080) == "http://10.0.0.1:8080"
assert build_proxy_url("socks5", "127.0.0.1", 1080, "u", "p@ss") == "socks5://u:p%40ss@127.0.0.1:1080"
assert build_proxy_url("http", "10.0.0.1", 8080, "u", "") == "http://u:@10.0.0.1:8080"
assert build_proxy_url("socks4", "127.0.0.1", 1080, "", "s3cret") == "socks4://:s3cret@127.0.0.1:1080"
with pytest.raises(ProxyError):
build_proxy_url("ss", "127.0.0.1", 1080)
def test_parse_proxy_rejects_other_schemes() -> None:
with pytest.raises(ValueError):
parse_proxy("ss://secret")