# -*- coding: utf-8 -*- """修默认协议的判断。 问题:用户写 `192.168.2.156:8080`(不带协议头)时, 我之前一律补成 `https://` —— 但局域网中转服务的是**明文 HTTP**, 补成 https 就永远连不上,而且报错信息很误导。 判断规则: IP 地址 / localhost / .local -> http:// (局域网,明文) 其它(域名) -> https:// (公网,必须加密) 这样用户随便写 `192.168.2.156:8080` 或 `relay.xxmxxs.top` 都能对。 """ from __future__ import annotations import re import sys from pathlib import Path RELAY = Path(r"C:\Users\shu\Desktop\deepseekagent\LanRemote\windows" r"\lanremote\relay.py") OLD = ''' candidates = [] for piece in (url or "").replace(",", ";").split(";"): piece = piece.strip().rstrip("/") if not piece: continue if not piece.startswith(("http://", "https://")): piece = "https://" + piece if piece not in candidates: candidates.append(piece)''' NEW = ''' candidates = [] for piece in (url or "").replace(",", ";").split(";"): piece = piece.strip().rstrip("/") if not piece: continue if not piece.startswith(("http://", "https://")): piece = _guess_scheme(piece) + piece if piece not in candidates: candidates.append(piece)''' HELPER_ANCHOR = '''def _ssl_context() -> ssl.SSLContext:''' HELPER = '''# 私有网段 + 回环,这些肯定是局域网,用明文 HTTP _PRIVATE_HOST = re.compile( r"^(?:localhost|127\\.|10\\.|192\\.168\\.|172\\.(?:1[6-9]|2\\d|3[01])\\.)" r"|^\\d{1,3}(?:\\.\\d{1,3}){3}(?::\\d+)?$" # 纯 IP(含公网 IP) r"|\\.local(?::\\d+)?$", re.IGNORECASE) def _guess_scheme(address: str) -> str: """用户没写 http/https 时,猜一个。 IP 地址 / localhost -> http:// 局域网里的中转服务是明文 HTTP。如果猜成 https,永远连不上, 而且报的是 SSL 错误,很容易误导人去查证书。 域名 -> https:// 走公网必须加密(Cloudflare 隧道本来就是 https)。 """ host = address.split("/", 1)[0] return "http://" if _PRIVATE_HOST.match(host) else "https://" ''' + HELPER_ANCHOR def main() -> int: text = RELAY.read_text(encoding="utf-8") ok = True # 需要 re 模块 if "\nimport re\n" not in text: text = text.replace("import json\n", "import json\nimport re\n", 1) print(" 加了 import re") if "_guess_scheme" in text: print(" 已经加过协议猜测") else: for old, new, tag in ((OLD, NEW, "start() 用 _guess_scheme"), (HELPER_ANCHOR, HELPER, "_guess_scheme 函数")): if old not in text: print(f" [失败] {tag} —— 锚点没找到") ok = False continue text = text.replace(old, new, 1) print(f" {tag}") RELAY.write_text(text, encoding="utf-8", newline="\n") import ast try: ast.parse(text) print(" 语法 OK") except SyntaxError as exc: print(f" 语法错误: {exc}") ok = False return 0 if ok else 1 if __name__ == "__main__": sys.exit(main())