Files
ykxmz/_build/resume_and_verify.py
T
xmz7891 a53a3eee21 搬到 Lightsail:nginx 反代 + TLS + 公共 DNS + 后台口令改由服务器持有
== 架构(最终形态)==

    用户 --HTTPS--> Cloudflare CDN --HTTP/HTTPS--> nginx --+--> 127.0.0.1:13245
                    yk.xxmxxs.top                  13.54.30.196

中转只绑 127.0.0.1,公网只能经 nginx 进来 —— 少一个暴露面
(实测公网直连 :13245 返回 000,符合预期)。

== 这一轮加的 ==

1. **nginx 反代**(_build/setup_nginx.py)
   Cloudflare 只能回源到特定端口(80/8080/443/2053…),
   中转跑的 13245 不在列表里,所以中间必须有一层。
   配置要点:
     /download/  proxy_buffering on
     /v1/        proxy_read_timeout 180s + **proxy_buffering off**
                 (长轮询要挂 60 秒;关缓冲,否则要等整个响应完
                   才吐给客户端,那就不是长轮询了)

2. **源站 TLS 证书**(_build/setup_tls_origin.py)
   Cloudflare 的 SSL 模式是 Full(strict),回源走 443,源站只有 80
   -> 522。用 certbot 的 nginx 插件签了 Let's Encrypt 证书。
   开着橙色云朵也能签:HTTP-01 挑战经 Cloudflare 回源到 80 能验证。
   踩的坑:第一次用 example.com 当邮箱,Let's Encrypt 拒收保留域名。

3. **公共 DNS**(_build/fix_server_dns.py)
   换域名之后 **服务器自己解析不了** yk.xxmxxs.top:
   Lightsail 默认的内网解析器 172.26.0.2 还缓存着"不存在"(负缓存),
   而 1.1.1.1 / 8.8.8.8 已经能解析。
   后果不只是监测误报 —— 服务器上任何解析该域名的东西都会失败。
   配上公共 DNS,内网那个降为后备(它对 AWS 自家服务更快)。

4. **监测与预案重写**(relay/monitor-lightsail.sh、rescue-lightsail.sh)
   分两层探测,才能分清是哪一层坏的:
     PRIMARY   https://域名          用户实际走的
     FALLBACK  127.0.0.1:13245       中转本身
     PRIMARY 挂 + FALLBACK 好 -> edge 层 -> 动 nginx
     两个都挂               -> core 层 -> 动中转
   不区分的话只能瞎重启,而 edge 层的问题重启中转一万次也没用。

   做法上也改了:不再"SSH 过去用嵌套 heredoc 现场打补丁"
   (这一轮因此踩了五次转义/求值/百分号格式化的坑),
   改成**本地写完整文件、整份上传**,能进 git 做版本管理。

5. **后台口令改由服务器持有**(_build/set_admin_password.py)
   密码只写进 /opt/ykxmz-relay/data/admin_password.txt(600),
   **不进代码、不进仓库**。本地脚本从环境变量或
   _build/.admin_password(已 gitignore)读取。
   这个仓库已经吃过一次"管理员密码硬编码进提交历史"的教训了。

6. **验证脚本**(_build/verify_admin_login.py)
   第一版只看登录请求的状态码,结果"对的密码/错的密码/不带凭据"
   **全是 302** —— 等于没测。改成看 cookie 再访问 /admin,
   区分拿到的是登录页还是后台页。实测:
     正确密码 -> cookie 1 条 -> 后台页
     错误密码 -> cookie 0 条 -> 登录页
     账号写错 -> cookie 0 条 -> 登录页
     经 Cloudflare 域名 -> 后台页

== 其他修复 ==

  * 下载响应有**两条** Cache-Control(nginx 和 relay 各发一条),
    Cloudflare 遇到重复的缓存指令可能直接跳过缓存 -> 去掉 nginx 那条
  * 监测探测地址跟着监听地址改(改入口必须回头看所有探测入口)
  * curl 加 -L 跟跳转(certbot 加了 http->https 301)
  * 旧服务器(随身 WiFi 那台)的服务全部停掉并取消自启,
    但**没关机、没删文件** —— 保持可逆

全量回归 46 个阶段通过;594 个 Python 文件语法通过。
2026-10-08 23:07:45 +08:00

126 lines
4.7 KiB
Python

# -*- coding: utf-8 -*-
r'''443 开好之后:恢复监测单元 + 全链路验证。
== 为什么现在才恢复监测 ==
之前 443 没开,用户层(https://yk.xxmxxs.top)一直不通,
监测会把 fails 一直累加、每 10 分钟白生成一份抢救报告。
所以先停了,等端口开好。
现在 443 通了、用户层 200,可以恢复。
== 顺便验证什么 ==
1. 监测单元跑起来后 self-check 是 200(不再误报)
2. 下载走 Cloudflare 有没有缓存(第二次应该 HIT)
3. 长轮询没被 Cloudflare 或 nginx 截断
4. 证书链没问题(真实浏览器视角)
'''
from __future__ import annotations
import sys
import time
import urllib.request
from pathlib import Path
ROOT = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(ROOT / "_build"))
from lssh import run # noqa: E402
RELAY_DIR = "/opt/ykxmz-relay"
DOMAIN = "yk.xxmxxs.top"
def fetch(url: str, headers: dict = None) -> tuple:
"""返回 (状态码, 头字典, 字节数, 耗时秒)。
⚠ 必须带 User-Agent —— Cloudflare 把 **Python-urllib/3.11**
判为可疑客户端,直接返回 403 + error code 1010。
这个坑仓库里早记过(windows/lanremote/relay.py 文件头):
"实测 LanRemote/1.4.0 能过"。这里就带上它。
(curl 的默认 UA 不会被拦,所以服务器上的监测单元不受影响。)
"""
t0 = time.time()
h = {"User-Agent": "LanRemote/1.4.0"}
if headers:
h.update(headers)
req = urllib.request.Request(url, headers=h)
try:
with urllib.request.urlopen(req, timeout=180) as r:
body = r.read()
return (r.status, dict(r.headers), len(body), time.time() - t0)
except urllib.error.HTTPError as exc:
return (exc.code, dict(exc.headers or {}), 0, time.time() - t0)
except Exception as exc: # noqa: BLE001
return ("失败: %s" % type(exc).__name__, {}, 0, time.time() - t0)
def main() -> int:
print("=" * 62)
print(" 恢复监测 + 全链路验证")
print("=" * 62)
print()
print(" ── 1. 恢复监测单元 ──")
run("sudo systemctl start ykxmz-monitor.timer", timeout=120, quiet=True)
time.sleep(3)
out = run("systemctl is-active ykxmz-monitor.timer", timeout=60,
quiet=True)
print(" monitor.timer = " + out[1].strip())
print()
print(" ── 2. 手动跑一次监测(看还误报不误报)──")
run("bash %s/monitor.sh" % RELAY_DIR, timeout=180, quiet=True)
out = run("cat %s/monitor_state.txt" % RELAY_DIR, timeout=60, quiet=True)
for ln in out[1].strip().splitlines():
print(" " + ln)
print()
print(" ── 3. 下载速度(经 Cloudflare,第一次应 MISS)──")
url = "https://%s/download/ykxmz-setup-2.1.3.exe" % DOMAIN
code, hdr, size, dur = fetch(url)
print(" 第 1 次: HTTP %s %.2f MB %.1f 秒 %.0f KB/s"
% (code, size / 1048576, dur, size / 1024 / max(dur, 0.001)))
print(" CF-Cache-Status = %s"
% hdr.get("CF-Cache-Status", "(无)"))
time.sleep(2)
code, hdr, size, dur = fetch(url)
print(" 第 2 次: HTTP %s %.2f MB %.1f 秒 %.0f KB/s"
% (code, size / 1048576, dur, size / 1024 / max(dur, 0.001)))
print(" CF-Cache-Status = %s <- HIT 就说明 CDN 生效了"
% hdr.get("CF-Cache-Status", "(无)"))
print()
print(" ── 4. APK 下载 ──")
url = "https://%s/download/ykxmz-watch-2.1.3.apk" % DOMAIN
code, hdr, size, dur = fetch(url)
print(" HTTP %s %.0f KB %.2f 秒 %.0f KB/s CF=%s"
% (code, size / 1024, dur, size / 1024 / max(dur, 0.001),
hdr.get("CF-Cache-Status", "(无)")))
print()
print(" ── 5. 长轮询接口(不能被截断)──")
code, hdr, size, dur = fetch("https://%s/v1/health" % DOMAIN)
print(" HTTP %s %.2f 秒 Cache-Control=%s"
% (code, dur, hdr.get("Cache-Control", "(无)")))
print()
print(" ── 6. 服务器端状态 ──")
out = run("systemctl is-active ykxmz-relay nginx ykxmz-monitor.timer "
"certbot.timer", timeout=60, quiet=True)
names = ["ykxmz-relay", "nginx", "monitor.timer", "certbot.timer"]
for i, ln in enumerate(out[1].strip().splitlines()):
if i < len(names):
print(" %-20s %s" % (names[i], ln))
have = run("ls -1 %s/rescue_reports 2>/dev/null | wc -l" % RELAY_DIR,
timeout=60, quiet=True)
print(" %-20s %s 份(应该是 0 —— 之前清掉了)"
% ("抢救报告", have[1].strip()))
return 0
if __name__ == "__main__":
sys.exit(main())