#!/usr/bin/env python3 """Add reliable clipboard and reconnect handling to ttyd's pinned client.""" from __future__ import annotations import argparse import socket import subprocess import time import urllib.request from pathlib import Path MARKER = "atlas-ttyd-clipboard" UPSTREAM_COPY = 'document.execCommand("copy")' CLIPBOARD_ADAPTER = r""" """ def patch_html(content: str) -> str: """Insert the adapter before ttyd and disable its false-success copy call.""" if content.count(UPSTREAM_COPY) != 1 or content.count("") != 1: raise RuntimeError("ttyd index patch context changed") if MARKER in content: raise RuntimeError("ttyd index is already patched") content = content.replace(UPSTREAM_COPY, "void 0", 1) return content.replace("", f"{CLIPBOARD_ADAPTER}", 1) def fetch_embedded_index(ttyd: Path) -> str: """Serve and retrieve ttyd's embedded page without vendoring its bundle.""" with socket.socket() as listener: listener.bind(("127.0.0.1", 0)) port = listener.getsockname()[1] process = subprocess.Popen( [ str(ttyd), "--interface", "127.0.0.1", "--port", str(port), "/bin/sh", "-c", "sleep 30", ], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, ) try: for _ in range(100): try: with urllib.request.urlopen( f"http://127.0.0.1:{port}/", timeout=1 ) as response: return response.read().decode("utf-8") except OSError: if process.poll() is not None: raise RuntimeError("temporary ttyd exited before serving its index") time.sleep(0.05) raise RuntimeError("timed out retrieving ttyd's embedded index") finally: process.terminate() try: process.wait(timeout=3) except subprocess.TimeoutExpired: process.kill() process.wait(timeout=3) def main() -> int: """Generate one patched index for the ttyd sidecar.""" parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("ttyd", type=Path) parser.add_argument("output", type=Path) args = parser.parse_args() content = patch_html(fetch_embedded_index(args.ttyd)) args.output.parent.mkdir(parents=True, exist_ok=True) args.output.write_text(content, encoding="utf-8") return 0 if __name__ == "__main__": raise SystemExit(main())