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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
"""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")