patch_spec.py 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216
  1. #!/usr/bin/env python3
  2. # -*- coding: utf-8 -*-
  3. """
  4. Fmode Matrix 附件直读 https(s3.fmode.cn) 补丁 —— 按 App 侧任务书 §三/§四 规格实现
  5. 目标: /opt/hermes/plugins/platforms/matrix/adapter.py
  6. 用法: python3 patch_spec.py --check | --apply | --revert
  7. 幂等; 任一定位串匹配次数 != 1 即整体中止不写; 语法失败自动回滚。
  8. """
  9. import argparse
  10. import ast
  11. import tempfile
  12. import glob
  13. import io
  14. import os
  15. import shutil
  16. import subprocess
  17. import sys
  18. import time
  19. TARGET = "/opt/hermes/plugins/platforms/matrix/adapter.py"
  20. HELPER = '''# Fmode: 允许容器直接拉取的附件域名。防 SSRF:只放行这一个。
  21. # 注意:file-cloud.fmode.cn 证书已过期(2026-11-13 实测),不要加回来。
  22. # 🔴 urlparse 必须在函数内 import —— 模块顶部只导入了 urljoin/urlsplit/urlunsplit,
  23. # 裸用 urlparse 会 NameError,被 except 吞掉后静默返回 False,附件照旧被拒。
  24. _FMODE_MEDIA_HOSTS = {"s3.fmode.cn"}
  25. def _is_allowed_media_url(u: str) -> bool:
  26. """mxc:// 一律放行;https:// 只放行个人存储白名单域名。"""
  27. if u.startswith("mxc://"):
  28. return True
  29. if not u.startswith("https://"):
  30. return False
  31. try:
  32. from urllib.parse import urlparse
  33. return (urlparse(u).hostname or "").lower() in _FMODE_MEDIA_HOSTS
  34. except Exception:
  35. return False
  36. '''
  37. FETCH = ''' async def _fetch_http_media(self, url: str, event_id: str):
  38. """Fmode: 从个人存储(https)流式拉取附件。超限/失败返回 None。"""
  39. if not _is_allowed_media_url(url):
  40. logger.warning("[Matrix] Refusing non-allowed media URL %s: %s", event_id, url)
  41. return None
  42. limit = self._max_media_bytes or 0
  43. async def _read_aiohttp():
  44. import aiohttp
  45. timeout = aiohttp.ClientTimeout(total=600)
  46. async with aiohttp.ClientSession(timeout=timeout) as session:
  47. async with session.get(url, allow_redirects=False) as resp:
  48. if resp.status != 200:
  49. logger.warning("[Matrix] HTTP media fetch failed %s: %s", event_id, resp.status)
  50. return None
  51. buf = bytearray()
  52. async for chunk in resp.content.iter_chunked(64 * 1024):
  53. buf.extend(chunk)
  54. if limit and len(buf) > limit:
  55. logger.warning("[Matrix] Rejecting oversized HTTP media %s", event_id)
  56. return None
  57. return bytes(buf)
  58. async def _read_httpx():
  59. import httpx
  60. async with httpx.AsyncClient(timeout=600, follow_redirects=False) as hc:
  61. async with hc.stream("GET", url) as resp:
  62. if resp.status_code != 200:
  63. logger.warning("[Matrix] HTTP media fetch failed %s: %s", event_id, resp.status_code)
  64. return None
  65. buf = bytearray()
  66. async for chunk in resp.aiter_bytes(64 * 1024):
  67. buf.extend(chunk)
  68. if limit and len(buf) > limit:
  69. logger.warning("[Matrix] Rejecting oversized HTTP media %s", event_id)
  70. return None
  71. return bytes(buf)
  72. try:
  73. return await _read_aiohttp()
  74. except ImportError:
  75. return await _read_httpx()
  76. except Exception as e:
  77. logger.warning("[Matrix] HTTP media download error %s: %s", event_id, e)
  78. return None
  79. '''
  80. A1 = (' if url and not str(url).startswith("mxc://"):\n'
  81. ' logger.warning("[Matrix] Rejecting inbound media %s with non-MXC URL", event_id)\n'
  82. ' return')
  83. B1 = (' if url and not _is_allowed_media_url(str(url)):\n'
  84. ' logger.warning("[Matrix] Rejecting inbound media %s with non-allowed URL: %s", event_id, url)\n'
  85. ' return')
  86. A2 = (' if url and not str(url).startswith("mxc://"):\n'
  87. ' logger.warning("[Matrix] Rejecting inbound encrypted media %s with non-MXC URL", event_id)\n'
  88. ' return')
  89. B2 = (' if url and not _is_allowed_media_url(str(url)):\n'
  90. ' logger.warning("[Matrix] Rejecting inbound encrypted media %s with non-allowed URL: %s", event_id, url)\n'
  91. ' return')
  92. A3 = ' file_bytes = await self._client.download_media(ContentURI(url))'
  93. B3 = (' if str(url).startswith("https://"):\n'
  94. ' # Fmode: 附件直读个人存储(s3.fmode.cn),不经 Matrix media\n'
  95. ' file_bytes = await self._fetch_http_media(url, event_id)\n'
  96. ' if file_bytes is None:\n'
  97. ' return None\n'
  98. ' else:\n'
  99. ' file_bytes = await self._client.download_media(ContentURI(url))')
  100. def read(p):
  101. return io.open(p, encoding="utf-8").read()
  102. def write(p, s):
  103. compile(s, p, "exec")
  104. directory = os.path.dirname(p) or "."
  105. fd, temporary = tempfile.mkstemp(prefix=".fmode-media-", suffix=".tmp", dir=directory)
  106. try:
  107. with os.fdopen(fd, "w", encoding="utf-8") as stream:
  108. stream.write(s)
  109. stream.flush()
  110. os.fsync(stream.fileno())
  111. if os.path.exists(p):
  112. os.chmod(temporary, os.stat(p).st_mode & 0o7777)
  113. os.replace(temporary, p)
  114. finally:
  115. if os.path.exists(temporary):
  116. os.unlink(temporary)
  117. def build(s):
  118. rep = []
  119. ast.parse(s)
  120. if "_is_allowed_media_url" in s or "async def _fetch_http_media" in s:
  121. # FMODE_ATOMIC_MEDIA_PATCH_V1: syntax and the complete transformation are required.
  122. if not all(part in s for part in (B1, B2, B3, "def _is_allowed_media_url(", "async def _fetch_http_media(")):
  123. raise ValueError("残缺的媒体补丁,保留原文件并停止启动;请检查已验证备份")
  124. rep.append("已验证完整媒体补丁与语法,跳过")
  125. return s, rep, True
  126. for a, b, nm in ((A1, B1, "P1 主url放行"), (A2, B2, "P2 加密媒体放行"), (A3, B3, "P3 下载分支")):
  127. n = s.count(a)
  128. if n != 1:
  129. raise SystemExit("[中止] %s 定位串出现 %d 次(期望 1),文件未改动" % (nm, n))
  130. for a, b, nm in ((A1, B1, "P1"), (A2, B2, "P2"), (A3, B3, "P3")):
  131. s = s.replace(a, b, 1)
  132. rep.append("%s 已替换" % nm)
  133. i = s.index("\n\nclass ")
  134. s = s[:i] + "\n\n" + HELPER.rstrip("\n") + "\n" + s[i:]
  135. rep.append("P4 白名单函数已插入")
  136. anchor = " async def _download_and_cache_media("
  137. if s.count(anchor) != 1:
  138. raise SystemExit("[中止] 找不到 _download_and_cache_media,文件未改动")
  139. s = s.replace(anchor, FETCH + anchor, 1)
  140. rep.append("P5 下载方法已插入")
  141. return s, rep, False
  142. def syntax_ok(p):
  143. r = subprocess.run([sys.executable, "-m", "py_compile", p], capture_output=True, text=True)
  144. return r.returncode == 0, (r.stderr or "").strip()
  145. def main():
  146. ap = argparse.ArgumentParser()
  147. g = ap.add_mutually_exclusive_group(required=True)
  148. g.add_argument("--check", action="store_true")
  149. g.add_argument("--apply", action="store_true")
  150. g.add_argument("--revert", action="store_true")
  151. a = ap.parse_args()
  152. if a.revert:
  153. baks = sorted(glob.glob(TARGET + ".bak-spec.*"))
  154. if not baks:
  155. raise SystemExit("没有可回滚的备份")
  156. write(TARGET, read(baks[-1]))
  157. ok, err = syntax_ok(TARGET)
  158. print("已从 %s 还原;语法 %s" % (baks[-1], "OK" if ok else "FAIL " + err))
  159. return
  160. src = read(TARGET)
  161. new, rep, already = build(src)
  162. print("=== 变更计划 ===")
  163. for r in rep:
  164. print(" -", r)
  165. changed = new != src
  166. print("文件是否变化:", "是" if changed else "否")
  167. if a.check:
  168. tmp = "/tmp/.spec_check_%d.py" % os.getpid()
  169. write(tmp, new)
  170. ok, err = syntax_ok(tmp)
  171. os.unlink(tmp)
  172. print("语法预检:", "OK" if ok else "FAIL " + err)
  173. print("_is_allowed_media_url 次数:", new.count("_is_allowed_media_url"))
  174. return
  175. if not changed:
  176. print("无需改动。")
  177. return
  178. bak = "%s.bak-spec.%s" % (TARGET, time.strftime("%Y%m%d%H%M%S"))
  179. shutil.copy2(TARGET, bak)
  180. print("已备份 ->", bak)
  181. write(TARGET, new)
  182. ok, err = syntax_ok(TARGET)
  183. if not ok:
  184. write(TARGET, read(bak))
  185. raise SystemExit("[回滚] 语法失败已还原: %s" % err)
  186. print("语法: OK")
  187. print("落地计数 _is_allowed_media_url =", read(TARGET).count("_is_allowed_media_url"))
  188. if __name__ == "__main__":
  189. main()