Coverage for src/ai_shell/cdp_relay.py: 91%
103 statements
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
« prev ^ index » next coverage.py v7.17.0, created at 2026-11-17 21:40 +0000
1"""A host-side relay from the address containers reach to Chrome's loopback port.
3A windowed Chrome binds its DevTools port to ``127.0.0.1`` only: it ignores
4``--remote-debugging-address`` (that flag works in the old headless shell
5alone). On Docker Desktop that is fine, because ``host.docker.internal``
6lands on the host's loopback. On a Linux host (Docker or Podman) the
7container reaches the host at a real address, where nothing listens, so the
8bridge never connected there.
10This relay listens on that address, on the same port number, and forwards
11each connection to ``127.0.0.1:<port>``. It accepts connections only from
12the host's own addresses: a rootless Podman or Docker container's traffic
13arrives from one of them, while another machine on the network does not, so
14the DevTools port (which has no authentication) stays private to this host.
16It exits by itself once Chrome's loopback port has been gone for a while,
17so it never outlives the browser for long. ``python -m ai_shell.cdp_relay
18<bind-address> <port>`` runs it; ai-shell starts it detached.
19"""
21from __future__ import annotations
23import argparse
24import asyncio
25import contextlib
26import logging
27import socket
28import sys
29import time
31logger = logging.getLogger(__name__)
33LOOPBACK = "127.0.0.1"
34#: How often the relay checks that Chrome still answers on loopback.
35WATCHDOG_INTERVAL_SECONDS = 5.0
36#: How long Chrome's port may stay closed before the relay exits.
37WATCHDOG_GRACE_SECONDS = 30.0
38#: How long after start the relay waits for Chrome's port to open at all.
39STARTUP_GRACE_SECONDS = 90.0
40BUFFER_BYTES = 65536
43def local_addresses(bind_address: str = "") -> set[str]:
44 """Every address that is this host: loopback, the bind address, all interfaces."""
45 addresses = {LOOPBACK, "::1"}
46 if bind_address:
47 addresses.add(bind_address)
48 try:
49 for info in socket.getaddrinfo(socket.gethostname(), None):
50 addresses.add(str(info[4][0]))
51 except OSError:
52 pass
53 return addresses
56def peer_allowed(peer: str, allowed: set[str]) -> bool:
57 """True when *peer* (an IP text, IPv4-mapped IPv6 unwrapped) is one of *allowed*."""
58 if peer.startswith("::ffff:"):
59 peer = peer[len("::ffff:") :]
60 return peer in allowed
63def port_open(port: int, host: str = LOOPBACK, timeout: float = 1.0) -> bool:
64 """True when something accepts a TCP connection on *host*:*port*."""
65 try:
66 with socket.create_connection((host, port), timeout=timeout):
67 return True
68 except OSError:
69 return False
72async def _pump(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
73 try:
74 while True:
75 data = await reader.read(BUFFER_BYTES)
76 if not data:
77 break
78 writer.write(data)
79 await writer.drain()
80 except (ConnectionError, asyncio.IncompleteReadError, OSError):
81 pass
82 finally:
83 with contextlib.suppress(Exception):
84 writer.close()
87async def _handle(
88 reader: asyncio.StreamReader,
89 writer: asyncio.StreamWriter,
90 *,
91 target_port: int,
92 allowed: set[str],
93) -> None:
94 peer = writer.get_extra_info("peername")
95 peer_host = str(peer[0]) if peer else ""
96 if not peer_allowed(peer_host, allowed):
97 logger.warning("Refused a DevTools connection from %s", peer_host or "unknown")
98 writer.close()
99 return
100 try:
101 upstream_reader, upstream_writer = await asyncio.open_connection(LOOPBACK, target_port)
102 except OSError as exc:
103 logger.info("Chrome's loopback port %d refused: %s", target_port, exc)
104 writer.close()
105 return
106 await asyncio.gather(
107 _pump(reader, upstream_writer),
108 _pump(upstream_reader, writer),
109 )
112async def _watchdog(target_port: int, stop: asyncio.Event) -> None:
113 started = time.monotonic()
114 seen = False
115 last_seen = started
116 while not stop.is_set():
117 if port_open(target_port):
118 seen = True
119 last_seen = time.monotonic()
120 else:
121 now = time.monotonic()
122 grace = WATCHDOG_GRACE_SECONDS if seen else STARTUP_GRACE_SECONDS
123 if now - last_seen > grace:
124 logger.info("Chrome's loopback port %d is gone; relay exiting", target_port)
125 stop.set()
126 return
127 with contextlib.suppress(asyncio.TimeoutError):
128 await asyncio.wait_for(stop.wait(), timeout=WATCHDOG_INTERVAL_SECONDS)
131async def serve(bind_address: str, port: int, target_port: int | None = None) -> None:
132 """Run the relay until Chrome's port is gone (or the task is cancelled)."""
133 target = target_port or port
134 allowed = local_addresses(bind_address)
135 stop = asyncio.Event()
137 async def handler(reader: asyncio.StreamReader, writer: asyncio.StreamWriter) -> None:
138 await _handle(reader, writer, target_port=target, allowed=allowed)
140 server = await asyncio.start_server(handler, bind_address, port)
141 logger.info("Relaying %s:%d -> %s:%d", bind_address, port, LOOPBACK, target)
142 watchdog = asyncio.create_task(_watchdog(target, stop))
143 try:
144 await stop.wait()
145 finally:
146 watchdog.cancel()
147 server.close()
148 await server.wait_closed()
151def main(argv: list[str] | None = None) -> int:
152 parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
153 parser.add_argument("bind_address", help="address the containers reach the host at")
154 parser.add_argument("port", type=int, help="port to listen on and to forward to")
155 parser.add_argument(
156 "--target-port", type=int, default=None, help="Chrome's loopback port (default: PORT)"
157 )
158 args = parser.parse_args(argv)
159 logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
160 try:
161 asyncio.run(serve(args.bind_address, args.port, args.target_port))
162 except OSError as exc:
163 logger.error("Relay could not listen on %s:%d: %s", args.bind_address, args.port, exc)
164 return 1
165 return 0
168if __name__ == "__main__": # pragma: no cover - entry point
169 sys.exit(main())