| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216 |
- #!/usr/bin/env python3
- # -*- coding: utf-8 -*-
- """
- Fmode Matrix 附件直读 https(s3.fmode.cn) 补丁 —— 按 App 侧任务书 §三/§四 规格实现
- 目标: /opt/hermes/plugins/platforms/matrix/adapter.py
- 用法: python3 patch_spec.py --check | --apply | --revert
- 幂等; 任一定位串匹配次数 != 1 即整体中止不写; 语法失败自动回滚。
- """
- import argparse
- import ast
- import tempfile
- import glob
- import io
- import os
- import shutil
- import subprocess
- import sys
- import time
- TARGET = "/opt/hermes/plugins/platforms/matrix/adapter.py"
- HELPER = '''# Fmode: 允许容器直接拉取的附件域名。防 SSRF:只放行这一个。
- # 注意:file-cloud.fmode.cn 证书已过期(2026-11-13 实测),不要加回来。
- # 🔴 urlparse 必须在函数内 import —— 模块顶部只导入了 urljoin/urlsplit/urlunsplit,
- # 裸用 urlparse 会 NameError,被 except 吞掉后静默返回 False,附件照旧被拒。
- _FMODE_MEDIA_HOSTS = {"s3.fmode.cn"}
- def _is_allowed_media_url(u: str) -> bool:
- """mxc:// 一律放行;https:// 只放行个人存储白名单域名。"""
- if u.startswith("mxc://"):
- return True
- if not u.startswith("https://"):
- return False
- try:
- from urllib.parse import urlparse
- return (urlparse(u).hostname or "").lower() in _FMODE_MEDIA_HOSTS
- except Exception:
- return False
- '''
- FETCH = ''' async def _fetch_http_media(self, url: str, event_id: str):
- """Fmode: 从个人存储(https)流式拉取附件。超限/失败返回 None。"""
- if not _is_allowed_media_url(url):
- logger.warning("[Matrix] Refusing non-allowed media URL %s: %s", event_id, url)
- return None
- limit = self._max_media_bytes or 0
- async def _read_aiohttp():
- import aiohttp
- timeout = aiohttp.ClientTimeout(total=600)
- async with aiohttp.ClientSession(timeout=timeout) as session:
- async with session.get(url, allow_redirects=False) as resp:
- if resp.status != 200:
- logger.warning("[Matrix] HTTP media fetch failed %s: %s", event_id, resp.status)
- return None
- buf = bytearray()
- async for chunk in resp.content.iter_chunked(64 * 1024):
- buf.extend(chunk)
- if limit and len(buf) > limit:
- logger.warning("[Matrix] Rejecting oversized HTTP media %s", event_id)
- return None
- return bytes(buf)
- async def _read_httpx():
- import httpx
- async with httpx.AsyncClient(timeout=600, follow_redirects=False) as hc:
- async with hc.stream("GET", url) as resp:
- if resp.status_code != 200:
- logger.warning("[Matrix] HTTP media fetch failed %s: %s", event_id, resp.status_code)
- return None
- buf = bytearray()
- async for chunk in resp.aiter_bytes(64 * 1024):
- buf.extend(chunk)
- if limit and len(buf) > limit:
- logger.warning("[Matrix] Rejecting oversized HTTP media %s", event_id)
- return None
- return bytes(buf)
- try:
- return await _read_aiohttp()
- except ImportError:
- return await _read_httpx()
- except Exception as e:
- logger.warning("[Matrix] HTTP media download error %s: %s", event_id, e)
- return None
- '''
- A1 = (' if url and not str(url).startswith("mxc://"):\n'
- ' logger.warning("[Matrix] Rejecting inbound media %s with non-MXC URL", event_id)\n'
- ' return')
- B1 = (' if url and not _is_allowed_media_url(str(url)):\n'
- ' logger.warning("[Matrix] Rejecting inbound media %s with non-allowed URL: %s", event_id, url)\n'
- ' return')
- A2 = (' if url and not str(url).startswith("mxc://"):\n'
- ' logger.warning("[Matrix] Rejecting inbound encrypted media %s with non-MXC URL", event_id)\n'
- ' return')
- B2 = (' if url and not _is_allowed_media_url(str(url)):\n'
- ' logger.warning("[Matrix] Rejecting inbound encrypted media %s with non-allowed URL: %s", event_id, url)\n'
- ' return')
- A3 = ' file_bytes = await self._client.download_media(ContentURI(url))'
- B3 = (' if str(url).startswith("https://"):\n'
- ' # Fmode: 附件直读个人存储(s3.fmode.cn),不经 Matrix media\n'
- ' file_bytes = await self._fetch_http_media(url, event_id)\n'
- ' if file_bytes is None:\n'
- ' return None\n'
- ' else:\n'
- ' file_bytes = await self._client.download_media(ContentURI(url))')
- def read(p):
- return io.open(p, encoding="utf-8").read()
- def write(p, s):
- compile(s, p, "exec")
- directory = os.path.dirname(p) or "."
- fd, temporary = tempfile.mkstemp(prefix=".fmode-media-", suffix=".tmp", dir=directory)
- try:
- with os.fdopen(fd, "w", encoding="utf-8") as stream:
- stream.write(s)
- stream.flush()
- os.fsync(stream.fileno())
- if os.path.exists(p):
- os.chmod(temporary, os.stat(p).st_mode & 0o7777)
- os.replace(temporary, p)
- finally:
- if os.path.exists(temporary):
- os.unlink(temporary)
- def build(s):
- rep = []
- ast.parse(s)
- if "_is_allowed_media_url" in s or "async def _fetch_http_media" in s:
- # FMODE_ATOMIC_MEDIA_PATCH_V1: syntax and the complete transformation are required.
- if not all(part in s for part in (B1, B2, B3, "def _is_allowed_media_url(", "async def _fetch_http_media(")):
- raise ValueError("残缺的媒体补丁,保留原文件并停止启动;请检查已验证备份")
- rep.append("已验证完整媒体补丁与语法,跳过")
- return s, rep, True
- for a, b, nm in ((A1, B1, "P1 主url放行"), (A2, B2, "P2 加密媒体放行"), (A3, B3, "P3 下载分支")):
- n = s.count(a)
- if n != 1:
- raise SystemExit("[中止] %s 定位串出现 %d 次(期望 1),文件未改动" % (nm, n))
- for a, b, nm in ((A1, B1, "P1"), (A2, B2, "P2"), (A3, B3, "P3")):
- s = s.replace(a, b, 1)
- rep.append("%s 已替换" % nm)
- i = s.index("\n\nclass ")
- s = s[:i] + "\n\n" + HELPER.rstrip("\n") + "\n" + s[i:]
- rep.append("P4 白名单函数已插入")
- anchor = " async def _download_and_cache_media("
- if s.count(anchor) != 1:
- raise SystemExit("[中止] 找不到 _download_and_cache_media,文件未改动")
- s = s.replace(anchor, FETCH + anchor, 1)
- rep.append("P5 下载方法已插入")
- return s, rep, False
- def syntax_ok(p):
- r = subprocess.run([sys.executable, "-m", "py_compile", p], capture_output=True, text=True)
- return r.returncode == 0, (r.stderr or "").strip()
- def main():
- ap = argparse.ArgumentParser()
- g = ap.add_mutually_exclusive_group(required=True)
- g.add_argument("--check", action="store_true")
- g.add_argument("--apply", action="store_true")
- g.add_argument("--revert", action="store_true")
- a = ap.parse_args()
- if a.revert:
- baks = sorted(glob.glob(TARGET + ".bak-spec.*"))
- if not baks:
- raise SystemExit("没有可回滚的备份")
- write(TARGET, read(baks[-1]))
- ok, err = syntax_ok(TARGET)
- print("已从 %s 还原;语法 %s" % (baks[-1], "OK" if ok else "FAIL " + err))
- return
- src = read(TARGET)
- new, rep, already = build(src)
- print("=== 变更计划 ===")
- for r in rep:
- print(" -", r)
- changed = new != src
- print("文件是否变化:", "是" if changed else "否")
- if a.check:
- tmp = "/tmp/.spec_check_%d.py" % os.getpid()
- write(tmp, new)
- ok, err = syntax_ok(tmp)
- os.unlink(tmp)
- print("语法预检:", "OK" if ok else "FAIL " + err)
- print("_is_allowed_media_url 次数:", new.count("_is_allowed_media_url"))
- return
- if not changed:
- print("无需改动。")
- return
- bak = "%s.bak-spec.%s" % (TARGET, time.strftime("%Y%m%d%H%M%S"))
- shutil.copy2(TARGET, bak)
- print("已备份 ->", bak)
- write(TARGET, new)
- ok, err = syntax_ok(TARGET)
- if not ok:
- write(TARGET, read(bak))
- raise SystemExit("[回滚] 语法失败已还原: %s" % err)
- print("语法: OK")
- print("落地计数 _is_allowed_media_url =", read(TARGET).count("_is_allowed_media_url"))
- if __name__ == "__main__":
- main()
|