import hmac, threading, secrets, socket, struct, click, json, sys from pathlib import Path _CONN_LIMIT = threading.BoundedSemaphore(64) from rich.console import Console from datetime import datetime console = Console() def _recv_exact(sock:socket.socket, n:int) -> bytes: buf = b"" while len(buf) < n: chunk = sock.recv(n - len(buf)) if not chunk: raise ConnectionError("Connection closed") buf += chunk return buf def _log(addr:tuple, command:str, profile:str|None, status:str, error:str|None=None) -> None: ts = datetime.now().strftime("%H:%M:%S") addr_str = f"{addr[0]}:{addr[1]}" profile_str = f"[dim]{profile}[/dim] " if profile else "" if error: console.print(f"[dim]{ts}[/dim] {addr_str} {profile_str}[cyan]{command}[/cyan] [red]{status}[/red] {error}") else: console.print(f"[dim]{ts}[/dim] {addr_str} {profile_str}[cyan]{command}[/cyan] [green]{status}[/green]") def _proxy_request(client_sock:socket.socket, addr:tuple, profile:str|None, server_token:str|None, auth_keys:list[str]|None, auth_keys_path:"Path|None", nonce:str) -> None: from browser_cli.client import _resolve_socket, BrowserNotConnected from browser_cli.platform import is_windows try: header = _recv_exact(client_sock, 4) msg_len = struct.unpack(" None: err = json.dumps({"id": msg_id, "success": False, "error": msg}).encode() try: client_sock.sendall(struct.pack(" None: if not _CONN_LIMIT.acquire(blocking=False): client_sock.close() return client_sock.settimeout(30) try: with client_sock: # reload on every connection so auth trust --remote takes effect immediately if auth_keys_path is not None: from browser_cli.auth import load_authorized_keys auth_keys: list[str] | None = load_authorized_keys(auth_keys_path) else: auth_keys = None nonce = secrets.token_hex(32) challenge = json.dumps({"type": "challenge", "nonce": nonce}).encode() try: client_sock.sendall(struct.pack("