| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111 |
- """Small fail-closed fixes applied to the exported, immutable baseline sources."""
- import ast
- DELIVERY_MARKER = '# FMODE_ROOM_SCOPED_REUSE_V1'
- OLD_HUB = ''' if (chk.get("count") or 0) > 0 and (chk.get("files") or []):
- first = chk["files"][0]'''
- NEW_HUB = ''' # FMODE_ROOM_SCOPED_REUSE_V1: a URL in another room is not this room's registration.
- matches = [item for item in (chk.get("files") or [])
- if isinstance(item, dict) and item.get("roomId") == room_id
- and (not item.get("agentId") or item.get("agentId") == _resolve_agent_id())]
- if matches:
- first = matches[0]'''
- OLD_REUSE = ''' log("REUSE %s url=%s did=%s" % (owner, cached_url, old.get("id")))
- res.append({"path": owner, "ok": True, "url": cached_url,
- "did": old.get("id"), "detail": "reused-existing"})'''
- NEW_REUSE = ''' if any(item.get("path") == owner and item.get("url") for item in res):
- continue
- hub = _hub_register(owner, cached_url, thread_root, room_id, old.get("id"))
- digest = hashlib.sha256()
- with open(owner, "rb") as stream:
- for chunk in iter(lambda: stream.read(1 << 20), b""):
- digest.update(chunk)
- log("REUSE %s url=%s did=%s registered=%s" % (owner, cached_url, old.get("id"), hub.get("ok")))
- res.append({"path": owner, "ok": hub.get("ok") is True, "url": cached_url,
- "did": old.get("id"), "hub": hub, "sha256": digest.hexdigest(),
- "detail": "reused-existing" if hub.get("ok") is True else "reuse-register-failed"})'''
- OLD_NOTICE = ''' subprocess.Popen(
- ["python3", str(NOTICE_SCRIPT)],
- stdin=subprocess.PIPE,
- stdout=subprocess.DEVNULL,
- stderr=subprocess.DEVNULL,
- env=env,
- start_new_session=True,
- ).communicate(input=json.dumps(payload, ensure_ascii=False).encode("utf-8"))'''
- NEW_NOTICE = ''' # FMODE_NOTICE_NONBLOCKING_V1: file-backed stdin cannot wait on child network I/O.
- import tempfile
- import threading
- with tempfile.TemporaryFile(mode="w+b") as input_stream:
- input_stream.write(json.dumps(payload, ensure_ascii=False).encode("utf-8"))
- input_stream.seek(0)
- worker = subprocess.Popen(
- ["python3", str(NOTICE_SCRIPT)], stdin=input_stream,
- stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- env=env, start_new_session=True,
- )
- threading.Thread(target=worker.wait, daemon=True).start()'''
- def once(source, old, new):
- if source.count(old) != 1:
- raise ValueError('Runtime differs from verified baseline; refusing partial patch')
- return source.replace(old, new, 1)
- def patch_delivery(source):
- ast.parse(source)
- if DELIVERY_MARKER in source:
- if not all(item in source for item in [NEW_HUB, NEW_REUSE, NEW_NOTICE]):
- raise ValueError('Incomplete room-reuse or nonblocking-notice patch')
- return source
- updated = once(source, OLD_HUB, NEW_HUB)
- updated = once(updated, OLD_REUSE, NEW_REUSE)
- updated = once(updated, 'reused = {r["path"] for r in res if r.get("ok")}',
- 'reused = {r["path"] for r in res if r.get("ok") or r.get("detail") == "reuse-register-failed"}')
- updated = once(updated, OLD_NOTICE, NEW_NOTICE)
- ast.parse(updated)
- return updated
- OLD_ALREADY = ''' if "_is_allowed_media_url" in s or "async def _fetch_http_media" in s:
- rep.append("已存在补丁标记 → 视为已打过(跳过)")
- return s, rep, True'''
- NEW_ALREADY = ''' 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'''
- OLD_WRITE = '''def write(p, s):
- io.open(p, "w", encoding="utf-8").write(s)'''
- NEW_WRITE = '''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 patch_media(source):
- ast.parse(source)
- if 'FMODE_ATOMIC_MEDIA_PATCH_V1' in source:
- if NEW_ALREADY not in source or NEW_WRITE not in source:
- raise ValueError('Incomplete atomic media patch')
- return source
- updated = once(source, 'import argparse\n', 'import argparse\nimport ast\nimport tempfile\n')
- updated = once(updated, OLD_ALREADY, NEW_ALREADY)
- updated = once(updated, OLD_WRITE, NEW_WRITE)
- updated = once(updated, 'shutil.copy2(baks[-1], TARGET)', 'write(TARGET, read(baks[-1]))')
- updated = once(updated, 'shutil.copy2(bak, TARGET)', 'write(TARGET, read(bak))')
- ast.parse(updated)
- return updated
|