driver / mes_proxy.py
bevisssssss's picture
fix: recover from expired admin token instead of showing a load error
79dca2e
Raw History Blame Contribute Delete
16.3 kB
"""MES 查询代理 + 监控看板。
在你本地跑,把 MES 通过 Cloudflare Tunnel 安全暴露给 HF Spaces。
用法:
1. 确保 VPN 已连接
2. python mes_proxy.py
3. cloudflared tunnel --url http://localhost:8099
4. 打开 http://localhost:8099/dashboard 看监控
安全:
- Bearer Token 鉴权(MES_PROXY_TOKEN,默认随机生成)
- 每分钟 60 次限流
- IP 黑名单(手动封禁)
- 看板本地访问免 token,远程访问需 token
"""
import os
import time
import uuid
import logging
from collections import deque
from datetime import datetime, timezone, timedelta
import uvicorn
import requests
from fastapi import FastAPI, HTTPException, Request, Response
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import HTMLResponse
from pydantic import BaseModel
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
)
logger = logging.getLogger("mes_proxy")
# ─── Config ───
MES_API_URL = os.getenv(
"MES_API_URL",
"https://vpn.emdoor.com:8099/EIS/MES/helper/dllMain",
)
MES_ACCESS_KEY = os.getenv("MES_ACCESS_KEY", "")
MES_ACCESS_SECRET = os.getenv("MES_ACCESS_SECRET", "")
PROXY_TOKEN = os.getenv("MES_PROXY_TOKEN") or str(uuid.uuid4())
PROXY_PORT = int(os.getenv("MES_PROXY_PORT", "8099"))
RATE_LIMIT = int(os.getenv("MES_PROXY_RATE_LIMIT", "60")) # per minute
CST = timezone(timedelta(hours=8))
# ─── In-memory request log ───
MAX_LOG = 2000
request_log: deque = deque(maxlen=MAX_LOG)
blocklist: set[str] = set()
_total_requests = 0
_total_success = 0
_total_failed = 0
_last_reset = time.time()
# ─── App ───
app = FastAPI(title="MES 查询代理")
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
class QueryReq(BaseModel):
sn: str
def _now_str() -> str:
return datetime.now(CST).strftime("%H:%M:%S")
def _is_local(request: Request) -> bool:
host = request.client.host if request.client else ""
return host in ("127.0.0.1", "::1", "localhost")
def _check_auth(request: Request):
"""Token 校验 — 本地访问免检。"""
if _is_local(request):
return True
auth = request.headers.get("Authorization", "")
if auth == f"Bearer {PROXY_TOKEN}":
return True
return False
# ─── Rate limiter ───
class RateLimiter:
def __init__(self, max_per_minute: int):
self.max = max_per_minute
self.window = 60.0
self.tokens: dict[str, list] = {}
def check(self, key: str) -> bool:
now = time.monotonic()
window_start = now - self.window
history = self.tokens.setdefault(key, [])
self.tokens[key] = [t for t in history if t > window_start]
if len(self.tokens[key]) >= self.max:
return False
self.tokens[key].append(now)
return True
limiter = RateLimiter(RATE_LIMIT)
def _log_entry(ip: str, sn: str, status: str, detail: str = ""):
request_log.appendleft({
"time": _now_str(),
"ip": ip,
"sn": sn,
"status": status,
"detail": detail,
})
# ─── Query endpoint ───
@app.post("/query")
def query(req: QueryReq, request: Request):
global _total_requests, _total_success, _total_failed
client_ip = request.client.host if request.client else "unknown"
_total_requests += 1
# Auth
if not _check_auth(request):
_total_failed += 1
_log_entry(client_ip, req.sn, "❌ 鉴权失败")
logger.warning("鉴权失败: %s", client_ip)
raise HTTPException(403, "Forbidden")
# Blocklist
if client_ip in blocklist:
_total_failed += 1
_log_entry(client_ip, req.sn, "🚫 已封禁")
logger.warning("封禁 IP 试图访问: %s", client_ip)
raise HTTPException(403, "Blocked")
# Rate limit
if not limiter.check(client_ip):
_total_failed += 1
_log_entry(client_ip, req.sn, "⚠️ 限流")
logger.warning("限流: %s", client_ip)
raise HTTPException(429, "Too Many Requests")
# Call MES
logger.info("查询 SN: %s (from %s)", req.sn, client_ip)
body = f'data={{"type":"GetMakeRelation","detail":{{"iSN":"{req.sn}"}}}}'
headers = {
"Content-Type": "application/x-www-form-urlencoded",
"Charset": "UTF-8",
"AccessKey": MES_ACCESS_KEY,
"AccessSecret": MES_ACCESS_SECRET,
"RequestId": str(uuid.uuid4()),
}
last_error = None
for attempt in range(3):
try:
resp = requests.post(
MES_API_URL,
headers=headers,
data=body,
timeout=30,
)
resp.raise_for_status()
_total_success += 1
_log_entry(client_ip, req.sn, "✅ 成功")
return resp.json()
except (
requests.exceptions.SSLError,
requests.exceptions.ConnectionError,
requests.exceptions.Timeout,
) as e:
last_error = e
logger.warning("MES 请求失败 (attempt %d/3): %s", attempt + 1, e)
if attempt < 2:
time.sleep(2**attempt)
continue
_total_failed += 1
_log_entry(client_ip, req.sn, "❌ MES 错误", str(last_error)[:80])
raise HTTPException(502, f"MES query failed: {last_error}")
# ─── Health ───
@app.get("/health")
def health():
return {
"status": "ok",
"uptime_sec": int(time.time() - _last_reset),
"total_requests": _total_requests,
}
# ─── API: 日志 ───
@app.get("/api/logs")
def api_logs(request: Request, limit: int = 100):
if not _check_auth(request):
raise HTTPException(403, "Forbidden")
logs = list(request_log)[:min(limit, MAX_LOG)]
return {
"total": _total_requests,
"success": _total_success,
"failed": _total_failed,
"blocked_ips": sorted(blocklist),
"logs": logs,
}
# ─── API: 封禁/解封 ───
@app.post("/api/block/{ip}")
def api_block(ip: str, request: Request):
if not _check_auth(request):
raise HTTPException(403, "Forbidden")
blocklist.add(ip)
logger.warning("封禁 IP: %s", ip)
return {"blocked": sorted(blocklist)}
@app.delete("/api/block/{ip}")
def api_unblock(ip: str, request: Request):
if not _check_auth(request):
raise HTTPException(403, "Forbidden")
blocklist.discard(ip)
return {"blocked": sorted(blocklist)}
# ─── Dashboard HTML ───
DASHBOARD_HTML = r"""<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>MES 代理监控</title>
<style>
*{margin:0;padding:0;box-sizing:border-box}
body{font-family:-apple-system,'Segoe UI',sans-serif;background:#0f172a;color:#e2e8f0;padding:20px;min-height:100vh}
h1{font-size:22px;font-weight:600;margin-bottom:4px;display:flex;align-items:center;gap:10px}
h1 small{font-size:13px;font-weight:400;color:#94a3b8}
.subtitle{color:#94a3b8;font-size:13px;margin-bottom:20px}
.stats{display:grid;grid-template-columns:repeat(auto-fit,minmax(140px,1fr));gap:12px;margin-bottom:24px}
.stat-card{background:#1e293b;border-radius:10px;padding:16px}
.stat-card .num{font-size:28px;font-weight:700}
.stat-card .label{font-size:12px;color:#94a3b8;margin-top:4px}
.stat-card.green .num{color:#22c55e}
.stat-card.red .num{color:#ef4444}
.stat-card.blue .num{color:#3b82f6}
.stat-card.yellow .num{color:#eab308}
.toolbar{display:flex;gap:10px;margin-bottom:12px;flex-wrap:wrap;align-items:center}
.toolbar select,.toolbar input{padding:6px 10px;border-radius:6px;border:1px solid #334155;background:#1e293b;color:#e2e8f0;font-size:13px}
.toolbar button{padding:6px 14px;border-radius:6px;border:none;cursor:pointer;font-size:13px;background:#3b82f6;color:#fff}
.toolbar button:hover{background:#2563eb}
.toolbar .badge{font-size:12px;padding:3px 10px;border-radius:99px;background:#334155;color:#94a3b8}
table{width:100%;border-collapse:collapse;font-size:13px;background:#1e293b;border-radius:10px;overflow:hidden}
th{text-align:left;padding:10px 12px;background:#0f172a;color:#94a3b8;font-weight:500;font-size:11px;text-transform:uppercase;letter-spacing:.5px;border-bottom:1px solid #334155}
td{padding:8px 12px;border-bottom:1px solid #1a2332;font-family:'SF Mono','Cascadia Code','Consolas',monospace;font-size:12px;white-space:nowrap}
tr:hover td{background:#1e293b}
.status-ok{color:#22c55e}
.status-fail{color:#ef4444}
.status-block{color:#eab308}
.status-rate{color:#f97316}
.ip-col{color:#818cf8}
.sn-col{color:#e2e8f0}
.time-col{color:#64748b}
.detail-col{color:#94a3b8;max-width:200px;overflow:hidden;text-overflow:ellipsis}
.block-btn{padding:2px 8px;border-radius:4px;border:1px solid #ef4444;background:transparent;color:#ef4444;cursor:pointer;font-size:11px}
.block-btn:hover{background:#ef4444;color:#fff}
.unblock-btn{padding:2px 8px;border-radius:4px;border:1px solid #22c55e;background:transparent;color:#22c55e;cursor:pointer;font-size:11px}
.unblock-btn:hover{background:#22c55e;color:#fff}
.blocklist-section{margin-top:20px}
.blocklist-tags{display:flex;flex-wrap:wrap;gap:6px}
.block-tag{display:inline-flex;align-items:center;gap:6px;padding:4px 10px;border-radius:99px;background:#1e293b;border:1px solid #ef4444;font-size:12px;font-family:monospace}
.block-tag button{background:none;border:none;color:#ef4444;cursor:pointer;font-size:14px;padding:0;line-height:1}
.empty{text-align:center;padding:30px;color:#64748b;font-size:14px}
</style>
</head>
<body>
<h1>🔐 MES 查询代理 <small id="status-badge" style="display:inline-flex;align-items:center;gap:4px"><span style="display:inline-block;width:8px;height:8px;border-radius:50%;background:#22c55e"></span>运行中</small></h1>
<div class="subtitle" id="uptime-info">启动中...</div>
<div class="stats" id="stats"></div>
<div class="toolbar">
<label style="font-size:13px;color:#94a3b8">筛选:</label>
<select id="filter-status" onchange="refresh()">
<option value="all">全部</option>
<option value="success">✅ 成功</option>
<option value="fail">❌ 失败</option>
<option value="block">🚫 封禁</option>
</select>
<input type="text" id="filter-ip" placeholder="搜索 IP..." style="width:150px" oninput="refresh()">
<input type="text" id="filter-sn" placeholder="搜索 SN..." style="width:200px" oninput="refresh()">
<span class="badge" id="log-count">0 条</span>
<button onclick="toggleAutoRefresh()" id="refresh-btn">⏸ 暂停</button>
</div>
<table>
<thead><tr><th>时间</th><th>IP</th><th>SN</th><th>状态</th><th>详情</th><th>操作</th></tr></thead>
<tbody id="log-table"></tbody>
</table>
<div class="blocklist-section">
<h3 style="font-size:14px;font-weight:500;margin-bottom:8px">🚫 黑名单(<span id="block-count">0</span>)</h3>
<div class="blocklist-tags" id="blocklist"></div>
</div>
<script>
let autoRefresh = true;
let refreshTimer = null;
async function fetchJSON(url) { const r=await fetch(url); return r.json(); }
function escape(s) { if (!s) return ''; return String(s).replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'); }
async function refresh() {
const data = await fetchJSON('/api/logs');
document.getElementById('uptime-info').textContent = `共 ${data.total} 次请求 · ${data.success} 成功 · ${data.failed} 失败 · ${data.blocked_ips.length} 个封禁 IP`;
// Stats
document.getElementById('stats').innerHTML = `
<div class="stat-card blue"><div class="num">${data.total}</div><div class="label">总请求</div></div>
<div class="stat-card green"><div class="num">${data.success}</div><div class="label">成功</div></div>
<div class="stat-card red"><div class="num">${data.failed}</div><div class="label">失败</div></div>
<div class="stat-card yellow"><div class="num">${data.blocked_ips.length}</div><div class="label">封禁 IP</div></div>
`;
// Logs
const filterStatus = document.getElementById('filter-status').value;
const filterIp = document.getElementById('filter-ip').value.toLowerCase();
const filterSn = document.getElementById('filter-sn').value.toLowerCase();
const rows = data.logs.filter(l => {
if (filterStatus === 'success' && l.status !== '✅ 成功') return false;
if (filterStatus === 'fail' && !l.status.includes('❌')) return false;
if (filterStatus === 'block' && !l.status.includes('🚫')) return false;
if (filterIp && !l.ip.includes(filterIp)) return false;
if (filterSn && !l.sn.toLowerCase().includes(filterSn)) return false;
return true;
});
document.getElementById('log-count').textContent = rows.length + ' 条';
const tbody = document.getElementById('log-table');
if (rows.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="empty">暂无请求记录</td></tr>';
} else {
tbody.innerHTML = rows.map(l => {
const cls = l.status.includes('✅') ? 'status-ok' : l.status.includes('🚫') ? 'status-block' : l.status.includes('⚠') ? 'status-rate' : 'status-fail';
const blocked = data.blocked_ips.includes(l.ip);
const btn = blocked
? `<button class="unblock-btn" onclick="unblock('${l.ip}')">解封</button>`
: `<button class="block-btn" onclick="block('${l.ip}')">封禁</button>`;
return `<tr><td class="time-col">${escape(l.time)}</td><td class="ip-col">${escape(l.ip)}</td><td class="sn-col">${escape(l.sn)}</td><td class="${cls}">${escape(l.status)}</td><td class="detail-col">${escape(l.detail)}</td><td>${btn}</td></tr>`;
}).join('');
}
// Blocklist
const bl = document.getElementById('blocklist');
document.getElementById('block-count').textContent = data.blocked_ips.length;
if (data.blocked_ips.length === 0) {
bl.innerHTML = '<span style="color:#64748b;font-size:13px">无封禁 IP</span>';
} else {
bl.innerHTML = data.blocked_ips.map(ip =>
`<span class="block-tag">${escape(ip)} <button onclick="unblock('${ip}')">×</button></span>`
).join('');
}
}
async function block(ip) {
await fetch('/api/block/' + encodeURIComponent(ip), {method:'POST'});
refresh();
}
async function unblock(ip) {
await fetch('/api/block/' + encodeURIComponent(ip), {method:'DELETE'});
refresh();
}
function toggleAutoRefresh() {
autoRefresh = !autoRefresh;
document.getElementById('refresh-btn').textContent = autoRefresh ? '⏸ 暂停' : '▶ 继续';
if (autoRefresh) { refreshTimer = setInterval(refresh, 3000); refresh(); }
else { clearInterval(refreshTimer); }
}
refresh();
if (autoRefresh) { refreshTimer = setInterval(refresh, 3000); }
</script>
</body>
</html>"""
@app.get("/dashboard", response_class=HTMLResponse)
def dashboard():
return HTMLResponse(DASHBOARD_HTML)
# ─── Auto-detect VPN proxy ───
def _detect_vpn_proxy():
proxy = (
os.getenv("HTTPS_PROXY")
or os.getenv("https_proxy")
or os.getenv("HTTP_PROXY")
or os.getenv("http_proxy")
)
if proxy:
return proxy
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
try:
s.settimeout(1)
s.connect(("127.0.0.1", 22307))
s.close()
return "http://127.0.0.1:22307"
except Exception:
return None
_vpn_proxy = _detect_vpn_proxy()
if _vpn_proxy:
os.environ["HTTPS_PROXY"] = _vpn_proxy
logger.info("VPN 代理已自动检测: %s", _vpn_proxy)
else:
logger.info("未检测到 VPN 代理,直连 MES")
if __name__ == "__main__":
print(f"\n{'='*54}")
print(f" 🔐 MES 查询代理已启动")
print(f" {'='*54}")
print(f" 端口: {PROXY_PORT}")
print(f" Token: {PROXY_TOKEN}")
print(f" 限流: {RATE_LIMIT} 次/分钟/IP")
print(f" MES: {MES_API_URL}")
print(f" {'='*54}")
print(f" 📊 监控看板: http://localhost:{PROXY_PORT}/dashboard")
print(f" 📌 HF Spaces 设置:")
print(f" MES_PROXY_URL={{{{ Cloudflare Tunnel URL }}}}")
print(f" MES_PROXY_TOKEN={PROXY_TOKEN}")
print(f" {'='*54}\n")
uvicorn.run(app, host="0.0.0.0", port=PROXY_PORT, log_level="info")